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 |
|---|---|---|---|---|---|
Oxidizing your Python with some Rust
Python and its ecosystem are filled with a plethora of libraries and packages that make up some of Stack Overflow’s most popular tools & technologies [1]. The ecosystem is thoroughly embedded and the ease of use and learning curve is beginner-friendly. This is Python’s main strength: someone who is curious about the language can pick it up with little to no headache, especially with the vast number of resources to help kick-start their learning. However, with most things in life, the ease of use has its drawbacks.
Making Sense of Energy, Time, and Memory Performance
The figure above displays the energy, time, and memory performance across several programming languages. Python lags in energy, and time performance, but ranks slightly higher in the memory performance category[2]. Although Python is easy to use, its performance is not as strong as many other languages.
These runtime attributes are critical to modern engineering and are almost positively associated with improved software. When software can run faster, with less memory, and use less power (good for the environment when thinking of computing at-scale), it’s almost always better.
On the opposite end of the spectrum, Rust ranks second in energy, and time performance — only trailing behind C — and reasonably well in memory consumption [2]. Rust’s values, from the
rust-lang website, give us a sense of what their design goals are: [3]
- Performance
- Reliability
- Productivity
Rust competes with C and C++ with respect to performance. Rust has some very key guarantees that make it reliable. An excerpt from the Rust website states, [3]
“Rust’s rich type system and ownership model guarantee memory-safety and thread-safety — enabling you to eliminate many classes of bugs at compile-time.”
An analysis of
chromium, the core of Google Chrome & Chrome OS, found that 70% of their bugs are caused by memory safety issues [4]. Rust eliminates these classes of bugs at compile-time with the help of the Borrow Checker removing this class of bugs at compile time [5]. You can have confidence that a successful compilation will remain reliable and perform well.
Getting Started — Building Extensions for Python
The pyo3 Rust crate (package) lets us build Python extensions that can allow us to build highly efficient, highly performant, and safe code in Rust. At the same time, Python users can utilize these tools without learning a whole new language.
In this example, I will go over a simple example of building a Python extension in Rust. We will be using the
maturin build system by pyo3. This build system works seamlessly for building python packages from Rust. To start this tutorial I will be creating the package oxidizer that contains a function that calculates the sum of primes to a given value
n. Wherever you see
oxidizer, please note you should replace this with your own project / package / module name.
Please install Rust, Python, and
maturin before continuing.
New Package
First, we need to create a new Rust library using
cargo new oxidizer --lib
This will generate our Rust library with a
./src directory and some
Cargo files. Next, let’s add the
pyo3 dependency to our
./Cargo.toml file and specify the
crate-type to be a
cdylib.
Next, create a
pyproject.toml file to specify the build system for our python project.
Next, we’ll need to specify our
setup.py file with the following:
Implementation
Here is a trivial implementation of calculating the sum of primes from 0 to n. The key parts are the
#[pyfunction] and
#[pymodule] macros. These macros are what will be publicly visible to the python package. I will make use of using the
primal crate to calculate the primality of a number. Both Rust and Python will be making use of the Miller-Rabin primality test [6].
Now, all we need to do is create the remaining folders and files for
maturin. I’ll create the
./oxidizer folder and create the
__init__.py file inside with the following content:
from .oxidizer import sum_primes
Now we build our Python package with
maturin
maturin build --release
This builds the python wheels into
./target/wheels/ . We can now install this package with:
cd target/wheels && pip install oxidizer-{...}
Alternatively,
maturin can install locally for you with the
develop command
maturin develop
I highly recommend going through the
maturin documentation for an in depth explanation.
Benchmarks
Below I’ve implemented a
pytest micro-benchmark that compares the two implementations.
Here are the results.
The benchmark speaks for itself. Rust has significantly better performance and runs faster in this benchmark. Roughly speaking, the benchmark displays a ~20x performance increase by using Rust as opposed to Python in this scenario in each benchmark attribute.
By writing Python extensions in Rust, there are many performance benefits in terms of time. We also get memory safety with compile-time guarantees that no data races will occur (assuming there’s no use of the
unsafe keyword). End-users don’t need to know the implementation details of our Rust package, but they can reap the benefits without sacrificing the comfort and ergonomics of using Python. Python may not ever be replaced by another language, especially in the data space. However, there is always room for improvement. This implementation style is already used in projects like TensorFlow , and PyTorch where the core of the library is built in C++, and the bindings are made available to Python. By implementing functionality to lower-level languages like Rust, and having the ability to use the library in higher level languages like Python, it will provide us memory safety guarantees and significantly improve the performance of the package without the need to change the end user’s expectations and experience of working in Python.
Appendix
Here are some Rust resources if this blog post hasn’t convinced you to get take a sip of the sweet, sweet Rust kool-aid yet.
-
-
-
References
-
-
-
-
-
- | https://bradleybonitatibus.medium.com/oxidizing-your-python-with-some-rust-a3815a4d23ac?source=post_page-----a3815a4d23ac-------------------------------- | CC-MAIN-2021-21 | refinedweb | 993 | 54.12 |
Yammer Moving from Scala to Java
An e-mail, sent from Yammer employee Coda Hale to Scala's commercial management at Typesafe, ended up being leaked via YCombinator and a gist at GitHub. The e-mail confirms that Yammer is moving its basic infrastructure stack from Scala back to Java, owing to issues with complexity and performance.
Yammer PR Shelley Risk confirmed to InfoQ that the e-mail represented the personal opinions of Coda Hale, rather than an official statement from Yammer itself; a follow up from the original author has been published at. In it, Coda clarified that the message was a result of a request for feedback from Donald Fischer (CEO of Typesafe) following an earlier tweet indicating the move.
Update: Code has published Yammer's official position on the subject; which confirms the above points. It also points out that any language has flaws (not just Scala) and that the e-mail was an attempt at offering advice for how to improve Scala's performance and other concerns. Finally, it concluded that when rolling out any high performance project (for which Scala is their production environment) there are rough edges which need to be filed down; the e-mail was an attempt at helping Scala improve.
Although the e-mail was not meant to be publicly shared, Coda put it on GitHub via a Gist (since deleted) to get feedback from other friends; however, the content was then subsequently shared and then reported more widely.
Back in August 2010, Coda said on the Yammer Engineering blog that they were moving to Scala for their realtime future. The goal was to continue running on the JVM (for performance reasons) and that the conversion had resulted in approximately a 50% code reduction:
Fast forward a year and a quarter later, and the decision is being reversed:.
Stephen Colebourne, who recently posted the thread on Is Scala the new EJB2? has annotated the mail with a number of bullet points, summarising the issues involved:
- Scala, as a language, has some profoundly interesting ideas in it. But it's also a very complex language.
- In addition to the concepts and specific implementations that Scala introduces, there is also a cultural layer of what it means to write idiomatic Scala … at some point a best practice emerged: ignore the community entirely.
- In hindsight, I definitely underestimated both the difficulty and importance of learning (and teaching) Scala. Because it's effectively impossible to hire people with prior Scala experience, this matters much more than it might otherwise.
- Adding to the unease in development were issues with the build toolchain. … This emphasis on SBT being the one true way has meant the marginalization of Maven and Ant -- the two main build tools in the Java ecosystem.
- Each major Scala release being incompatible with the previous one biases Scala developers towards newer libraries and promotes wheel-reinventing in the general ecosystem.
- Via profiling and examining the bytecode we managed to get a 100x improvement by adopting some simple rules:
- Don't ever use a for-loop
- Don't ever use scala.collection.mutable
- Don't ever use scala.collection.immutable
- Always use private[this]
- Avoid closures
- I broached this issue [moving back to Java] with the team, demo'd the two codebases, and was actually surprised by the rather immediate consensus on switching. There's definitely aspects of Scala we'll miss, but it's not enough to keep us around.
Some of these issues are likely to be circumstantial (for example, the ease of hiring a developer with existing experience increases the longer a language is popular), there are some which can be empirically tested. For example, one of the pieces of advice is to avoid
for loops. This can be tested with the following piece of code:
scala> var start = System.currentTimeMillis(); var total = 0;for(i <- 0 until 100000) { total += i }; var end = System.currentTimeMillis(); println(end-start); println(total); 114 scala> scala< var start = System.currentTimeMillis(); var total = 0;var i=0;while(i < 100000) { i=i+1;total += i }; var end = System.currentTimeMillis(); println(end-start); println(total); 8
Using the for loop with an 'until' pattern here (which many Scala programmers would consider idiomatic) can be seen to be significantly slower than the corresponding while loop, even if the code is less readable. The corresponding Java implementation of the same loop shows a result of 2ms for both the
for and
while loops.
Another test we can perform is the performance of the mutable map by loading in a data set consisting of Integer objects. (This can be compared in Java and Scala and the cost of boxing should be equivalent.):
scala> val m = new scala.collection.mutable.HashMap[Int,Int]; var i = 0; var start = System.currentTimeMillis(); while(i<100000) { i=i+1;m.put(i,i);}; var end = System.currentTimeMillis(); println(end-start); println(m.size) 101 scala> val m = new java.util.HashMap[Int,Int]; var i = 0; var start = System.currentTimeMillis(); while(i<100000) { i=i+1;m.put(i,i);}; var end = System.currentTimeMillis(); println(end-start); println(m.size) 28 scala> val m = new java.util.concurrent.ConcurrentHashMap[Int,Int]; var i = 0; var start = System.currentTimeMillis(); while(i<100000) { i=i+1;m.put(i,i);}; var end = System.currentTimeMillis(); println(end-start); println(m.size) 55
Compared against the vanilla Java code, performance is identical when comparing the
java.util.HashMap, and the Java implementation with
java.util.concurrent.ConcurrentHashMap is twice as fast as its Scala counterpart. Both of the Java collection classes outperform the Scala counterpart, however. (Timings taken on OSX JVM 1.6.0_29 and Scala 2.9.1, the latest at the time of writing.)
Unfortunately, the Scala collections are pervasive in the Scala library APIs, and as such, they may be promoted from the Java object types to the Scala object types through implicits in the code. According to the migration mail, this resulted in significant re-writing for performance reasons.
Performance of closures (lambdas) may be improved if the Scala compiler generates code with
invokedynamic; something that might happen in future versions of the Scala compiler. In addition, in JDK 8 (which will bring both native lambdas and method handles to Java ) has a number of performance advantages which a future Scala version may be able to take advantage of.
Finally, there is increasing pressure for Scala to fix its backward compatibility between releases (rather than just in the minor releases between 2.9.2 and 2.9.3). There has been no official announcement from Typesafe regarding the future roadmap on Scala, or when a stable compiled binary format will permit code to be backwardly (or forwardly) compatible between releases. Having a backward compatible format would enable for more stable libraries to be released and build a community repository, which would help anyone interested in building upon Scala for the future.
Macro vs Mircro Optimization
by
Thomas Santana
Measurings...
by
Daniel Sobral
At any rate, I could not reproduce your results. Scala's mutable.HashMap, either 2.9.1 or trunk, performs pretty much on par with Java when executing the same code snippets you provided.
Re: Measurings...
by
Robin St
java.util.HashMap: 47, 44, 54, 51, 43
scala.collection.mutable.HashMap: 81, 81, 82, 81, 84
Scala version:
Welcome to Scala version 2.9.1.final (OpenJDK 64-Bit Server VM, Java 1.6.0_23).
Re: Measurings...
by
Joost de Vries
Re: Measurings...
by
Robin St
Re: Measurings...
by
Daniel Sobral
Without proper profiling tools you are lost - regardless
by
Faisal Waris
I can attest to the importance of profiling. I actually ported the Google benchmark to F#. There was a big difference in performance in the initial F# implementation and the final one. I used the Visual Studio 2010 profiler (an excellent tool) to quickly zero-in on the "hotspots" and optimize the code.
The final version of F# turned out to be even faster than the original C++ implemenation as independently verified by someone.
Note that the final C++ implementation was fastest of all and is more directly comparable to final Scala and F# implementations. The orginal C++ implementation did too many allocations which were removed in the final version and caching was used instead. (you have to dig through the links to find all of that)
Bottom line: Write your code idiomatically and then profile and tune. The code does not have to be super optimized in all locations. Good profiling tools are a must.
Re: Without proper profiling tools you are lost - regardless
by
Michael Campbell
1000 times, this. For what I'm guessing to be a large portion of us, the absolute fastest is not what we need. Our requirements are unlike Yammer's. For a lot of us, it doesn't matter if something is "slower", if we get it out the door 3 to 6 months quicker.
But there are those of use for whom it DOES matter. And for these cases, you absolutely have got to profile. Performance isn't a problem until performance is a problem.
Please don't use REPL for benchmarking
by
Andriy Plokhotnyuk
::#!
@echo off
set JAVA_OPTS=-server
call scala %0 %*
goto :eof
::!#
val n = 1000000000
def timed[T](name: String)(f: => T) = {
printf("%s :\n", name)
val t = System.nanoTime
val r = f
val d = System.nanoTime - t
printf("%,d ns\n", d)
printf("%,d ops/s\n", (n * 1000000000L) / d)
printf("%,f ns/op\n", d.toFloat / n)
}
timed("while") {
var sum = 0L;
var i= 1;
while (i <= n) {
sum += i
i += 1
}
sum
}
timed("for") {
var sum = 0L;
for (i <- 1 to n) {
sum += i
}
sum
}
while :
1,172,919,768 ns
852,573,234 ops/s
1.172920 ns/op
for :
2,059,442,013 ns
485,568,417 ops/s
2.059442 ns/op
Re: Measurings...
by
Charles Humble
Re: Measurings...
by
Peter Thomas
object Test {
def scala() {
val s = new collection.mutable.HashMap[Int,Int]();·
var i = 0;
val start = System.currentTimeMillis();
while(i<100000) { i=i+1;s.put(i,i);};
val end = System.currentTimeMillis();
println(end-start);
println(s.size)
}
def javaHashMap() {
val m = new java.util.HashMap[Int,Int];·
var i = 0;
val start = System.currentTimeMillis();
while(i<100000) { i=i+1;m.put(i,i);};
val end = System.currentTimeMillis();
println(end-start);
println(m.size)
}
def javaConcurrentHashMap() {
val c = new java.util.concurrent.ConcurrentHashMap[Int,Int];·
var i = 0;
val start = System.currentTimeMillis();
while(i<100000) { i=i+1;c.put(i,i);};
val end = System.currentTimeMillis();
println(end-start);
println(c.size)
}
def main(args: Array[String]) {
println("--")
println("-- JAVA CONCURRENTHASHMAP:")
println("--")
javaConcurrentHashMap()
println("--")
println("-- JAVA HASHMAP:")
println("--")
javaHashMap()
println("--")
println("-- SCALA:")
println("--")
scala()
}···
}
my test result after a few cycles (scala version: 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_29)):
--
-- JAVA CONCURRENTHASHMAP:
--
61
100000
--
-- JAVA HASHMAP:
--
56
100000
--
-- SCALA:
--
68
100000
scala is still slower but not that much. In most scenarios (where the collections are relatively small) this should be a non-issue.<//pre>
Re: Measurings...
by
James Watson
I won't call this FUD, but something's fishy
by
Ed Lover
The for and while loop tests were only different by a couple of milliseconds. The even more idiomatic
(0 until 100000).sum
was a bit slower, but all these microbenchmarks are fraught.
the mutable.HashMap and java.util.HashMap tests came out about the same, give or take a millisecond. Something doesn't add up with this article.
(I put the snippets in files and ran them that way. My setup: Ubuntu 64bit, 3-year-old mid-range Intel c2d, Java 1.6.0_26, Scala 2.9.1)
Re: I won't call this FUD, but something's fishy
by
Steve McJones
So I would recommend stop using it in benchmarks ... it won't loop anymore in the future. :-)
Int-overrun, immature code
by
Stefan Wagner
var total = 0L; for (i <- 0 until 100000) { total += i };
and
var total = 0L; var i=0; while (i < 100000) { i=i+1; total += i };
to avoid that, but there is a far faster solution:
val n = 100000L
val result= n*n/2-n
But calculating the result isn't the aim of the example? Not? So what is it? In far more complex computations, the costs of looping often vanish.
Yammer responds.
by
Richard Hightower
Scala is currently the main language for our high-performance backend services and in the past two years we've solved a number of hard problems using it. We built a real-time message delivery service which has scaled to hundreds of thousands of concurrent users. We built a distributed data store for message feeds which serves tens of thousands of requests per second over terabytes of data. We built a new search system, including both a distributed data store for denormalizing business objects into indexable documents and a low-latency query system for auto-completing the millions of people and group names on Yammer. We built a specialized server for integrating with Active Directory which streams staff changes from companies with hundreds of thousands of employees. We built a service for handling Yammer notifications which handles thousands of notifications a second with extremely low latency. We built an OAuth token service which manages gigabytes of cached principal objects and returns results in single-digit milliseconds.
All of these Scala projects are running in production right now, and we built them all with a team of seven people.
Along the way, we've found some problems with Scala. And Java. And Ruby. And C. And Javascript. And Objective-C. And Erlang.
So benchmarks lie
by
Joao Pedrosa
For instance, everyone knows the Lua programming language that is one of the fastest dynamic languages. There's a LuaJIT2 that makes it much much faster. But if you are not careful with declaring closures when nesting them in hot loops, it can slow the code down after a little over 1000 iterations. So the rule is watch out for that.
Whereas in Javascript, nesting functions and hence closures is a very common construction.
Many times I wonder about screaming fast programming languages as they can be screaming fast but if we hardly use them they are screaming fast at doing nothing most of the time.
As slow as Ruby can be, it's great to see a Ruby sample anywhere where there is a small algorithm challenge. Someone posts a challenge in his blog, soon there'll be a Ruby sample posted in the comments. I used to be one of the guys posting Ruby samples in people's blogs. Recently I've started posting Dart and Go samples instead. :-) Of the three of them, Go is the fastest which is great to show off. But even Go can get beaten by Ruby if the problem is simple enough that Ruby can offload the work to its C libraries.
Scala is the topic, though. I have noticed people rushing to post Scala samples to challenges on the web. Scala has a REPL that makes getting something small working in a short time span very easy. Plus the convenient syntax. There's a whole lot to Scala than just the more powerful than most languages aspects of it. Unraveling some code so it runs faster is par for the course in many of the modern languages.
Re: I won't call this FUD, but something's fishy
by
Alex Blewitt
Re: Yammer responds.
by
Alex Blewitt
Response by Typesafe
by
Joost de Vries
Basically it comes down to that they'll fix these things.
Which is very welcome.
Only by addressing these concerns can Scala be a real world language bringing higher order programming and pattern matching to the JVM instead of an academic one.
Re: Without proper profiling tools you are lost - regardless
by
Daniel Sobral
On Clojure
by
Alex Miller
Re: Without proper profiling tools you are lost - regardless
by
Matthew Tov | http://www.infoq.com/news/2011/11/yammer-scala | CC-MAIN-2014-41 | refinedweb | 2,675 | 65.22 |
Red Hat Bugzilla – Full Text Bug Listing
Created attachment 497172 [details]
Patch to fix the bug
Description of problem:
I found the bug in Ubuntu Natty:
The progress_obj is documented as:
But it is called as:
Regression (worked fine in Ubuntu Maverick)
Version-Release number of selected component (if applicable):
Ubuntu version of python-urlgrabber: 3.9.1-4
How reproducible:
100% reproducible
Steps to Reproduce:
1. Pass a progress_obj to the grabber
2. Implement the documented API
3. Code fails when called incorrectly by grabber.py
Actual results:
Code fails with a KeyboardInterrupt
Expected results:
Should work as documented, and as it used to work
Additional info:
See details in ubuntu bug:
This code has been like this pretty much forever (2005 the text param. was added), I can see how you might be confused if you just looked at the documentation though. Alas. we can't just remove the param name from the call, as the API has other params:
def start(self, filename=None, url=None, basename=None,
size=None, now=None, text=None):
...so our only sane option is to treat it as a documentation bug, and fix that. Sorry, if that doesn't help you much.
The documentation was fixed upstream.. | https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=702457 | CC-MAIN-2017-30 | refinedweb | 206 | 62.27 |
WP7 TimeSpanPicker in depthpublished on: 1/25/2011 | Views: N/A | Tags: C4FToolkit windows-phone
by WindowsPhoneGeek
In this article I am going to talk about the TimeSpanPicker control that comes with the official release of the Coding4fun Toolkit. TimeSpanPicker is an UI elements that will automatically provide you with a TextBox input and when the user selects it, the picker will display form where you can choose another date/time using infinite scrolling. Basically this control is extended DatePicker/TimePicker that allows timespan restriction.
NOTE:For more information about the toolkit visit our previous article: Coding4Fun Toolkit for WP7 Overview and Getting Started
NOTE:For more information about the DatePicker/TimePicker controls from the Silverlight for WP7 toolkit visit this article: WP7 DatePicker and TimePicker in depth | API and Customization
Getting Started
To begin using TimeSpanPicker first add a reference to the Coding4Fun.Phone.Controls.Toolkit.dll assembly. Just create a new folder in your project and add the assembly there, after that add it as a reference to your project.
NOTE: You have to download and rebuild the Coding4Fun Toolkit project in order to generate the assembly. You can get Coding4Fun.Phone.Controls.Toolkit.dll from the the following folder: \coding4fun-61253\Coding4Fun.Phone\Coding4Fun.Phone.Controls.Toolkit\Bin\Debug
the next step is to add the "controls" prefix declaration. Make sure that your page declaration includes the "controls" namespace:
xmlns:controls="clr-namespace:Coding4Fun.Phone.Controls.Toolkit;assembly=Coding4Fun.Phone.Controls.Toolkit"
The sample code should looks like:
<controls:TimeSpanPicker/>
NOTE: To see the correct ApplicationBar icons in the TimeSpanPicker , you will need to create a folder in the root of your project called "Toolkit.Content" and put the icons in there. The toolkit provides the necessary icons, but you have to copy them from the Coding4Fun.Phone.TestApplication project. They must be named "ApplicationBar.Cancel.png" and "ApplicationBar.Check.png", and the build action must be "Content"!
Key Properties and Events
(NOTE: The only difference between TimeSpanPicker public API and DatePicker/TimePicker public API are two properties: Max and Step. For more information about the public API in details please visit the WP7 DatePicker and TimePicker in depth | API and Customization.)
Properties
- Header
- HeaderTemplate
- PickerPageUri
- Value
- ValueString
- ValueStringFormat
- Max
Max is a dependency property of type TimeSpan. It determines the max value of the TimeSpanPicker . If no value is set then there is no maximum and the TimeSpanPicker loops through its items in the following way:
From 0 to 59 for the seconds
From 0 to 59 for the minutes
From 0 to 23 for the hours
- Step
Step is a dependency property of type TimeSpan. It determines the looping step between the items in a TimeSpanPicker control, The default value is 1.
Events
- ValueChanged
Event that is invoked when the Value property changes.
Sample Usage
Example1:
<controls:TimeSpanPicker
Example2:
TimeSpanPicker timespanPicker = new TimeSpanPicker(); timespanPicker.Max = new TimeSpan(0, 0, 6); timespanPicker.Step = new TimeSpan(0, 0, 2);
Example3:
<controls:TimeSpanPicker
public MainPage() { InitializeComponent(); DataContext = this; } public TimeSpan TimeSpan6Sec { get { return TimeSpan.FromSeconds(6); } } public TimeSpan TimeSpan2Sec { get { return TimeSpan.FromSeconds(2); } }
This means that the TimeSpanPicker is restricted between 0 seconds and 6 seconds and the looping step is 2 seconds. So the final result is the following sequence 0 - 2 - 4- 6.
Styling and Customization
Unfortunately for now you can customize only the TextBox field of the TimeSpanPicker control. If you want to customize the Full Screen popup then you will have to implement your CustomPicker page and add the looping logic on your own.
Changing the TimeSpanPicker Style
You can customize the TimeSpanPicker TextBox style either by adding some elements in the ControlTemplate of simply by changing some colors like for example:
<Style x: <Setter Property="Background" Value="Black"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="Foreground" Value="YellowGreen"/> </Style>
<controls:TimeSpanPicker
Cuztomizing the Full Screen Mode
You will have to create a Custom Picker page and ass the looping logic on your own. For more information take a look at the WP7 DatePicker and TimePicker in depth | API and Customization article. You can also take a look at another interesting custom implementation by Richard Griffin: WP7 Contrib - Customising the DateTime Picker
That was all about the TimeSpanPicker control from the Coding4fun Toolkit in details. I hope that the article was helpful.
You can find the full source code here:
You can also follow us on Twitter: @winphonegeek for Windows Phone; @winrtgeek for Windows 8 / WinRT
TimeSpanControl is great
posted by: Thimoty on 1/25/2011 5:15:38 PM
Thank you again guys! Glad to see these new controls and your in depth articles. Actually I asked a question a few weeks ago about how to implement a TimeSpan control and now after I read this post the fog begin to clear :) Looking forward to read the rest of the in depth articles.
Cheers!
Thanks a ton guys
posted by: Ramesh on 1/31/2011 9:41:36 PM
Thanks a lot guys for sharing these great articles all time.
I would like to thanks to you all. - As we are getting lot of information on this site. Regularly & keeping us up to date. I have completed my one app successfully.
In my next app I am stuck on calender control they want customize calender in that events / appointments has to set like in phone. Guys can you please help me how to proceeds on same? And if is there any default control {Which can open full calender} then how can we get that?
I would really appreciate.
Thanks!!! Waiting for next great article :)
RE:@Ramesh, Calendar control
posted by: winphonegeek on 2/1/2011 9:35:34 AM
You can use this Calendar Control:
It is a pretty cool free (open source) control.
Hope that this will help you.
Calender Control
posted by: @winphonegeek on 2/1/2011 12:07:54 PM
Thanks a lot, I will try to use it & get back to you with it's experience.
But WP7 default calender & event handling things is pretty cool, My client is asking for those.
Many Thanks.
@winphonegeek, Calender Control
posted by: Ramesh on 2/4/2011 12:35:55 PM
Thanks a lot for giving the great & correct information.
It's working very nicely.
Can you please share some more information about local storage on WP7. In my previous app I was working with Isolated Storage that works great. Now in this app we need to store the events for particular date & that needs to load on selected date, So while using Isolated Storage, application is not opening into phone if lot of events in xml file. Please help me if any other DB is supporting on WP7 like - ".SDL" etc... Where I can maintain the mapping between the objects as in iPhone - 'SQLite' is supporting.
I would really appreciate for your valuable answer :)
Regards
Ramesh
RE:local storage
posted by: winphonegeek on 2/7/2011 7:37:13 PM
Thank you for your suggestion.
We will consider writing such article as soon as possible!
@winphonegeek
posted by: Ramesh Kumar on 2/14/2011 4:51:27 PM
Thanks for your expert comment!
eagerly waiting for same -:)
Thanks!
Ramesh Kumar | http://www.geekchamp.com/articles/wp7-timespanpicker-in-depth | CC-MAIN-2014-52 | refinedweb | 1,200 | 53.41 |
Until just now I didn't really get Microformats. The following section from their website is what made me understand it:
What are microformats?This is what made me realize that Microformats are implemented using existing XHTML or HTML elements. That way they are something that can always be viewed by humans (since they're implemented using existing HTML elements) but can also be parsed by software (like web crawlers) to extract semantic knowledge.
Designed for humans first and machines second, microformats are a set of simple, open data formats built upon existing and widely adopted standards.
I used to think Microformats were simply a new name for things like:
- XML Namespace based extensions. (Like RSS modules.)
- Attribute based extensions. (Like Atom link extension mechanism.)
In some cases I think Microformats work great. Things like rel-license and rel-tag are examples of great Microformats. However, I see problems with some. (Although maybe I'm missing something.) For example things like the hCalendar and hCard Microformats are identified by the class attribute. That seems to like a bad idea to me. Here's an example hCard:
<div class="vcard"> <a class="url" href=""> <span class="n" style="display:none"> <!-- hide this from display with CSS --> <span class="family-name">Krempeaux</span> <span class="given-name">Charles Iliya</span> </span> <span class="fn">Charles Iliya Krempeaux</span> </a> </div>
You can't force people not to use your magic class name. It's common practice to apply the class attribute everything to apply CSS styles to them. And this may confuse we crawlers and any other type of software trying to obtain semantic knowledge.
Instead of using the class attribute I think what I'd do is bring in a new attribute through a new namespace. (Although that will only work for XHTML and not HTML.) For example:
<html xmlns:
...
<div vcard: <a vcard: <span vcard: <!-- hide this from display with CSS --> <span vcard:Krempeaux</span> <span vcard:Charles Iliya</span> </span> <span vcard:Charles Iliya Krempeaux</span> </a> </div>
Also, this nice thing about this is that if you follow the normal RSS Module style of doing things, the URL for the XML Namespace will point to a document that details the extension.
But, strictly speaking, that wouldn't really work with HTML. (Although I wonder if it would break web browsers to use it anyways.) | http://www.advogato.org/person/tnt/diary/38.html | CC-MAIN-2015-40 | refinedweb | 396 | 65.73 |
Author: Aaron Watters
I created a Notebook that describes how to examine, illustrate, and solve a geometric mathematical problem called "House Location" using Python mathematical and numeric libraries. The discussion uses symbolic computation, visualization, and numerical computations to solve the problem while exercising the NumPy, SymPy, Matplotlib, IPython and SciPy packages.
I hope that this discussion will be accessible to people with a minimal background in programming and a high-school level background in algebra and analytic geometry. There is a brief mention of complex numbers, but the use of complex numbers is not important here except as "values to be ignored". I also hope that this discussion illustrates how to combine different mathematically oriented Python libraries and explains how to smooth out some of the rough edges between the library interfaces.
The House Location Problem is taken from the HackerRank.com programming challenges and is described here:. The input to the problem are the coordinates of Kimberly, Bob, Jack, and Janet's houses and two ratios 'a' and 'b'. The goal of the problem is to find a location (x,y) where
The distance to Kimberly's house = 'a' times the distance to Bob's house
AND
The distance to Janet's house = 'b' times the distance to Jack's house.
The problem statement also provides one example input set with the expected output for those inputs. Let's express the example as code. Here are the inputs and the expected output for the example provided
# coordinates of Kimberly's house (xk,yk) = (4,0) # coordinates of Bob's house (xb,yb) = (0,0) # coordinates of Jack's house (xj,yj) = (-2,-4) # coordinates of Janet's house (xn,yn) = (-2,-1) # the ratios (a,b) = (3,4) # expected solution (xsoln,ysoln) = (-2,0)
Let's check that the solution actually solves the problem by calculating the distances between the solution point and the house locations. I will define the distance between points using the squared distance as an intermediate value because the squared distance function will be useful later.
def dist2(x0,y0,x1,y1): "distance between (x0,y0) and (x1,y1) squared" return (x0-x1)**2 + (y0-y1)**2 # use the numpy sqrt function, because it is the most general import numpy as np def distance(x0,y0,x1,y1): "distance between (x0,y0) and (x1,y1)" return np.sqrt(dist2(x0,y0,x1,y1)) BobDist = distance(xsoln, ysoln, xb,yb) KimDist = distance(xsoln, ysoln, xk,yk) print "comparing Bob and Kim", (BobDist, KimDist), "equal?", (BobDist*a, KimDist)
comparing Bob and Kim (2.0, 6.0) equal? (6.0, 6.0)
So the distance to Bob and Kim satisfy the requested relationship.
JackDist = distance(xsoln, ysoln, xj, yj) JanetDist = distance(xsoln, ysoln, xn, yn) print "comparing Jack and Janet", (JackDist, JanetDist), "equal?", (JanetDist*b, JackDist)
comparing Jack and Janet (4.0, 1.0) equal? (4.0, 4.0)
... and the example solution checks out.
Can we draw a diagram that illustrates the House Location Problem? How can we compute a solution location (xsoln,ysoln) from the input locations?
Evidently we need to find the set of points where JanetDist $\times$ b == JackDist and intersect that set with the set of points where BobDist $\times$ a == KimDist: the points in the intersection will solve the problem. How can we represent those sets?
It turns out that we can represent each set as the set of pairs (x,y) that satisfy an algebraic equation. The symbolic mathematics library sympy can make creating and manipulating these equations easy. The following code creates an "equation object" representing the set of points where JackDist=JanetDist*b.
import sympy as s # Let x and y represent variable symbolic values. x,y = s.symbols("x y") # define symbolic expression objects for the squares of distances to Janet and Jacks house. JackDist2 = dist2(x, y, xj, yj) JanetDist2 = dist2(x, y, xn, yn) print "JackDist2:", JackDist2 print "JanetDist2:", JanetDist2 # Relate the squared distances in an equation (square b because the distances are squared). # JackDist2 == JanetDist2 * b**2 Jack_Janet_shape = s.Eq( JackDist2, JanetDist2 * b**2 ) # Eq creates an equation object print "Equation:", Jack_Janet_shape
JackDist2: (x + 2)**2 + (y + 4)**2 JanetDist2: (x + 2)**2 + (y + 1)**2 Equation: (x + 2)**2 + (y + 4)**2 == 16*(x + 2)**2 + 16*(y + 1)**2
For people not used to symbolic computing these steps may be a little mind blowing. The above steps created symbolic expression objects JackDist2 and JanetDist2 which can be manipulated in Python much like numbers or arrays, and then created an equation object for expressing a relationship between the expressions. We avoid the need for square roots in the equation by using squared distances.
The text representation for Jack_Janet_shape is a little hard to read. Let's use a trick to put it into more standard mathematical notation.
from IPython.display import display, Math def showsym(expression): display(Math( s.latex(expression) ) ) # format the Jack_Janet_shape equation object using standard LaTeX conventions. showsym(Jack_Janet_shape)
Sadly, by itself the Jack_Janet_shape equation does not really help me understand much about the set of
points the right distance from Jack and Janet's house.
I would really like to know what the set of points looks like on the XY plane. How can we plot the points?
The sympy module has an automatic plot function, but I was not able to figure out how to get it to display visualizations the way I wanted (probably due to my ignorance), so I'll plot it myself.
First note that we can solve for x in terms of y in the Jack_Janet_shape equation using the sympy.solve function. This works well because the Jack_Janet_shape equation is not too complex. [In general the sympy.solve function may not work or may give horribly complex results for more difficult equations.] Below we use the sympy.solve function to solve the Jack_Janet_shape equation for y.
ysolutions = s.solve(Jack_Janet_shape, y) ysolutions
[-sqrt(-25*x**2 - 100*x - 84)/5 - 4/5, sqrt(-25*x**2 - 100*x - 84)/5 - 4/5]
# Format the solutions using more conventional mathematical notation for soln in ysolutions: showsym(soln)
Here we have 2 solutions that express y in terms of x and we would like to use these expressions to plot the (x,y) points that satisfy the Jack_Janet_shape equation.
However, the symbolic solutions as shown are not suitable for actually computing y values from x values because they are symbolic expressions and not numerical functions. The sympy.lambdify function will convert a symbolic expression to a numerical function, but you have to be a bit careful with it as we will see. In particular this first attempt below doesn't work well:
# let's convert the first solution into a numeric function of x ysoln0 = ysolutions[0] yfunction0 = s.lambdify(x, ysoln0)
# let's try out the yfunction0 on some values yfunction0(-1.5)
-1.4244997998398399
yfunction0(0)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-10-f440f216a2c3> in <module>() ----> 1 yfunction0(0) /Users/awatters/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/numpy/__init__.pyc in <lambda>(x) ValueError: math domain error
# Uh oh. Looks like the computation above tried to find the square root of a negative number. # You can't do that for real numbers. Maybe it will work for a complex number input? yfunction0(complex(0))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-11-9e19acfcdf76> in <module>() 1 # Uh oh. Looks like the computation above tried to find the square root of a negative number. 2 # You can't do that for real numbers. Maybe it will work for a complex number input? ----> 3 yfunction0(complex(0)) /Users/awatters/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/numpy/__init__.pyc in <lambda>(x) TypeError: can't convert complex to float
As shown above the yfunction0 function is not defined at all values and will not work for complex numbers even though the algebraic expression ysoln0 is well defined for all complex numbers. The underlying problem is that lambdify used the standard math.sqrt function in the definition of yfunction0 and math.sqrt will not operate on complex numbers and will generate an error for negative numbers.
To make things easy it is best to use a function which is defined everywhere even though we are not interested in function values that are not real numbers.
We can create a different function that will work for negative arguments, complex number arguments and even array arguments too if we direct lambdify to use the numpy implementation of sqrt as follows:
yfunction0 = s.lambdify(x, ysoln0, modules="numpy") # by using numpy.sqrt we have a yfunction0 that is defined for all reals (and all complexes) yfunction0( complex(0) )
(-0.80000000000000004-1.8330302779823358j)
Now that we have a well behaved function we can plot it as follows:
# Let's guess that some x values between -8 and 8 map to # interesting y values. Let's try 2000 of them. x_range = np.linspace(-8.0, 8.0, 2000) # Convert the x_range array to complex numbers (with 0 imaginary part) # so that roots of negative numbers work. x_range_complex = np.array(x_range, dtype=np.complex) # Compute the y values for the range all at once (array application) y_values = yfunction0( x_range_complex ) # We only want to plot points for y_values which are "real" # -- that is, have imaginary part of 0. # The following finds the indices of y_values where the # imaginary part is 0. real_indices = np.where( np.imag(y_values)==0 ) # Find the "real" y values. real_y = np.real( y_values[ real_indices ] ) # Find the x values that correspond to the "real" y values. real_x = x_range[ real_indices ] # Plot the (x,y) pairs using matplotlib from matplotlib.pyplot import plot, text, axes, show plot(real_x, real_y) # For illustration also show where Jack and Janet's houses are by marking them J and N text(xj,yj, "J") text(xn,yn, "N") # put a reference line between the J and the N plot([xj, xn], [yj, yn]) # Tell matplotlib to keep the axes equal (don't distort them to fit) axes().set_aspect("equal", "datalim") # show the result show()
Of course this plot only shows half of the (x,y) pairs which satisfy the equation Jack_Janet_shape because there was another way to solve for y.
But at this point we have the tools to build an illustration for the whole problem.
The following functions automate the process we used to plot equation solutions.
def xplot(x, xexpr, xrng): a = np.array(xrng, np.complex) f = s.lambdify(x, xexpr, modules="numpy") fa = f(a) realrng = np.where(np.imag(fa)==0) realx = xrng[realrng] realy = np.real( fa[realrng] ) return (realx, realy) def plot_x_solutions(x, y, equality, xrng): solns = s.solve(equality, y) for soln in solns: #print "plot", soln (xx,yy) = xplot(x, soln, xrng) plot(xx,yy)
We can create an equation for the points that are the right distance from Kim and Bob's house just like we did for Jack and Janet.
# define symbolic expression objects for the squares of distances to Kim and Bob's house. KimDist2 = dist2(x, y, xk, yk) BobDist2 = dist2(x, y, xb, yb) print "KimDist2:", KimDist2 print "BobDist2:", BobDist2 # Relate the squared distances in an equation (square 'a' because the distances are squared). # KimDist2 == BobDist2 * a**2 Kim_Bob_shape = s.Eq( KimDist2, BobDist2 * a**2 ) # Eq creates an equation object showsym(Kim_Bob_shape)
KimDist2: y**2 + (x - 4)**2 BobDist2: x**2 + y**2
The following generates a diagram illustrating the House location problem for the example inputs.
plot_x_solutions(x,y, Kim_Bob_shape, x_range) plot_x_solutions(x,y, Jack_Janet_shape, x_range) # mark the input points and put lines between them plot([xk,xb], [yk,yb]) text(xk,yk, "K") text(xb,yb, "B") plot([xj,xn], [yj,yn]) text(xj,yj, "J") text(xn,yn, "N") axes().set_aspect("equal", "datalim") show()
It looks like the House Location problem is looking for the intersection of two ellipses. In fact the ellipses look like they might be circles. Are they?
Also note that one of the intersections is at the solution offered for the example (x,y) = (-2, -1).
Now that we have equations for the two shapes, we can solve for the intersection points by simply letting the sympy solver magically do all the work for us.
s.solve( [Kim_Bob_shape, Jack_Janet_shape], x, y)
[(-2, 0), (-386/289, -360/289)]
Using sympy.solve works and it will work for any other set of input parameters, but it's a little disappointing because the black box solver doesn't give us any additional insight into the problem. It's also disappointing because this solution cannot be used to solve the HackerRank challenge since the HackerRank Python instances do not include the sympy package.
I will leave the reader to find a solution that is acceptible to HackerRank.
The Enthought Canopy environment automatically includes all software used in this example. Get the free version of Canopy from Enthought here:.
As mentioned above, the official statement of the House Location problem is here:.
The official documentation for sympy is here:.
The scipy and numpy documentation is here:. | http://nbviewer.jupyter.org/github/awatters/CanopyDemoArchive/blob/master/misc/house_locations.ipynb | CC-MAIN-2018-13 | refinedweb | 2,182 | 53.31 |
Per p0734r0.
The condition
S->isTemplateParamScope()
fails in this case
template<concept T> concept D1 = true; // expected-error {{expected template parameter}}
ParseTemplateDeclarationOrSpecialization calls ParseTemplateParameters which eventually calls ParseNonTypeTemplateParameter. ParseNonTypeTemplateParameter prints the diag and fails but does not cause ParseTemplateParameters to fail (I'm not sure why). ParseTemplateDeclarationOrSpecialization proceeds to parse the concept definition, and we get this
/home/changyu/test.cpp:1:10: error: expected template parameter
template<concept T> concept D1 = true; // expected-error {{expected template parameter}}
^
clang: /home/changyu/git/llvm/tools/clang/lib/Sema/SemaTemplate.cpp:7747: clang::Decl* clang::Sema::ActOnConceptDefinition(clang::Scope*, clang::MultiTemplateParamsArg, clang::IdentifierInfo*, clang::SourceLocation, clang::Expr*): Assertion `S->isTemplateParamScope() && "Not in template param scope?"' failed.
What should we do?
I think this occurs because our template parameter list is incorrectly perceived as empty - i.e. once the error occurs - to continue processing errors clang assumes this case is an explicit-specialization and replaces the template parameter scope with the outer scope. I think the thing to do here - which might also address the case where folks actually write 'template<> concept' is to actually check if template-parameter-list is empty - and emit a diagnostic about concepts can not be explicit specializations or some such ...
On a somewhat related note - i think the logic for signaling, handling and propagating failures of parsing the template parameter list might be a little broken (fixing which, might avoid triggering the assertion in template<concept> but not template<>). I might submit a patch to fix that error handling-issue separately - but either way I think we should handle the explicit-specialization error?
Thoughts?
I removed it here since Saar fixed it in his patch.
I think this looks good enough to commit - do you have commit privileges - or do you need one of us to commit it for you?
thank you!
I don't have commit privilege. And also there's one more problem we might want to address first.
Thank you.
There's one problem here.
I added this if in attempt to catch the following case (but it's wrong)
template<> concept D1 = true; // expected-error {{expected template parameter}}
The problem is I'm not sure how to differentiate between the above situation and the following
template<concept T> concept D1 = true; // expected-error {{expected template parameter}}
Both have an empty template parameter list. The latter case has diagnostic printed by ParseNonTypeTemplateParameter while the former has not (so we try to catch it here).
I was thinking that we would just emit a (redundant in the case of a bad template parameter) message in Sema if the template-parameters are empty that explicit specializations are not allowed here. while it would be a little misleading in the invalid template parameter case - to fix this robustly would require some fine-tuning and correcting some of the handshaking/error-propagation between the parsing of the template parameters and the code that calls it, I think. I would vote for not holding up this patch for that, unless you feel strongly you'd like to fix that behavior - then we can try and work on that first?
I moved some template param checks from Parser::ParseTemplateDeclarationOrSpecialization to Parser::ParseConceptDefinition and Sema::ActOnConceptDefinition.
Sure, let's fix that in another patch. I added a note for this in cxx2a-concept-declaration.cpp.
Perhaps add a LangOpts.ConceptsTS check here?
We could accept 'bool' here to be nice to people coming in from the old Concepts TS version of these decls - and emit a proper warning. ...
This comment isn't appropriate. Please just describe what the node is. (And note that a definition is a kind of declaration, despite common parlance.)
Please remove this again. ASTDeclReader should set the ConstraintExpr field directly. The AST is intended to be immutable after creation, so should generally not have setters.
There's a bigger problem here:
TemplateDecl *TD = /*some ConceptDecl*/;
auto SR = TD->getSourceRange(); // crash
TemplateDecl has a hard assumption that it contains a TemplatedDecl. So, three options:
I think option 2 is my preference, but option 3 is also somewhat appealing (there are other ways in which a concept is not a template: for instance, it cannot be constrained, and it cannot be classified as either a type template or a non-type template, because its kind depends on the context in which it appears).
Of course, this leads to one of the Hard Problems Of Computer Science: naming things. ConceptDecl for a concept-definition and ConceptTemplateDecl for the template-head concept-definition would be consistent with the rest of the AST. It's a little unfortunate for the longer name to be the AST node that we actually interact with, but the consistency is probably worth the cost.
Hmm, concepts don't really have specializations, though, do they? (Much like alias templates.) And because they're substituted incrementally, and the result of evaluation can vary at different points in the same translation unit, it's not obvious how much we can actually cache.
I suppose I'll see this was handled in later patches in the series :)
I would expect something more general here. For an alias-declaration, we say:
"error: name defined in alias declaration must be an identifier"
This is then also appropriate for other kinds of invalid concept-names such as
template<typename T> concept operator int = true;
"must be 'bool'" doesn't make sense. Maybe "constraint expression must be of type 'bool' but is of type %0" or similar?
Do not use "may not" in this context; it's ambiguous (this could be read as "I'm not sure if this concept has associated constraints"). Use "cannot" instead.
(And generally prefer "can" over "may" or "must" in diagnostics.)
Please make this a bit less informal and a little more informative. Perhaps "sorry, unimplemented concepts feature used". For a temporary "under construction" error, it's also OK to include a %0 and pass in a string describing the feature if you like.
maybe not -> cannot
Note this comment. You need to track down the diagnostics that use this enum and update their %selects to cover the new name kind.
This comment just repeats what the comment before it already says: please remove it again.
No need. If you see a kw_concept keyword, you have the language feature enabled.
Please also check for a < after the identifier, and diagnose the attempt to form a concept partial / explicit specialization. (I'm fine with leaving that to a later patch if you prefer.)
One option would be to call ParseUnqualifiedId and then diagnose anything that's not a simple identifier. (See ParseAliasDeclarationAfterDeclarator for how we do this for alias declarations.)
Use tok::equal here, not a string literal.
This diagnostic doesn't take an argument.
This needs rebasing onto SVN trunk. (We have lambda'fied the dependent arguments check there.)
You need to check CurContext->getRedeclContext(). A concept can be defined in a LinkageSpecDecl (with C++ linkage) or an ExportDecl, for instance.
ConceptDecl::Create cannot return null. Checking this doesn't make sense, because (a) this is dead code, and (b) if this happened, you would return null without issuing a diagnostic.
The dummy decl is pretty confusing and will be a very weird decl in and of itself. I can't think of a good name right now, but your proposed naming will be pretty confusing given that a ConceptTemplateDecl does not template a concept declaration given the meaning of the phrase in the standard... Maybe ConceptBodyDecl? ConceptDummyDecl? ConceptDefinitionDecl? We need something that screams "this is not interesting" for the AST usage to be reasonable.
Option 3 feels like loads of code duplication.
I'm not entirely sure how many blind (through TemplateDecl) uses of getTemplatedDecl there are, but there might not be that many, in which case the first option might be the lesser of all these evils.
Address most of rsmith's CR comments, rebase onto trunk
Only the TemplatedDecl issue remains, all other comments have been addressed and we're rebased onto master.
@rsmith please reply to the last comment, and lets finally start merging these :)
Thanks!
Please revert the (presumably unintended) mode changes to the ptxas executables.
This should also derive from Mergeable<ConceptDecl>, since we are permitted to merge multiple definitions of the same concept across translation units by C++20 [basic.def.odr]/12.
Faisal's comment is marked "Done" but not done.
ConceptBodyDecl or something like it seems reasonable. But I think we can consider that after landing this patch, and leave the templated declaration null for now.
Generally we don't leave blank lines between diagnostic definitions, and instead use the continuation indent to visually separate them.
The phrasing of this (particularly the "if any") is a little confusing. I think it's fine to just use the err_concept_definition_not_identifier diagnostic for this case.
I'd probably phrase this as
"ISO C++2a does not permit the 'bool' keyword after 'concept'"
(The Concepts TS isn't really the past -- TSes are more like an alternative reality -- so "no longer" is a bit odd.) I'd also be tempted to turn this into an ExtWarn so that we can accept code targeting the Concepts TS with a warning.
Drop the ", did you attempt this?". It doesn't add anything to the diagnostic, and might be read as a little snarky, frustrating the user.
This needs rebasing; I believe the right place for this is now split between TextNodeDumper.cpp and ASTNodeTraverser.h.
This looks wrong: we'll only print the template parameters, and not the concept <name> = <expr>; part. Please add another else if for the ConceptDecl case (or similar).
This change looks redundant. Note that VisitTemplateDecl below already returned true if getTemplatedDecl() is null.
There's no 'export'[opt] in template-head.
Consider calling DiagnoseAndSkipCXX11Attributes before and after parsing the name of the concept; it seems likely that people will try adding attributes there, and we should give a good diagnostic for this until they start being permitted in one of those two locations.
This should be PushOnScopeChains(NewDecl, S); instead (though I think in practice it won't matter until/unless we start supporting block-scope concept definitions).
No need for a return here; the code after an llvm_unreachable is unreachable =)
Call mergeMergeable(D) at the end of this.
Address CR comments by rsmith
@rsmith are we done with CR on this?
LGTM with a few mechanical updates.
ExtWarn diagnostics should be named ext_ not err_. (This is important because readers of the code emitting the diagnostic need to know whether they can mark things as invalid (etc) during error recovery -- which is only correct to do after emitting an error.)
Nit: please wrap the first parameter onto the next line.
Yes, you need that :)
(You should be able to check this with -ast-dump: for a concept in a namespace, its template parameters should have the namespace as their semantic DeclContext, not the translation unit. This also has some impact on merging of default argument visibility with modules.)
Please revert the addition of the unused first parameter.
Awesome! I do not have commit permissions though, so can you do the actual commit?
@rsmith?
Final committed diff. | https://reviews.llvm.org/D40381 | CC-MAIN-2020-45 | refinedweb | 1,866 | 54.52 |
is‘try...except‘try...finally‘ statement and the ‘with‘.) Its truth value is true.
See Implementing the arithmetic operations for more details.
This type has a single value. There is a single object with this value. This object is accessed through the literal ... or the built-in name Ellipsis. Its truth value is true.:
These represent elements from the mathematical set of integers (positive and negative).
There are two types of.
These represent the truth values False and True. The two objects representing the values False and True are.
These represent complex numbers as a pair of machine-level double precision floating point numbers. The same caveats apply as for floating point numbers. The real and imaginary parts of a complex number z can be retrieved through the read-only attributes z.real and z.imag. and i <= x < j.
Sequences are distinguished according to their mutability::
A string is a sequence of values that represent Unicode code points. All the code points in the range U+0000 - U+10FFFF can to the corresponding length 1 string object. str.encode() can be used to convert a str to bytes using the given text encoding, and bytes.decode() can be used to achieve the opposite.., as does the collections module..
These represent finite sets of objects indexed by arbitrary index sets. The subscript notation a[k] selects the item indexed by k from the mapping a; this can be used in expressions and as the target of assignments or del statements. The built-in function len() returns the number of items in a mapping.
There is currently a single intrinsic mapping type: and 1.0) then they can be used interchangeably to index the same dictionary entry.
Dictionaries are mutable; they can be created by the {...} notation (see section Dictionary displays).
The extension modules dbm.ndbm and dbm.gnu provide additional examples of mapping types, as does the collections module.
These are the types to which the function call operation (see section Calls) can be if a user-defined method object is created by retrieving another method object from a class or instance, the behaviour is the same as for a function object, except that the __func__ attribute of the new instance is not the original method object but its __func__ attribute. C is a class which contains a definition for a function f(), and x.
A function or method which uses the yield statement statement. When the function executes a return statement or falls off the end, a StopIteration exception is raised and the iterator will have reached the end of the set of values to be returned.
A built-in function object is a wrapper around a C function. Examples of built-in functions are len() and math.sin() (math is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes: __doc__ is the function’s documentation string, or None if unavailable; __name__ is the function’s name; __self__ is set to None (but see the next item); __module__ is the name of the module the function was defined in or None if unavailable..
Modules are a basic organizational unit of Python code, and are created by the import system as invoked either by the import statement (see import), if unavailable; __file__ is is the pathname of the shared library file.
Custom class types are typically created by class definitions (see section Class definitions). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x__ attributes and sys.stderr are initialized to file objects corresponding to the interpreter’s standard input, output and error streams; they are all open in text mode and therefore follow the interface defined by the io.TextIOBase abstract class.
A few types used internally by the interpreter are exposed to the user. Their definitions may change with future versions of the interpreter, but they are mentioned here for completeness. free variables;code offsets to line numbers (for details see the source code of the interpreter); co_stacksize is the required stack size (including local variables); co_flags is an integer encoding a number of flags for the interpreter.
The following flag bits are defined for co_flags: bit 0x04 is set if the function uses the *arguments syntax to accept an arbitrary number of positional arguments; bit 0x08 is set if the function uses the **keywords syntax to accept arbitrary keyword arguments; bit 0x20 is set if the function is a generator.
Future feature declarations (from __future__ import division) also use bits in co_flags to indicate whether a code object was compiled with a particular feature enabled: bit 0x2000 is set if the function was compiled with future division enabled; bits 0x10 and 0x1000 were used in earlier versions of Python.
Other bits in co_flags are reserved for internal use.
If a code object represents a function, the first item in co_consts is the documentation string of the function, or None if undefined.
Frame objects represent execution frames. They may occur in traceback objects (see below)._lasti gives the precise instruction (this is an index into the bytecode string of the code object).
Special writable attributes: f_trace, if not None, is a function called at the start of each source code line (this is used by the debugger); f_lineno is the current line number of the frame — writing to this from within a trace function jumps to the given line (only for the bottom-most frame). A debugger can implement a Jump command (aka Set Next Statement) by writing to f_lineno.
Frame objects support one method:
This method clears all references to local variables held by the frame. Also, if the frame belonged to a generator, the generator is finalized. This helps break reference cycles involving frame objects (for example when catching an exception and storing its traceback for later use).
RuntimeError is raised if the frame is currently executing.
New in version 3.4..
Slice objects are used to represent slices for __getitem__() methods. They are also created by the built-in slice() function.
Special read-only attributes: start is the lower bound; stop is the upper bound; step is the step value; each is None if omitted. These attributes can have any type.
Slice objects support one method: value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime. doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x‘s_info()[2] second can be resolved by freeing the reference to the traceback object when it is no longer useful, and the third can be resolved by storing None in sys.last_traceback. Circular references which are garbage are detected and cleaned up when the cyclic garbage collector is enabled (it’s on by default). Refer to the documentation for the gc module for more information about this topic. calls object.__repr__().
Called by bytes() to compute a byte-string representation of an object. This should return a bytes object.
Called by the format() built-in function (and by extension, the str.format() method of class str).
These are the so-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: x<y calls x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y calls.().
Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict. __hash__() should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g. using exclusive or) the hash values for the components of the object that also play a part in comparison of objects. implies both that x is y and hash(x) == hash(y).
A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None. When the __hash__() method of a class is None, instances of the class will raise an appropriate TypeError when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking isinstance(obj, collections in the class definition. A class which defines its own __hash__() that explicitly raises a TypeError would be incorrectly identified as hashable by an isinstance(obj, collections.Hashable) call.
Note
By default,^2) complexity. See for details.
Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).
See also PYTHONHASHSEED.
Changed in version 3.3: Hash randomization is enabled by default..
The following methods can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of x.name) for class instances.).
Like __setattr__() but for attribute deletion instead of assignment. This should only be implemented if del obj.name is meaningful for the object.
Called when dir() is called on the object. A sequence must be returned. dir() converts the returned sequence to a list and sorts it.__...
By default, instances of classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.
The default can be overridden by defining __slots__ in a class definition. The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.
This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. __slots__ reserves space for the declared variables and prevents the automatic creation of __dict__ and __weakref__ for each instance.
By default, classes are constructed using type(). The class body is executed in a new namespace and the class name is bound locally to the result of type(name, bases, namespace).
The class creation process can be customised:
The appropriate metaclass for a class definition is determined as follows: initialised as an empty dict() instance., and cannot be accessed at all from static methods..
After the class object is created, it is passed to the class decorators included in the class definition (if any) and the resulting object is bound in the local namespace as the defined class.
The potential uses for metaclasses are boundless. Some ideas that have been explored include logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.
Here is an example of a metaclass that uses an collections.OrderedDict to remember the order that class variables are defined:
class OrderedClass(type): @classmethod def __prepare__(metacls, name, bases, **kwds): return collections.OrderedDict() def __new__(cls, name, bases, namespace, **kwds): result = type.__new__(cls, name, bases, dict(namespace)) result.members = tuple(namespace).
Called to implement operator.length_hint(). Should return an estimated length for the object (which may be greater or less than the actual length). The length must be an integer >= 0..
Called by dict.__getitem__() to implement self[key] for dict subclasses when key is not in the dictionary..
This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container.
Iterator objects also need to implement this method; they are required to return themselves. For more information on iterator objects, see Iterator Types. sequence. However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be a sequence..
The following methods can be defined to emulate numeric objects. Methods corresponding to operations that are not supported by the particular kind of number implemented (e.g., bitwise operations for non-integral numbers) should be left undefined..
Called to implement the unary arithmetic operations (-, +, abs() and ~).
Called to implement the built-in functions complex(), int(), float() and round(). Should return a value of the appropriate type..
Note
In order to have a coherent integer type class, when __index__() is defined __int__() should also be defined, and both should return the same value..
Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any. | https://docs.python.org/3/reference/datamodel.html | CC-MAIN-2015-18 | refinedweb | 2,098 | 57.37 |
Say you have a binary image file you wanted to transfer across a network. You’re amazed that the file wasn’t received properly on the other side—the file just contained strange characters!
Well, it seems that you attempted to send your file in its raw bits and bytes format, while the media used was designed for streaming text.
What would be the workaround to avoid such an issue? server, and many other applications.
What Is Base64?
Before moving more deeper in the article, let’s define what we mean by Base64.
Base64 is a way in which 8-bit binary data is encoded into a format that can be represented in 7 bits. This is done using only the characters
A-Z ,
a-z ,
0-9 ,
+ , and
/ in order to represent data, with
= used to pad data. For instance, using this encoding, three 8-bit bytes are converted into four 7-bit bytes.
The term Base64 is taken from the Multipurpose Internet Mail Extensions (MIME) standard, which is widely used for HTTP and XML, and was originally developed for encoding email attachments for transmission.
Why Do We Use Base64?
Base64 is very important for binary data representation, such that it allows binary data to be represented in a way that looks and acts as plain text, which makes it more reliable to be stored in databases, sent in emails, or used in text-based format such as XML. Base64 is basically used for representing data in an ASCII string format.
As mentioned in the introduction of this article, without Base64 sometimes data will not be readable at all.
Base64 Encoding
Base64 encoding is the process of converting binary data into a limited character set of 64 characters. As shown in the first section, those characters are
A-Z ,
a-z ,
0-9 ,
+ , and
/ (count them, did you notice they add up to 64?). This character set is considered the most common character set, and is referred to as MIME’s Base64. It uses
A-Z ,
a-z ,
0-9 ,
+ , and
/ for the first 62 values, and
+ , and
/ for the last two values.
The Base64 encoded data ends up being longer than the original data, so that as mentioned above, for every 3 bytes of binary data, there are at least 4 bytes of Base64 encoded data. This is due to the fact that we are squeezing the data into a smaller set of characters.
Have you ever seen part of a raw email file like the one shown below (which most likely originates from an email not being delivered)? If so, then you have seen Base64 encoding in action! (If you notice “=”, you can conclude that this is a Base64 encoding, since the equals sign is used in the encoding process for padding.) carried out in multiple steps, as follows:
- The text to be encoded in converted into its respective decimal values, that is, into their ASCII equivalent (i.e. a:97, b:98, etc.). Here’s the ASCII table .
- The decimal values obtained in the above.
- Finally, the decimal equivalents are converted into their Base64 values (i.e. 4: E). Here are the decimal values and their Base64 alphabet .
Base64 Decoding
Base64 decoding is the opposite of Base64 encoding. In other words, it is carried out by reversing the steps described in the previous section.
So, the steps of Base64 decoding can be described as follows:
-.
- Finally, the decimal values obtained are converted into their ASCII equivalent.
Encoding an Image
Let’s now get to the meat of this article. In this section, I’m going to show you how we can easily Base64 encode an image using Python.
I will be using the following binary image. Go ahead, download it and let’s get Python rolling! (I’m assuming that the name of the image is
deer.gif .)
The first thing we have to do in order to use Base64 in Python is to import the base64 module :
import base64
In order to encode the image, we simply use the function
base64.encodestring(s) . Python mentions the following regarding this function:
Encode the string s, which can contain arbitrary binary data, and return a string containing one or more lines of base64-encoded data. encodestring() returns a string containing one or more lines of base64-encoded data always including an extra trailing newline (‘/n’).
Thus, we can do the following in order to Base64 encode our image:
import base64 image = open('deer.gif', 'rb') #open binary file in read mode image_read = image.read() image_64_encode = base64.encodestring(image_read)
If you want to see the output of the encoding process, type the following:
print image_64_encode.
So, in order to decode the image we encoded in the previous section, we do the following:
base64.decodestring(image_64_encode)
Putting It All Together
Let’s put the program that Base64 encodes and decodes an image together. The Python script that does that should look something like the following:
import base64 image = open('deer.gif', 'rb') image_read = image.read() image_64_encode = base64.encodestring(image_read) image_64_decode = base64.decodestring(image_64_encode) image_result = open('deer_decode.gif', 'wb') # create a writable image and write the decoding result image_result.write(image_64_decode)
If you open
deer_decode.gif which you have on your desktop, you will notice that you have the original image
deer.gif we encoded in the first step.
As we have seen from this article, Python makes it very easy to perform what seems to be a complex » Base64 Encoding and Decoding Using Python
评论 抢沙发 | http://www.shellsec.com/news/4884.html | CC-MAIN-2018-05 | refinedweb | 917 | 64.81 |
30 June 2011 15:34 [Source: ICIS news]
LONDON (ICIS)--Shell expects to begin restarting its 2A olefins unit at ?xml:namespace>
Shell said it had been unable to restart the unit on 27 June as first planned because of “technical reasons”.
The restart is likely cause flaring on both Friday and Saturday, the company said.
Shell brought the unit down on 14 June for maintenance work.
It has two crackers at Wesseling: 2A, with a capacity of 260,000 tonnes/year of ethylene; and 2B, with an ethylene capacity of 240,000 tonnes/year, according to ICIS plants and projects.
Shell said last year that it plans to close 2B by the end of 2011 because the unit is no longer competitive. | http://www.icis.com/Articles/2011/06/30/9474125/shell-to-restart-wesseling-2a-cracker-on-friday-after-delay.html | CC-MAIN-2014-10 | refinedweb | 123 | 68.81 |
Gate adds OWIN support for the new ASP.NET Web API betaGate, internet, opensource, OWIN, programming, web, webapi February 20th, 2012
Hello again, everyone! As I’m sure you already know, ASP.NET MVC 4 beta is available and it has some fantastic stuff in it! One of the interesting bits is the latest ASP.NET Web API.
Looking at that, I’m absolutely certain you’re thinking the same thing Glenn Block was saying on Twitter:
@gblock: hmm I really wish there was an Owin adapter for #aspnetwebapi! /cc:@loudej
Wish no longer! Gate has a new drop available, version 0.3.4, and it contains a Get.Adapters.AspNetWebApi package which does exactly that – enabling you to mix the Web API into your OWIN based web applications.
Let’s take a look at how that feels. That should be even easier than before because of a few more things that are new in Gate – a handful of Quickstart nuget packages, and a Ghost “generic host” process which lets you use any of the available OWIN http servers interchangeably. Neat, right? Let’s jump right into that!
First – start with a new “ASP.NET Empty Web Application”
Then – to make it “really empty” – let’s remove a bunch of references. This step is optional, but should be very satisfying if you want to see some minimalism in action. Quickest way is to select the last assembly reference and lean on the “delete” key.
Finally let’s add the meta-package Gate.Quickstart.AspNetWebApi from Nuget.org.
PM> Install-Package Gate.Quickstart.AspNetWebApi Attempting to resolve dependency 'Gate.Quickstart.Core (≥ 0.3.4)'. Attempting to resolve dependency 'Gate.Hosts.AspNet (≥ 0.3.4)'. Attempting to resolve dependency 'Gate.Builder (≥ 0.3.4)'. Attempting to resolve dependency 'Owin (≥ 0.7.0)'. Attempting to resolve dependency 'Microsoft.Web.Infrastructure (≥ 1.0.0.0)'. Attempting to resolve dependency 'Gate.Middleware (≥ 0.3.4)'. Attempting to resolve dependency 'Gate (≥ 0.3.4)'. Attempting to resolve dependency 'Gate.Adapters.AspNetWebApi (≥ 0.3.4)'. Attempting to resolve dependency 'AspNetWebApi.Core (≥ 4.0.20126.16343)'. Attempting to resolve dependency 'System.Net.Http.Formatting (≥ 4.0.20126.16343)'. Attempting to resolve dependency 'System.Net.Http (≥ 2.0.20126.16343)'. Attempting to resolve dependency 'System.Web.Http.Common (≥ 4.0.20126.16343)'. Attempting to resolve dependency 'System.Json (≥ 4.0.20126.16343)'.
You can now press F5 and see this run. The quickstart adds an example Startup class -which is using a partial class trick because I wanted you to be able to add more then one demo to the same project. But that’s not really necessary – in your own projects a simpler Startup class like this would work exactly the same.
using System.Net; using System.Net.Http; using System.Web.Http; using Gate.Adapters.AspNetWebApi; using Owin; namespace HelloEverything { public class Startup { public void Configuration(IAppBuilder builder) { var config = new HttpConfiguration(new HttpRouteCollection("/")); config.Routes.MapHttpRoute( "Default", "{controller}", new {controller = "Main"}); builder .RunHttpServer(config); } public void Debug(IAppBuilder builder) { builder.UseShowExceptions(); Configuration(builder); } } public class MainController : ApiController { public HttpResponseMessage Get() { return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Hello, AspNetWebApi!") }; } } }
Next you should try adding the meta-meta-package Gate.Quickstart.All. Then you’ll be able to press F5 to see a demo of everything and the kitchen sink: Web API, Nancy, SignalR, Gate “test page”, and Direct output from code (res.Write style).
Direct output is kind of interesting, looks like this:
public class Startup { public void Configuration(IAppBuilder builder) { builder.RunDirect((req,res) => { res.ContentType = "text/plain"; res.Write("Hello, ").Write(req.PathBase).Write(req.Path).Write("!"); res.End(); }); } }
Well – that’s probably long enough for this post. Next topic – hopefully soon – will be about using the Ghost.exe “generic host” to run this web application on HttpListener, Kayak, or Firefly.
February 20th, 2012 at 1:57 pm
[...] This is using the OWIN web app we made in the last post. [...]
February 21st, 2012 at 8:38 am
[...] Gate adds OWIN support for the new ASP.NET Web API beta and Ghost.exe – a generic host for OWIN applications (Louis DeJardin) [...]
March 5th, 2012 at 6:53 am
[...] DeJardin created a host on top of [...]
August 22nd, 2012 at 9:44 pm
I simply could not leave your web site before suggesting that I extremely enjoyed the standard info a person provide to your visitors? Is gonna be again steadily to inspect new posts
September 4th, 2012 at 3:32 am
Good day! Just recently found a site on the Internet kamkam.rf . This is a site for singles, where video chat. Sort of liked the site : the design of a simple , not annoying. Even a pleasant one: check-in took only a few minutes. On this site is a sufficient number of registered – about one million . A video chat option is convenient – Roulette.That is, you come into the chat and your registered users are offered absolutely right.
But , to be honest , once I ‘m afraid to make friends while on this site. Maybe there are not real people .
People , share, maybe someone has already registered on this site? Maybe tell me what and how? Share experiences so to speak . Thank you all in advance for the information , I would appreciate any information – positive or not.
December 15th, 2012 at 5:39 am
People , share, maybe someone has already registered on this site? Maybe tell me what and how? Share experiences so to speak . Thank you all in advance for the information , I would appreciate any information – positive or not – ???
???
Now khow
January 27th, 2013 at 7:43 am?
July 22nd, 2013 at 9:32?
July 24th, 2013 at 12:37 pm
fantastic issues altogether, you just gained a emblem new reader.
What could you recommend in regards to your publish that you simply
made a few days in the past? Any certain?
August 26th, 2013 at 12:08 am
, thank you very much for posting this! It is going to help when I travel to the casino next time! Fabulous!
October 6th, 2013 at 11:19 pm
Pretty component to content. I just stumbled upon your website and in accession capital to claim that I acquire actually loved account your blog posts. Anyway I’ll be subscribing for your feeds and even I achievement you get entry to persistently fast.
November 2nd, 2013 at 9:19 pm
At a posh black-tie dinner in Maxim’s on the eve of last week’s 50th running of the Prix de l’ Arc de Triomphe at Longchamp, the Virginia sportsman and art collector,
ニューバランス メンズ スニーカー
February 13th, 2014 at 10:04 pm
Your style is very unique compared to other people I’ve read stuff from.
Many thanks for posting when you have the opportunity, Guess I will just bookmark
this page.
March 2nd, 2014 at 12:03 am
* Many states require you too have a license to work as a barber
or a cosmetologist. Let it set, then lightly dust the entire face with powder.
Online courses aand take-home materials in DVD or video formats are also available for students lokking for a
non-traditional education. | http://whereslou.com/2012/02/20/gate-adds-owin-support-for-the-new-asp-net-web-api-beta/comment-page-1 | CC-MAIN-2014-10 | refinedweb | 1,196 | 68.47 |
Most text editors support auto-folding import lines, and with this package, Atom does too!
Install this package and it will automatically start folding lines that begin with
import when you open any file.
If you don't want to automatically fold the imports when you open each editor, you can turn that setting off in this package's configs.
To toggle folding the imports, use the
Fold Imports: Toggle command or the default hotkey
ctrl-alt-i. You can disable this hotkey in the package configs and you can create your own hotkey in your
~/.atom/keymap.cson file.
In the future I hope to add
The way the folder currently works is by finding the first and last lines that begin with
import. It then folds in the range from the space after the first
import to the last character in the last line that begins with
import. This will fold any comments you have between those two lines. I'm not sure if this is a bug or a feature, but please raise an issue if this bothers you.
Contributions are appreciated! If you would like to contribute, please raise an issue first.
Good catch. Let us know what about this package looks wrong to you, and we'll investigate right away. | http://github-atom-io-herokuapp-com.global.ssl.fastly.net/packages/fold-imports | CC-MAIN-2021-39 | refinedweb | 215 | 70.94 |
Provided by: manpages-dev_4.04-2_all
NAME
umount, umount2 - unmount filesystem
SYNOPSIS
#include <sys/mount.h> int umount(const char *target); int umount2(const char *target, int flags);
DESCRIPTION
umount()
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
ERRORS available in glibc since version 2.11.
CONFORMING TO
These functions are Linux-specific and should not be used in programs intended to be portable.
NOTES
umount() and shared mount points Shared mount points cause any mount activity on a mount point, including umount(2) operations, to be forwarded to every shared mount point in the peer group and every slave mount of that peer group. This means that umount(2)(2) does not propagate in this fashion, the mount point may be remounted using a mount(2) call with a mount_flags argument that includes both MS_REC and MS_PRIVATE prior to umount(2) being called. Historical details 4.04 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | http://manpages.ubuntu.com/manpages/xenial/en/man2/umount2.2.html | CC-MAIN-2019-30 | refinedweb | 181 | 64.71 |
Is it the best code editor for Python and Data Science?
Are you struggling to find an optimal code editor for Python programming and data science? You’re not alone. There’s a ton of options to choose from — both free and paid — and today I’ll show you my favorite free one.
It’s Visual Studio Code — a completely free code editor from Microsoft. It’s by far the most flexible and feature-rich code editor I found. It even has more features than PyCharm Community, which is supposed to be a professional IDE. And don’t even get me started on Jupyter — it’s probably the best way to write notebooks, but notebooks alone aren’t enough for data professionals.
Today you’ll see my go-to approach for setting up VSCode for Python programming and data science. We’ll start with the installation and go through the plugins from there.
Don’t feel like reading? Watch my video instead:
Download and install Visual Studio Code
Head over to code.visualstudio.com to download VSCode. The webpage should detect your OS automatically, so you only need to hit the big blue download button:
On Mac, it will download a ZIP file which you can extract and drag the app to the Applications folder. On Windows, I assume you need to open the .EXE file and click on Next a couple of times, and for Linux, it’s probably either a Terminal command or a DEB file.
Here’s what you should see once you launch it:
You can create a Python file by opening any folder on your machine, right-clicking the left sidebar and selecting New file. I’ve created a folder on Desktop and a
main.py file in it:
By default, you won’t have the best debugging options, nor you’ll have IntelliSense. You also won’t be able to select a virtual environment. Fixing this is quick and easy. You only need to install a plugin. But let’s address something more urgent first.
Download a theme (optional)
The first thing I like to do in VSCode is to change the theme. It has nothing to do with Python and data science, so you can either skip this section or consider it as a bonus point.
The default theme is just too Microsofty for me. To change it, you can click on the Extension tab and search for themes. I particularly like the One Dark Pro theme, which is free, even though it says Pro:
Click on the theme and hit the Install button. The default skin is a bit too light for my liking. On Mac, you can press CMD+K CMD+T to open the theme dropdown. My favorite is One Dark Pro Darker:
Much nicer, isn’t it? Let’s address the extensions next.
Official Python extension
This one is a must-have if you want to work with Python. Go to the Extensions tab once again and search for Python. You should install the official extension from Microsoft:
You’ll now have a much easier time writing Python files. You can also choose a virtual environment now, which is something you’ll do daily. Click on the bottom left text that says Python 3.9.7 64 bit (at least on my machine) and select any environment you want:
Do you know what the best part is? You can immediately start working with Jupyter Notebooks! Create a
.ipynb file to verify — it might prompt you to install some additional dependencies, so just agree to everything.
Once installed, you can enter Python code to a cell to verify everything works:
And that’s it — you now have the basics installed, so you can work with Python either through scripts or through notebooks. Let’s add some additional functionality next.
Python docstring generator
One essential tip for writing good Python code is documentation. VSCode can help you with that. All you need to do is to install the Python Docstring Generator extension.
Let’s see how it works. You’ll write a dummy Python function that sums up two integers:
def add(a: int, b: int) -> int: return a + b
Write the function inside
main.py:
You can now add a docstring by writing three double quotes below the function declaration and selecting the Generate Docstring option:
It will immediately write the boilerplate for you:
All you’ll have to now is to edit the description and the role each parameter has:
That’s much easier than writing everything from scratch. Maybe you don’t see the benefit because we have only one function, but imagine you had multiple Python modules, each having dozens of functions — then this extension is a huge time saver.
Python linter
And finally, I want to discuss linting. You can enable linting in VSCode to automatically tell you if you’re not following Python conventions. It will tell you if you have unused imports, variables, or if there’s anything to improve in your code.
To start, open up the Command Palette (Settings — Command Palette… or press SHIFT + CMD + P) and type in Linter. Choose the Select Linter option:
PyLint is the most popular one, so just click on it:
It will ask you to install PyLint if it’s not installed already. You’ll have to repeat the process for every virtual environment, so keep that in mind:
Let’s now delete the
add() function and explore what PyLint has to offer. You’ll import
json and
random modules and print a random integer between 1 and 100:
import json import random print(random.randint(1, 100))
Here’s how it should look like:
You’ll see warning messages as soon as you save the file. The
The top import statement is underlined because we don’t have a file-level docstring on the top, so let’s write one quickly:
The warning won’t go away if you save the file. It now complains that you’ve imported
json but aren’t using it in the file:
The message will go away once you delete the unused import.
To summarize, linters can help you write better Python code and make sure you’re following all the conventions. Your code will still run if the linter gives you warning messages, but it’s annoying to look at them, so you’ll likely address them as they come.
And that’s it for today. My Python and data science setup in VSCode is somewhat simplistic, but it gets the job done.
What are your favorite VSCode extensions for Python and data science? Please let me know in the comment section below.
This article was republished from towardsdatascience.com | https://aster.cloud/2021/10/25/visual-studio-code-for-python-and-data-science-top-3-plugins-you-must-have/ | CC-MAIN-2021-49 | refinedweb | 1,122 | 72.16 |
The couchdb-python package comes with a view server to allow you to write views in Python instead of JavaScript. When couchdb-python is installed, it will install a script called couchpy that runs the view server. To enable this for your CouchDB server, add the following section to local.ini:
[query_servers] python=/usr/bin/couchpy
After restarting CouchDB, the Futon view editor should show python in the language pull-down menu. Here’s some sample view code to get you started:
def fun(doc): if doc['date']: yield doc['date'], doc
Note that the map function uses the Python yield keyword to emit values, where JavaScript views use an emit() function. | http://packages.python.org/CouchDB/views.html | crawl-003 | refinedweb | 112 | 76.35 |
From: Samuel Krempp (krempp_at_[hidden])
Date: 2002-01-21 13:37:33
On Mon, 2002-01-21 at 17:17, Jeremy Siek wrote:
> Hi Sam,
>
> Just a reminder: you don't need to make changes to your library until
> *after* the review period. Making changes based on each reviewer's
> comments, as they come in, leads to confusion as we've seen.
On the other hand, some points are raised almost every time, while the
fix is already planned.
Also, the MSVC6 compatibily problems prevents some potential reviewers
from compiling the code, so I'll upload an updated archive once I get
this point fixed
In the meantime I'll just send notices in this new thread about all the
fixes that are already planned (or even implemented on my local files),
and try to write summaries of the 'open issues', so reviewers don't
waste their time to repeat what has been said.
*** Planned fixes : ***
- better documentation.
- tabs replaced by spaces in the source files
- size_t used, should be std::size_t
(same for std::isdigit)
- calls to s.insert(0, ..) are ambiguous, fix is
either s.insert(s.begin(), ..)
or s.insert( string::size_type(0), ..)
- "%{1}11" now possible.
- format::exceptions( .. ) added to choose what errors will throw
exceptions
- samples programs were using assert to show the results inside the
code. this is better achieved with comments // prints "that" ..
- non homogneous coding style
mixing Capitalized names and underscores, (parse_Pdirective..)
and sometimes appending '_' to data members, sometimes not.
=> stick to the all_lower_case_with_underscores naming scheme,
and name all data members in all classes with a '_' suffix.
- MSVC6 comptibilty (based on rogeef's suggestions)
This includes :
- renaming .cc files to .cpp, and *.ihh to *_implementation.hpp
- cutting the code into smaller headers,
so that the primary header would merely do :
#include "boost/format/format_fwd.hpp"
#include "boost/format/format_internals.hpp"
#include "boost/format/format_class.hpp"
#include "boost/format/format_exceptions.hpp"
#include "boost/format/format_implementation.hpp"
#include "boost/format/format_funcs.hpp"
- moving many function template definitions in their declarations
- and more :-)
*** Open Issues : ***
- operator%, or (), or [].
- Provide or not a function-call interface
( format("%1 %2", x, y) )
see
and Tom Becker's messages
- how to pass manipulators.
use a dedicate operator, or a function and wrapper class ?
at least, I plan renaming the 'glue' function to 'manip'.
- document the undocumented advanced functions (the 'bind' family,
etc..) or drop them if it is found useless.
- const T& / T& versions of operator% are causing overload ambiguity
with MSVC6.
see rogeef's message
Drop the non-const, only for MSVC, or for any compiler ?
The case of manipulators is again delicate, since functions of type
typedef std::ios_base&(manip)(std::ios_base&);
can not be passed by const-reference..
-- Samuel
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2002/01/23322.php | CC-MAIN-2021-17 | refinedweb | 478 | 50.94 |
I have a provider which uses another provider, and I am getting this error when viewing the app through ionic serve:
Encountered undefined provider! Usually this means you have a circular dependencies (might be caused by using ‘barrel’ index.ts files
I have read that it can be fixed using forwardref, but the examples seem very different to what I am trying to do.
Does forwardref need to go in app.module.ts somewhere?
Thanks.
My personal opinion is: most of the time, if you need to use forwardRef, you designed something incorrectly. Circular dependencies can cause bugs that are extremely hard to track, even with a time traveler. How would you diagram your injections? If it’s A -> B -> A, then you might want to rethink.
Hi thanks for the reply, no it’s just A->B. The page imports provider A, and provider A imports provider B. Am I right in thinking this is a normal implementation?
Yeah that’s perfectly fine.
How/where are you importing the providers as far as modules go?
I have declared/imported them at the top of app.module.ts, then added them into providers in ngModule. Then in the provider files and page files, imported them at the top and added into the constructors.
Are you following some tutorial that suggested this? It sounds wrong.
Ok, that is how I have seen it in every example online.
For example
I just found that from a quick search and it is exactly how all other examples I have seen have done it.
Not if you put it in app.module.ts also. You do one or the other. I think you’d be better off reading the official Ionic Github sample projects.
So those stack overflow answers are incorrect?
It is strange that it has been working for me with one provider, but started giving me the error when I added another.
It’s a common pattern IMO. The framework changes a lot, so a lot of half-answers time out after a few months. In this case, though, the issue is Angular, not Ionic. If you put a provider in a local module and also into app.module.ts, you break what Angular is expecting, and it defines the provider as both a global and a local provider, which will lead to bad behavior.
Crawl @mhartington’s repo if you want code samples that work. For example:
That example is exactly as mine and the SO examples. The SpotifyProvider is present in all the same places.
app.module.ts:
import { SpotifyProvider } from '../providers/spotify/spotify';
...
@NgModule({
...
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
SpotifyProvider
]
})
home.ts:
import { SpotifyProvider } from '../../providers/spotify/spotify'
...
export class HomePage {
...
constructor(
public navCtrl: NavController,
public fb: FormBuilder,
public spotify: SpotifyProvider
)
...
Then why did you say you put the provider into the page’s module also? That’s what I said was wrong.
I think they only said that they put the provider in the page’s constructor.
But if everything is done correctly, why is there an issue?
No I haven’t changed the page module files, the only difference to the above example is that I am trying to access one of my providers in another of my providers.
That is pretty much the reason for opening this thread, to answer that question.
I won’t respond again unless you post code. I’m done trying to decipher vague English.
Sure, I’ll post code. Sorry, I was trying to be as clear as possible, to be fair, you were the one that misinterpreted what I had said, SigmundFroyd understood me well enough. | https://forum.ionicframework.com/t/encountered-undefined-provider/108666 | CC-MAIN-2017-43 | refinedweb | 608 | 76.22 |
- 03 Dec 2015 14:31:54 UTC
- Distribution: File-Find-Rule
- Module version: 0.34
- Source (raw)
- Browse (raw)
- Changes
- How to Contribute
- Issues (16)
- Testers (14853 / 3 / 0)
- KwaliteeBus factor: 0
- 71.15% Coverage
- License: unknown
- Activity24 month
- Tools
- Download (15.79KB)
- MetaCPAN Explorer
- Permissions
- Permalinks
- This version
- Latest version++ed by:17 non-PAUSE users
- Dependencies
- File::Find
- File::Spec
- Number::Compare
- Test::More
- Text::Glob
- and possibly others
- Reverse dependencies
- CPAN Testers List
- Dependency graph
- NAME
- SYNOPSIS
- DESCRIPTION
- METHODS
- TWO FOR THE PRICE OF ONE
- EXPORTS
- TAINT MODE INTERACTION
- );
DESCRIPTION
File::Find::Rule is a friendlier interface to File::Find. It allows you to build rules which specify the desired files and directories.and
orare interchangeable.
# find avis, movs, things over 200M and empty files $rule->any( File::Find::Rule->name( '*.avi', '*.mov' ), File::Find::Rule->size( '>200M' ), File::Find::Rule->file->empty, );
none( @rules )
-
not( @rules )
Negates a rule. (The inverse of
any.)
noneand
notareas part of the options hash.
For example this allows you to specify following of symlinks like so:
my $rule = File::Find::Rule->extras({ follow => 1 });
May be invoked many times per rule, but only the most recent value is used.
relative
Trim the leading portion of any path found
canonpath
Normalize paths found using
File::Spec-canonpath>. This will return paths with a file-seperator that is native to your OS (as determined by File::Spec), instead of the default
/.
For example, this will return
tmp/foobaron Unix-ish OSes and
tmp\foobaron Win32.
not_*
Negated version of the rule. An effective shortand related to ! in the procedural interface.
$foo->not_name('*.pl'); $foo->not( $foo->new->name('*.pl' ) );
Query Methods
in( @directories )
Evaluates the rule, returns a list of paths to matching files and directories.
start( @directories )
Starts a find across the specified directories. Matching items may then be queried using "match". This allows you to use a rule as an iterator.
my $rule = File::Find::Rule->file->name("*.jpeg")->start( "/web" ); while ( defined ( my $image = $rule->match ) ) { ... }
match
Returns the next file which matches, false if there are no more.
Extensions
Extension modules are available from CPAN in the File::Find::Rule namespace. In order to use these extensions either use them directly:
use File::Find::Rule::ImageSize; use File::Find::Rule::MMagic; # now your rules can use the clauses supplied by the ImageSize and # MMagic extension
or, specify that File::Find::Rule should load them for you:
use File::Find::Rule qw( :ImageSize :MMagic );
For notes on implementing your own extensions, consult File::Find::Rule::Extending.
TWO FOR THE PRICE OF ONE
File::Find::Rule also gives you a procedural interface. This is documented in File::Find::Rule::Procedural
EXPORTS
TAINT MODE INTERACTION
As of 0.32 File::Find::Rule doesn't capture the current working directory in a taint-unsafe manner. File::Find itself still does operations that the taint system will flag as insecure but you can use the "extras" feature to ask File::Find to internally
untaintfile paths with a regex like so:
my $rule = File::Find::Rule->extras({ untaint => 1 });
Please consult File::Find's documentation for
untaint,
untaint_pattern, and
untaint_skipfor more information.
BUGS
The code makes use of the
ourkeyword and as such requires perl version 5.6.0, 2011 Richard Clamp. All Rights Reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
File::Find, Text::Glob, Number::Compare, find(1)
If you want to know about the procedural interface, see File::Find::Rule::Procedural, and if you have an idea for a neat extension File::Find::Rule::Extending
Module Install Instructions
To install File::Find::Rule, copy and paste the appropriate command in to your terminal.
cpanm File::Find::Rule
perl -MCPAN -e shell install File::Find::Rule
For more information on module installation, please visit the detailed CPAN module installation guide. | https://metacpan.org/dist/File-Find-Rule/view/lib/File/Find/Rule.pm | CC-MAIN-2022-33 | refinedweb | 653 | 56.45 |
Facebook page
I developed this language because I don't find the other languages perfect for the things that I want to do. My problem with C++ is that it's slow to develop in it, and doesn't have such features that C# has, but .NET languages are not native and use CIL. This doesn't allow to use standard x86 assembly and maybe also slower.
I have been working on developing Anonymus since March 2010 in C#. Its performance is competitive with C++ while it will be a high level language. The syntax and libraries are similar to C#, C++, so I don't think it would be hard to learn, but I also change syntax if I think it could be better.
Some functions are used from BlitzMax modules, because I haven't implemented all of the graphical libraries yet. Some of the sample programs use C++ to compare the performance. To run these, you'll need to install MinGW. To compile the programs written in Anonymus, you should run the “As.exe” which is in the “Binaries” directory. In the command line, you can use options and the others will be the input files. They can be Anonymus files, C, C++, Object files, etc. or libraries which start with "-l". For example:
As.exe -x -lBlitzMax -lAnonymus -format app -out Something.exe
The Anonymus library should be always used. The -x option means that the compiler should run the output file, in this case "Something.exe” file. The output format can be app (.exe), obj (.o), or arc (.a).
-x
This sample draws fading squares. When the mouse is over the square, it appears. I have created some constants and an array that contains the fading rate. The Width and Height variables contain how many squares should be in the graphics window:
Width
Height
using System
using BlitzMax
const var SquareSize = 32,
Width = 24,
Height = 20
float[Width, Height] Array
The type doesn't have to be specified, use can use var unlike C# where you can't use var for globals and class members and only one declaration is allowed.
var
There are two helper functions. The first decreases a value, the second returns true if the mouse is in the specified area:
true
float Decrease(float Val)
return if Val < 0.02: 0 else Val - 0.02
bool InArea(int x, y, w, h)
return x <= MouseX() < x + w and y <= MouseY() < y + h
The Update function updates the squares and draws them. If the mouse is on the square, it draws a white square and sets the fading rate to 1 which means it's fully visible, otherwise it draws with a color based on square's position:
Update
1
void Update()
for var x = 0 until Width
for var y = 0 until Height
var Value = Array[x, y]
var XPos = x * SquareSize
var YPos = y * SquareSize
if InArea(XPos, YPos, SquareSize, SquareSize)
Value = 1
SetColor 255, 255, 255
DrawRect XPos, YPos, SquareSize, SquareSize
else if Value > 0
var Color = 255 * Value
var Red = (int)(((float)x / Width) * Color)
var Greed = (int)(((1 - (float)y / Height)) * Color)
var Blue = (int)(((float)y / Height) * Color)
SetColor Red, Greed, Blue
DrawRect XPos, YPos, SquareSize, SquareSize
Array[x, y] = Decrease(Value)
The Reset function sets the array to zero, because it can contain any data. The Main function creates a graphics window, and updates it until the user hits the escape key or clicks the exit button:
Reset
Main
void Reset()
for var x = 0 until Width
for var y = 0 until Height
Array[x, y] = 0
public stdcall void Main()
Reset
Graphics SquareSize * Width, SquareSize * Height
while !KeyHit(Keys.Escape) and !AppTerminate()
Cls
Update
Flip
The for until loop is different from for to loop. It doesn't reach the value at the right side, so subtracting one can be saved in some cases.
for until
for to
LEB128 is used to store numbers without size limits. The first bit of a byte stores 1 if there is another after that byte, otherwise 0. So 7 bits of each byte stores the number. You can learn more at Wikipedia. I created the sample based on the algorithm in that page:
1
0
using System
using BlitzMax
byte[4] Bytes
int Position
extern cdecl void CEntry()
byte GetByte()
: Ret = Bytes[Position]
Position++
int DecodeInt(fun byte() GetByte)
: Result = 0
var Shift = 0b
var Byte = 0b
cycle Byte = GetByte()
Result |= (int)(Byte & $7F) << Shift
Shift += 7
if Byte & $80 == 0: break
if Shift < sizeof(int) * 8 and (Byte & $40) != 0
Result |= -1 << Shift
void TestLoop()
repeat 200000000
Position = 0
DecodeInt GetByte
void AsEntry()
BeginPerf
Bytes = [$E5b, $C1b, $C3b, $6Fb]
TestLoop
Bytes = [$BBb, $D6b, $1Bb, $00b]
TestLoop
EndPerf
public stdcall void Main()
CEntry
AsEntry
I compared the performance of C#, G++ and Anonymus. These are the results:
In this sample, I calculate the color of each pixel. This sample's aim is also to compare the performance with C++. It calculates the distance from the middle point of the window and it takes the sine and cosine of it. To make it faster, it creates a smaller image that it draws to, and then it's scaled up.
I made some helper functions. The ArgbColor function combines the four components of a color to a single number. The GetDistance function simply calculates a distance, and the Wrap function cuts down parts of a integer that cannot fit in a byte.
ArgbColor
GetDistance
Wrap
The UpdateImagefunction does the main task of the program. It works as I wrote it in the beginning of the sample.
UpdateImage
using System
using BlitzMax
int ArgbColor(byte a, r, g, b)
return (int)a << 24 | (int)r << 16 | (int)g << 8 | b
double GetDistance(double x1, y1, x2, y2)
var x = x2 - x1, y = y2 - y1
return Math.Sqrt(x * x + y * y)
byte Wrap(int x)
if x < 0: x = 0
if x > 255: x = 255
return (byte)x
void UpdateImage(IntPtr Image)
var Pixmap = LockImage(Image, 0, true, true)
var Width = ImageWidth(Image)
var Height = ImageHeight(Image)
var Time = MilliSecs()
for var x = 0 until Width
for var y = 0 until Height
var RelX = (float)x / Width
var RelY = (float)y / Height
var Distance = GetDistance(RelX, RelY, 0.5, 0.5) * 3 - (float)Time / 1000
var Light = (int)((RelY * 100) * Math.Abs(Math.Sin(Distance / 1.5)))
var Red = (int)((RelX * 255) * Math.Abs(Math.Cos(Distance))) + Light
var Green = (int)(((1 - RelY) * 255) * Math.Abs(Math.Sin(Distance))) + Light
var Blue = (int)((RelY * 255) * Math.Abs(Math.Cos(Distance / 3))) + Light
var Color = ArgbColor(255, Wrap(Red), Wrap(Green), Wrap(Blue))
WritePixel Pixmap, x, y, Color
UnlockImage Pixmap, 0
public stdcall void Main()
Graphics 1024, 720
var Image = CreateImage(512, 360, 1, -1)
while not KeyHit(Keys.Escape) and not AppTerminate()
Cls
UpdateImage Image
DrawImageRect Image, 0, 0, 1024, 720, 0
DrawFrameStats
Flip
To increase the performance, you can decrease the size of the image. The FPS of the Anonymus version is 12, and C++ version's FPS is 8 on my computer. So in this sample, it's about 33% faster than C++. And I haven't finished SSE support yet.
12
8
The ArgbColor function takes 4 byte parameters. These are passed in the al, ah, dl, dh registers, in that order. al is the first byte, ah is the second byte of the eax register. The result will be stored in the eax register too.
al
ah
dl
dh
eax
The ah register will be overwritten, so it copies it to the cl register. Then it clears the high 3 bytes of the eax register by doing a bitwise and on them and shifts the last byte from blue color place to the alpha. It does almost the same with the others.
cl
_ArgbColor:
mov cl, ah
and eax, 0xFF
shl eax, 24
and ecx, 0xFF
shl ecx, 16
or eax, ecx
movzx ecx, dl
shl ecx, 8
or eax, ecx
movzx ecx, dh
or eax, ecx
ret
The float numbers can be only stored in memory with FPU, so the parameters will be on the stack. The return value will be on the FPU stack. Anonymus doesn't save the stack pointer to ebp register, it rather uses it to store data, but it makes assembly less readable, because you may don't know the variables' positions. In this function, the parameters starts at esp + 4, because the caller's eip is stored in the stack. It doesn't need to subtract 16 from esp, because no functions are called by GetDistance function.
ebp
esp + 4
eip
16
esp
_GetDistance:
fld qword[esp + 20]
fsub qword[esp + 4]
fstp qword[esp - 16]
fld qword[esp + 28]
fsub qword[esp + 12]
fstp qword[esp - 8]
fld qword[esp - 16]
fmul qword[esp - 16]
fld qword[esp - 8]
fmul qword[esp - 8]
faddp
fsqrt
ret 32
This is the most simple function. It uses conditional moves. The disadvantage of this is that the cmov instruction's second parameter must be a memory position, and reading memory is slow. But I read the conditional jumps are also slow if we do it a lot because of branch prediction.
cmov
_Wrap:
cmp eax, 0
cmovl eax, dword[_11]
cmp eax, 255
cmovg eax, dword[_18]
ret
I think describing them doesn't make much sense. The only thing I would mention is that in the future, I will add function inlining to improve performance. I suppose G++ does the same.
The type of integer literals can be specified by a suffix that is a lower case short form of the type name. The hexadecimal numbers have to be upper case in order to distinguish them:
$FFb '' An unsigned byte
-$1Asb '' A signed byte
%100 '' A binary number
Basically, these are the same as C#:
struct Rect
public float X, Y, Width, Height
'' Constructor: This is called when a Rect is created
public Rect(float X, Y, Width, Height)
this.X = X
this.Y = Y
this.Width = Width
this.Height = Height
public Rect Copy()
return new Rect(X, Y, Width, Height)
public float Area:
get return Width * Height
public float GetValue(int x)
switch x
case 0: return X
case 1: return Y
case 2: return Width
case 3: return Height
default return 0
static class Console
public static void PrintInt(int x)
public static void PrintLong(long x)
public static void PrintDouble(double x)
enum Keys
A = 65, B, C, D, E, F, G, H, I, J, K, L, M, N, O
P, Q, R, S, T, U, V, W, X, Y, Z,
F1 = 112, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12
flag Modifiers
None = 0
Shift = 1, Control, Option, System
Alt = Option, Menu = Option, Apple = System, Windows = System
For the flag type, the automatic value is always multiplied by 2 unlike C#. It adds 1 even if it's declared with Flags attribute. The switch command doesn't need case statements to jump out from the switch.
flag
Flags
switch
case
The tuples allow storing multiple values in a variable with different types. You can write the multiplication of vectors in Anonymus language like this:
type float3 = (float x, y, z)
float3 Cross(float3 a, b)
return a.y * b.z – a.z * b.y,
a.z * b.x – a.x * b.z,
a.x * b.y – a.y * b.x
If I don’t define the float3 type or name the members, they can be identified by numbers:
float3
float, float, float Cross((float, float, float) a, b)
return a.1 * b.2 – a.2 * b.1,
a.2 * b.0 – a.0 * b.2,
a.0 * b.1 – a.1 * b.0
For the simple vector operations (addition, subtraction), you don’t have to call functions, it's enough to write a + b.If I want to manage the members of the tuple, it's enough to separate the components by commas at the left of the assignment:
float x, y, z
x, y, z = Cross(a, b)
It’s also possible to declare and give values to the variable, but in this case you have to write out the types to be unambiguous:
(var x, var y, var z) = Cross(a, b)
This is also the same in C#. This is how BlitzMax.Grapics function looks in Anonymus:
BlitzMax.Grapics
public extern cdecl asmname("_brl_graphics_Graphics")
IntPtr Graphics(int Width, Height, Depth = 0, Hertz = 60, Flags = 0)
To call it, it's possible to miss the last parameters, or by specifying each parameter individually:
Graphics 800, 600
Graphics Width: 800, Height: 600
Graphics 800, 600, Hertz: 75
It swaps two or more data simple without used temporary variable:
a, b = b, a
Without this, the only way is to declare new variables or create a function that does the swapping, but this is also not perfect because the parameter can be only type. In order to be able to output values in parameters, I use the ref types. When you pass a parameter with ref, you pass the address of the variable, not its value:
ref
void SwapInts(ref int a, b)
var c = a
a = b
b = c
'' Usage:
SwapInts ref a, ref b
In C, pointers are also needed:
void SwapInts(int* a, int* b)
{
int c = *a;
*a = *b;
*b = c;
}
// Usage:
SwapInts(&a, &b);
Returning with a variable that is created at the beginning of a function is a common case. This function calculates the length of a zero-terminated string where the return command is not necessary:
string
public static UInt_PtrSize StringLength(char* Str)
: Ret = 0
while Str[Ret] != '~0'
Ret++
It's possible to create multiple variables, in this case the return type will be a tuple.
You can reference them with the extern modifier. The asmname enables you to specify the name that this identifier will have in the compiled code. You can also give the calling convention of the function. Currently, my language supports cdecl, stdcall, and ascall:
extern
asmname
cdecl
stdcall
ascall
public extern cdecl asmname("_brl_polledinput_KeyHit") bool KeyHit(Keys key)
In C, there wouldn't be asmname setting, you need to use it with the full name or declare a macro:
void brl_polledinput_KeyHit(uint KeyCode);
#define KeyHit brl_polledinput_KeyHit
The default function call is ascall that uses eax, edx and ecx for parameters, but passes pointers, classes, etc. first, then the numbers (except the floating point numbers because it's not possible to calculate if they are in general registers). It can also handle high and low byte of the registers that have that variant to store two data in the same register.
edx
ecx
Here is an example (System.Math.Truncate from Anonymus library):
System.Math.Truncate
public static asm double Truncate(double x)
fldcw $[_x86Helper.TruncateFPUControlWord]
fld qword[esp + 4]
frndint
fldcw $[_x86Helper.DefaultFPUControlWord]
ret 8
As you can see, it's possible to use globals with $[ ]. For function parameters direct location is needed, if I implement it, the code would be less optimal, because not all of the instructions' operand data types are allowed.
$[ ]
These can be types, variable or functions. All variables and functions have types. The latter is determined by the return value and the parameter’s type. The variables are also divided into ground. They can be local, global or member of a structure.
They can be found before the declaration (e.g., cdecl, asmname, etc.). They are isolated and stored in a list that will receive a function that does the declaration. For example, if a variable is marked with static, then it will create a global identifier.
static
These are parsed by different recognizers. It’s possible to create a new or replace one without a large modification in the language. An expression recognizer can recognize more operations. E.g., The Multiplicative recognizes multiplication, division and modulus. If it succeeded, then it should call the plugin that the recognizer received by parameter.
The plugins can modify the recognized expression. The MultiPlugIn class manages multiple plugin joint work. The type manager plugin’s task is to determine the type of the expressions and do the conversions. The calculator plugin calculates a value if we want to operate with constants.
MultiPlugIn
If the expression recognizer wants to declare a variable, it should call a plugin’s function. If it can’t do this, it gives an error message. The multi plugin redirects the declaration to the compiler plugin, if it exists.
It processes all statements starting with #. You can create a macro or if a condition is true, run another code. There’s a preprocessor plugin that replaces the expressions created by call recognizer to the given expression:
#
true
#define min(x, y) if x < y then x else y
#define max(x, y) if x > y then x else y
int Something(int i, j)
return max(i, j) / min(i, j)
The preprocessor produces this from it:
int Something(int i, j)
return (if i > j: i else j) / (if i < j: i else j)
In the Anonymus language, statements that have the same number of whitespace characters belong to a scope. First the compiler creates a global scope, then calls the preprocessor, processes the types and then the functions and variables. These are processed multi-threaded.
In the code, scopes can contain commands that can also contain things. E.g., an if command has an expression which is the condition and one or more code scopes. A function scope is the outermost scope in a function that is also a code scope.
if
It’s possible to do more architecture that create assembly code. If necessary, it can use a plugin or attach data to identifiers, identifier containers. Currently the x86 architecture is implemented.
The language consists of recognizers, and supporting new languages can be done by replacing recognizers. The functions, types, variables will be available between Anonymus and the new languages. I don't use parser generators, because I think using other software could prevent from implementing some of the functionalities or I would have to do things in a different way.
The CompilerState class has a Language object that contains all recognizers. Here is the Language class:
CompilerState
Language
public abstract class Language : LanguageNode
{
public IList<IExprRecognizer> ExprRecognizers;
public IList<IIdRecognizer> IdRecognizers;
public IList<ICommRecognizer> CommRecognizers;
public IList<IModRecognizer> ModRecognizers;
public IList<INameGenerator> NameGenerators;
public IList<IResultSkippingHandler> GlobalHandlers;
public IArgRecognizer ArgRecognizer;
public IGenericRecognizer GenericRecognizer;
public IGroupRecognizer GroupRecognizer;
public IRetValLessRecognizer RetValLessRecognizer;
public IInnerScopeRecognizer InnerScopeRecognizer;
public IVarDeclRecognizer VarDeclRecognizer;
public ITypeDeclRecognizer TypeDeclRecognizer;
public IConstDeclRecognizer ConstDeclRecognizer;
public INamespaceDeclRecognizer NamespaceDeclRecognizer;
public IDeclarationRecognizer DeclarationRecognizer;
public IGlobalScopeProcessor GlobalScopeProcessor;
public ICodeFileProcessor CodeFileProcessor;
public ICodeProcessor CodeProcessor;
...
}
Anonymus uses StringRange to store strings to avoid a new string allocation when it calls string.Substring. This structure also has functions for bracket handling and other operations. The CodeString structure consists of a StringRange and a reference to CodeFile class that can also manage lines and indents of them. CodeString has a Line field and when its substring is needed, it updates the Line member. Most of the CodeString's methods are just wrapper around StringRange's functions.
StringRange
string
string.Substring
CodeString
CodeFile
Line
The ISkippingHandler interface is used to skip results that are in a string constant or bracket. The recognizers can store data in ResultSkippingManager.Datas, if it's needed. In some cases, it's necessary to make sure that the brackets are not skipped. A bracket recognizer shouldn't skip brackets if ResultSkippingManager.DoNotSkipBrackets is true.
ISkippingHandler
ResultSkippingManager.Datas
ResultSkippingManager.DoNotSkipBrackets
public class BracketRecognizer : LanguageNode, IExprRecognizer,
IIdRecognizer, IResultSkippingHandler
{
...
public int SkipResult(ref ResultSkippingManager RSM)
{
if (!RSM.DoNotSkipBrackets && Helper.GetBracket(RSM.CurrentChar, RSM.Back))
{
var Handlers = RSM.SkippingHandlers;
if (RSM.Back)
{
var NewString = RSM.String.Substring(0, RSM.Current + 1);
var Pos = NewString.GetBracketPos(true, Handlers);
if (Pos != -1) return Pos;
}
else
{
var NewString = RSM.String.Substring(RSM.Current);
var Pos = NewString.GetBracketPos(false, Handlers);
if (Pos != -1) return Pos + RSM.Current;
}
}
return -1;
}
}
So this is the BracketRecognizer class. It has to return an index where the string search should be continued or -1. The GetBracketPos method returns the position of the bracket's pair which the string ends or starts with. If the first parameter is false, the string has to begin with a bracket that looks to the right.
BracketRecognizer
-1
GetBracketPos
false
The LanguageNode class contains an array of strings called Operators that it recognizes and another array of strings (LanguageNode.Skip) that it should skip, because the operators, that it has to recognise, is the part of them. E.g., an addition recognizer has +, - operators then the skip array should contain ++, --. The NewLine strings contain which operators need the previous or the next line. E.g., if the line ends with +, then it will continue with the next:
LanguageNode
Operators
LanguageNode.Skip
NewLine
public abstract class LanguageNode
{
public DataList Data = new DataList();
public Language Root;
public LanguageNode Parent;
public IList<LanguageNode> Children;
public IList<IResultSkippingHandler> SkippingHandlers;
public string[] Operators;
public string[] SkipFind;
public string[] Skip;
public string[] NewLineLeft;
public string[] NewLineRight;
public string[] OnlyLeft;
public string[] OnlyRight;
...
}
Recognizations are done in a recursive way. I think it's simple but maybe not the fastest way to parse a code file. To decrease the time spent on string operations, I use my own functions which are optimized for these things and significantly faster, although far more time spent on code generation. Currently my compiler can process 10 000 lines of code in about 900 milliseconds.
An expression recognizer should inherit from this class and IExprRecognizer interface. Recognizers can use Find2 function to determine which operators aren't unary. If the left side of the result ends with an operator or there's nothing, it will ignore that result. When it's not enough to use the LanguageNode.Operators, for example the cast recognizer needs to implement the IFind2Handler interface. The following code is the addition recognizer:
IExprRecognizer
Find2
LanguageNode.Operators
IFind2Handler
public class AdditiveRecognizer : LanguageNode, IExprRecognizer
{
public AdditiveRecognizer()
{
Operators = new string[] { "+", "-" };
NewLineLeft = NewLineRight = Operators;
}
public ExprRecognizerRes Recognize
(CodeString Code, ExprPlugIn PlugIn, ref ExpressionNode Ret)
{
var Result = ExprRecognizerHelper.Find2(this, PlugIn.Container, Code.String);
if (Result.Position != -1)
{
var Ch = ExprRecognizerHelper.TwoParamOpNode(Code, Result, PlugIn);
if (Ch == null) return ExprRecognizerRes.Failed;
Operator Op;
if (Result.Index == 0) Op = Operator.Add;
else if (Result.Index == 1) Op = Operator.Subract;
else throw new ApplicationException();
Ret = new OpExpressionNode(Op, Ch, Code);
return ExprRecognizerRes.Succeeded;
}
return ExprRecognizerRes.Unknown;
}
}
This still wouldn't be compatible with the NumberRecognizer, because floating point numbers can have e notation (2e+2 = 2 * 102). To solve this problem, the NumberRecognizer adds a result skipper to LanguageNode.SkippingHandlers. ExprRecognizerHelper.Find2 takes a LanguageNode parameter first, which is used to get the skipping handlers from.
NumberRecognizer
LanguageNode.SkippingHandlers
ExprRecognizerHelper.Find2
This is most complex part of Anonymus. It is about the third of the whole project. These are major steps it does to compile a function:
int Fib(int x)
if x < 2: return 1
else return Fib(x - 1) + Fib(x - 2)
This function would have the following assembly without jump optimizations:
_Fib:
push ebx
push ebp
mov ebp, eax
cmp ebp, 2
jge _26
mov eax, 1
jmp _2
jmp _24
_26:
mov eax, ebp
dec eax
call _Fib
mov ebx, eax
mov eax, ebp
sub eax, 2
call _Fib
add eax, ebx
jmp _2
_24:
_2:
pop ebp
pop ebx
ret
The label _26 and _24 are for the condition and the label _2 is for function return. There are some unnecessary jumps and labels that should be deleted:
_26
_24
_2
_Fib:
push ebx
push ebp
mov ebp, eax
cmp ebp, 2
jge _26
mov eax, 1
jmp _2
_26:
mov eax, ebp
dec eax
call _Fib
mov ebx, eax
mov eax, ebp
sub eax, 2
call _Fib
add eax, ebx
_2:
pop ebp
pop ebx
ret
It could save a jump if it does the same as where it jumps to. Unless it is too long, it replaces the jump:
_Fib:
push ebx
push ebp
mov ebp, eax
cmp ebp, 2
jge _26
mov eax, 1
pop ebp
pop ebx
ret
_26:
mov eax, ebp
dec eax
call _Fib
mov ebx, eax
mov eax, ebp
sub eax, 2
call _Fib
add eax, ebx
pop ebp
pop ebx
ret
The IsEqual function needs 3 temporary register to fulfil that the mov instruction can only have one memory operand, and the memory location can't have a memory address:
IsEqual
mov
long* g_Pointers
int g_Index
long g_Value
bool IsEqual()
return g_Value == g_Pointers[g_Index]
_IsEqual:
mov eax, dword[_g_Pointers]
mov edx, dword[_g_Index]
mov ecx, dword[eax + edx * 8]
cmp dword[_g_Value], ecx
jne _27
mov ecx, dword[eax + edx * 8 + 4]
cmp dword[_g_Value + 4], ecx
jne _27
mov al, 1
ret
_27:
xor al, al
ret
This is the main function for condition assembly generation (Anonymus.CodeGenerator.GetConditionCode):
Anonymus.CodeGenerator.GetConditionCode)
void GetConditionCode(ExpressionNode Node, int Then, int Else, bool ElseAfterCondition)
The Then and Else are the index of labels. If ElseAfterCondition is
Then
Else
ElseAfterCondition
True
False
void WhileTest(bool Loop)
var a = 0
while Loop
a++
void DoWhileTest(bool Loop)
var a = 0
do
a++
while Loop
; This is the assembly without jump replacements
_WhileTest:
xor edx, edx
_1:
test al, al
jz _13
_72:
inc edx
jmp _1
_13:
ret
; After jump replacements
_WhileTest:
xor edx, edx
test al, al
jz _13
_72:
inc edx
test al, al
jnz _72
_13:
ret
_DoWhileTest:
xor edx, edx
_76:
inc edx
test al, al
jnz _76
ret
In the WhileTest function, the condition is followed by the then scope, ElseAfterCondition is false. In the DoWhileTest it's followed by the return command (which happens if the condition is false), the ElseAfterCondition is true.
WhileTest
DoWhileTest
This is how the and and or operators work:
and
or
void While_OrTest(bool x, y, z)
var a = 0
while x or y or z
a++
void DoWhile_OrTest(bool x, y, z)
var a = 0
do
a++
while x or y or z
void While_AndTest(bool x, y, z)
var a = 0
while x and y and z
a++
void DoWhile_AndTest(bool x, y, z)
var a = 0
do
a++
while x and y and z
_While_OrTest:
xor ecx, ecx
_45:
test al, al
jnz _44
test ah, ah
jnz _44
test dl, dl
jz _7
_44:
inc ecx
jmp _45
_7:
ret
_DoWhile_OrTest:
xor ecx, ecx
_50:
inc ecx
test al, al
jnz _50
test ah, ah
jnz _50
test dl, dl
jnz _50
ret
_While_AndTest:
xor ecx, ecx
_57:
test al, al
jz _9
test ah, ah
jz _9
test dl, dl
jz _9
inc ecx
jmp _57
_9:
ret
_DoWhile_AndTest:
xor ecx, ecx
_62:
inc ecx
test al, al
jz _10
test ah, ah
jz _10
test dl, dl
jnz _62
_10:
ret
In all the while and do-while tests, the last condition remains the same, the ElseAfterCondition is only changed for the first two conditions. For the and conditions, the ElseAfterCondition is false, for the or conditions it's true.
while
do
Here is an example that contains both operators:
void While_AndOrTest(bool x, y, z, w)
var a = 0
while (x or y) and (z or w)
a++
void DoWhile_AndOrTest(bool x, y, z, w)
var a = 0
do
a++
while (x or y) and (z or w)
_While_AndOrTest:
xor ecx, ecx
_71:
test al, al
jnz _72
test ah, ah
jz _11
_72:
test dl, dl
jnz _70
test dh, dh
jz _11
_70:
inc ecx
jmp _71
_11:
ret
_DoWhile_AndOrTest:
xor ecx, ecx
_77:
inc ecx
test al, al
jnz _79
test ah, ah
jz _12
_79:
test dl, dl
jnz _77
test dh, dh
jnz _77
_12:
ret
Currently the most important plan is to make the language stable and usable. In this version, objects can be created, but inheritance with properties doesn't work, and there's no gc yet. I hope I will be able to implement a proper string class within 2-3 months. This takes much time, because I want to program all libraries in Anonymus, so I have a lot of things to do among operator functions.
This could help to create IEnumerable<T> instances. I would create a recognizer to find commands, and then it would create an inline lambda like function and call it. C# doesn't support even the yield keyword in lamdas.
IEnumerable<T>
yield
void Something(int* pInt, int Count)
AnotherFunction for var i = 0 until Count
yield pInt[i]
void AnotherFunction(IEnumerable(:int) list)
for var x, y in 0..Width, 0..Height
for var x, y in 0...Width - 1, 0...Height - 1
These cycles mean the same. The first is equivalent to two for until loops, the other is equivalent to two for to loops..
namespace HelloByrdExample
rem these go inside the namespace, not outside
using System
public void Main()
print "Hello Little Byrd,"
print "Please sing a song"
/*synchronized*/ class myobject
{
// any method call to this object is locked or perhaps queued
}
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=192825&av=484411&fid=1625401&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None&fr=11 | CC-MAIN-2014-49 | refinedweb | 4,875 | 59.43 |
Docs |
Forums |
Lists |
Bugs |
Planet |
Store |
GMN |
Get Gentoo!
Not eligible to see or edit group visibility for this bug.
View Bug Activity
|
Format For Printing
|
XML
|
Clone This Bug
Scigraphica segfaults straight away after being run. It manages to open a
window and report the segfault (and save the project) but then just dies.
Reproducible: Always
Steps to Reproduce:
1. type scigraphica
Actual Results:
james $ scigraphica
Segmentation fault
Expected Results:
run.
james $ emerge info
Portage 2.0.47-r10 (default-x86-1.4, gcc-3.2.2, glibc-2.3.1-r2)
=================================================================
System uname: 2.4.20-gentoo-r2 i686 Pentium III (Coppermine)
GENTOO_MIRRORS="" avi crypt cups encode gif jpeg gnome libg++ mikmod mmx
mpeg ncurses nls pdflib png quicktime spell truetype xml2 xmms xv zlib gtkhtml
gdbm berkdb slang readline arts svga java guile X sdl gpm tcpd pam libwww ssl
python esd imlib oggvorbis gtk qt kde motif opengl alsa bonobo doc dvd gtk2 imap
jikes junit ldap leim mozilla mysql pcmcia perl plotutils samba slp sse tcltk
tetex usb"
COMPILER="gcc3"
CHOST="i686-pc-linux-gnu"
CFLAGS="-march=pentium3 -O3 -pipe -fomit-frame-pointer"
CXXFLAGS="-O2 -mcpu=i686 -pipe"
ACCEPT_KEYWORDS="x86"
MAKEOPTS="-j2"
AUTOCLEAN="yes"
SYNC="rsync://rsync.uk.gentoo.org/gentoo-portage"
FEATURES="sandbox ccache"
please run it with strace and attach the output
Hi James.
Thanks for the report. Though I could not reproduce the problem.
Did you try doing what semant suggested?
George
Created an attachment (id=10297) [edit]
output of strace scigraphica
output of strace scigraphica - looks like it can't find various files and dies
because of it.
Created an attachment (id=11672) [edit]
strace of scigraphica startup segfault
I get segfaults with scigraphica at startup too. Here is my strace.
Hi guys.
Just an idea:
James I see you have Pentium-III, but your USE flags contain 3dnow. Could this be what's causing the problem by chance? May be even idirectly, but via some library perheaps?
Note, that 3dnow belongs to make.defaults, so if you don't want this flag, you have to specifically set -2dnow in make.conf...
>output of strace scigraphica - looks like it can't find various files and dies
>because of it.
Um, if you mean stuff like this:
stat64("/etc/gnome/config-override//Gnome", 0xbfffccc0) = -1 ENOENT (No such file or directory)
stat64("./gnome/config-override//Gnome", 0xbfffccc0) = -1 ENOENT (No such file or directory)
stat64("/etc/gnome/config//Gnome", 0xbfffccc0) = -1 ENOENT (No such file or directory)
stat64("./gnome/config//Gnome", 0xbfffccc0) = -1 ENOENT (No such file or directory)
then I doubt it - I have bunch of such lines myself and that does not prevent scigraphica from functioning properly. Strace output is quite noisy - it reports every single action app and os try to do, including searching for that apps everywhere in $PATH and for configs in all possible places...
However comparing my strace with yours I see that you are getting quite a bit more complaints about gnome-related stuff. Any possibility something is screwed there?
There are also few complaints about python stuff, but these are approcimately matched in both straces I compared, even at the end, right before it segfaults.
However I noticed you have quite a bit more complaints about:
>gtk-2.0/gtk/encodings.py - gtk-2 and encodings in many variations, which I don't seem to see here.. I know sometimes gtk-based apps segfault because of some fonts. I was able to segfault mozilla and phoenix here in this way and only made them work by removing "offending" fonts. Are you using xfree-4.3.0? If yes, this is another area to look into...
George
I also have gentoo on my work pc, a pentium4. When I emerge scigraphica on
this, it gets a little bit further
before dying.
It opens a window saying 'couldn't import module gtk'. If I click view error
log, I get a python window saying
ImportError: No module named gtk
>>>
So it looks like a pyhton error?? Where does python look for its modules? How
do I check the gtk module is
installed?
Hi James.
Well, now I seem to have this complaint (no such module) as well, however this does not segfault scigraphics - it starts up and works seemingly ok.
However I was able to segfault it by typing the following sequence in that python window:
import pygtk
pygtk.require("2.0")
import gtk
This requires pygtk-1.99.x installed.
Apparently gtk module is provided by pygtk, which is not in DEPEND. However it seems to be optional and what's more seems to break scigraphics. Thus I don't think its wise to add it to DEPEND, at least until this issue is sorted out.
I'll try to look more into this soon.
George
Exact same problem as James. Here's my emerge info.
Portage 2.0.49-r13 (default-x86-1.4, gcc-3.2.3, glibc-2.3.2-r1, 2.4.22)
=================================================================
System uname: 2.4.22 i686 AMD Athlon(TM) XP 2500+
Gentoo Base System version 1.4.3.10p1
ACCEPT_KEYWORDS="x86"
AUTOCLEAN="yes"
CFLAGS="-mcpu=athlon-xp -O2 /ge
neric/config/ /usr/share/texmf/tex/platex/config/ /usr/share/config"
CONFIG_PROTECT_MASK="/etc/gconf /etc/env.d"
CXXFLAGS="-mcpu=athlon-xp -O2 -pipe"
DISTDIR="/usr/portage/distfiles"
FEATURES="sandbox ccache autoaddcvs"
GENTOO_MIRRORS="
oo.inode.at/source/"
MAKEOPTS="-j2"
PKGDIR="/usr/portage/packages"
PORTAGE_TMPDIR="/var/tmp"
PORTDIR="/usr/portage"
PORTDIR_OVERLAY=""
SYNC="rsync://rsync.gentoo.org/gentoo-portage"
USE="x86 apm avi gif jpeg libg++ mad mikmod mpeg ncurses pdflib png xml2
xmms zl
ib gdbm berkdb slang readline tetex bonobo X sdl gpm tcpd pam libwww ssl
perl im
lib oggvorbis gtk qt mozilla 3dnow acl alsa -arts canna cdr cjk crypt csope
cups
dvd encode -esd foomaticdb freewnn gatos -gnome guile ipv6 java jikes junit
-kd
e -motif nls opengl -oss python quicktime ruby scanner -svga spell tcltk
truetyp
e usb videos xinerama xv video_cards_radeon"
Created an attachment (id=21617) [edit]
my stack trace
I'm having the same problem here you have my stack trace
Created an attachment (id=21618) [edit]
here is my environment info
I've got the message "Could not load module pysga" (but I cannot see the
error log, it segfaults first)
In my opinion this bug is related to the fact that pygtk-2.0.0 is linked
to gtk+-2.2.4-r1, but scigraphica is linked to gtk+-1.2.10-r10 and
gtk+-extra-0.99.17, this seems not to be consistent.
(shouldn't be a gtk-1.2 version of pygtk?)
On the other hand, scigraphica seems to depend on pygtk but
emerge -pe scigraphica
does not inform about this!
Adding pygkt-0.6.11 to DEPEND and a routine to reemerge 2.0 should fix it.
Emerging 0.6.11 fixed scigraphica on my machine.
It's still in portage and emerges nicely. I had to reemerge pygtk-2.0
afterwards though. For example the Python-Fu-Filters of Gimp-1.3 stopped
working with the pygtk.py file from 0.6.11. Reemerging 2.0 afterwards helps and
doesn't affect scigraphica.
A short addition:
It looks like you have to start scigraphica once after emerging pygtk-0.6.11 before reemerging pygtk-2.0 or scigraphica will keep crashing. (Noticed it today while updating Python to 2.3)
I think comment #13 could be interesting for the python herd since SLOTted
packages should co-exist peacefully.
Just tried emerging pygtk-0.6.11 after pygtk-2.0.0 and got:
epm -V pygtk-2.0.0
..5....T /usr/lib/python2.2/site-packages/pygtk.py
..5....T /usr/lib/python2.2/site-packages/pygtk.pth
..5....T /usr/lib/python2.2/site-packages/pygtk.pyc
..5....T /usr/lib/python2.2/site-packages/pygtk.pyo
So indeed old pygtk conflicts with the new one.
Felix, about your comment #14 - looks like the right paths are written into the config file once it was started successfully.
I managed to get it running even after installing pygtk-2 by calling it
PYTHONPATH="/usr/lib/python2.2/site-packages/gtk-1.2" scigraphica.
I'd say: As soon as the python guys have brought an improved pygtk-0.6.11, we
can make scigraphica DEPEND on this and provide a wrapper that sets PYTHONPATH
right.
scigraphica doesn't have pygtk in its deps.
anyway the correct way to use pygtk-0.6.11 is by doing:
import pygtk
pygtk.require("1.2")
import gtk
and not by using the PYTHONPATH hack. the author of scigraphica should actually be informed that the scripts need to follow that convention, as for the pygtk 0.6.11 overwriting files with pygtk-2, i need to look at that seperately, but not in this bug
George, what's the current status? Don't want to annoy the author by sending a
note if you maybe already did.
Well maybe more of a question,
How come that an application is marked stable, when it segfaults every time it's being run after a emerge ?
Hi guys.
Thanks for doing more problem tracing. Since I could not reliably reproduce the segfaulting this was essential!
I have issued the -r2 ebuild which should fix things. Unfortunately, because of the way scigraphica wants to set itself up and because of some still non-resolved overlap in pygtk 1.2 and 2.0 slots the process has to be somewhat manual.
I created pkg_setup and (a reminder) pkg_postinst functions. pkg_setup wil check for installed version of pygtk and if it detects >=1.99, it will ask user to do this unmerge run remerge dance.. (see ebuild for details).
I could not come up with something more automated but as reliable (stuff cannot be emerged from within the ebuild, plus we need to run the program as user once..), but if anybody has any ideas they are definitely wellcome.
The ebuild is in portage (~x86 for now), please test. If this works we probably need to unmask it and remove (first hardmask) previous versions.
Barry:
>How come that an application is marked stable, when it segfaults every time it's >being run after a emerge ?
Well, if you will look at the history, you will see that the app was running fine in the beginning. Apaprently it developed these issues when gtk2+ started to be used more widely, and even then not everybody could reproduce the problem..
Give us just a bit of faith ;).
George
Just an additional note.
When #35863 gets resolved we may be able to do a "real" and more automated fix.
George
scigraphica-0.8.0-r2 didn't work for me. I'm using
python-2.2.3-r5
gtk+extra-0.99.17
pygtk-2.0.0
(shouldn't scigraphica depend on pygtk?)
Isn't there a clean solution to this problem? Multiple versions
of pygtk should coexist peacefully (in different SLOTs)
Hi Pablo.
Did you test the -r2, that I just releeased? If so then strange:
didn't the emerge stop and weren't you asked to unmerge pygtk before proceeding? If yes, did you follow? (it shoulod have automatically pulled the right pygtk version then).
If you did all the above, did you remove your stale ~/.scigraphica/config as you were reminded by the ebuild? (you need to do it for the intended user that will be routinely running it).
Did you then run scigraphica once as that user, before emerging pygtk (-2.0) again (if you need that)?
I am afraid, untill the #35863 is resolved there is not easier way around if you want to get it working :(.
>(shouldn't scigraphica depend on pygtk?)
Well, the -r2 does. As a matter of fact I was able to run it without pygtk, so it seems to be optional (but on top of that I have difficulty reproducing segfault over here in general :)). Still I put it in, in order to resolve this until said bug above gets fixed.
Sorry for the obvious, but are you absolutely sure you tested the -r2? It is keymasked, so if you are running stable you need to ACCEPT_KEYWORDS=~arch emerge scigraphica to pick it up..
George
>didn't the emerge stop and weren't you asked to unmerge pygtk before >proceeding?
that didn't happened
>Sorry for the obvious, but are you absolutely sure you tested the -r2?
I've run
emerge -b scigraphica-0.8.0-r2.ebuild
from /usr/portage/app-sci/scigraphica directory.
Sorry for the delay.
>>didn't the emerge stop and weren't you asked to unmerge pygtk before proceeding?
>that didn't happened
That's strange, try upgrading portage (to latest testing)? Although this shouldn't matter - has_version has been supported for a while now.. And I just retested the ebuild - all complained fine.
In any case, you can still do the part it asks you to do. Unmerge pygtk (all versions, that's the simplest) and then emerge scigraphica. login as a user who will be using it, remove (or rename) ~/.scigraphica/config and then run scigraphica once (as that user). After that you can emerge pygtk-2* if necessary..
This should fix it for you. More automated fix has to waint for #35863
George
Bug #35863 is fixed now, may be we can find a real fix for this bug
now. I'll try to test it.
In fact, I finally succed in running scigraphica-0.8.0-r2 using
pygtk-0.6.11 (I also have pygtk-2.0.0 installed) and python-2.3.3 | http://bugs.gentoo.org/18436 | crawl-002 | refinedweb | 2,273 | 67.25 |
The term Exponential generally denotes rapid growth, and mathematically it means increasing in powers.
For example:
Exponential growth of 2: 2^0, 2^1, 2^2, 2^3, 2^4 and so on => (1, 2, 4, 8, 16,…..)
Exponential growth of 3: 3^0, 3^1, 3^2, 3^3, 3^4 and so on => (1, 3, 9, 27, 81,….)
We use the same generated numbers ( powers of 2 ) to jump indexes in array and get closer to the index of key.
In this algorithm, ultimately we rely on Binary Search for searching, but before that, we finalize a range in which the element we want to search might be present.
To finalize this range we follow a certain algorithm, let’s have a quick look at the overview of working of this algorithm with the help of an example.
Consider a sorted Array:
7 12 34 57 65 74 81 88 89 93 100
Element to search:
93
We will start by comparing the first element of the array with the key.
But
Array[0]=7, which is not equal to
93.
Now we will take a variable whose value will increase exponentially, hence the name,
exponential search.
int i= 1 ( because
2^0=1)
Now we will see if
Array[i] is less than or equal to the key.
If it is, then we will keep on increasing the value exponentially.
i=i*2
This will generate values in powers of 2.
( 2, 4, 8, 16, 32...)
We will keep on increasing the value of
i, until the condition
Array[i]<=key is satisfied.
So in the above example, the value of
i will reach
8 (in the actual code it will reach 16, then we will divide it by 2) and the sub-array after this index will be selected (including the index of
i), and then the binary search will be applied to this range.
There are majorly two steps included in implementing exponential search:-
i=1
i < nand
Array[i]<=key, where
nis the number of elements in the array and key is the element being searched
i=i*2
iuntil the condition is satisfied
i/2till the end of Array -
binarySearch(Array, i/2, min(i,n-1))
Consider the array:-
1 3 5 7 9 11 13 15 17 19
Element to search:
19
Array[0]element to key, which in our case would return false.
iwill be initialized to
1
Now we will keep on incrementing the value of
i until it is less than or equal to the key
After 1st pass i will be 2 - condition satisfied After 2nd pass i will be 4 - condition satisfied After 3rd pass i will be 8 - condition satisfied After 4th pass i will be 16 - CONDITION FAILED
Note that the value of i is now
16, and the index
16 is out of range in this case, so to get the previous value of
i we will divide it by
2, and call binary search using index of
low as
i/2.
Now we call the binary search method.
binarySearch(Array, i/2, min(i, n-1), key)
low = 8, high = 10 mid = (low + high)/2 = 18/2 = 9
Array[9]=19, which is the required element.
Now let’s have a look at the Java code for the same.
public class Searching { boolean exponentialSearch(int arr[], int key) { int lengthOfArray = arr.length; if (arr[0] == key) { // Checking whether first element is the key return true; } // Finding the range in which the element might be present int i = 1; while (i < lengthOfArray && arr[i] <= key) { i = i * 2; // Exponentially increasing value of i. } return binarySearch(arr, i / 2, Math.min(i, lengthOfArray - 1), key); // calling binary search method on the sub-array } boolean binarySearch(int arr[], int low, int high, int key) { int mid; // to store middle element while (low <= high) { mid = (low + high) / 2; // we can also do mid = low+(high-low)/2 to avoid overflow in some cases if (arr[mid] == key) { return true; } else if (arr[mid] < key) { low = mid + 1; } else { high = mid - 1; } } return false; } // Driver Code public static void main(String args[]) { Searching search = new Searching(); int arr[] = { 1, 3, 4, 6, 8, 13, 15, 24 }; if (search.exponentialSearch(arr, 15)) { System.out.println("Element found !"); } else { System.out.println("Element not found :( "); } } }
Here
i is the index of the key.
Exponential search is useful in cases where the arrays are unbounded or of infinite size and can converge to the solution much faster than binary search in these cases.
Help us improve this content by editing this page on GitHub | https://tutswiki.com/data-structures-algorithms/exponential-search/ | CC-MAIN-2021-17 | refinedweb | 774 | 62.72 |
I've written here and in other places about the type/variable name ambiguity that arises when parsing C code. I've also hinted that in C++ it's much worse, without giving details. Well, today while reading an interesting report on GLR parsing, I came across a great example of this ambiguity in C++; one that should make every parser writer cringe. I've modified it a bit for simplicity.
Here's a snippet of C++ code:
int aa(int arg) { return arg; } class C { int foo(int bb) { return (aa)(bb); } };
Nothing fancy. The weird thing here is (aa)(bb), which in this case calls the function aa with the argument bb. aa is taken as a name, and names can be put inside parens - the C++ grammar allows it. I've asked Clang to dump the AST resulting from parsing this code. Here it is:
class C { class C; int foo(int bb) (CompoundStmt 0x3bac758 <a.cpp:6:21, line:8:5> (ReturnStmt 0x3bac738 <line:7:9, col:23> (CallExpr 0x3bac6f0 <col:16, col:23> 'int' (ImplicitCastExpr 0x3bac6d8 <col:16, col:19> 'int (*)(int)' <FunctionToPointerDecay> (ParenExpr 0x3bac668 <col:16, col:19> 'int (int)' lvalue (DeclRefExpr 0x3bac640 <col:17> 'int (int)' lvalue Function 0x3bac1d0 'aa' 'int (int)'))) (ImplicitCastExpr 0x3bac720 <col:21> 'int' <LValueToRValue> (DeclRefExpr 0x3bac688 <col:21> 'int' lvalue ParmVar 0x3bac4f0 'bb' 'int')))))
As we can see, Clang parsed this to a function call, as expected.
Now let's modify the code a bit:
int aa(int arg) { return arg; } class C { int foo(int bb) { return (aa)(bb); } typedef int aa; };
The only difference is the typedef added to the end of the class. Here's Clang's AST dump for the second snippet:
class C { class C; int foo(int bb) (CompoundStmt 0x2a79788 <a.cpp:6:21, line:8:5> (ReturnStmt 0x2a79768 <line:7:9, col:23> (CStyleCastExpr 0x2a79740 <col:16, col:23> 'aa':'int' <NoOp> (ImplicitCastExpr 0x2a79728 <col:20, col:23> 'int' <LValueToRValue> (ParenExpr 0x2a796f8 <col:20, col:23> 'int' lvalue (DeclRefExpr 0x2a796d0 <col:21> 'int' lvalue ParmVar 0x2a79500 'bb' 'int')))))) typedef int aa; };
Clang now interprets (aa)(bb) as a cast from bb to type aa. Why?
Because in C++, type declarations in a class are visible throughout the class. Yes, that's right, even in methods defined before them. The typedef defines aa as a type, which inside the class scope masks the external aa name. This affects parsing. The cruel thing here is that the parser only finds out about aa being a type after it went over the foo method.
It's not unsolvable, of course, but it's another good example of what makes real-world programming languages hard to parse, and another case where a straightforward generated LALR(1) parser would completely bomb without significant "lexer hacking". | https://eli.thegreenplace.net/2012/06/28/the-type-variable-name-ambiguity-in-c | CC-MAIN-2018-17 | refinedweb | 468 | 58.01 |
Opened 9 years ago
Closed 7 years ago
#6783 closed (fixed)
DecimalField tests with locale
Description (last modified by )
I ran into an python locale issue with the DecimalField. During INSERTs and UPDATEs invalid sql-statements are generated since a comma-seperator ',' is used for formating DecimalField instead of the expected dot-seperator '.'
decimal-python.py (for simple testing):
from django.db.models.fields import DecimalField from locale import setlocale, LC_NUMERIC d = DecimalField(max_digits=6, decimal_places=3) setlocale(LC_NUMERIC,'de_DE') print d.format_number(3.456) setlocale(LC_NUMERIC,'en_US') print d.format_number(3.456)
linux-f426d:/home/admin/django/projects # export DJANGO_SETTINGS_MODULE=ais.settings linux-f426d:/home/admin/django/projects # python decimal-python.py 3,456 3.456
Environment:
- Django-SVN
- SuSE Linux Enterprise Server 10
- Python 2.4.2
On my private notebook this is no issue both outputs will be
3.456 3.456
Private Environment:
- Django-SVN
- OpenSuSe 10.3
- Python 2.5.1
Attachments (7)
Change History (18)
Changed 9 years ago by
Changed 9 years ago by
short work-around for DecimalField format problems in db_prep methods
Changed 9 years ago by
base tests for the issue
comment:1 Changed 9 years ago by
my test machine doesn't have the appropriate locales but I'll run the tests tomorrow.
Changed 9 years ago by
slightly better tests
comment:2 Changed 9 years ago by
The tests all pass with sqlite and mysql. I tried with both python 2.4.4 and 2.5.1. I'm marking ready for checking so we can commit the regression tests and hopefully get those run with other backends/versions.
Please note that the tests need the 'fr_FR' locale to run. If it's not available the test will be omitted (no failure though). If anyone has a more elegant solution I'd be happy to update the patch :)
comment:3 Changed 9 years ago by
comment:4 Changed 9 years ago by
Two problems here:
- On a triage level, the test changes should have been part of the main patch. It took a while to realise that this "ready for checkin" thing was actually the second and the fourth patch.
- More importantly, the solution isn't correct.
setlocale()cannot be used in multi-threaded programs, since it changes the global locale, so it will affect the operation of other threads.
Changed 9 years ago by
comment:5 Changed 9 years ago by
I'm sorry to hijack this ticket.
I've uploaded a simple_patch.diff that should is a quick and dirty way of sorting this out.
comment:6 Changed 9 years ago by
comment:7 Changed 8 years ago by
mtredinnick: sorry I wasn't explicit, but actually my plan was to commit only the tests, not the OP's patch. I haven't been able to reproduce the issue even though I use FR_fr on my servers.
comment:8 Changed 8 years ago by
Changed 8 years ago by
Tests against Django 1.1 trunk rev 11368
Changed 8 years ago by
Verbose Log output on running model_regress test which fails
comment:9 Changed 8 years ago by
I understand what's failing, but I don't understand what are you trying to achieve by using setlocale. Do you use it for displaying data on templates, and then you get errors from the db?
If that's the case, we should close this ticket as invalid, so the problem is not in Django, but in your code. As Malcolm says, you can't use setlocale in Django. Of course another ticket about being able to change number formats on Django would be correct. Actually it's not necessary, so this is already possible on the i18n branch.
comment:10 Changed 7.
short work-around for DecimalField format problems in db_prep methods | https://code.djangoproject.com/ticket/6783 | CC-MAIN-2017-09 | refinedweb | 635 | 64.81 |
/* $NetBSD: ulp.c,v 1.2 2006/01/25 15:27:42 kleink Exp $ */ /**************************************************************** The author of this software is David M. Gay. Copyright (C) 1998, 1999" double ulp #ifdef KR_headers (x) double x; #else (double x) #endif { Long L; double a; L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1; #ifndef Sudden_Underflow if (L > 0) { #endif #ifdef IBM L |= Exp_msk1 >> 4; #endif word0(a) = L; word1(a) = 0; #ifndef Sudden_Underflow } else { L = (unsigned int)-L >> Exp_shift; if (L < Exp_shift) { word0(a) = 0x80000 >> L; word1(a) = 0; } else { word0(a) = 0; L -= Exp_shift; word1(a) = L >= 31 ? 1 : 1 << (31 - L); } } #endif return a; } | http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/gdtoa/ulp.c?rev=1.2&content-type=text/x-cvsweb-markup&sortby=rev&only_with_tag=mjf-devfs2 | CC-MAIN-2021-17 | refinedweb | 102 | 59.67 |
27 August 2012 18:05 [Source: ICIS news]
HOUSTON (ICIS)--?xml:namespace>
Market activity was mostly held to trade discussions, as no fresh trades have been confirmed.
Trade sources said mixed xylene (MX) and toluene spot prices were moving higher, while benzene prices were stable.
Mixed xylene (MX) spot was bid at $3.99/gal FOB (free on board) for August and at $3.95/gal FOB for September, which was up from Friday’s prompt range of $3.85-4.00/gal.
Nitration-grade (n-grade) toluene prices were heard at $4.01-4.05/gal FOB on Friday, but trade sources said the market was stronger.
Benzene spot levels were stable at $4.19-4.25/gal FOB from the previous session.
One trade source said that benzene prices may have already been inflated, which may be why there was not much reaction in that market.
Although there have been some refinery and chemical shutdowns and productions are taking precautions ahead of Isaac, there have been no major aromatics production | http://www.icis.com/Articles/2012/08/27/9590146/us-aromatics-steady-to-stronger-ahead-of-isaacs-impact-on-us-gulf.html | CC-MAIN-2013-48 | refinedweb | 172 | 75.71 |
Slimming down our API Controller code
First off, our original plan was to show iTunes music information. So let’s modify the API controller to better handle this information. Before we start making changes I want to simplify the class. We’re going to use the sendAsynchronousRequest we learned about in part 5, and slim down our API controller. To do that, let’s remove the following functions:
func connection(connection: NSURLConnection!, didFailWithError error: NSError!) func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { func connection(connection: NSURLConnection!, didReceiveData data: NSData!) { func connectionDidFinishLoading(connection: NSURLConnection!) {
Also we won’t be needing our mutable data object any more, so let’s remove that too:
var data: NSMutableData = NSMutableData()
Finally, in our searchItunesFor() function, let’s remove the part that creates and sends the request
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false) connection.start()
And replace that with the following:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in if error? { println("ERROR: (error.localizedDescription)") } else { var error: NSError? let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary // Now send the JSON result to our delegate object if error? { println("HTTP Error: (error?.localizedDescription)") } else { println("Results recieved") self.delegate?.didRecieveAPIResults(jsonResult) } } })
What we’ve done here is removed our Protocol-Delegate functions, and instead opted to use the more functional API, sendAsynchronousRequest. What’s happening here is the function is sending our ‘request’ object as a parameter to sendAsynchronousRequest, on the main queue, with a completion handler which is another function. When the request is done it calls our inline function, which checks for an error and logs it to the console if there is one. If there is no error, it then converts the result in to a JSON NSDictionary, and passes it back to our delegate after checking if the JSON was parsed successfully. That’s quite a bit of replaced code, and it’s the kind of thing we have to look forward to when working with the newer APIs designed for a functional approach to iOS development.
In a part 3 Part 3: Developing iOS8 Apps Using Swift – Best Practices when we created this class, we inherited from NSObject, but this isn’t necessary. So modify the class definition to look like this:
class APIController {
What this does change however, is now we don’t have an init method! So let’s add one, and let’s make sure it includes the delegate. An API Controller without a delegate isn’t all that useful, so why even offer the option to make one?
init(delegate: APIControllerProtocol?) { self.delegate = delegate }
Now in our SearchResultsController, we need to change a few things. First of all we need to make the api an optional, because we can’t pass self in the initializer. Where we have our declaration of ‘api’ now we need to swap out for this:
var api: APIController?
This says we have an object called api who is of type APIController, but it may be nil.
Then, in viewDidLoad we need to instantiate the api.
self.api = APIController(delegate: self)
There’s no longer any need to set the delegate on a separate line, our init method now handles that automatically.
Creating a Swift model for iTunes Albums
Let’s also modify our call to the searchItunesFor() method to use a search term for music, and adjust it so that it forces unwrapping of the api object by adding a ! to the end. We do this because we just created api and we know it exists. We’ll also show a networkActivityIndicator, to tell the user a network operation is happening. This will show up on the top status bar of the phone.
UIApplication.sharedApplication().networkActivityIndicatorVisible = true self.api!.searchItunesFor("Bob Dylan");
Now in our urlPath in the APIController, let’s modify the API parameters to look specifically for albums.
var urlPath = "\(escapedSearchTerm)&media=music&entity=album"
Great! Now we have a much cleaner API Controller with a lot less code!
We need a model!
In order to facilitate passing around information about albums, we should create a model of what an album is exactly. Create a new swift file and call it Album.swift with the following contents:
class Album { var title: String? var price: String? var thumbnailImageURL: String? var largeImageURL: String? var itemURL: String? class, it just holds a few properties about albums for us. We create the 6 different properties as optional strings, and add an initializer that requires each on be unwrapped before use. The initializer is very simple, it just sets all the properties based on our parameters.
So now we have a class for album objects, let’s use it!
Using our new Swift Album model
Back in our SearchResultsController, let’s remove the tableData NSArray variable, and instead opt for a Swift native array for Albums. In swift, this is as easy as:
var albums: Album[] = []
This creates an empty array containing exclusively:
let album = self.albums[indexPath.row] cell.text = album.title cell.image = UIImage(named: "Blank52") cell.detailTextLabel.text = album.price
And a little later where we grab the thumbnail, swap out the urlString setter with this:
let urlString = album.thumbnailImageURL
Some of you may have noticed that our image sometimes are buggy, and overwrite each other. This is happening due to cell re-use. I’ve modified the code to check for the existence of the cell in question (which implies it’s visibility) which can be seen within our sendAsynchronousRequest function. It’s a big block of code so here is a gist with the swift code in.
Creating Album objects from JSON
Now, all of this is not much use if we aren’t creating our album information in the first place. We need to modify our didRecieveAPIResults method to take album results, create them from the JSON response, and save them in to the albums array. The final method should look like this:
func didRecieveAPIResults(results: NSDictionary) { // Store the results in our table data array if results.count>0 { let allResults: NSDictionary[] = results["results"] as NSDictionary[] // Sometimes iTunes returns a collection, not a track, so we check both for the 'name' for result: NSDictionary in allResults { var name: String? = result["trackName"] as? String if !name? { name = result["collectionName"] as? String } // Sometimes price comes in as formattedPrice, sometimes as collectionPrice.. and sometimes it's a float instead of a string. Hooray! var price: String? = result["formattedPrice"] as? String if !price? { price = result["collectionPrice"] as? String if !price? { var priceFloat: Float? = result["collectionPrice"] as? Float var nf: NSNumberFormatter = NSNumberFormatter() nf.maximumFractionDigits = 2; if priceFloat? { price = "$"+nf.stringFromNumber(priceFloat) } } } let thumbnailURL: String? = result["artworkUrl60"] as? String let imageURL: String? = result["artworkUrl100"] as? String let artistURL: String? = result["artistViewUrl"] as? String var itemURL: String? = result["collectionViewUrl"] as? String if !itemURL? { itemURL = result["trackViewUrl"] as? String } var newAlbum = Album(name: name!, price: price!, thumbnailImageURL: thumbnailURL!, largeImageURL: imageURL!, itemURL: itemURL!, artistURL: artistURL!) albums.append(newAlbum) } self.appsTableView.reloadData() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } }
This may look like a lot of new code, but what’s happening here is actually very simple. First, we’re grabbing an NSDictionary of the results key from the API results, which contains all our albums info.
let allResults: NSDictionary[] = results["results"] as NSDictionary[]
Then, we loop through every nested dictionary in allResults, assigning each element to a temporary variable named result by using the iOS8 Swift’s for-each syntax:
for result: NSDictionary in allResults {
Next you’ll see lots of this happening:
var name: String? = result["trackName"] as? String if !name? { name = result["collectionName"] as? String }
What’s happening here is that iTunes is using a different key for tracks vs albums. So all these fields should be declared as optionals, and we should check for both so at least one of them gets saved. This may be important for your app if you opted to use a different media type.
Finally after formatting all our information and validating that it all exists, we create our new album, and add it to our albums array:
var newAlbum = Album(name: name!, price: price!, thumbnailImageURL: thumbnailURL!, largeImageURL: imageURL!, itemURL: itemURL!, artistURL: artistURL!) albums.append(newAlbum)
Now that that’s taken care of, we reload our table view and turn off the network activity indicator
self.appsTableView.reloadData() UIApplication.sharedApplication().networkActivityIndicatorVisible = false Xcode 6push’, a title Label, a button, and a text view. Drag all of these objects out of the object library and arrange them any way you like on the new view. Please note that before you do this, in Xcode 6 there is a concept of size classes. For our purposes, we just need to set the size class to iPhone. At the bottom of the window you’ll see something that might say something like ‘wAny hAny’. This is the current size class for the storyboard. If you’ve been wondering why your views are square, this is why. Click this and change it to represent iPhone portrait by setting it to ‘Compact Width | Any Height’.) { var albumCover : UIImageView
We just created a new IBOutlet, and now it’s connected to our storyboard’s DetailsViewController. How cool is that?
Do the same thing for the rest of the objects you added to your view. Next, let’s modify viewDidLoad so that it will load in the info we’re being passed to our view objects, here’s the final DetailsViewController code:
import UIKit class DetailsViewController: UIViewController { @IBOutlet var albumCover : UIImageView @IBOutlet var titleLabel : UILabel @IBOutlet var detailsTextView : UITextView @IBOutlet var openButton : UIButton var album: Album? (@jquave) that you pulled it off! You are well on your way to creating real iOS applications with Swift.
What's Next....
In the next part, we set up a full Detail view with a working music player, and implement some great animations. Stay tuned! | https://www.ios-blog.com/tutorials/swift/developing-ios8-apps-using-swift-part-6-interaction-with-multiple-views/ | CC-MAIN-2018-13 | refinedweb | 1,647 | 57.16 |
When building content for the web, you might need to communicate with other elements on your web page. Or you might want to implement functionality using Web APIs which Unity does not currently expose by default. In both cases, you need to directly interface with the browser’s JavaScript engine. provides different methods to do this.
The recommended way of using browser JavaScript in your project is to add your JavaScript sources to your project, and then call those functions directly from your script code. To do so, place files with JavaScript code using the .jslib extension under a “Plugins” subfolder]); }, });
Then you can call these functions from your C# scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary like this:
using UnityEngine; using System.Runtime.InteropServices; public class NewBehaviourScript : MonoBehaviour { [DllImport("__Internal")] private static extern void Hello(); [DllImport("__Internal")] private static extern void HelloString(string str); [DllImport("__Internal")] private static extern void PrintFloatArray(float[] array, int size); [DllImport("__Internal")] private static extern int AddNumbers(int x, int y); [DllImport("__Internal")] private static extern string StringReturnValueFunction(); [DllImport("__Internal")] private static extern void BindWebGLTexture(int texture); void Start() { Hello(); HelloString("This is a string."); float[] myArray = new float[10]; PrintFloatArray(myArray, myArray.Length); int result = AddNumbers(5, 7); Debug.Log(result); Debug.Log(StringReturnValueFunction()); var texture = new Texture2D(0, 0, TextureFormat.ARGB32, false); BindWebGLTexture(texture.GetNativeTextureID()); } }
Simple numeric types can be passed to JavaScript in function parameters without requiring any conversion. Other data types will be passed as a pointer in the emscripten heap (which is really just a big array in JavaScript). For strings, you can use the
Pointer_stringify helper function to convert to a JavaScript string. To return a string value you need to call
_malloc to allocate some memory and the
stringToUTF8 helper function to write a JavaScript string to it. If the string is a return value, then the il2cppA Unity-developed scripting back-end which you can use as an alternative to Mono when building Projects for some platforms. More info
See in Glossary runtime will take care of freeing the memory for you. For arrays of primitive types,
emscripten provides different
ArrayBufferViews into it’s heap for different sizes of integer, unsigned integer or floating point representations of memory: HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64. To access a texture in WebGL, emscripten provides the
GL.textures array which maps native texture IDs from Unity to WebGL texture objects. WebGL functions can be called on emscripten’s WebGL context,
GLctx.ObjectsThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary in your project - it will automatically get compiled with your scripts, and you can call functions from it, just like in the JavaScript example above.
If you are using C++ (.cpp) to implement the plugin then you must ensure the functions are declared with C linkage to avoid name mangling using gameInstance.Module.
2017–11–14 Page amended
Fixed error in code example.
Updated in 5.6 | https://docs.unity3d.com/2018.4/Documentation/Manual/webgl-interactingwithbrowserscripting.html | CC-MAIN-2022-27 | refinedweb | 542 | 54.42 |
Recently I installed my gaming notebook with Ubuntu 18.04 and took some time to make Nvidia driver as the default graphics driver ( since the notebook has two graphics cards, one is Intel, and the other is Nvidia). I do not want to talk about the details of installation steps and enabling Nvidia driver to make it as default, instead, I would like to talk about how to make your PyTorch codes to use GPU to make the neural network training much more faster.
Below is my graphics card device info.
Check if GPU is available on your system
We can check if a GPU is available and the required NVIDIA drivers and CUDA libraries are installed using torch.cuda.is_available.
import torchtorch.cuda.is_available()
If it returns True, it means the system has Nvidia driver correctly installed. initialized with either of the following inputs.
- cpu for CPU
- cuda:0 for putting it on GPU number 0. Similarly, if your system has multiple GPUs, the number would be the GPU you want to pu tensors on
Generally, whenever you initialize a Tensor, it?s put on the CPU. You should move it to the GPU to make the related calculation faster.
if torch.cuda.is_available(): dev = “cuda:0” else: dev = “cpu” device = torch.device(dev) a = torch.zeros(4,3) a = a.to(device)
cuda() function
Another way to put tensors on GPUs is to call cuda(n) a function on them where n is the index of the GPU. If you just call cuda, then the tensor is placed on GPU 0.
The torch.nn.Module class also has to add cuda functions which put the entire network on a particular device. Unlike, Tensors calling to on the nn.Module the object is enough, and there’s no need to assign the returned value from the to function.
clf = myNetwork() clf.to(torch.device(“cuda:0”))
Make sure using the same device for tensors the call are put on GPU 0, but this can be changed by the following statement if you have more than one GPU.
torch.cuda.set_device(0) # or 1,2,3
If a tensor is created as a result of an operation between two operands which are on the same device, so the operation will work out. If operands are on different devices, it will lead to an error.
That?s the main ways to put the data operation on GPU. If you don?t have one, use Google Colab can be an option. Anyway, below codes can be used to see your running environment info regarding Cuda and devices information. Try them on your jupyter notebook
import torchimport sysprint(‘__Python VERSION:’, sys.version)print(‘__pyTorch VERSION:’, torch.__version__)print(‘__CUDA VERSION’, )from subprocess import call# call([“nvcc”, “–version”]) does not work! nvcc –versionprint(‘__CUDNN VERSION:’, torch.backends.cudnn.version())print(‘__Number CUDA Devices:’, torch.cuda.device_count())print(‘__Devices’)# call([“nvidia-smi”, “–format=csv”, “–query-gpu=index,name,driver_version,memory.total,memory.used,memory.free”])print(‘Active CUDA Device: GPU’, torch.cuda.current_device())print (‘Available devices ‘, torch.cuda.device_count())print (‘Current cuda device ‘, torch.cuda.current_device())
And this one is for finding out the exact device information of your graphics driver
!pip install pycudaimport torchimport pycuda.driver as cudacuda.init()## Get Id of default devicetorch.cuda.current_device()# 0cuda.Device(0).name() # ‘0’ is the id of your GPU
And here is the output from my desktop and my Colab environment
| https://911weknow.com/use-gpu-in-your-pytorch-code | CC-MAIN-2022-40 | refinedweb | 575 | 59.3 |
RationalWiki:Saloon bar/Archive255
Contents
- 1 More techs
- 2 Criminology
- 3 What is this fallacy?
- 4 Trump
- 5 Playing around with Rationalwiki's CSS
- 6 Help TYT host the next Democratic debate
- 7 We've Been Debunked!
- 8 ...Is this real life? ...Is this just fantasy?
- 9 "RationalWiki vs Wikipedia"
- 10 Another public service announcement
- 11 MSitB cover story nom
- 12 April Fools
- 13 Bronze Articles?
- 14 MediaWiki:Ipbreason-dropdown and MediaWiki:Deletereason-dropdown
- 15 The consensus on privacy and the encryption debate
- 16 From the makers of God's Not Dead and God's Not Dead 2
- 17 What are some good shows to watch?
- 18 Ali Sina
- 19 By The Numbers - The Untold Story of Muslim Opinions & Demographics
- 20 African arrival to London
- 21 Monthly stats
- 22 RW 1.0?
- 23 Vote:
- 24 Block appeal
- 25 Introducing myself
- 26 Jesusandmo
- 27 Help debating against a pro-flat taxxer
- 28 Is there any way to get out of the bin?
- 29 I have been here before...
- 30 My Faith in Science
- 31 SpaceX Conspiracy Theories?
- 32 Potential coup of Phyllis Schlafly from the Eagle Forum
- 33 GMail is randomly accepting rationalwiki.org email, or not
- 34 Mission survey
- 35 Hilarious Atheist Breakdown
- 36 Poll on hatnotes for the GG trio of articles
- 37 Anyone want a giggle ...
- 38 Community Standards change
- 39 The Kalaam Argument Against God
- 40 For the record - to those who still care about that
- 41 Protect the Saloon Bar from the internet!
- 42 So... how to do suggestions?
- 43 Category bans
- 44 WIGO:Vandalism
- 45 Ghosts (not!)
- 46 Are we ever going to be fixing gadgets?
- 47 Stormfront Knowledge
- 48 The Sanders article is reading like from some alternate reality
- 49 The 1960 Presidential election
- 50 USA saint's day
- 51 Good Yontif everybody.
- 52 Bernie Sanders article
- 53 Bob Beck Blood Electrification Woo
- 54 so why is it called rational wiki
- 55 Men's rights portal
- 56 Dragon Age series
- 57 Gitmo
- 58 Philosophy of science icon
- 59 Hastert - biggest political scandal in the history of the Republic?
- 60 "But no one who posts RationalWiki as a source should be taken seriously"
- 61 Animal Rights
- 62 Can I make an article on al-Farabi?
- 63 Trump is a much better advocate for poor citizens compared to Obama
- 64 Robert Maydole's Ontological argument
- 65 We need you!
More techs[edit]
We're a bit low on techs.
- Armondikov (inactive)
- Bertran (inactive)
- David Gerard [active]
- FuzzyCatPotato [active]
- Gooniepunk (inactive)
- Ikanreed (inactive)
- John Jacob Jingleheimer Schmidt (inactive)
- NoiseBot (inactive)
- Nutty Roux (inactive)
- Tmtoulouse (inactive)
- Tyrannis (inactive)
- ZooGuard (inactive)
- Π (inactive)
People who could make themselves techs but haven't:
- 142․124․55․236 [active]
- Human (inactive)
- ScepticWombat [active]
- Weaseloid [active]
Techs can edit the Special:AbuseFilters, MediaWiki-space, and other pages that help make RW run.
The abuse filter is especially relevant. RW has been being hit with an IP-hopping vandal who posts personal information but has few consistent patterns of vandalism. This makes it difficult to filter out every edit they might make, but a regularly-updated abuse filter makes it increasingly more annoying for them to vandalize. However, I'm basically the only one running the filter at the moment, and the vandal has gotten maybe 100 vandalized edits in. Thus:
I would like to add about 4 new techs.
1: Are people OK with this? 2: How should these techs be selected? αδελφός ΓυζζγςατΡοτατο (talk/stalk) 19:45, 22 March 2016 (UTC)
- Wasn't CarpetSmoker ever a tech? Huh. Well, he would be listed as inactive if he were, anyhow (cause LANCB). Reverend Black Percy (talk) 19:48, 22 March 2016 (UTC)
- Past tense indeed ;-) Apparently RationalWiki thought it was a good idea do nothing when the last who actually did anything was bullied away. Ah well... Carpetsmoker (talk) 20:45, 22 March 2016 (UTC)
- WeaseloidMethinks it is a Weasel 00:57, 24 March 2016 (UTC)
- Hey buddy! Glad to see you posting. Reverend Black Percy (talk) 20:47, 22 March 2016 (UTC)
- Also, for the record, I think this is a great idea. How about Owlman and/or JorisEnter? They're good guys (just to name two). Reverend Black Percy (talk) 19:49, 22 March 2016 (UTC)
- I think it may be a good idea. ℕoir LeSable (talk) 19:57, 22 March 2016 (UTC)
- I dunno really how the abuse filters work, though, so I wouldn't be much use as a tech. Are there any techy individuals that want to volunteer for the position? 142.124.55.236 (talk) 21:12, 22 March 42016 AQD (UTC)
- So... Will all moderators be techs then? Or can you be a tech without being a mod?
- Also I nominate weasel! StickySock (talk) 21:34, 22 March 2016 (UTC)
- Nah, as Fuzzy's first list illustrates, there's plenty of non-mod techs. They're just not very active. :/ 142.124.55.236 (talk) 22:03, 22 March 42016 AQD (UTC)
- I feel honoured by RBP's recommendation, but I really don't know much about the technical stuff at all. I can do some Python, but my skills are limited to what a first year astronomy undergrad needs to survive.--JorisEnter (talk) 23:32, 22 March 2016 (UTC)
- For what it's worth, you've earned it buddy. Reverend Black Percy (talk) 03:26, 23 March 2016 (UTC)
Re: Difficulty: It's extremely simple. The already-existing filters can mostly just be copy-pasted or expanded. It's not even a programming language proper. For example, the "blanking articles" filter is an entire 6 lines of text long. If you're worried, MediaWiki has a very helpful guide for the rules formats. And there's me to help! Fuzzy "Cat" Potato, Jr. (talk/stalk) 23:47, 22 March 2016 (UTC)
- I'm only inactive in terms of like edits. Anyone who needs anything can drop a message on my account. ikanreed You probably didn't deserve that 20:54, 27 March 2016 (UTC)
Potential techs[edit]
People seem OK with more techs. Here are some I had in mind: FU22YC47P07470 (talk/stalk) 23:55, 22 March 2016 (UTC)
- Carpetsmoker (if he ever comes back)
- JorisEnter
- Owlman
- Throw me in. I've already made the mediawiki upgrade package for when Dave gets to it. Zero (talk - contributions) 01:04, 23 March 2016 (UTC)
- Meh, I do basic coding at work all day anyway. Would nice to get rid of those damn "WINDOWS CUSTOMER SUPPORT" bullshit popups. CorruptUser (talk) 01:08, 23 March 2016 (UTC)
- So what kind of rights do techs have?--Owlman (talk) (mail) 06:03, 23 March 2016 (UTC) 06:03, 23 March 2016 (UTC)
- The chief thing is the ability to modify site-wide CSS and JS. What this means is that basically any tech can steal your account if they so desired. That's probably the best reason not to make everyone a tech ;-) There are also some things like modifying the AbuseFilter and seeing deleted revs that are invisible to sysops... It's not that exciting, and basically it's just a "super janitor" status ;-) Carpetsmoker (talk) 08:55, 23 March 2016 (UTC)
- I don't mind poking at filters and stuff. I spend time at work messing with regexes, so it's soup and nuts, really. Queexchthonic murmurings 12:29, 23 March 2016 (UTC)
I could always try to keep the edit filter updated, I suppose. We'll see how it goes.--JorisEnter (talk) 14:17, 23 March 2016 (UTC)
Final list[edit]
As Carpetsmoker noted, techs have the ability to affect things site-wide. Does anyone have any final objections to anyone on this list?
Herr FuzzyKatzenPotato (talk/stalk) 15:15, 23 March 2016 (UTC)
- No objections from me - on the contrary, I would easily go as far as to endorse everyone on that list. Looking forward to us having more tech staff on hand! Reverend Black Percy (talk) 15:27, 23 March 2016 (UTC)
- To be honest, I could see you on that list as well. You've done a good job reverting and blocking the recent vandalism.--JorisEnter (talk) 15:29, 23 March 2016 (UTC)
- Thanks for the vote of confidence, buddy! I'm just doing what I can to help the community. Reverend Black Percy (talk) 20:44, 23 March 2016 (UTC)
- Looks fine by me. Are they all interested in the job, though? 142.124.55.236 (talk) 16:00, 23 March 42016 AQD (UTC)
- Queex has expressed his willingness to take the job, as have I. Owlman has not explicitly stated that he'll take it, but I have not seen him refuse it either. I believe that Zero and CU have not responded yet.--JorisEnter (talk) 16:04, 23 March 2016 (UTC)
- EDIT: O wait, CU and Zero have said they'd take the job.--JorisEnter (talk) 18:56, 23 March 2016 (UTC)
These persons have been tech'd. Herr FuzzyKatzenPotato (talk/stalk) 17:35, 24 March 2016 (UTC)
Criminology[edit]
I think we should start a project on criminology. There is a whole host of pseudoscience, racial prejudice, and authoritarian misuse within the field.--Owlman (talk) (mail) 02:02, 26 March 2016 (UTC) 02:02, 26 March 2016 (UTC)
- Hell yes! ClickerClock (talk) 02:29, 26 March 2016 (UTC)
- Well there is a criminology wiki, but it doesn't appear to have a lot of regular, contributing users.--Owlman (talk) (mail) 02:38, 26 March 2016 (UTC) 02:38, 26 March 2016 (UTC)
- Which is why we should do it. There's not much information on that wikia. ClickerClock (talk) 02:54, 26 March 2016 (UTC)
- A criminology woo article would be good, yes. It could link up with racial profiling or psychic detection. Flannan Isle (talk) 18:31, 27 March 2016 (UTC)
- Wait a minute - why do we not have a psychic detection article? People have been put in jail because of that crap. Flannan Isle (talk) 18:34, 27 March 2016 (UTC)
- Cool idea! ClickerClock (talk) 02:00, 28 March 2016 (UTC)
What is this fallacy?[edit]
Recently, I read a debate with an apologist, after the apologist's last argument (an argument from ignorance) was refuted, they wrote the following:
The problem is when the ignorance is intentional when wahy is rejected. Wahy, or divine communication, is Allah's communication with mankind. What is derived from wahy can explain many things that are gaps and nonGaps. Just because we use tools to understand natural processes and materials better does not automagically exclude the Creator's hand in the existence of those processes and materials. This is where the God of the Gaps category of fallacies is biased against wahy whereas Muslims are convinced in what wahy has brought.
When is was pointed out that all religions say this, the apologist basically repeated their stance in a more direct fashion:
Allah guides through the heart of a human being and does not guide those who are puffed up with pride in their own logic and reasoning. The test of this life is listening to the heart (spiritual heart) through which Allah guides, and to confirm it through knowledge transferred through wahy which is given only to Prophets. After combining these two channels of knowledge, the open-minded and unbiased person should be on guidance. Its the job of wahy to also explain who is also not on guidance.
This type of "open your heart" argument is always employed by the religious, but I'm wondering exactly what fallacies are at play here. It seems to be a combination of an argument from assertion and circular reasoning. Any thoughts? Lord Aeonian (talk) 19:25, 28 March 2016 (UTC)
- Aside from the obvious appeal to emotion tucked into "open your heart", to me, the constant reference to this non-existant "wahy" that everyone should listen for but not everyone gets to hear sounds exactly like an example of other ways of knowing. Which is, bullshit. It also appears to quite literally be a form of revelation - again, bullshit. Reverend Black Percy (talk) 19:59, 28 March 2016 (UTC)
- Possibly related articles: Self projection as god and Authenticity of divine revelation. Reverend Black Percy (talk) 20:04, 28 March 2016 (UTC)
- The fallacy is ultimately one of special pleading or circular logic. He says that Allah reveals truth only to the Prophets -- but how can we know that Muslim prophets are the true ones, and the Hindu prophets weren't the ones getting the truth? oʇɐʇoԀʇɐϽʎzznℲ (talk/stalk) 23:10, 28 March 2016 (UTC)
- You both have good responses, but let me just clarify a bit - wahy is an Arabic word that means "revelation." It can mean two things - the "revelation" of Allah to Prophets, such as the Qur'an, and the personal revelation, i.e. "open your heart." The apologist is refering to the first kind in the first paragraph, and the second kind in the second. He had made a god of the gaps fallacy, and was basically trying to say the Qur'an was what gave Islam support; hence why he said "The problem is when the ignorance is intentional when wahy is rejected." So, an argument from assertion in my book. Lord Aeonian (talk) 00:29, 29 March 2016 (UTC)
- Given what you say, might fall under equivocation. FuzzyCatPotato!™ (talk/stalk) 00:45, 29 March 2016 (UTC)
- No, they were referring to the Qur'an (wahy #1) in the first response as evidence for Islam, when this was refuted they made the "open your heart" argument (wahy #2). Wahy can refer to both, but the context for each was clear. Lord Aeonian (talk) 01:15, 29 March 2016 (UTC)
- I always respond to these arguments by asking about how they know that they aren't getting their info from Satan? Specifically things like "can Satan's followers write books? Can they copy a bible and change words around; this would explain why there are so many different versions of the bible. So how do you know your version isn't yet another adultered one?" You'll get lots of screaming and little productive, of course, but it's a good way to get them to leave you alone. CorruptUser (talk) 02:11, 29 March 2016 (UTC)
Trump[edit]
Is there any opposition to making the Donald Trump page at least a Bronze? Perhaps it should also be given a priority rating since he is the likely GOP nominee? Bongolian (talk) 05:11, 18 March 2016 (UTC)
- Can we create a special orange level just for Trump? Maybe add some gold plating too, really class up the joint. --Ymir (talk) 10:22, 18 March 2016 (UTC)
- Hell, just call the level Trump. That'd really help build his brand - Kitsunelaine 「SJW Illuminati shill.」 10:39, 18 March 2016 (UTC)
- Is there like a home shopping level of gold? Where it looks expense till it turns out to just be cheap crap that contaminates everything it touches till all you are left with is a rash that doesn't go away. -EmeraldCityWanderer (talk) 14:36, 18 March 2016 (UTC)
- If we "help him build his brand" as Kitsunelaine said, he'll probably make us pay for it.'Legionwhat do you want from me 17:21, 18 March 2016 (UTC)
- I propose a Pyrite level for Trump. Petey Plane (talk) 17:36, 18 March 2016 (UTC)
- I propose a guacamole level, because it would annoy him. Flannan Isle (talk) 19:40, 18 March 2016 (UTC)
- Boy I sure do hate me some Trump. Maybe if I spend all my time talking about him and giving him more coverage and thus feeding his ego, that'll make him go away. CorruptUser (talk) 22:07, 19 March 2016 (UTC)
- OK, let's delete the page. Maybe Trump will go away. ;-) Bongolian (talk) 07:19, 20 March 2016 (UTC)
- polished turd. It has so many uses AMassiveGay (talk) 01:38, 20 March 2016 (UTC)
Playing around with Rationalwiki's CSS[edit]
You need to click to expend the screenshots. ClickerClock (talk) 02:28, 26 March 2016 (UTC)
- Does it look better? ClickerClock (talk) 02:55, 26 March 2016 (UTC)
- I'd say no. Narky Sawtooth (BoN is paranoid!) 05:59, 26 March 2016 (UTC)
- K. Does it look just as good? ClickerClock (talk) 03:03, 27 March 2016 (UTC)
- It makes the topquote bigger at the expense of visible text, and since this site basically lives on what it says rather than what it looks like, I think it's slightly worse.— Unsigned, by: username / talk / contribs
- Remember to sign your name. ClickerClock (talk) 01:59, 28 March 2016 (UTC)
- I tried,now I have marker pen on my screen. Flannan Isle (talk) 19:50, 29 March 2016 (UTC)
Help TYT host the next Democratic debate[edit]
I usually don't push for petitions, but I think it would be awesome to see the last Dem debate being hosted by a progressive news network. I think that this is an exciting prospect for not just TYT, but also both the candidates. If you are interested sign here.--Owlman (talk) (mail) 06:37, 26 March 2016 (UTC) 06:37, 26 March 2016 (UTC)
- The TYT has too many problems for me to support. FU22YC47P07470 (talk/stalk) 13:19, 26 March 2016 (UTC)
- Like what?---Mona- (talk) 14:26, 26 March 2016 (UTC)
- Cenk seems pretty avoidant about the Armenian genocide issue and their channel happens to share its name with the Turkish political movement that was behind said genocide. Some of their criticisms of conservative pundits are also not particularly well-considered and I've seen them engage in slutshaming among other things. 141.134.75.236 (talk) 16:17, 26 March 2016 (UTC)
- Yeah if you refuse to watch because their name is based on the Young Turk movement then I understand, but I don't blame the channel for whatever Cenk's views are on the Armenian genocide. I know they have had highly sexually comments, but I don't remember them slut-shaming though it wouldn't surprise me; I could guess the names of the hosts that would have slut-shamed.--Owlman (talk) (mail) 17:05, 26 March 2016 (UTC) 17:05, 26 March 2016 (UTC)
- When I google "The Young Turks slut shaming," all I get are youtube vids and stories about TYT hosting pieces against it. In light of that, and absent counter-evidence, I reject the claim that TYT engages in this practice. As for them making "ill-considered" comments about conservative pundits, I don't care. Finally, I'm aware that the Armenian genocide is a controversial, hot button topic, one about which I am pretty ignorant. So, I can't express an opinion. Tho, I've read that last year Cenk dealt with this topic on TYT. ---Mona- (talk) 18:43, 26 March 2016 (UTC)
- For all of TYT's faults, I still highly support this potential debate because I believe the staff would be ambitious to press Clinton on issues which all of the mainstream news outlets wouldn't. But that's also the reason I think the DNC wouldn't consider it because they might believe a TYT debate could make Hillary look bad and it's no mystery the TYT crew are totally enamored with Bernie. But if the DNC declines it would still be a loss for Hillary anyway as they would have to go into verbal gymnastics to explain why they are afraid to let Hillary the supposed progressive candidate attend a debate hosted by a relatively progressive news show. ∈ NameThatNobodyTakes (✎) 22:15, 26 March 2016 (UTC)
- TYT isn't my fav, but hey an online debate sounds awesome! Sorry but I ain't american so I cant exactly do anything.ClickerClock (talk) 03:06, 27 March 2016 (UTC)
- I find their pro-Bernie fanboyism extremely annoying. They always criticize Hillary, but they never say anything negative about Bernie. When they do their "best line/worst line" videos covering Democratic debates, the best line is always Bernie's, and the worst line is always Hillary's (or at least by not Bernie), even when they say it was Hillary who won. So, I think you're right.--Кřěĵ (ṫåɬк) 03:37, 27 March 2016 (UTC)
I don't like the way Cenk emphasizes points with his voice. It gets extremely tiresome if you watch a couple of those videos in a row. A similar thing can be said of Kyle Kullinsky. Also, they are oversimplifying a lot of things (again, the same goes for secular talk) among other things with their talk of "corporatism" as somehow distinct from capitalism (which they seem to vaguely support) Pizzameister (talk) 16:04, 30 March 2016 (UTC)
- They are basically social democrats; I think that oversimplification and science illiteracy is rampant throughout the media so I wouldn't hold it as unique among TYT's correspondents.--Owlman (talk) (mail) 18:10, 31 March 2016 (UTC) 18:10, 31 March 2016 (UTC)
We've Been Debunked![edit]
... by a bunch of reposts some dude found.
Not sure where else to put this. Fuzzy "Cat" Potato, Jr. (talk/stalk) 17:17, 29 March 2016 (UTC)
- "It is a wiki run by autists, perverts and genuinely bat-shit insane atheists". ROTFLMAO.--JorisEnter (talk) 17:20, 29 March 2016 (UTC)
- Hey, i'm not autistic!Petey Plane (talk) 17:23, 29 March 2016 (UTC)
- Wow, a creationist declares reality has been debunked. Like that hasn't happened before to shit's and giggles of everyone involved. :-p -EmeraldCityWanderer (talk) 17:31, 29 March 2016 (UTC)
- Their "definition" for us is from an Urban Dictionary user called "Atheism is bullshit." lol, we must be dealing with masterdebators here. Lord Aeonian (talk) 22:05, 29 March 2016 (UTC)
Hilariously dumb find, FCP! More like this, plox. The guy in question would, based on that one blog post, appear to be;
- Not only a practicing Christian, but a staunch believer in the Gospels as relaying history
- A creationist
- A 9/11 truther
- A MGTOW supporter (or, atleast embeds one of their videos)
...and that's really just the beginning. Here's a list of the blogs operated by "JM Talboo", including Undebunking UFOs, Undebunking Bigfoot, Debunking Death and Time Travel Babble. If all of these blogs operated by this account were to represent the views of a single individual? Then holy shit, David Icke may just have met his match. I mean, if two RW articles mated and had this guy as their demented offspring, they'd be Crank magnetism and Fractal wrongness (possibly formed in a threesome with Conspiracy_theory#Unified_Conspiracy_Theory). Reverend Black Percy (talk) 22:20, 29 March 2016 (UTC)
- Wow, this guy is great...he seems to believe in every steaming pile of bullshit and wrote a verbal diarrhea that's as close to logic as I am a turnip. My mistake is to keep thinking that this is so utterly laugh out loud silly that he's got to be a Poe. -EmeraldCityWanderer (talk) 13:58, 30 March 2016 (UTC)
- Well, I mean, he is a Poe. Poe's Law does not mean that the person is in fact a parody; Poe's Law means that the person is so over the top extreme that he cannot be told apart from a hypothetical parody of himself. I've actually seen a lot of people mistakenly use Poe here, thinking that if somebody is a Poe, they're a fake (as in, if somebody is extreme enough they must be a parody). Which is incorrect. Glad to have helped! Reverend Black Percy (talk) 14:22, 30 March 2016 (UTC)
- Hummm, I agree there in the use of the law. It might be confusion on my part but I thought "A Poe" as the noun was to differentiate good parodies likely to be a joke and those who are actually nuttier than squirrel shit. From the article that concisely describes it: "In most cases, this is specifically in the sense of posts and people who are taken as legitimate, but are probably parody." -EmeraldCityWanderer (talk) 14:40, 30 March 2016 (UTC)
- Well, therein lies the problem to me. I argue that Poe's means "Any sufficiently extreme person or view will be indistinguishable from a parody of the same". Adding the part you quote from the article about likelyhood of examples being parody or not and such is not only wrong (as the vast majority of Poe's law examples are real people and opinions, not comedians and parody), but it also appears to be logically inconsistent with the law itself. Since the point of Poe's is that we cannot easily tell actual extremism from a parody of extremism, having a sentence in the article that says that "in most cases" and "are probably parody" is clearly logically inconsistent. We should amend the article so that the descriptive text actually follows the law it intends to describe. Reverend Black Percy (talk) 15:20, 30 March 2016 (UTC)
...Is this real life? ...Is this just fantasy?[edit]
How the hell don't we have an article on this guy yet? Even TOW finds him noteworthy! Reverend Black Percy (talk) 22:54, 29 March 2016 (UTC)
- I have no way of describing that. He appears to be a new age-y Christian, but he also performs faith healings and exorcisms. I can't understand why he is wearing that wig, but his Southern accent only makes his wig that much more ridiculous.--Owlman (talk) (mail) 00:38, 30 March 2016 (UTC) 00:38, 30 March 2016 (UTC)
- Caught in a landslide... Petey Plane (talk) 01:03, 30 March 2016 (UTC)
- No escape from reality... Pizzameister (talk) 17:57, 31 March 2016 (UTC)
- Except for the dear Mr. Spivey, who appears to already have left it way behind... Reverend Black Percy (talk) 18:00, 31 March 2016 (UTC)
"RationalWiki vs Wikipedia"[edit]
Apparently we've got a Swedish fan. Google-translated. The FCP Foundation (talk/stalk) 16:37, 31 March 2016 (UTC)
- Forget that silly translate link - I'll do the honors of translating once I'm no longer editing from my phone. That guy seems nice and he really liked the site, anyways. I ought to ask him to sign up. Good find, FCP! Reverend Black Percy (talk) 16:43, 31 March 2016 (UTC)
- No longer on my phone! Here we go;
- (Then there's a few examples that are already in english.)
- (Then there's a few examples that are already in english.)
- Something like that. Reverend Black Percy (talk) 17:11, 31 March 2016 (UTC)
- Someone recently argued Finnish was a dying language because (almost) all Finns know English... Notice how this text was written in Swedish, a similarly obscure language as Finnish? Pizzameister (talk) 18:02, 31 March 2016 (UTC)
- Though, Swedish is easily not as obscure as Finnish is when we compare the two to English. Swedish is a germanic language (like English), but Finnish is a uralic language. Reverend Black Percy (talk) 18:04, 31 March 2016 (UTC)
- It seems that I can actually understand a few words here and there - Swedish is a bit like Dutch.--JorisEnter (talk) 18:14, 31 March 2016 (UTC)
- Again, Dutch is also germanic. Now, try reading some finnish... Reverend Black Percy (talk) 18:17, 31 March 2016 (UTC)
- Let's start with the fact that they call their own country "Suomi".--JorisEnter (talk) 18:20, 31 March 2016 (UTC)
Another public service announcement[edit]
To move a page, don't copy-and-paste it. Use MediaWiki's page move feature. For information, see our help page, and the MediaWiki manual. I'm posting this because I just saw yet another person do a copy-and-paste. --Ymir (talk) 22:05, 31 March 2016 (UTC)
- If you're talking about people working on a draft article in their userspace & then copy-pasting it to article space, I don't see how that is a problem. WeaseloidMethinks it is a Weasel 22:09, 31 March 2016 (UTC)
MSitB cover story nom[edit]
The nomination for Modern Science in the Bible has been out there for more than a month, with a grand total of two replies (one by FCP about a minor wording fix, one by RBP saying that he couldn't find any problems). Anyone else got comments? (see the talk page).--JorisEnter (talk) 12:58, 28 March 2016 (UTC)
- As it's a single-author piece on an obscure topic, I don't think it would make a particularly good showcase or entry point to be featured on the site homepage. Those quotes at the top of page are also an awful way to start an article on an obscure topic. Start by explaining what it is; not with what people we've never heard of say about. WėąṣėḷőįďMethinks it is a Weasel 13:16, 28 March 2016 (UTC)
- At any rate, surely we ought to consider upgrading it from Silver to Gold? Reverend Black Percy (talk) 13:25, 28 March 2016 (UTC)
- I must say that two quotes by theologians at the start of an article does not impress me. Two quotes by theologians I have never heard of impresses me even less. Two quotes by theologians I have never heard of giving me their opinions about a book I have never heard of doesn't really motivate me to read the article.
- I guess that some people might think that theologians opinions on this subject might carry weight - but it's rather like homeopaths criticizing chiropractors for me.--Bob"Life is short and (insert adjective)" 13:43, 28 March 2016 (UTC)
- I had never heard of either of them until I started writing this article (and in doing some Google searches happened to stumble upon Smedes's blog post in which he points out Hobrink's plagiarism), but Smedes appears to be kind of well known in Dutch theology circles (though I suppose none of us are really into that). I thought these were some nice quotes about the book, but if anyone can find a better one than please replace it. As regards the single-author bit: that's why I would like other people to work on this article as well (though that's kind of hard given that it's about a book most of us probably don't have, but there's a link to a Google Books version at the bottom).--JorisEnter (talk) 13:57, 28 March 2016 (UTC)
- Don't replace the topqotes; take them out or incorporate them somewhere more appropriate in the text. "Modern Science in the Bible is a book by Dutch Young Earth creationist Ben Hobrink" should be the first thing readers see on this page, as most will be unfamiliar with the topic & reading a load of quotecruft first without knowing what it's talking about is just confusing. WẽãšẽĩõĩďMethinks it is a Weasel 15:48, 28 March 2016 (UTC)
Still support covering. Fuzzy. Cat. Potato! (talk/stalk) 14:27, 28 March 2016 (UTC)
- Me too; the article text is actually pretty great, for those of you who manage to get past the two quotes and actually read on at length before giving your verdict (not pointing any fingers). Weaseloid is right about the placement of the quotes, for the record - they belong baked into the article text or indeed as part of one of the final segments of the article, not in the intro. My two cents. Reverend Black Percy (talk) 16:32, 28 March 2016 (UTC)
- The quotes could be moved to the bottom, under "Accusations of plagiarism" or "Other criticism", but I rather like the idea of having some sort of introductory quote describing the book or its subject (the problem is that I can't find too much that fits).--JorisEnter (talk) 17:18, 28 March 2016 (UTC)
- EDIT: The longer of the two quotes has been moved to the relevant section, the shorter one can probably stay at the top.--JorisEnter (talk) 17:48, 28 March 2016 (UTC)
- I would still consider moving the shorter quote to another section of the article (especially if it will give your article frontpage status), e.g. just a small step down to the "General overview" segment or the "Dissecting the book" segment. The quote would also fit there, perhaps even better than at the top in my opinion. Just my two cents. Reverend Black Percy (talk) 18:33, 28 March 2016 (UTC)
- I agree that two quotes may have been a bit much (especially since the one that got moved was pretty long) but quite some other cover story articles have quotes at the top as well, including Atheism, Ray Comfort, Evolution, Genetically modified food and a bunch of others.--JorisEnter (talk) 18:47, 28 March 2016 (UTC)
- Of course - and a good article is often topped off with a great opening quote. I've easily added more than 50 opening quotes since I first joined last spring. However, Weaseloid literally said ""Modern Science in the Bible is a book by Dutch Young Earth creationist Ben Hobrink" should be the first thing readers see on this page", and BoB M seems to share that view. That's all. I'm just coming at this from the angle that getting the article rated Gold is in line with my own views of it. *shrugs* Reverend Black Percy (talk) 19:55, 28 March 2016 (UTC)
- I've relocated the other quote as well. It's currently under "Accusations of plagiarism", but it might be better in another location. Noch jemand was zu meckern?--JorisEnter (talk) 05:54, 29 March 2016 (UTC)
Considering the quotes have now been moved by JorisEnter, will Weaseloid et al further consider Gold status? Reverend Black Percy (talk) 10:20, 29 March 2016 (UTC)
- Weaseloid and Bob M mainly objected to the quotes, as far as I can see; FCP "supports covering".--JorisEnter (talk) 10:23, 29 March 2016 (UTC)
- We'll have to await updated comments from them before we can count them as either pro or con (considering the changes made in the article); however, I am to be counted among the pro votes since this discussion began. Thus, so far, we've got FCP, you and me supporting Gold status (that is, front page). Great job on the article buddy. Reverend Black Percy (talk) 10:34, 29 March 2016 (UTC)
- Thanks!--JorisEnter (talk) 10:42, 29 March 2016 (UTC)
I have also started some sort of cover abstract thingy at User:JorisEnter/Modern Science in the Bible. At the moment it's not much more than the first paragraph of the article, so if anyone's got something to add to it, feel free to do so.--JorisEnter (talk) 10:45, 29 March 2016 (UTC)
So[edit]
Any other comments? The voting appears to be 3 ayes (FCP, RBP and me), one nay-at-least-until-you-remove-those-quotes (Weaseloid; quotes have been relocated), and one voter whose position is not entirely clear (Bob M).--JorisEnter (talk) 13:45, 30 March 2016 (UTC)
- Just do it. If nobody got their knickers twisted enough to oppose, it's fine. Fuzzy "Cat" Potato, Jr. (talk/stalk) 15:28, 30 March 2016 (UTC)
- Ze cover abstract is done. As far as I can see, everything is ready for this page to be elevated to Cover Story level.--JorisEnter (talk) 15:54, 30 March 2016 (UTC)
You're putting words in people's mouths. My comment about the quotes was pointing out a problem with the article I noticed at first glance. My comment about the cover nomination was "As it's a single-author piece on an obscure topic, I don't think it would make a particularly good showcase or entry point to be featured on the site homepage". WěǎšěǐǒǐďMethinks it is a Weasel 18:49, 30 March 2016 (UTC)
- That's three ayes, one nay, and one unclear one.--JorisEnter (talk) 23:50, 30 March 2016 (UTC)
- All I can add here is a renewal of my "yes" vote. Also, since the quotes were moved, I think we ought to be extra lenient towards the addition from Joris. It's not like this article is being voted to be the exclusive frontpage; it'll simply be added to the batch of front page articles that exist already and a select portion of new visitors will have it shown as such. We need not discard work as diligent as this. Reverend Black Percy (talk) 01:56, 31 March 2016 (UTC)
- Also note that the article is not exclusively about this book: Hobrink uses many arguments that are regularly used by creationists (evolution can't add new information, micro but not macroevolution, etc) and in debunking his points, the article simultaneously takes on many standard creationist points as well. Our current articles on creationism and young Earth creationism are also kinda crap, so having an article on the front page that takes down a healthy amount of creationist crap won't hurt.--JorisEnter (talk) 09:18, 31 March 2016 (UTC)
Anyone else? It's currently still 3:1 in favour of golding.--JorisEnter (talk) 05:19, 1 April 2016 (UTC)
- As there was no response in the last 4
85 hours, I have upgraded the page to Cover story status (including editnotice and cover abstract).--JorisEnter (talk) 22:31, 1 April 2016 (UTC)
April Fools[edit]
What are some of your favorite April Fools pranks/jokes? Some of Blizzard's have been pretty good over the years. Lightning Dust (talk) 03:11, 1 April 2016 (UTC)
- Google Noose is the most notable April Fools joke for me.--Owlman (talk) (mail) 04:21, 1 April 2016 (UTC) 04:21, 1 April 2016 (UTC)
- this AMassiveGay (talk) 13:22, 1 April 2016 (UTC)
Bronze Articles?[edit]
Would anyone object if a couple of
my personal pets articles were upgraded to Bronze status?
- Horizontal gene transfer: Relatively missional, but not a core mission. Moderately fleshed out.
- Castration: A bit more missional, moderately sourced, but nowhere near gold level.
- Jeb Bush: At this point it's so fleshed out and missional I'd actually say the article is worthy of being silver.
- Glyphosate: Relatively missional since it's brought up constantly by the chemophobes, but not a core mission, fairly fleshed out.
CorruptUser (talk) 05:18, 1 April 2016 (UTC)
- The one on horizontal gene transfer is a bit short. The other three are worthy of bronze, I think.--JorisEnter (talk) 05:30, 1 April 2016 (UTC)
- These all appear worthy of bronze to me, especially Castration and Jeb Bush. Nice work, CorruptUser. Reverend Black Percy (talk) 10:35, 1 April 2016 (UTC)
- Heh, community did quite a bit of work too. Most of the work actually :P CorruptUser (talk) 12:19, 1 April 2016 (UTC)
- Well, credit where credit is due! But you helped! So you get yours too :3 Reverend Black Percy (talk) 12:33, 1 April 2016 (UTC)
MediaWiki:Ipbreason-dropdown and MediaWiki:Deletereason-dropdown[edit]
Weaseloid and I disagree what should be listed in the "block reason" and "deletion reason" dropdown menus. The difference:
Any preference? Mʀ. Wʜɪsᴋᴇʀs, Esϙᴜɪʀᴇ (talk/stalk) 13:07, 1 April 2016 (UTC)
- i'm not sure self explanatory terms need any explanatory text, unless to provide fuel for inevitable wikilawyering AMassiveGay (talk) 13:19, 1 April 2016 (UTC)
- I actually prefer the FCP version, for example, as a new editor, I wouldn't have such an easy process of understanding the ban reasons without those. Though on the other hand, isn't it correct that if you type text into the "extra" field when you have one of those options set, it'll show in that way anyhow? E.g. if we were to use Weaseloid's list to the left, and I'd pick one of them - say, "Spam" - and then type extra text, if I'd type "vandalizing or posting something over and over" in that field, wouldn't the final block log entry look about the same as FCP's "Spam" but with an empty extra text field? Because if the answer to that is "yes", then I'd actually stand to be convinced that Weaseloid's list might be better. I hope this question and example made sense, for the record. Reverend Black Percy (talk) 13:22, 1 April 2016 (UTC)
- the thing is, if we are going downto the road of defining the self explanatory, then the explainations should not be even vaguer? than the term being explained. For example, vandalizing is arguably more vague than spam. Also, what does 'attacking other users' entail? Does it include all forms of harrasment? I would argue that the terms wealoid uses on their own are well known enough to stand on their own, and broad enough to include all that they may encompass. AMassiveGay (talk) 14:09, 1 April 2016 (UTC)
- Mostly I wanted to define doxing; the others are more commonplace. Admittedly the definitions could be better; if you've suggestions, please provide. Herr FuzzyKatzenPotato (talk/stalk) 14:29, 1 April 2016 (UTC)
- [ec] Weaseloid quite properly put it back to status quo ante in my opinion. FCP's change smacks too much of "belt and suspenders" ("belt and braces" in the Queen's English) taking up space every time to explain things that only need it one time. Most web-savvy readers will not need any explanation at all. Alec Sanderson (talk) 14:35, 1 April 2016 (UTC)
Anyone with some understanding of the English language will understand what harassment and spam are, though doxing may not be known to everybody - in that case I'd say just look it up.--JorisEnter (talk) 14:48, 1 April 2016 (UTC)
- I'll go along with that. I'd never heard of "doxing" before I came to RationalWiki. But I'm pretty sure that anybody who got blocked for it would know only to well what it was. Spud (talk) 14:53, 1 April 2016 (UTC)
- I wouldn't be too sure about harassment or doxing, people have many, many conflicting views on what it is. Spam is probably less ambiguous, though.--Kugelschreiber (talk) (mail) (block) 14:57, 1 April 2016 (UTC) 14:57, 1 April 2016 (UTC)
- Actually, there are other meanings too.--JorisEnter (talk) 15:00, 1 April 2016 (UTC)
- getting too specific is also a problem. Imagine the coop cases of '...but the definition says this, while i'm doing that thing you forgot to include.' I say imagine, you could prob just look in the archives. AMassiveGay (talk) 15:19, 1 April 2016 (UTC)
- besides which, any detailed explaination would be in the community standards and is entirely redundant in a dropdown reason. AMassiveGay (talk) 15:24, 1 April 2016 (UTC)
- I've had that problem, too. Somebody creating a page with some sort of telephone number, for example, is not "posting something over and over" (because they usually get banhammered after the first attempt) and probably also not "vandalizing" (because that would be done to something that's already there). Despite this, it's pretty damn obvious that the telephone thingy is spam.--JorisEnter (talk) 15:32, 1 April 2016 (UTC)
- Short versions - the long versions only constructs a set of playground equipment for trolls and wikilawyers. The trouble with malice is not a failure to understand what they're doing, and the trouble with stupidity is not that nobody has ever explained that stupidity is bad - David Gerard (talk) 15:37, 1 April 2016 (UTC)
Everyone talking about "wikilawyering" is talking shit. When's the last time anyone has appealed their ban? Much less appealed their ban on a technicality? The only benefit or harm of this is to the ban-er, not the ban-ee. Mʀ. Wʜɪsᴋᴇʀs, Esϙᴜɪʀᴇ (talk/stalk) 16:16, 1 April 2016 (UTC)
- Yesterday I deleted a page and blocked the account which created it. The page was something about a Lexmark printer helpline number (presumably fraudulent). This is surely, by any normal standards, spam. Yet according to the definition appearing in the dropdown menus (vandalizing or posting something over and over) it isn't, since I only saw it posted the once. I would like to be able to use the dropdown options in these situations for convenience, because that's what they're there for, without having to choose an inaccurate description. I reiterate that these arbitrary parenthetical definitions aren't necessary or helpful. WeaseloidMethinks it is a Weasel 17:39, 1 April 2016 (UTC)
- Being a dedicated follower of fashion, I think it is time to poll the quorum here assembled. Alec Sanderson (talk) 18:46, 1 April 2016 (UTC)
Poll[edit]
Terse[edit]
- Status quo, as restored by Weaseloid, perhaps with a link to doxing. Alec Sanderson (talk) 18:46, 1 April 2016 (UTC)
- Same for me.--JorisEnter (talk) 18:47, 1 April 2016 (UTC)
- Works as-is for me - David Gerard (talk) 23:24, 1 April 2016 (UTC)
- I'm currently under the impression that, as long as we link to an explanation for Doxing, Weaseloid's more spartan delete reasons might actually serve to confuse less in the long run. So thus far in the discussion, I'm pro-terse. Reverend Black Percy (talk) 02:47, 2 April 2016 (UTC)
- Since my experience would suggest that "doxing" is the only one of those words that might be unfamiliar to an English-speaker of average intelligence alive in 2016, I wholeheartedly agree with the above. Spud (talk) 05:13, 2 April 2016 (UTC)
- Keep it short, but add links to doxing and the legal FAQ. It's what links are for. - Smerdis of Tlön, LOAD "*", 8, 1. 18:01, 2 April 2016 (UTC)
- Precise, wordy definitions lead to wikilawyering. The fact that nobody has done so recently doesn't mean nobody ever has (they certainly have) or ever will. Flannan Isle (talk) 19:43, 2 April 2016 (UTC)
Verbose[edit]
I like the verbose, just make the descriptions a bit
shorter more vague. Bubba41102The place where you can scream at me 19:18, 1 April 2016 (UTC)
Goat[edit]
I probably wont ever use them either way AMassiveGay (talk) 02:31, 2 April 2016 (UTC)
Consensus[edit]
Thanks for voting, everyone. Seems like most people want the terse version, with a link to doxing. I've changed it to:
- Malicious:
- Doxing
- Legal threats (please see RationalWiki:Legal FAQ)
- Harassment
- Spam
Fuzzy. Cat. Potato! (talk/stalk) 18:12, 2 April 2016 (UTC)
- This seems like a good idea. Links to Doxing and the Legal FAQ are good, because many people (including me until I encountered it somewhere on RW) do not know what doxing is.--JorisEnter (talk) 18:36, 2 April 2016 (UTC)
- That's fair. I've had to explain it elsewhere too. Flannan Isle (talk) 19:44, 2 April 2016 (UTC)
The consensus on privacy and the encryption debate[edit]
I believe it is very important that we establish the mobs stance on privacy and the encryption debate as soon as possible, this has been forced into the public spotlight, and it would be nice to establish at least some precedent on the mobs views on encryption and privacy in general. I also believe it will be good to create a privacy nav, and multiple pages on privacy and encryption. Privacy has become a major public issue, and i believe it will be in our best interest to debunk bullshit claims about encryption and privacy in general. I personally believe that privacy is very important, and that it is in everyone's best interest to keep privacy strong. Bubba41102The place where you can scream at me 19:08, 1 April 2016 (UTC)
- people dont give a shit about privacy. Its been given up cheaply for facebook and iphones. Google reads your emails and Apple's only been noisy bout the feds because they want to be the only ones spying on their customers. AMassiveGay (talk) 02:29, 2 April 2016 (UTC)
- Do we need a stance? Can't we just present the evidence and refute the bullshit? Certainly coverage of issues is good, and nav bars in moderation. But do you need a stance to do that? (Personally I like privacy but I also like posting nonsense on the internet. And should governments, politicians, corporations, etc, have a right to privacy?) Annquin (talk) 16:09, 2 April 2016 (UTC)
From the makers of God's Not Dead and God's Not Dead 2[edit]
I'm Not Ashamed "based" on the story and journal entries of Rachel Joy Scott who was killed in the Columbine high school shooting in 1999. — Unsigned, by: Cms13ca / talk / contribs
- I actually remember reading a book when I was much younger called "She Said Yes" which (I think) was about the same girl, written by her mother. Despite the premise I don't remember it being super preachy but my memory may fail me on that front as well, in any case it did stick out in my mind. Telling the story of a teenager's religious questioning/discovery might actually be interesting ground for a movie, but undoubtedly it will be morphed into ridiculous nonsense, and it's rather sickening (though not surprising in the slightest) that her life will be exploited in such a matter. It's one thing to just make up ridiculous nonsense propaganda. I'm also sure they won't say a word about the gun violence that actually murdered her. Hentropy (talk) 03:43, 2 April 2016 (UTC)
- Different student. At least according to Goodreads[4], She Said Yes: The Unlikely Martyrdom of Cassie Bernall by Misty Bernall is actually pretty good, even if you know the central premise is bullshit and question her mother's super-quick rush to publication (which some reviewers do). It's interesting that they've now found another Christian martyr after Bernall's death was debunked. No idea about the truth of I'm Not Ashamed, but most sources say Rachel Scott was Christian (which isn't too surprising). Annquin (talk) 16:17, 2 April 2016 (UTC)
What are some good shows to watch?[edit]
I havent watched television in a long ass time, so I'm wondering if there are any good shows (like the West-wing, a show that I'm interested in seeing) or cartoons that are worth watching. So, do any of you have any recommendations? Sierra Nav (talk) 03:40, 30 March 2016 (UTC)
- I like Empire, Being Mary Jane, Star Trek DS9 (and sometimes Enterprise) re-runs, The Office, and some Korean dramas. I used to hate South Park, but it's grown on me since I like they way they deal with current issues. Your mileage may vary XD Lord Aeonian (talk) 06:34, 30 March 2016 (UTC)
- Comic book shows are hitting a good stride. Supergirl is simply the best thing on network television right now. The streamed shows Daredevil, now on 2d season, and Jessica Jones, are both pretty good. Agents of SHIELD is slow starting, but has hit its stride. As for cartoons, Archer is going to start its sixth season tomorrow. - Smerdis of Tlön, LOAD "*", 8, 1. 12:28, 30 March 2016 (UTC)
- House of Cards and Empire are really good. Hemlock Grove was decent once you get into it. AyzmoCheers 12:59, 30 March 2016 (UTC)
Better Call Saul. Herr FuzzyKatzenPotato (talk/stalk) 15:29, 30 March 2016 (UTC)
- Unbreakable Kimmy Schmidt and Orange is the New Black ChrisAmiss (talk) 16:08, 30 March 2016 (UTC)
- venture bros. Is awesome AMassiveGay (talk) 18:09, 30 March 2016 (UTC)
- Hannibal, if you have Amazon Prime, as it's off the air now. Really well written and produced, but be warned, pushes the boundaries on network television gore. The 1st season actually fills in a lot of backstory referenced in Manhunter and Silence of the Lambs, if you liked those (and haven't read the books). For funny, Always Sunny in Philadelphia is good, but the earlier seasons are definitely superior to the new ones. Petey Plane (talk) 19:00, 30 March 2016 (UTC)
- is he a panto villian like he is in the films? AMassiveGay (talk) 19:05, 30 March 2016 (UTC)
- Ha, yeah, Hopkins definitely hams it up in the films following Silence of the Lambs (but those mostly suck anyway). No, not campy in the show, closer to Brian Cox's portrayal in Manhunter (my favorite Lector movie). He's played by this guy: Mads Mikkelsen.Petey Plane (talk) 19:23, 30 March 2016 (UTC)
Newsroom, House of Cards. Pbfreespace3 (talk) 01:31, 31 March 2016 (UTC)
- I'm going to go balls to the wall and say: BoJack Horseman. It's on NetFlix, and it's brilliant to the bone. Reverend Black Percy (talk) 01:57, 31 March 2016 (UTC)
- Futurama. CorruptUser (talk) 03:07, 31 March 2016 (UTC)
Only shows I watch are Star Trek (TNG, and TOS) It's Always Sunny in Philadelphia, and some anime that my brother watches. 'Legionwhat do you want from me 06:35, 31 March 2016 (UTC) The CW's Flash and Arrow TV shows are good, though Arrow isn't for everyone, and is mostly good for background noise. House of Cards, Daredevil, they're both okay suggestions too. I don't watch too many TV shows, there's not a lot on that interests me these days (I miss Fringe and Stargate :()- Kitsunelaine 「SJW Illuminati shill.」 09:55, 31 March 2016 (UTC)
- >:() There is always The Wire (lives up to the hype, maybe greatest TV drama of all time) and Deadwood, but i assume people have seen those by now. Petey Plane (talk) 13:41, 31 March 2016 (UTC)
What about Tatort, though? Pizzameister (talk) 17:59, 31 March 2016 (UTC)
--Ymir (talk) 18:14, 31 March 2016 (UTC)
I loathe american tv shows. I dont care how well made, how acclaimed, how fucking amazing they are, i flat out refuse to commit years of my life to a fucking tv show. And not just a few weeks each year either, those fuckers go on for ever. Marriages do not last as long. AMassiveGay (talk) 00:53, 1 April 2016 (UTC)
- @AMG: But marriages also don't (usually) take 1 hour per week... FuzzyCatPotato of the Belittling Cellphones (talk/stalk) 12:12, 1 April 2016 (UTC)
- Or 2 afternoons of binge watching on a streaming service. I get what you are saying, and i do like the BBC method of shows having a definite 3 or 4 season ending written in from the start, but there are plenty of American shows that are like that as well, and some BBC shows that aren't (cough... Dr. Who... cough)Petey Plane (talk) 14:57, 1 April 2016 (UTC)
- Unlike that one British show about some Doctor, can't remember who. That show has been on so long I think the original cast are all dead by now.
- But seriously, you are free to stop watching after a couple of seasons if you like. As long as the seasons aren't all filler, that is. You might want to avoid Japanese cartoons if you hate things going on forever. I mean, Dragonball has like 500 episodes, mostly filled with screaming and dear God has Freeza been powering up for three entire episodes?! And now they are making new episodes, about Super Sayian God Super Sayian God Super Whatever. Oh and over two dozen movies that mostly take a dump on the franchise. StickySock (talk) 15:06, 1 April 2016 (UTC)
- Anime producers very often don't have the decency to just stop a series when they're out of intelligent ideas for it.--Kugelschreiber (talk) (mail) (block) 15:09, 1 April 2016 (UTC) 15:09, 1 April 2016 (UTC)
- As much as i liked watching DB with my little brother as a kid, once i realized that power levels were absolutely meaningless, and therefor so to the 10 episodes of two characters screaming at each other before the 5 minute fight, it lost some of it's appeal. I can't imagine anyone over the age of 15 actually liking that show.Petey Plane (talk) 15:11, 1 April 2016 (UTC)
- dr who can go fuck himself, nust on the grounds of being awful. AMassiveGay (talk) 15:14, 1 April 2016 (UTC)
- (giant nerd alert) That's not really true. Only the big shonen and merchandise-seller series (Dragonball, One Piece, Pokémon, Pretty Cure) targeted at kids go on forever. Most anime series go 12 or 24 episodes, and if it was particularly popular they might release some OVAs later. This is largely due to how Japanese TV works. Production companies can buy a time slot on a station a season at a time and air whatever they want, in contrast to the U.S. model where the network decides what to air and has the power of life and death over each show. --Ymir (talk) 18:58, 1 April 2016 (UTC)
- i want to like anime, and ive really tried to. But the characterisation in those fhings - its just physically painful to watch. I'd say its a cultural thing, but i have no problem with japanese cinema, just the anime. AMassiveGay (talk) 02:38, 2 April 2016 (UTC)
- I agree with the excessively large homosexual above. I like a lot of Japanese cinema, but i can't get into the over-the-top melodrama of most anime. I also don't find japanese humor very funny. That being said, Akira is in my top 5 fav movies of all time. Petey Plane (talk) 14:24, 4 April 2016 (UTC)
- I like everything by Studio Ghibli, but outside of that only a few anime. E.g. Tokyo Godfathers is my all time favourite Christmas movie. I don't mind Akira but can't get excited about it, & Ghost in the Shell didn't interest me at all. I used to like pulpy stuff like Cowboy Bebop & Hellsing but can't really get into that any more either. WēāŝēīōīďMethinks it is a Weasel 23:36, 4 April 2016 (UTC)
- Guys we have to be honest here, we all know Barney the Dinosaur is the best show out there, be honest guys, that dinosaur knows what he is talking about. Bubba41102The place where you can scream at me 01:32, 2 April 2016 (UTC)
- Barney the Dinosaur proves evolution is false. Petey Plane (talk) 14:26, 4 April 2016 (UTC)
- It also recruits kids into being gay just like Teletubbies, Spongebob and Batman & Robin do.--Kugelschreiber (talk) (mail) (block) 14:29, 4 April 2016 (UTC) 14:29, 4 April 2016 (UTC)
- Barney? That show was half decent, but lets be honest, The BooBahs (yes that seriously exists) is CLEARLY superior to that purple plebian! Sierra Nav (talk) 21:45, 4 April 2016 (UTC)
Ali Sina[edit]
Some BON made the page with:
Ali Sina is the founder of Faith Freedom International. An Ex-Muslim, his website claims to help Ex-Muslims leave Islam and criticises the religion. However in reality, he is a Far-Right Anti-Muslim bigot, homophobe[1], Birther [2] and He Who Must Not Be Named supporter[3] who is far more of a hindrance than help to the cause of Muslim critics and Ex-Muslims, the latter being a highly oppressed people. He has repeatedly argued for Islam to be banned and Muslims to be deported[4] and has engaged in victim blaming with regards to Syrian Refugees [5]. However, in spite of this, noted Atheists Richard Dawkins and Ibn Warraq have praised his organisation. Please, if you are an Ex-Muslim and/or critic of Islam check out Maryam Namazie or Maajid Nawaz. Completely ignore this asshole.
How close/far from the truth does this hit? FuzzyCatPotato of the Bloated Staplers (talk/stalk) 13:40, 31 March 2016 (UTC)
- The sources appear to check out at a glance, and it certainly appears missional if true... maybe place it in essay a space for now and try to research it and grow it (or discard it) before moving to mainspace? Reverend Black Percy (talk) 14:26, 31 March 2016 (UTC)
- Oh my god, not another one of these retarded Voldemort-jokes about Teh Donald.--Kugelschreiber (talk) (mail) (block) 15:33, 31 March 2016 (UTC) 15:33, 31 March 2016 (UTC)
Well, I'm confused already. Maryam Namazie? I thought she was the biggest Islamophobe of all according to some circles. Also, I've heard good things from other sources regarding FFI, though I don't know enough to comment here. I'd suggest someone do some more research on the subject and make the page more accurate if needed. Lord Aeonian (talk) 06:13, 1 April 2016 (UTC)
- We already kind of had a discussion about Namazie. IMO, she's not Islamophobic, although more conservative or fundamentalist Muslims (like the Goldsmiths Univ. ISOC president, who shut down one of her talks) may see her as one (like how conservative Christians may see criticism of the Bible as "oppression"). ℕoir LeSable (talk) 17:18, 6 April 2016 (UTC)
By The Numbers - The Untold Story of Muslim Opinions & Demographics[edit]
Thoughts? 32℉uzzy; 0℃atPotato (talk/stalk) 23:19, 2 April 2016 (UTC)
- Well besides there not actually giving any numbers on its "Islamic sphere" graph, this video cites Sam Harris fro Bill Maher's interview with him; in that interview, Sam Harris makes a wild claim that 20% of Muslims supported radical Islam, but gives no evidence to his claim. The problem with those the poll she cites about Muslim support for the execution of apostates is that Muslims in Kosovo, Albania, Turkey, and Indonesia don't hold those views. These are cultural views mixed with religion. Raheel Raza has called for a ban on individuals coming from "high risk" countries and was against Park51. The CAIR has not been associated with Hamas for some time now and the UAE's designation is frivolous.--Owlman (talk) (mail) 01:36, 3 April 2016 (UTC) 01:36, 3 April 2016 (UTC)
- Haven't watched the video, though there are opinion studies, too. For example, this one. “Islamic fundamentalism is widely spread. WZB study shows significantly high numbers amongst Europe’s Muslims” ~ Aneris ✻ 01:00, 4 April 2016 (UTC)
- There is a lot of fundamentalists within Islam, but the video doesn't explain the cultures that these Muslims come from. A good example would be stating how many Hindus, who mostly come from India, are misogynistic, but the culture of India is very misogynistic so blaming just the religion ignores other factors.--Owlman (talk) (mail) 01:11, 4 April 2016 (UTC) 01:11, 4 April 2016 (UTC)
- @Aneris: Usually the problems with these polls is that the cultural libertarian side (so to speak) only cites the bits where Muslims are bigoted nutters and the SJW side (so to speak) only cites the bits where they are reasonably progressive.
- @Owlman: The source of the bigotry is really irrelevant. So what if someone's from the misogynist South, and we can't blame their woman-hate on Christianity? They're still bigoted, and ought to stop -- possibly, to be made to stop. Fuzzy. Cat. Potato! (talk/stalk) 01:17, 4 April 2016 (UTC)
African arrival to London[edit]
Has anyone seen the Arrival of black immigrants in London WP page before? It mentions African descendants in London before the Romans and during Catherine of Aragon's visit to London w/o a lot of references. Is this all BS or are there any academic articles on these arrivals?--Owlman (talk) (mail) 00:24, 3 April 2016 (UTC) 00:24, 3 April 2016 (UTC)
- I don't know if you're reading a different version of the article to me, but the one I read mentioned only depictions in London in Roman times. And it's hardly controversial that Catherine of Aragon (a Spanish noblewoman) had African servants in the early 16th century. Some refs here. There were Africans in southern Europe from the 15th century. I suggest you get a good biography of Catherine. Annquin (talk) 01:32, 3 April 2016 (UTC)
- Well how did the depiction of Africans get there because there is no ref (it leads to the Museum of London, but I can't find the page mentioning it). I also I looked up the Catherine of Aragon claim and found it, but nothing on Cornelius, the first African man in London; I mentioned Catherine because there weren't a lot of refs on that section.--Owlman (talk) (mail) 01:41, 3 April 2016 (UTC) 01:41, 3 April 2016 (UTC)
- It's been tagged as needing additional references for more than eight years now. It's not a great article but I think it just contains statements that need to be verified, rather than actual bullshit. I'm a bit surprised that the article isn't semi-protected and they let BoNs edit it. But then the title would put off the real crazies who insist that everyone in Britain was black until some white devils arrived in the 17th century or something. Spud (talk) 05:22, 3 April 2016 (UTC)
- or, more pertinently, that there were no blacks until the post-war immigration wave. Flannan Isle (talk) 07:33, 4 April 2016 (UTC)
-
- The Roman depiction could have been an image of Septimus Severus who spent a significant amount of time in Britain, and with his African ancestry is often reckoned to be of mixed race.[5] A lot of images show him in idealised (white Roman) form but not all.[6] All this can easily be Googled or raised on Wikipedia talk pages. Annquin (talk) 09:43, 4 April 2016 (UTC)
Monthly stats[edit]
May 2016, RW had 46 (4.80%) more users with 1+ edits than Feb 2016, -9 (-2.70%) with 3+, -11 (-1.41%) with 30+, and -1 (-11.11%) with 300+. RW had -566 (-3.88%) more edits than Feb 2016.
RW had -24 (-2.33) more users with 1+ edits than May 2015, -52 (-13.83%) with 3+, 9 (15.52%) with 30+, and -1 (-11.11%) with 300+. RW had -449 (-0.17%) more edits than May 2015.
Overall, RW had more users and less edits than the previous month, and less users and less edits than the previous year.
Excel file link:
FuzzyCatPotato!™ (talk/stalk) 00:15, 4 April 2016 (UTC)
- That's kinda depressing. ℕoir LeSable (talk) 02:48, 4 April 2016 (UTC)
- Meh. As the chart shows, there's huge variation between most months. It's genuinely unfortunate that, as RW's userbase has risen, its edits have not also rise. Herr FuzzyKatzenPotato (talk/stalk) 03:09, 4 April 2016 (UTC)
- Every time I see the edit numbers falling, I think. "Hmm, maybe people have learnt to use the preview button, rather than make 10 changes in close succession." Occasionally that might even be true. Annquin (talk) 09:33, 4 April 2016 (UTC)
- I'm considering putting up some "advertisments" for the site around campuses of Uppsala University - that might atleast give us a longterm user or two. *shrugs* Also FCP, I think it's really nice that you take the time to make these graphs so we can all be a part of keeping track how things are going. Appreciated buddy. For the record, is it possible to see some kind of graph or number on a single user's contributions? I've been working my ass off lately, would be fun to see what the numbers say. All the best, Reverend Black Percy (talk) 11:39, 4 April 2016 (UTC)
- You can see your total number of edits under 'Preferences'. I don't think we have any good analysis tools à la WP, though.--JorisEnter (talk) 11:53, 4 April 2016 (UTC)
- Thanks buddy! Hey, 4100 and still going strong! I wish they'd show the total amount of symbols, though. Reverend Black Percy (talk) 11:57, 4 April 2016 (UTC)
It is possible to view individual user contributions. Visit User edit counts and click on the username. Mʀ. Wʜɪsᴋᴇʀs, Esϙᴜɪʀᴇ (talk/stalk) 15:36, 4 April 2016 (UTC)
- Quick and dirty pull of stats - apart from disappearing in Jan/Feb, you're on an upwards trend (included are overall edits plus breakdown of three of the biggest namespaces used) Worm (talk) 15:49, 8 April 2016 (UTC)
RW 1.0?[edit]
Is there any stuff from it still in existence? KOMF 01:56, 4 April 2016 (UTC)
- Probably not. Fuzzy. Cat. Potato! (talk/stalk) 16:49, 4 April 2016 (UTC)
Vote:[edit]
Recently departed user Sorte Slyngel has asked that their username be removed from the site. It's extremely easy to do this. I previously replaced all instances of the signature "[[User:Sorte Slyngel|Sorte Slyngel]] ([[User talk:Sorte Slyngel|talk]])" with "[[User:Uppivindinn|Uppivindinn]] ([[User talk:Uppivindinn|talk]])." This scrubs most mentions of the username from most pages but still links people to a page from which Uppivindinn's contributions can be accessed.
I could also more generally replace all instances of "Sorte Slyngel" with "Uppivindinn". This might break something, but probably not.
However, Weaseloid reverted the topmost scrubbing and asked that I get community consensus. So: Sir ℱ℧ℤℤϒℂᗩℑᑭƠℑᗩℑƠ (talk/stalk) 15:35, 4 April 2016 (UTC)
Don't allow username scrubbing[edit]
- FCP is pandering to one ex member's wishes and ought to stop now. Pippa (talk) 16:36, 4 April 2016 (UTC)
- seems like you're doing a pile of work (and setting a precedent) for one person who was an irritant. Why? Just because you can doesn't mean you should. Just change their username by the usual method. Flannan Isle (talk) 18:17, 4 April 2016 (UTC)
- Don't. A user can change a name going forward, but no need to do it retroactively. Besides, it screws with the conversation when a person refers to a prior comment. If FuckPants posts something and I respond "Hey FuckPants, stop it", I'll retroactively look like an ass when FuckPants becomes Pretty Doll Head. Don't do that to me. MarmotHead (talk) 20:53, 4 April 2016 (UTC)
- As said above. This would fuck up every archive that contains Sorte's name. Besides, why would we need to erase his name from the records? It's not as if it's his property that he can force us to remove at his bidding. (I know it was FCP who did this, but just in case anyone was going to make this point)--JorisEnter (talk) 20:55, 4 April 2016 (UTC)
- No.--Bob"Life is short and (insert adjective)" 19:46, 5 April 2016 (UTC)
- Its only purpose is to confuse and obfuscate. I can understand if someone registered using their real name and wished to change it, but that's not relevant here. Pbfreespace3 (talk) 21:13, 5 April 2016 (UTC)
- No. With possible exceptions as Carpetsmoker described below. But generally, no, and not in the instant case.---Mona- (talk) 02:19, 8 April 2016 (UTC)
Allow signature scrubbing[edit]
Allow general scrubbing[edit]
- It's a shame MediaWiki doesn't incorporate this. Mʀ. Wʜɪsᴋᴇʀs, Esϙᴜɪʀᴇ (talk/stalk) 15:35, 4 April 2016 (UTC)
- I don't know why we even need a vote on this.--Owlman (talk) (mail) 15:53, 4 April 2016 (UTC) 15:53, 4 April 2016 (UTC)
- As long as this doesn't break any continuity of now-archived discussions held with and/or about the user, as long as it is technically simple to both do and reverse (in case of error), as long as it's only done on request and as long as the procedure is standardized, e.g. always performed by The Fuzz and not done in a haphazard way in future cases... as long as all this is met, I don't see why not, especially in cases where it might help a LANCB'd user to more fully separate from the site and/or maybe not hold extra grudge towards the site that may or may not ferment into accosting the site at some future time. Reverend Black Percy (talk) 17:21, 4 April 2016 (UTC)
- Allow Petey Plane (talk) 13:12, 5 April 2016 (UTC)
Only if there is a good reason[edit]
- Ragequiting is not a good reason, but there are some. For example in cases where people are scoring high in Google ranking with some embarrassing stuff, we should remove it when requested. This can have real effects on their lives (e.g. getting a job). So in this particular case: no. But in some future cases: perhaps. Carpetsmoker (talk) 13:19, 6 April 2016 (UTC)
Discussion[edit]
This requires considerably more discussion. As in, why are we disrupting the wiki for a dramatist? And what exactly is changing the username to another known username going to do to hide their trail of drama as they wish? I mean there's LANCB and there's "ok, you're gone, we'll remove your name a bit", then there's whatever this is. And you just know the guy's gonna be back repeatedly - David Gerard (talk) 16:02, 4 April 2016 (UTC)
- Meh, a bunch of people who've left have asked for stuff like this (as I recall). And LTR kept getting pissy that their name was mentioned; would've been easy to scrub and avoid any vandalism.
- Some people might want to unlink their activities at RW from whatever their username was, I suppose.
- Also, again, this is pretty damn easy. (ofc doesn't mean it's a good idea.) Fuzzy "Cat" Potato, Jr. (talk/stalk) 16:49, 4 April 2016 (UTC)
"I previously replaced all instances of the signature Sorte Slyngel (talk) with Uppivindinn (talk). This scrubs most mentions of the username from most pages but still links people to a page from which Uppivindinn's contributions can be accessed." No you didn't & no it doesn't. Your bot changed some pages & missed others; besides which there were plenty of mentions of the username Sorte Slyngel by other editors talking to or about him. Your bot edits make nonsense of these conversations (including coop cases which we may need to refer to again) by creating a dialogue where users appear to be talking to or about a non-existent user while Sorte's own comments appear under a different name.
"A bunch of people who've left have asked for stuff like this (as I recall)." Yeah, and we've always said no, with good reason. It's kindof shitty that you would undermine this by just volunteering to revise a lot of old talk page posts when it wasn't even asked for.
"Also, again, this is pretty damn easy. (ofc doesn't mean it's a good idea.)" No shit Sherlock. It may be pretty damn easy for the minority of editors who run bots, but you're creating a precedent & an expectation which is going to be a massive pain in the ass dealing with every time somebody throws a tantrum. If a user wants to stop editing here, & if they want to make a petulant gesture out of doing so, that's their prerogative but not something we should be using admin tools to facilitate. WěǎšěǐǒǐďMethinks it is a Weasel 17:32, 4 April 2016 (UTC)
- ↑ Wot 'e sed. Pippa (talk) 17:41, 4 April 2016 (UTC)
- Besides a tone that I find a little uncalled for, these arguments from the Weasel are compelling. I'll be awaiting a rebuttal to them, and if none can be produced, I may change my current vote. Reverend Black Percy (talk) 18:17, 4 April 2016 (UTC)
Just as a heads up, if you plan to replace every instance of "Sorte" with "Uppi" or some abbreviated form of Sorte's name, remember to exclude all pages in French. "Sorte" means "type" or "way/manner", e.g.: C'est une sorte de connerie pseudo-scientifique. = "It's a kind of pseudoscientific bullshit." (Please pardon my French, it's been years.) ℕoir LeSable (talk) 18:55, 4 April 2016 (UTC)
- "Sorte" is also Danish for black, in case we have any Danish articles lying around. Also, "Sorte Slyngel" is just a foreign-language online alias, so why bother changing any instance of it at all? It's different from that Brazilian antisemite guy, who actually used his real name for his account. 141.134.75.236 (talk) 19:07, 4 April 2016 (UTC)
- Sorte Slyngel, literally black rapscallion, is the Danish translation for Phantom Blot, apparently a character from the Mickey Mouse comics. I hadn't heard of the character in English. - Smerdis of Tlön, LOAD "*", 8, 1. 21:02, 4 April 2016 (UTC)
Alright, sounds fine. Won't scrub. Mʀ. Wʜɪsᴋᴇʀs, Esϙᴜɪʀᴇ (talk/stalk) 20:50, 4 April 2016 (UTC)
Block appeal[edit]
Isn't time User:Fat Aardvark gets unblocked? I mean it wasn't like the block was justified and the dictator Paravant has finally gone and didn't God say in the bible that "thou shall love thy aardvarks"?.--Lord High Worm (talk) 16:06, 5 April 2016 (UTC)
- Fuzzy "Cat" Potato, Jr. (talk/stalk) 16:30, 5 April 2016 (UTC)
- I like the idea of writing a bot that will unblock him, then revert his next post and block him again for the obvious non-improvement in behavior. ikanreed You probably didn't deserve that 17:58, 5 April 2016 (UTC)
- "JusticeBot", roll out! Reverend Black Percy (talk) 18:13, 5 April 2016 (UTC)
- There is nothing to stop this Fat Aardvark person from returning under a different name. Perhaps even now he has decided to return, named after an aristocratic annelid. Flannan Isle (talk) 21:00, 5 April 2016 (UTC)
- Whereas us more lowly working class invertebrates just toil away in the dirt mines. Worm (talk) 08:26, 6 April 2016 (UTC)
- I'm glad you know your place, User:Worm. As for the rest of you I am very disappointed. The way I've been treated is appalling. Why do you all insist on keeping the "rules" of Paravant the dictator even though he finally left? It wouldn't surprise me if he left to take over another wiki if I'm honest.--Noble Lord Worm (talk) 09:31, 6 April 2016 (UTC)
Introducing myself[edit]
Hi, I would like to introduce myself. I lurk here a little bit and because of this site lurk at Conservapedia. Quite honestly, I'm probably TOO conservative for Conservapedia, which is now a dead site anyways and has been for some years now. My broader point is that I'm unapologetically very right wing, at least to y'all, but I'm not socially conservative. Anyways, thought I'd join this community because even if I don't agree with your politics, I think y'all are smart. TooConservative (talk) 04:26, 7 April 2016 (UTC)
- Interesting. Based on your statement I'd assume you are right wing on economics and foreign policy, correct? Does your lack of conservatism on social issues have anything to do with your religious views? Pbfreespace3 (talk) 04:37,)
- Funny. My uncle is an economic moonbat but a social wingnut. Ok that's an exaggeration; he is ok with higher taxes if we get socialized healthcare and he wants wallstreet to be more tightly regulated than a nuclear power plant, but he despises everything about the current social justice movement, which is to be expected since my great grandpa once beat up Father Coughlin. Linear political spectrums are too limited. CorruptUser (talk) 04:54,)
−
- TooConservative, you see merit in anti immigration arguments. OK. The reason why you oppose arbitrary rules is because they prohibit behavior (homosexuality/drugs/etc.) that doesn't hurt anyone else. Would you oppose building a wall or pursuing similar anti-illegal immigration measures if I could show you there is a net benefit from letting people come across the border illegaly? Because illegal immigrants do more to help our economy than hurt it. For example, they pay more in taxes than they receive in social services. Also, most of our farmers are illegals. If illegal immigration is helping people more than it is hurting, why would you lean towards opposing it? Pbfreespace3 (talk) 05:01, 7 April 2016 (UTC)
- Opposing immigrants is doing it the hard way. You're dealing with people, who have posable thumbs and stuff, and are often clever enough to figure out a way around any barriers you put in their way. It's far, far easier to close your borders to foreign manufactured goods. At any rate, welcome to the site. I'm another of the somewhat right-leaning users here, I'd call myself a socially liberal Old Rightist and America Firster. And not a libertarian either, just a libertine. - Smerdis of Tlön, LOAD "*", 8, 1. 14:58, 7 April 2016 (UTC)
- FULLY AUTOMATED LUXURY DEGENERACY NOW - David Gerard (talk) 20:42, 7 April 2016 (UTC)
Welcome. People might better understand your viewpoint if you explained what "economic" versus "social" means for you. Migration of peoples, for example. Some people consider it an economic issue; others a social one. You? Cømяade FυzzчCαтPøтαтø (talk/stalk) 05:15, 7 April 2016 (UTC)
Welcome buddy, that was a nice and civil introduction. While I don't share your views on certain topics already based on your introduction, I would defend to the death your right to say them, etc... Again, welcome, and remember to do the duty of every upstanding intellectual (since Socrates) and make sure to not get married to your opinions. Our pages on logical fallacies and cognitive biases are great examples of pages that educate regardless of political spectrum, and also help to break the reader free from the rigidity of their own opinion. Everybody wins the more people read and understand those pages. All the best, Reverend Black Percy (talk) 09:04, 7 April 2016 (UTC)
- If you support the scientific method and evidence-based beliefs you are welcome to edit articles. If you don't, then you might be better off on talk pages. But welcome in any case. :-)--Bob"Life is short and (insert adjective)" 18:40, 7 April 2016 (UTC)
Those who are protectionist and anti immigrant (Trump voters and maybe some Sanders and Cruz voters) are voting on economic insecurity. Immigration, both legal and illegal, can be argued as depressing working wages. Faith in free trade is overrated, and Obama, Clinton, Bush, and Kasich are notoriously married to the free trade religion. Immigration is an economic issue, not a social one. Who you bang is social issue, notwithstanding the minor issue of gay marriage tax treatment (actually I don't know why gay people knowingly are signing up for a marriage tax penalty if they are equal earners.)
Sadly, I don't have time to edit articles, because I would want to make a good effort (call that scientific method/good research/etc). For example, one belief y'all may disagree with me on, not to engage in vanity here, is global warming. Global warming is science. No question . But there's a big leap between accepting global warming science and questioning the cost vs benefit of proposed solutions against global warming, especially if big polluters like China are not held to the same standards of a compact as the US. TooConservative (talk) 03:26, 8 April 2016 (UTC)
- I take it you would support global climate rules, such as the guidelines introduced last year in Paris, that apply to all UN countries? These apply to China and India just as well as the US, which is why many people were supporting them. I wouldn't shy away from doing a cost-benefitanalysis of anything important, especially when it could improve the lives of so many people affected by climate change. Pbfreespace3 (talk) 15:06, 8 April 2016 (UTC)
- It has no binding enforcement mechanism and contains just promises, which makes it glorified toilet paper.--Kugelschreiber (talk) (mail) (block) 15:25, 8 April 2016 (UTC) 15:25, 8 April 2016 (UTC)
Jesusandmo[edit]
In case any of you Goats haven't seen it before, I thought this might appeal to some of you in need of a little humor.
jesusandmo.net
Enjoy! B4Xiphos (talk) 07:38, 7 April 2016 (UTC)
- See the article image on our Koran article, for one. Sweet tip though, thanks for taking the time giving it! Reverend Black Percy (talk) 09:06, 7 April 2016 (UTC)
- Whoops! I don't always look at pictures... sorry. Feel free to delete this thread. B4Xiphos (talk) 09:52, 7 April 2016 (UTC)
- No, it's fine, you just gave your recommendation in case any of us Goats hadn't seen it before. Nothing wrong with that. Reverend Black Percy (talk) 10:11, 7 April 2016 (UTC)
Help debating against a pro-flat taxxer[edit]
Hello, RationalWiki.
I was having a debate with an internet acquaintance on Skype. He wants to replace income tax with a flat tax because "paying for more if you have more is theft." Despite my best efforts (including linking him to RationalWiki), I could not convince him to give up his views. Here is an archive of my debate (I'm gutza1, my acquaintance is Rick):
— Unsigned, by: 68.205.92.113 / talk / contribs 18:54, 7 April 2016 (UTC)
- Self edit: as the OP clearly understands why the flat-tax doesn't work. This is really an argument of opposing world-views, and not the practical merits of progressive taxation. Petey Plane (talk) 19:11, 7 April 2016 (UTC)
- If you do read the chat log, you'll find (after nodding off a couple of times) that your opponents facts are wrong. However, his use of "theft" suggests that you'll never persuade him. When you start with highly divergent assumptions, it's extremely unlikely that any amount of argumentation can get you to the same conclusion. MarmotHead (talk) 19:19, 7 April 2016 (UTC)
- It appears that you have to point out that you are taking more from the poor than you are from the rich which is theft in his view. You will also need to point out that since the rich store more of their money a flat tax will harm income velocity (also called the velocity of money) since the poorest in society spend most of their money or more (e.g. loans) which increases economic growth. You could also point out how an income tax helps to fight inflation.--Owlman (talk) (mail) 19:20, 7 April 2016 (UTC) 19:20, 7 April 2016 (UTC)
- OK, skimmed the chatlong. I don't think the other person believes is a "Social Contract". Without some appreciation for that concept, i'm not sure if you'll ever be able to ague with them that regressive taxation is bad. Their solution seems to be that all we need to do is shift 10% of defense spending to those areas funded by income tax. That's a really naive understanding of the vast complexity of how money is appropriated in the federal government, and really beside the point.Petey Plane (talk) 19:26, 7 April 2016 (UTC)
- You've made me realize that I need to lead more arguments with "Hey this seems like a non-sequitur, but could you please derive the need for a government from first principles?" ikanreed You probably didn't deserve that 19:33, 7 April 2016 (UTC)
- I guess how you want to approach this scenario depends on how much you value the friendship you have with this guy. The easiest solution? Let it go. If this is a good friend of yours (and I hope that's not his real name you posted), then eh. People will have different opinions, and if it's something that's not causing active or impending harm to them or people around them (like homeopathy, faith healing, or anti-vaxx views), then there really isn't as much of an impetus to convince him. On top of that, please check out the backfire effect. No seriously, read it.
- As for his points, the first that comes to mind is that I have no idea where he's getting the 54% figure from. Federal Defense spending only accounts for 16% of the budget, not 54%. Granted, yes, that's still $600B dollars, but it isn't the mass of spending your friend makes it out to be. Even more goes into Medicare and other health services (25%) and social security (24%). So when it comes time for Congress to decide where to start putting things on the chopping block to accommodate that flat tax, guess who'll more likely be affected? Yep, the poor.
- Oh, and please don't forget to add a space and four tildes (" ~~~~") to the end of your post. It allows us to keep track of who said what on discussion pages. Cheers! ℕoir LeSable (talk) 19:40, 7 April 2016 (UTC)
Please don't use your friend's real name! Herr FuzzyKatzenPotato (talk/stalk) 19:54, 7 April 2016 (UTC)
- Here's an obvious but often overlooked point in these discussions where so much energy is expended: the only it would work is by Constitutional Amendment becasuse nothing would stop a future Congress in 2 years from reinstituting the brackets again. And what is the likelihood 38 states would take it upon themselves to do that anytime soon? It's more likely they'd call Constitutional Convention first, of which this would only one issue among dozens aimed at reform. nobsLewinsky 2020 22:11, 7 April 2016 (UTC)
- I actually agree with a lot of what your friend says, although I favor a 2-3 bracket system which I suppose is still technically progressive. For example, Bracket 1: 0%, Bracket 2: income - (reasonable living wage), Bracket 3: 30%. People who make less or equal to than a reasonably livable wage pay no tax. Once you are making more than a livable wage, you pay the remainder, until you surpass (living wage)/(1-30%) at which point you pay 30% regardless of how much you earn. I consider (reasonable living wage) to be enough for your family to have a home appropriately sized for the family/individual, healthy food, necessary services (electricity, internet, phone, healthcare, etc), plus a moderate amount for savings or recreation. That amount would need to be based on many factors including location, family size, etc and so would vary among individuals and families, but I think it could be determined by people smarter than myself. Basically enough to live a happy healthy life. Beyond that value is a life where you can afford unnecessary comforts like a bigger house. --130.16.210.9 (talk) 13:24, 8 April 2016 (UTC)
- There's a lot of things that sound really good in general but work very badly practically. It seems strangely full of faith to have a set ending point for taxes, and a vague general idea of basic living support, and then believe "people smarter than me" will find a way to make it work somehow and be indifferent as to the how otherwise. The devil is always in the details. I find being in favor of vague generalities without caring about details is a great way to get royally screwed. -EmeraldCityWanderer (talk) 15:43, 8 April 2016 (UTC)
- No faith required. The 30% rate is not set in stone and can be raised or lowered as necessary or possible by congress or parliament, it would just only apply to bracket 3. As for the liveable wage, the feds have already done a large portion of that research in the US ( Beyond that it's not particularly difficult to aggregate all necessary services and their prices. The IRS is already sizeable enough to make those bracket calculations, especially since under this plan there will be far fewer audits. No loopholes, no breaks, no deductions. Deddryk (talk) 21:07, 8 April 2016 (UTC)
- Okay, I'll wait for those you want to help to come up with the detailed solution in order to review. -21:48, 8 April 2016 (UTC)
Is there any way to get out of the bin?[edit]
- This discussion was moved to RationalWiki:Chicken coop/Archive45. This is just a continuation of the (closed) coop case & doesn't belong in the Saloon Bar. WèàšèìòìďMethinks it is a Weasel 07:31, 11 April 2016 (UTC)
I have been here before...[edit]
...but i have spent more days high this week than sober and things a spiralling downward, so i am asking for the advice of the mob, specificly those who have had mental health issues. I am not asking where to go, as i am sure my gp will refer me fo someone, but what to expect. I have a horror for discussing intimate details of my life which has prevented me in the past from seeming help which i have often been told i need. I figure if i had some idea of whats in store i might this time actually get it. Sorry if this all a bit vague, i will try to clarify in the morning when the effects of, jesus, i dont even know the name of the ketamine like stuff i'm currently on. Thanking you all for your patience. AMassiveGay (talk) 21:59, 8 April 2016 (UTC)
- You need to make sure you don't take different things at the same time, or within 12 hours of each other. Don't mix alcohol with ANYTHING. If you can find a space where you're not too tired or high, go out to some park or place without too many people and walk around a bit. Listen to some music or just listen to the noises of the street/nature, whichever you prefer. If you do these things, and stop taking the drugs, you can expect to have it clear up in 48 hours or so depending on what you've put in you. I'd really like to know what you've taken, as that would help me predict effects, both short and long-term. Best of luck. Onward. Pbfreespace3 (talk) 05:16, 9 April 2016 (UTC)
- thanks for hour response, but i think you misunderstand. Not surprising as i was off my face when i wrote the above. I was not having a bad trip. I am only too awwre of the effects of the stuff i was on - i have been a habitual drug user for a long time. This is the problem. My drug use is fast becoming something out of my control and exasperating my very many pre existing mental heAlth issues. What i need to know is what to expect from the possible treatments if i have the strength to get help for these. AMassiveGay (talk) 10:44, 9 April 2016 (UTC)
- I could tell you a lot about mental health issues and some of the problems with how our society handles them, but from your description the main problem seems to be your exacerbating drug use. So let's start with that, why is your drug use spiraling out of control? The force of habit combined with a recent lack of social interactions to draw your priorities away from drugs? Or maybe the opposite; group pressure? Or is it just the need to get that rush and your usual dose not doing the trick anymore? 141.134.75.236 (talk) 14:50, 9 April 2016 (UTC)
- Is this why AMassiveGay's talk page edits have had a lot of typos recently? I'll sleep well tonight knowing that mystery is finally solved. Bye, and good luck! 2.123.153.190 (talk) 15:04, 10 April 2016 (UTC)
Hey how are you doing now, AMassiveGay? Better? Pbfreespace3 (talk) 20:11, 10 April 2016 (UTC)
- sober and reflecting on poor life decisions. Fortunately my financial situation will keep me sober for while in which time i will exercise, eat right and generally look after myself until i climb back on the horse and try to stick to rules next time. Thus the cycle continues. AMassiveGay (talk) 21:02, 10 April 2016 (UTC)
It's good that you're sober now. Exercise is a good substitute: it causes an endorphin rush that's very similar chemically to the opium and amphetamine high. It'll also improve your self-image, helping your mindset when dealing with future problems. I'm a proponent of running, as it's the oldest human activity (we ran from predators and to kill prey on the savannah). Get out and run! Pbfreespace3 (talk) 02:22, 11 April 2016 (UTC)
My Faith in Science[edit]
Hello guys. I come here because of a problem with my views on the world. My acceptance of the scientific consensus is not because I have studied the facts, but because I blindly believe almost any scientific consensus. In an argument with a creationist, I could not prove my point, and my position would be based on faith just like his. I have tried rectifying this problem by buying a few books, but "The Greatest Show on Earth" is long and I couldn't get through it. What are some resources which could help me understand the basics of the evidence for evolution? --TeslaK20 (talk)
- On talk pages, please sign your comments using four tildes (~~~~) or by clicking on the sign button: on the toolbar above the edit panel. You can also indent successive talk page comments using one more colon (:) for each line. Thank you.
- Regarding your question, if you just want to "bone up a little" on it, you could always try a well-made, scientific video. It can be easier to go through than text if you're looking to polish your basics. I'd recommend starting with "How Evolution Works" by In A Nutshell:
- For a more in-depth view, I'd watch this entire playlist of CrashCourse Biology:
- There's tons and tons and tons more of videos on the topic, these were just off the top of my head. Also, remember that educating yourself on the science of evolution and having to present the same proven findings to a creationist are two very different things. For one, the creationist will derail the discussion pretty quickly, using various fallacies and rhetorical strategies on you. Debating a Creationist is a science in itself. Regardless, it's always a good idea to consume more science, even in video form. Hope the links helped! Reverend Black Percy (talk) 16:11, 9 April 2016 (UTC)
- PS: I haven't watched the following videos myself (as I've largely read my way to my understanding of Evolution), but they seem alright and are highly voted. Check them out - the playlist "Genetics and Evolution" from Clearly Stated: Reverend Black Percy (talk) 16:14, 9 April 2016 (UTC)
- I'd recommend Berkeley's Intro to Evolution Lord Aeonian (talk) 22:29, 9 April 2016 (UTC)
There are indeed many good videos, some well illustrated, but if you want to be slightly more serious, check out Jerry Coyne's talk here. If you have a specific question, then ask it, and we may give you more specific resources. ~ Aneris ✻ 00:11, 10 April 2016 (UTC)
OK, thanks everyone. --TeslaK20 (talk) 07:28, 10 April 2016 (UTC)
- Nobody has the time to independently verify every (purported) fact they encounter. We generally trust facts (or not) based on the source & our preconceptions about what sources we trust, and only tend to check up on things we're uncertain about. Believing what the scientific consensus says is a reasonable position, & pretty much what most people do, although of course science was wrong before and there are always areas where the consensus should be challenged (ideally by people who know what they're talking about). The counterposition — distrusting the scientific establishment while believing any old crap you read on the internet which conforms to your worldview — is much less reasonable. ЩєазєюіδMethinks it is a Weasel 16:02, 10 April 2016 (UTC)
- 1+. That being said, even though it is rational to simply redirect to science when the discussion comes up, it's also a lot nicer personally to actually have scrubbed up a bit on the facts and the science. So, it's still a worthwhile project to dive in and check out some of the technicalities for yourself. E.g. via the links above. Reverend Black Percy (talk) 16:22, 10 April 2016 (UTC)
- Oh, and by the way, don't let that guy get away with trying to use the on the spot fallacy on you. Reverend Black Percy (talk) 16:51, 10 April 2016 (UTC)
SpaceX Conspiracy Theories?[edit]
After SpaceX's landing on their barge, are any conspiracy theorists acting up about it? KOMF 22:12, 9 April 2016 (UTC)
- i'm sure Alex Jones will call it fake in the first 30 seconds of his next show. Petey Plane (talk) 00:18, 10 April 2016 (UTC)
- Oh boy. I just googled space x fake: the flat earth and the "space travel is impossible" people are onto it. The miracles of CGI. Got to keep the money rolling in to NASA.[7][8] Nothing particularly unique to SpaceX that I can see. But yeah it's all done with powerful CG workstations that aren't over the horizon. Annquin (talk) 12:37, 10 April 2016 (UTC)
Not really a conspiracy theory, but i believe the drone ship the rocket landed on, "Of Course I Still Love You", gets its name from The Culture series of novels bu Ian M. Banks. Drones play a large roles in those books. Made me smile when i saw that. Petey Plane (talk) 20:01, 12 April 2016 (UTC)
Potential coup of Phyllis Schlafly from the Eagle Forum[edit]
Members of the Eagle Forum, including Shlafly's own daughter, Ana Cori, are attempting to kick the old bag out of her own club, after she endorsed Drumpf. Have Andy or Rog weighed in on this yet? Petey Plane (talk) 17:23, 11 April 2016 (UTC)
- I believe that teh Assfly also supports Fuckface von Clownstick, so I don't think he'll agree with this. Not sure about Roger boy.--JorisEnter (talk) 17:28, 11 April 2016 (UTC)
- I thought that
Teh DolanThe Donald wouldn't have enough fundie cred for an endorsement from Andy.--Kugelschreiber (talk) (mail) (block) 19:04, 11 April 2016 (UTC) 19:04, 11 April 2016 (UTC)
- A hypocritical Christian fundamentalist you say? Also, waiting to see how this all plays out before updating her page. Petey Plane (talk) 19:06, 11 April 2016 (UTC)
- What page are you talking about?--Kugelschreiber (talk) (mail) (block) 19:09, 11 April 2016 (UTC) 19:09, 11 April 2016 (UTC)
- I meant Phyllis' page, but i see that it's already been updated. That's fine, i just figured more would come out of this over the next week or so. Petey Plane (talk) 19:17, 11 April 2016 (UTC)
- Remember when there were debates over whether Andy is a racist or not? Vulpius (talk) 19:58, 11 April 2016 (UTC)
- Well, is he or isn't he? --Kugelschreiber (talk) (mail) (block) 20:25, 11 April 2016 (UTC) 20:25, 11 April 2016 (UTC)
From the crone's FB page, "...the attendees purported to pass several motions to wrest control of the organization from me. They are attempting to seize access to our bank accounts, to terminate employees, and to install members of their own Gang of 6 to control the bank accounts and all of Eagle Forum... This kind of conduct will not stand and I will fight for Eagle Forum and I ask all men and women of good will to join me in this fight."
Couldn't have happened to a nicer person. Petey Plane (talk) 00:11, 12 April 2016 (UTC)
- Authoritarian nut on Authoritarian nut, seems pretty normal for many of these groups. If the world is lucky the group will fall apart from internal strife and people no longer being able to work together. -EmeraldCityWanderer (talk) 13:35, 12 April 2016 (UTC)
- Say what you want about Drumpf, it's been a lot of fun watching his candidacy cause massive rifts within wingnut groups. First Breitbart.com, then Fox News, and now Eagle Forum. Petey Plane (talk) 14:15, 12 April 2016 (UTC)
- Someone upsetting the party establishment is always fun to watch (that's much harder to accomplish with the Democrats, as they have Hillary and the superdelegates (holey fuck, "Hillary and the Superdelegates" sounds like the name of a band!!), but not impossible, Sanders is rocking the boat and Hillary is busy fighting back, ratfucking included).--Kugelschreiber (talk) (mail) (block) 14:21, 12 April 2016 (UTC) 14:21, 12 April 2016 (UTC)
- Yeah, you've gotta love when the established powers of a political machine that is so obviously corrupt are challenged by a person they can't control. Forget Nader; Trump's candidacy should be a case study in how to sway an election vote. BurgerDominar (talk) 00:45, 14 April 2016 (UTC)
GMail is randomly accepting rationalwiki.org email, or not[edit]
GMail is being flaky as hell about accepting or not accepting email from the RW server - sometimes works, sometimes hits spam, sometimes gets 550 refused. Google doesn't do customer service, so it's difficult to get them doing anything about this or not.
We aren't in the email blackhole lists (I see our IP 173.255.233.133 gets 6 DNSBL hits in [9], but I go to the sites in question and they say it's not listed), so the only other hypothesis that springs to mind is that they don't like email coming from J. Random Linode VM (and at least one DNSBL does consider that a reason). SPF records might help, though this will involve (a) working them out (b) getting Trent to do it 'cos I don't have access to the DNS config. In the meantime, if you aren't getting emails and have an alternate email provider, try that. Are any other large email providers being flaky in accepting our email?
I've also asked on mediawiki-l for general advice on this sort of problem - David Gerard (talk) 12:50, 2 April 2016 (UTC)
- At a minimum, adding an SPF record for rationalwiki.org would make it more trustworthy. --JeevesMkII The gentleman's gentleman at the other site 21:27, 2 April 2016 (UTC)
- yeah, we just did this precise thing at work, I guess I'll need to work this out (and then catch Trent's beleaguered attention) - David Gerard (talk) 22:40, 2 April 2016 (UTC)
- You might as well ask if it's possible to set a sensible reverse DNS entry while you're at it. Then you could use DKIM as well, which should give all your mail a healthy not-spam score. --JeevesMkII The gentleman's gentleman at the other site 00:44, 3 April 2016 (UTC)
- Is that the reason why I just can't receive the e-mail with the confirmation link?--Kugelschreiber (talk) (mail) (block) 00:40, 4 April 2016 (UTC) 00:40, 4 April 2016 (UTC)
- From the last email I got:
Received-SPF: none (rationalwiki.org: No applicable sender policy available) receiver=mx3.messagingengine.com; identity=mailfrom; envelope-from="www-data@rationalwiki.org"; helo=li243-133.members.linode.com; client-ip=23.239.12.253
- Reverse DNS for
173.255.233.133is
li243-133.members.linode.com− why not
mail.rationalwiki.org? Notice the
helo.
- Setting up SPF for the
rationalwiki.orgdomain should help and takes about a minute; e.g.
v=spf1 mx -allshould work (assuming only
mail.rationalwiki.orgis sending out mails).
- DKIM can also help, but is a bit more work to set up as you need to configure the MTA to sign mails.
- If it's in the spam, maybe try checking if there's a
X-Spamheader with a list of reasons?
- As I mentioned a few months ago over email, I've had random disappearing RW emails sometimes (e.g. someone left a talk page message, which *should* of sent an email but didn't) ... So perhaps this is related... Carpetsmoker (talk) 13:45, 6 April 2016 (UTC)
- "of" is not an auxiliary verb. :( 142.124.55.236 (talk) 13:49, 6 April 42016 AQD (UTC)
- Can't be perfect all the time ;-) I also see now that most had been mentioned already. Ah well... Carpetsmoker (talk) 14:02, 6 April 2016 (UTC)
I was about to ask why I wasn't getting the confirmation email after I changed to Gmail, but then I saw this. So I guess I'll just wait it out. 107Ag47 03:40, 16 April 2016 (UTC)
Mission survey[edit]
If you've got time, please fill out the 2016 RationalWiki Mission Survey!
I'll be leaving it open until 12 May 2016.
Any suggestions are welcome! Cømяade FυzzчCαтPøтαтø (talk/stalk) 23:29, 12 April 2016 (UTC)
- Mm. First suggestion for the survey: "This is a good idea; but you are going to get a very biased sample of the contributors."
- Aside from a reddit post, am not sure how to get non-contributors to answer. :/ FU22YC47P07470 (talk/stalk) 23:50, 12 April 2016 (UTC)
- Probably best not to attract the anti-SJW obsessives. They'll just spam it and make the results next to useless. 142.124.55.236 (talk) 23:54, 12 April 42016 AQD (UTC)
- What happens to this survey? who wrote it? Who decided what the questions were? Flannan Isle (talk) 11:34, 13 April 2016 (UTC)
- I still hope that this survey is just a way to see if we even can get some kind of statistics on the popularity of the mission statement or not. I hope it's not related to any plans to change the mission statement (!?). Reverend Black Percy (talk) 12:11, 13 April 2016 (UTC)
- Given Fuzzy has a history of trying to pull major policy changes by vote with little discussion and changing premises, my confidence is also low - David Gerard (talk) 13:34, 13 April 2016 (UTC)
- @Flannan: I wrote it. If there's a next one, other people can help rewrite it.
- @RBP: It's just to survey whether people like the current mission. Presumably if people really dislike the current mission, then that'd be a reason to change it -- but that's not what the results currently show.
- @David: That's literally wrong. I wrote an essay that argued that RationalWiki should change its policy on politics -- and that's the same as "trying to pull major policy changes"? Right. (And doing things "by vote" is suddenly taboo on RW?) Sir ℱ℧ℤℤϒℂᗩℑᑭƠℑᗩℑƠ (talk/stalk) 14:21, 13 April 2016 (UTC)
- This should have been discussed prior to launch. ΨΣΔξΣΓΩΙÐMethinks it is a Weasel 18:37, 13 April 2016 (UTC)
- Anybody can create a survey on anything they like, but if it's promoted on every RW page then it looks like it's official. If nothing else, it's not a short survey and it seems like it's wasting everybody's time who does it in good faith thinking it's actually going to feed into RW policy. Annquin (talk) 18:54, 13 April 2016 (UTC)
Next time I'm thinking of asking RW users a question, I'll make sure to ask RW users whether they want to be asked the question. αδελφός ΓυζζγςατΡοτατο (talk/stalk) 20:02, 13 April 2016 (UTC)
- [EC] I've marked the intercom as read. It no longer appears at the top. FU22YC47P07470 (talk/stalk) 20:15, 13 April 2016 (UTC)
- this wasn't just "a question" though. Flannan Isle (talk) 20:14, 13 April 2016 (UTC)
- Pluralize it, same point. Herr FuzzyKatzenPotato (talk/stalk) 20:15, 13 April 2016 (UTC)
- Do you seriously not see a difference between "asking a question" and "broadcasting it on the intercom as if it's an official announcement"? - David Gerard (talk) 20:18, 13 April 2016 (UTC)
- I see the difference. Hence why I undid it. Herr FüzzyCätPötätö (talk/stalk) 20:20, 13 April 2016 (UTC)
- FCP is a wanker. Anyone coming round to that yet? Pippa (talk) 20:23, 13 April 2016 (UTC)
- Still shows on every page for me as "from FuzzyCatPotato (Talk), group Site wide (urgent) at 23:29, 12 April 2016" - the reason "Site wide" has "urgent" after it is that it's for things of site wide urgency - David Gerard (talk) 20:26, 13 April 2016 (UTC)
- @Pippa: Thanks, that's really useful.
- @DG: It's been marked as read for anonymous users. As a logged in user, you must mark it as read for it to disappear. Moreover, Site Wide is the only category that actually goes to everyone -- the mod elections were also apparently urgent. FU22YC47P07470 (talk/stalk) 20:28, 13 April 2016 (UTC)
- Mark as read applies only for the person marking as such. FCP is also incompetent. (as well as being a wanker) Pippa (talk) 20:30, 13 April 2016 (UTC)
- @Pippa: read the intercom log: Special:Log/intercom. It's marked as read for all anonymous users. 20:36, 13 April 2016 (UTC)
I don't think you're a wanker[edit]
But I do think you have some very bureaucratic urges that might best be excised with a sporting attempt at law school or similar. ikanreed You probably didn't deserve that 20:34, 13 April 2016 (UTC)
- You're probably right. Polling seems as unbureaucratic as it's gonna get, though, for trying to get people's opinions. αδελφός ΓυζζγςατΡοτατο (talk/stalk) 20:39, 13 April 2016 (UTC)
- For crying out loud. Before polling try to see if there's something to poll about first. King Log rather than King Stork. (= often the right thing to do is NOTHING) Pippa (talk) 21:13, 13 April 2016 (UTC)
- It may not be needed, but does it hurt? Lord Aeonian (talk) 23:56, 13 April 2016 (UTC)
- Yes it does! These unsolicited solicitations of my opinion hurt my back. :( 142.124.55.236 (talk) 00:16, 14 April 42016 AQD (UTC)
Plans for the results[edit]
Just as an interested participant, and considering this ball is already rolling and so forth - will you be producing the results to us here? Will you try to emulate the methodology section of a scientific study, by yourself taking the first tone to point out the limits of the conclusions that can be drawn? (E.g. how many answered it compared to how many active editors we have, how many people outside of the survey and on the actual site were critical of it, what type of selection bias do you think exists among those who did answer it, and so on...). Reverend Black Percy (talk) 00:14, 14 April 2016 (UTC)
- Sure, I or another certainly can. Whoever does, I'm sure they wouldn't pass up assistance. The FCP Foundation (talk/stalk) 00:23, 14 April 2016 (UTC)
Speaking of surveys[edit]
Anyone wanna check out this forum thingy I created a while back? In case of paranoia, make note of the Another note:. 142.124.55.236 (talk) 00:31, 14 April 42016 AQD (UTC)
- I opened the link, saw a wall of text... Interesting. I'll look at it and give a comment. Thanks for the tip! Reverend Black Percy (talk) 00:43, 14 April 2016 (UTC)
Unfortunately[edit]
Several responses have included personal information, and it is impossible with Google Forms to remove individual responses from the "Responses" page. As such, I've made that page private. I can provide the Google Spreadsheet of responses for anyone interested.
Relatedly, the amount of responses has gone 69-119-20-2. (The first two days were when the form was on the Intercom.) Is it worth it to wait a month? Fuzzy "Cat" Potato, Jr. (talk/stalk) 14:12, 15 April 2016 (UTC)
- Strike that. Apparently Google forms updated this February, I've removed the problematic individual responses. Herr FuzzyKatzenPotato (talk/stalk) 14:26, 15 April 2016 (UTC)
Hilarious Atheist Breakdown[edit]One of the less glorious moments of New Atheism. TheAmazingSkeptic (talk) 22:13, 14 April 2016 (UTC)
- Hilarious, but how is this a "moment of New Atheism"? More like a "moment of nutpicking". Reverend Black Percy (talk) 22:31, 14 April 2016 (UTC)
- Damn, I guess atheists really are just angry at God. Islam proven Subhanallah. Wait, wrong religion...Lord Aeonian (talk) 05:29, 15 April 2016 (UTC)
- Is it just me or does his behavior seem scripted as hell? His pauses inbetween make it seem like he struggles to remember his memorized lines... ∈ NameThatNobodyTakes (✎) 08:06, 15 April 2016 (UTC)
- all that shows is that he is not a good public speaker. And why isnt he wearing shoes? AMassiveGay (talk) 10:48, 15 April 2016 (UTC)
Poll on hatnotes for the GG trio of articles[edit]
This vote is currently underway, and I would humbly invite the eyes, minds and keyboard mashing hands of the community to participate in the ensuing discussion. Thank you in advance. All the best, Reverend Black Percy (talk) 11:42, 15 April 2016 (UTC)
Anyone want a giggle ...[edit]
... then try here. Its the New York School of Homeopathy's report on the 'proving' of Sanguis Didelphis Virginiana derived from the N American opossum. "Inspiration for this proving came from a client in the NYSH student clinic who had told us of a vivid and unusual vision; a drunken opossum (who had eaten compost from wine-making refuse) was dancing on the roof of her garage." Nuff Sed! Pippa (talk) 17:28, 16 April 2016 (UTC)
- A pseudoscience based on an anecdote based on a supernatural vision. Success guaranteed! oʇɐʇoԀʇɐϽʎzznℲ (talk/stalk) 16:37, 17 April 2016 (UTC)
Community Standards change[edit]
RationalWiki_talk:Community_Standards#Change_the_Mobocracy_section
I'd like to change the CS. The most important bit is just to limit Coop cases to 3 days, to prevent really drawn-out dramafests like what's currently going on. Fuzzy. Cat. Potato! (talk/stalk) 16:22, 17 April 2016 (UTC)
- What if a consensus hasn't been reached? Lord Aeonian (talk) 19:21, 17 April 2016 (UTC)
- That sort of thing doesn't bother FCP. I just spotted the words "Community Standards change" in recent changes & didn't have to think long about whose thread it would be. ЩєазєюіδMethinks it is a Weasel 19:59, 17 April 2016 (UTC)
- @LA: If consensus isn't reached, then status quo wins. (e.g., the Kugelschreiber vote failed, so Kugelschreiber remains in the same position -- unbanned.) For an individual case where the vote balance is actively changing after 3 days (which is unlikely), then, just like now, people ask for a longer time limit.
- @Weaseloid: Thanks for the love. The FCP Foundation (talk/stalk) 23:09, 17 April 2016 (UTC)
The Kalaam Argument Against God[edit]
Greetings all, recently I discovered the following variation of the kalaam cosmological argument against God. The purpose of the argument is not to prove the non-existence of God, but rather to show the flaws in the original Kalaam by working with the same premises. Here it is:
1. Nothing which exists can cause something which does not exist to begin existing.
2. Given (1), anything which begins to exist was not caused to do so by something which exists.
3. The universe began to exist
4. Given (2) and (3), the universe was not caused to exist by anything which exists
5. God caused the universe to exist
C. Given (4) and (5), God does not exist
So, do you guys think we could add this to the relevant articles? Namely, the article on the argument from first cause and perhaps the William Lane Craig article? I would add it myself but I'd like to double check with everyone here to make sure the argument is actually valid, it seems so to me but I could be wrong. Remember, by "valid" I don't mean an actual disproof of God, but rather that this argument faithfully follows the premises and assumptions of the original kalaam, so as to expose its problems. Lord Aeonian (talk) 07:26, 9 April 2016 (UTC)
- If you mean 'does it similarly beg the question?' then yes. Some of your assumptions seem to be the opposite of the regular deal, though. 142.124.55.236 (talk) 09:29, 9 April 42016 AQD (UTC)
- Your premises don't make a whole lot of sense. (1) is only meaningful when talking about matter & energy, and I don't think many people believe that God is composed of atoms. WẽãšẽĩõĩďMethinks it is a Weasel 09:43, 9 April 2016 (UTC)
- I don't really understand what you are getting at. 1, and 5 are simply stated. I see no obvious raeson to accept any of them as axiomatic.
- If your objective is to show an example of another bad argument then you have succeeded - but I think the example is more likely to confuse people than clarify things.
- Furthermore if your objective were to prove that god cannot exist then you run the danger of accepting the burden of proof. It seems this is not your objective but again there is considerable scope for confusion. --Bob"Life is short and (insert adjective)" 10:40, 9 April 2016 (UTC)
- Weaseloid came pretty close to what I would have said about #1. Kindly do not consider it casuistry if I claim it matters what the definition of "exists" is. What is the word's scope of application? I feel comfortable saying matter exists. Do patterns exist? In what ways does behavior "exist"? (Yes, I am getting at emergence here.)
- If we reify patterns or perceptions as "things" then it will take some wriggling to credibly assert that they "existed" before they came into being. Words, words, words... someone, who existed, was the first one to use "cromulent" in a human utterance. With Bob, as #1 was simply stated above, I see no obvious reason to accept it as axiomatic, for starters. Alec Sanderson (talk) 15:29, 9 April 2016 (UTC)
- (EC) Also, combining (4) and (5) results in a contradiction, so one of the two must be false. Your proposed conclusion does not logically follow. Unless with (4) you just mean "not caused to exist by anything which exists within the universe", in which case you've only 'proven' that God is transcendental. 141.134.75.236 (talk) 15:38, 9 April 2016 (UTC)
- (5) is not really part of the argument proper, it is the assertion of the Abrahamic religions. I suppose you could break this into two arguments; look at (1)-(4), and then use (4) as a separate conclusion to disprove (5). In other words, they don't contradict because (4) and (5) are not true at the same time, we assume (4) to disprove (5). Lord Aeonian (talk) 22:27, 9 April 2016 (UTC)
Alright, but let's look at the original kalaam:
1.Everything that begins to exist has a cause.
2.The universe began to exist.
C.Therefore, the universe must have a cause.
Many of you are saying "X isn't defined," "why should we accept Y," and so on, but the point is to show why the kalaam fails. The problems people have brought up are the very problems which plague the kalaam, which is the whole point. Lord Aeonian (talk) 22:27, 9 April 2016 (UTC)
- It might be easier to just say what's wrong with the kalaam argument in prose rather than think up a different thing arguing for the opposite and saying 'hey, you might think this thing I came up with is bogus but it's the same with the kalaam!' But if you wanna point out the flaws of the kalaam in argument form, try this:
- P1: Big stuff doesn't just appear out of nowhere and I'm betting (read: asserting) the same goes for small stuff too!
- P2: The universe is (currently!) made up out of a bunch of big stuff and smaller stuff!
- C: The universe didn't just appear out of nowhere! A magical girl named Sally poofed it into existence! Yup! (Sure!)
- PS: There's been an extensive discussion about similar arguments on the argument from first cause talkpage; might be worth checking out. 141.134.75.236 (talk) 23:09, 9 April 2016 (UTC)
- Thank you, I will look at the talk page. I usually just link apologist to RW or IronChariots if they use the argument, the reason I brought this up is because some theists will come at it from a "reasonable faith" standpoint, whereby even if the kalaam is not sound they still think it is "enough" when combined with faith. I think a kalaam against God is much more effective than, say, the example you gave, if only on an emotional level. After all, few are convinced by reason alone. Lord Aeonian (talk) 23:14, 9 April 2016 (UTC)
- Well, if you're going for an exact opposite of the kalaam argument, keep it simple, like:
- P1: Nothing that begins to exist has a cause.
- P2: The universe began to exist.
- C: Therefore, the universe wasn't created by God: it has no cause.
- Not sure if it'll have the effect you're aiming for though. 141.134.75.236 (talk) 23:54, 9 April 2016 (UTC)
- I agree with you on the keep in simple part, so I got it down to this:
- P1: Nothing which exists can cause something which does not exist to begin existing.
- P2: The universe began to exist
- C: Therefore, the universe was not caused to exist by anything which exists
- The rest of the premises seemed to be making things clear, rather than actually adding to the argument. I wouldn't use your example though, you have to be careful with the wording in order to stay faithful to the original kalaam. I can already see the immediate theist response - disputing the first premise with special pleading for God - which would cleanly lead to me pointing out the same problem with the first premise of the original kalaam. Lord Aeonian (talk) 00:00, 10 April 2016 (UTC)
- If you're arguing with people that don't need their arguments to be necessarily logically valid, but only sufficiently plausible(-sounding), they'll just jump onto some other concept to equate God with though. The order in the universe, objective truth, logic itself etc. 141.134.75.236 (talk)
- True, but that's a pantheistic idea of "God" and incompatible with the Abrahamic God, which the Kalaam is usually used to support. If they tried to use such concepts to support the Abrahamic God, they would have to use some sort of presuppositional apologetics and fall prey to the associated problems. I would also note that our page on the presuppositional transcendental argument has a section for a version against God, which is the same thing I'm proposing here for the kalaam. Lord Aeonian (talk) 00:48, 10 April 2016 (UTC)
- It pretty much debunks itself in the first point. If nothing is created without cause and in the same paragraph they argue god is created without cause then what really needs to be said? It just says "I'm scared and I want something, anything, to believe in even if it makes no sense coming out of my mouth." -EmeraldCityWanderer (talk) 20:54, 12 April 2016 (UTC)
Alright, from I'm seeing here this argument is a valid reversal of the kalaam, i.e. failing for the same reasons. I'm going to to add it to the cosmological argument in a similar fashion as the reverse transcendental argument is presented on that page. I've simplified it as follows:
P1: Nothing which exists can cause something which does not exist to begin existing.
P2: The universe began to exist
C: Therefore, the universe was not caused to exist by anything which exists Lord Aeonian (talk) 01:34, 18 April 2016 (UTC)
For the record - to those who still care about that[edit]
I saw that "Burger Dominar" was blocked as a supposed sock of mine. Let me tell you that this user is definitely not a sock of me. I don't know how to prove it to you. You could of course unblock Burger Dominar, because given that we are not the same person, you will soon find whatever evidence you need to be convinced. Anyway, I should probably stop defending him, because that might end up actually hurting me. Which might have been the plan all along. I don't know whose plan, though. Pizzameister (talk) 23:41, 18 April 2016 (UTC)
- It is possible that the user in question is not the same person as you. It is clear, though, that they were someone's sockpuppet and that they were intentionally imitating you (and Arisboch too a bit). And with impersonating other people being an actionable offence, it turns out it doesn't actually matter whether they're you or not. How about that, eh? ;) 142.124.55.236 (talk) 23:49, 18 April 42016 AQD (UTC)
- From what I read though, this user doesn't seem like a sockpuppet. And sockpuppeting is not in and of itself a bannable offense. The impersonation might have been in jest. Pbfreespace3 (talk) 23:53, 18 April 2016 (UTC)
- I'm not taking sides in this, but "dominar" is italian for "master" (in the same way as "meister" is german for "master"). Some argue pizzas and burgers are somehow related. And Joris said the same joke was used on the user page. But I'm not drawing any conclusions based on that. Reverend Black Percy (talk) 00:30, 19 April 2016 (UTC)
- That's why I said the impersonation was probably in jest. Perhaps we should ask this user if they are really impersonating Pizzameister or if they were just joking? Pbfreespace3 (talk) 00:35, 19 April 2016 (UTC)
Protect the Saloon Bar from the internet![edit]
" 20:28, 18 April 2016 142․124․55․236 (Talk | contribs | block) protected "RationalWiki:Saloon bar" [edit=autoconfirmed] (indefinite) [move=autoconfirmed] (indefinite) (Hmm...) "
Hmm indeed. Was there a spamist invasion or something? (IE, could be legit, after all.) ħuman 04:47, 19 April 2016 (UTC)
- Yup. Of the doxing kind, even. But it seems they buggered off for now, so I'll lift the protection. 142.124.55.236 (talk) 04:58, 19 April 42016 AQD (UTC)
So... how to do suggestions?[edit]
I want to suggest an article, and, excuse my noobishness, but is there some kind of protocol or do I just add it to the list? TheMyon (talk) 12:29, 19 April 2016 (UTC)
- We have had people suggest them here, but there is no guarentee that they will be created. Normally, people add suggestions to the to do list; you can also create an article yourself. I would suggest experimenting with your sandbox.--Owlman (talk) (mail) 12:39, 19 April 2016 (UTC) 12:39, 19 April 2016 (UTC)
Category bans[edit]
As some people keep edit-warring over some articles but not over others, it might be a good idea to be able to ban people from editing certain categories while letting them edit others. This could stop people from edit-warring while still letting them edit. KOMF 17:43, 18 April 2016 (UTC)
- Topic bands do exist on, say, Wikipedia. I have zero knowledge about Wikipedia administrativa, do they work? Do they help to lower the amount of drama or do theyy just shift drama and/or create new problems?--Kugelschreiber (talk) (mail) (block) 17:58, 18 April 2016 (UTC) 17:58, 18 April 2016 (UTC)
- They usually result in the bozo being kicked off Wikipedia altogether - David Gerard (talk) 18:35, 18 April 2016 (UTC)
I proposed this in the coop, the response was "a topic ban will effectively block these editors from RationalWiki." Being a zealot is a pretty sad way to live. Lord Aeonian (talk) 19:28, 18 April 2016 (UTC)
- It doesn't block anyone. If someone is a single-issue editor and won't edit if they can't work on their preferred topic that isn't our problem. The goal isn't to make everyone happy, but to have an effective, informative, somewhat civil wiki. If we're having constant battles on particular topics I'm not sure we're any of those things. AyzmoCheers 19:58, 18 April 2016 (UTC)
This seemed to work pretty well with Sorte Slyngel. Herr FuzzyKatzenPotato (talk/stalk) 20:32, 18 April 2016 (UTC)
- Sorte Slyngel is a good case in point. His edits and reverts were absurd, seriously citing to a known wingnut crank that our own wiki trashes at his own article page. He spewed some of the nastiest crap at me, all the time. Then there is Arisboch, who has been banned and binned often, and supposedly, finally, permanently - he enthusiastically participated with sociopaths who were orgnaizing to contact my son, and his neighbors -- having provided contact information -- and orders to tell them I was a "pedophile supporter." And Avenger, who pissed off almost everyone. It is not an accident that these three miscreants are Zionists who detest my POV on their issue.
- What really annoys me is when *I* get accused of also edit-warring when the people I'm having trouble with are those three! I have sometimes asked for help -- in the Sorte Slyngel case, I asked two mods, and one simply stated he didn't "care about the topic." The other wouldn't do anything until the situation had overtaken the place with drama.
- People here need to grasp this: Second only to the Gamergaters, Zionists are the most vicious and unreasonable politicos online. If anyone doubts this, I stand ready and able to write an entire article documenting it. That I have knowledge and interest in a topic in which the other side has a well-established tendency to behave atrociously should not be held against me.---Mona- (talk) 02:22, 19 April 2016 (UTC)
- Second only to the Gamergaters, Zionists are the most vicious and unreasonable politicos online. My my, what an objective position! Some political theists of the Abrahamic persuasion would beg to differ. Lord Aeonian (talk) 03:38, 19 April 2016 (UTC)
- You rant against the "Zionists" are quite amusing. Just keep it coming, I got chips and cola ready.--Kugelschreiber (talk) (mail) (block) 12:55, 19 April 2016 (UTC) 12:55, 19 April 2016 (UTC)
- Aeonian: as I wrote, I'm in a position to write an article on the vicious online behavior of many Zionists -- a fully documented one. All decent people would be fucking aghast at the emails and tweets guys like Glenn Greenwald or Max Blumenthal receive from Zionists, including threats. I'm privy to a lot of this material, and also have my own to draw from. Not to mention publicly available vileness all over the Internet. So, if you want it, I can do it. Do you? (Let me finish up with the page I'm currently active on, as well as the Targeted Individual piece, and I can make this next.)---Mona- (talk) 19:09, 19 April 2016 (UTC)
- By the way Aeonian, have you seen all the activity at my user page, and the accounts being created? Like one just created wiht the name "I Want to Rape Mona." All the accounts that various editors are busy deleting and hiding these cretains' unacceptable personally insulting rants? These are all Arisboch's good friends, the ones he encouraged in their hatred of me in a thread elsewhere about my supposed antisemtism. These sickos are both Gators and Zionists. Separately they can be depraved; combined, they are vicious and vile beyond description.---Mona- (talk) 19:16, 19 April 2016 (UTC)
These are all Arisboch's good friends [..] These sickos are both Gators and Zionists. [...]- {{{2}}} Proof or GTFO.--Kugelschreiber (talk) (mail) (block) 19:30, 19 April 2016 (UTC) 19:30, 19 April 2016 (UTC)
- You, Arisboch, are not the boss of me. Every sentient being knows this invasion of vermin originates at that site you've been so happily romping at. Four moderatros knew it, whihc is why the "perma-banned" you.---Mona- (talk) 19:38, 19 April 2016 (UTC)
- Argument by assertion, Jonanism and persecution complex. Cute. This is getting more and more unhinged. I also don't know and not care who of these fabled 4 moderators thought they "knew".--Kugelschreiber (talk) (mail) (block) 19:45, 19 April 2016 (UTC) 19:45, 19 April 2016 (UTC)
- Arisboch, no one who matters is going to believe you. The whole site saw what happened here, and especially (but not only) to me, that caused four mods to perma-ban you. What's been going on in Recent Changes in the last 48 hours does not represent some "persecution complex" on my part. No, it's the same vileness you promoted and helped bring here last December. Enough people are informed on all that such that your hand-waving cannot detract from the reality of the matter.---Mona- (talk) 20:37, 19 April 2016 (UTC)
- So now we're at argumentum ad populum? Keep it coming, Mona, keep it coming. You provide these clowns with the drama they love.--Kugelschreiber (talk) (mail) (block) 21:23, 19 April 2016 (UTC) 21:23, 19 April 2016 (UTC)
An argument for a majority is not fallacious, Arisboch, when the issue is credibility, of which you have almost none. But you are true to form: hurling various fallacies where they don't apply is among your favorite things to spew.---Mona- (talk) 22:51, 19 April 2016 (UTC)
- So I'm not popular here? Big deal.--Kugelschreiber (talk) (mail) (block) 23:01, 19 April 2016 (UTC) 23:01, 19 April 2016 (UTC)
Why don't you search through this subreddit to see the usual trolls and death threats...in addition to people getting assaulted, their properties vandalized, disowned by family, etc. Not to mention innocents being classified as terrorists by certain places. I hadn't heard of the incidents involving your son, and those are horrible if true, but to say that Zionists and god damn Gamergators are the nastiest people around? What a joke. Lord Aeonian (talk) 19:33, 19 April 2016 (UTC)
- Aeonian, you have repeatedly not answered my question. I am more than capable of documenting the grossly abusive online behavior of Zionists -- and not remotely confined to some sub-reddit -- nearly as bad as that of the Gators. You just let me know, and when I'm done with two articles I currently am trying to get finished, I'll get right to it.---Mona- (talk) 19:41, 19 April 2016 (UTC)
- I'm sure you can, and it doesn't matter, because the point is that Zionists are GGers are nowhere near the worst of your grab bag of adjectives. Also, the incidents I described are obviously not "confined to some subreddit," some are just documented there. Lord Aeonian (talk) 19:58, 19 April 2016 (UTC)
- "because the point is that Zionists are GGers are nowhere near the worst" I assure you, they are. And I can show it. Tho why it should have to be at this site, of all sites, is pretty silly. The Gators have been vile, and we've had big trouble from 3 Zionists who have had to be seriously disciplined. One of these joined with Gators and the results were obvious, as they still are, especially as directed at me. ---Mona- (talk) 20:33, 19 April 2016 (UTC)
- You assure me, they are? Really? Have you been physically assaulted by groups of Zionists - in a Western country - for your views? Has your property been vandalized and attacked? Have Zionists taken legal action against you for your views? Is there a death penalty for the thought crime of supporting Palestine in multiple countries, with a high risk of vigilante "justice?" Really, I think you should look through that sub and see what former Muslims have to endure before you come here with delusions of grandeur because of pathetic basement dwellers like the GGers. Lord Aeonian (talk) 20:42, 19 April 2016 (UTC)
- I'm talking about Westerners. The harassment online from Westerners who write in English (for the most part). If you refer to some of the more theocratic Muslim nations, that's a horse of a whole different color.---Mona- (talk) 21:01, 19 April 2016 (UTC).
- Again, I really wish you would look through that. The things I'm talking about occur in places like Tower Hamlets. Lord Aeonian (talk) 21:07, 19 April 2016 (UTC)
- I did look through it. I'm not sure what you want me to see?---Mona- (talk) 22:51, 19 April 2016 (UTC)
- Are you ex Muslim? There might be a good story there. Not sure if here or talk page. Worth a few unforgivable sins on the house. StickySock (talk) 20:45, 19 April 2016 (UTC)
- Yeah, here you go. I'm trying to recruit more editors to expand this site's coverage of Islamic theology and counter-apologetics, sadly RW's reputation proceeds it. Lord Aeonian (talk) 20:50, 19 April 2016 (UTC)
- Back in the mid-80s, I was racing away from Roman Catholicsm (an especially vicious version of it) and became good friends with an Iraqi-American who was also running fast from Islam; we both ended up atheists. She, however, remains opposed to Islamophobia and is supportive of Palestinian rights.---Mona- (talk) 21:06, 19 April 2016 (UTC)
- I actually support the Palestinian issue. What I don't support is users who are waging a damn jihad - complete with persecution complex - over it. And the whole Islamophobia BS is really just racism, the Western liberals and conservatives have turned "Islam" into a political football. If you think it has anything to do with Islam, ask yourself how many talking heads on either side have read Qur'an, tafseers, ahadith, etc. Now ask yourself why they think all Desis, Arabs, North Africans etc are "Muslims." Hell, these idiots think Sikhs wearing Turbans are Muslims. Is that Islamophobia? No, that's just racism and ignorance. Lord Aeonian (talk) 21:11, 19 April 2016 (UTC)
- I get your argument, but the fact is, the term for bigotry against Muslims has come to be known as "Islamophobia." To argue over that is, to my mind, as worthless as arguing with an antisemite who claims he can't be an anitsemite because he doesn't hate Arabs, or is an Arab, and they're all semites etc. That's true in a pedantic sense, but not true in any reasonable manner. Everybody understands that Antisemtism is simply the most current term for "Jew-hatred."---Mona- (talk) 22:56, 19 April 2016 (UTC)
- Well, welcome! Please stay, we could always use more help dissecting apologetics. As for our reputation, what are you referring to in specific? StickySock (talk) 21:00, 19 April 2016 (UTC)
- FCP's essay pretty much sums it up. People who leave Islam aren't exactly fans of the Islamist sycophants in the regressive left. Lord Aeonian (talk) 21:07, 19 April 2016 (UTC)
I proposed something like this back in January for Avenger. Carpetsmoker (talk) 20:03, 19 April 2016 (UTC)
- So are we talking about topic bans or ideological bans? WéáśéĺóíďMethinks it is a Weasel 20:44, 19 April 2016 (UTC)
- Aren't the former inevitably a subset of the latter? 141.134.75.236 (talk) 20:03, 20 April 2016 (UTC)
Mona, your observation of Zionists appears to very much be the spotlight fallacy. If you pissed off Cathy Brennan, you could get dozens, possibly a hundred or so TERF zealots sending you hateful messages. Yet they definitely do not represent feminism as a whole.Teurastaja (talk) 14:47, 20 April 2016 (UTC)
WIGO:Vandalism[edit]
So I noticed RationalWiki:Best of the crazy, which has a really small list.
It seems like it could be easily refitted to become a WIGO Vandalism (or something like it). There's lots of great gems. Like this one BON's comment on Sargon of Akkad:.
The posts might be a bit large to have the voting bits next to them, but hey. FuzzyCatPotato!™ (talk/stalk) 22:53, 18 April 2016 (UTC)
- Ugh, no. There used to be vandalism archives in the early early days of RW but we got rid of them because they were shitty & pointless & we moved away from being a site that celebrated wiki-vandalism & we especially don't need to celebrate vandalism of our own site. Let's not go back there, OK. WèàšèìòìďMethinks it is a Weasel 23:50, 18 April 2016 (UTC)
- Sounds fair. In line with that, should RationalWiki:Best of the crazy go or stay? oʇɐʇoԀʇɐϽʎzznℲ (talk/stalk) 01:02, 19 April 2016 (UTC)
- As much as I love the crazy for purposes of entertainment and education (trust me; I feverishly dared start this sandbox for that very reason), I don't think that the "Best of Crazy" page as it exists now is worth keeping. It's not sourced, it's not updated... It hardly even contains the best crazy we've had. And I don't see the editorial value of spending a lot of time keeping that page up to date, etc. So, I say screw it - I vote that we delete that page. We already cover the best of crazy in our actual articles, anyhow. Reverend Black Percy (talk) 23:21, 19 April 2016 (UTC)
Ghosts (not!)[edit]
Almost forgot to drag this here. Might be some good article meat in there somewhere if we - and by "we" I mean "you" - dig through the references/allusions to same. ħuman 04:45, 19 April 2016 (UTC)
- The level of clickbait-y-ness of that article's chosen headline ("Ghosts created by scientists in 'disturbing' lab experiment") is just majestic and immaculate. Reverend Black Percy (talk) 10:36, 19 April 2016 (UTC)
Are we ever going to be fixing gadgets?[edit]
Are we ever going to fix the completely random on and off gadgets? sometimes i would really like to use them to add categories to articles or to assign priorities to a few of them, but they only work every once in awhile for a few hours before disappearing, are we ever going to fix them? Bubba41102The place where you can scream at me 13:26, 19 April 2016 (UTC)
- Same for me. I had a look at the code for HotArticleRate (which I like to use) to add the priority to the main page, but I don't know shit about JavaScript. The gadgets and not working is also a big problem, especially when patrolling edits (gadgets enabled allows me to stay on the page after patrolling).--JorisEnter (talk) 13:32, 19 April 2016 (UTC)
- One thing i always noticed is that WikiEd always works regardless of whether the rest of the gadgets work. Bubba41102The place where you can scream at me 13:58, 19 April 2016 (UTC)
- You can fix it yourself by setting a different squid server. The problem is that one of them is misbehaving, and David doesn't want to fix it apparently (details here|) and Trent is nowhere to be seen. Not that two separate Squid servers are really needed, by the way (that's money for two servers that's being pissed away), but that's a different issue. There are also some other small things that don't work correctly, by the way, such as updating various special MediaWiki: pages not properly taking effect until weeks later...
- You can manually set the
NB_SRVIDcookie to
srv9623to choose squid1 (which is the working one). Or you can just remove all cookies for the rationalwiki.org domain and try a few times until you land on squid1 (you can see in the
ViaHTTP header or by the gadgets working). Carpetsmoker (talk) 15:19, 19 April 2016 (UTC)
- I checked and i am on 9623 and it still is not working, i think it might be an issue with chrome, not sure. Bubba41102The place where you can scream at me 19:19, 19 April 2016 (UTC)
- Nope, it's not a browser problem. But you're right in it not working − I tested it and it doesn't work for either squid server now (Special:Gadgets is always empty). It looks like the situation has devolved into even further ridiculousness than a few months ago... :-/ Carpetsmoker (talk) 20:00, 19 April 2016 (UTC)
- This change has a cause, I've been fiddling with squid2 (since I had a moment). Its config now reflects that of squid1. I am as delighted as you. Will prod further - David Gerard (talk) 21:46, 19 April 2016 (UTC)
- Why not just rip out Squid and replace it with Varnish? I can't think of a single thing Squid does better, and setting up Varnish for Mediawiki is pretty easy; plus, there are plenty of Varnish configs for MediaWiki floating around (including the one that Wikipedia uses). It's certainly a lot easier than mucking about with Squid. I'm also pretty sure you can run one Varnish machine to serve both Apache servers since Varnish is several orders of magnitude faster than Apache (or just run the cache on the Apache server itself, which also works quite well in >95% of the cases). Carpetsmoker (talk) 23:39, 19 April 2016 (UTC)
- I'm inclined that way actually. I would have preferred Varnish, but Trent whacked Squid on. We run Varnish at work and it's stupidly simple and efficient. When I hop on the server these days (after long hard days in the Linux mines at work I'm not immediately inclined to do the same at home) I am increasingly clearing out old crap that nobody has touched in ages - David Gerard (talk) 07:22, 20 April 2016 (UTC)
- Can't say that I can blame for not wanting to do sysadmin stuff in your free time after doing it all day long. Been there, done that. But ... things have been broken a long while, many people complain, and I did offer to help out several times last year. Offers that were completely ignored. So well ... Carpetsmoker (talk) 15:18, 20 April 2016 (UTC)
- A case for giving more people root access. oʇɐʇoԀʇɐϽʎzznℲ (talk/stalk) 20:12, 20 April 2016 (UTC)
I saw that gadgets are back, i suppose this is David Gerard's doing? Bubba41102The place where you can scream at me 19:31, 22 April 2016 (UTC)
Stormfront Knowledge[edit]
While on Stormfront (as I usually am) I encountered a hilarious WN post claiming that birth control causes autism in white people for even 5 years after they've been taken and that white people destroy their bodies by taking any chemicals whatsoever. I wonder if the Jews are responsible lol. Oh and I forgot the most important part, it had several users AGREEING with it and daring to celebrate their intellect, More knowledge from the master race. TheAmazingSkeptic (talk) 12:17, 20 April 2016 (UTC)
- Everyone knows chemicals were invented by the Jews! --Ymir (talk) 12:45, 20 April 2016 (UTC)
- Sounds like some anti-pharma, big-pharma woo is bleeding over Jrock1203 (talk) 14:37, 20 April 2016 (UTC)
- Crank magnetism definitely applies to neo-nazis. ikanreed You probably didn't deserve that 15:42, 20 April 2016 (UTC)
- I think there is a lot of overlap between the white nationalist movement and the quiverfull movement. Petey Plane (talk) 15:51, 20 April 2016 (UTC)
- White nationalism is a black hole for cranks *rimshot* --Kugelschreiber (talk) (mail) (block) 16:46, 20 April 2016 (UTC) 16:46, 20 April 2016 (UTC)
- Of course it is. Not sure if anyone still cares since the news is a bit old, but users from Stormfront also believed that Anuj Bidve was not gunned down by a white British person trying to boost their reputation in a bad area, but instead was fabricated by the media and police. I would have to assume the prison system is in on this to, since Stapleton (the shooter/criminal/scum) brutalized a feared prisoner to gain respect. It's like they're living in their own fantasy world completely separate from reality. 21:24, 23 April 2016 (UTC)TheAmazingSkeptic (talk)
The Sanders article is reading like from some alternate reality[edit]
- This discussion was moved to Talk:Bernie Sanders. WëäŝëïöïďMethinks it is a Weasel 18:22, 22 April 2016 (UTC)
The 1960 Presidential election[edit]
So there is a throwaway line in the Primary election article about Mayor Daley stealing the 1960 election from Nixon. Given that it seems to be a conservative talking point (at least on the wiki this wiki was founded to mock) we might a) wish to clarify said throwaway line b) wish to have an article going into details on those claims c) have a discussion where people call each other vile (as per our newfound tradition). What do you think? And if you wonder why I don't post on the talk page of the article in question... I thought this deserved a wider audience... Pizzameister (talk) 23:00, 21 April 2016 (UTC)
- Still trying to support the continued Zionist slaughter of Palestinian children, are we? Everyone knows that if Nixon won, the SJWs and postmodernists would never have taken over, and the vile Zionists wouldn't control RationalWiki at this very moment! Lord Aeonian (talk) 23:06, 21 April 2016 (UTC)
- If we hadn't gone into 'Nam, it's likely the 70's wouldn't have happened until the 90's. CorruptUser (talk) 23:58, 21 April 2016 (UTC)
- I've no idea what this has to do with antisemitic conspiracy theories. But a number of people have debunked claims of pro-Kennedy fraud.[10][11] Annquin (talk) 08:56, 22 April 2016 (UTC)
- And FWIW, this had nothing to do with the primary election, either; the allegations that Daley stole Illinois were about the general election. - Smerdis of Tlön, LOAD "*", 8, 1. 14:35, 22 April 2016 (UTC)
- I know, but the article while very informative and broad has a slant that seems to try and justify the old boss system and its stealthy continuation via "super" delegates... I would try to fix it myself, but.... Pizzameister (talk) 00:41, 23 April 2016 (UTC)
USA saint's day[edit]
Noticing the St George's day banner, it occurs to me that the US doesn't have a patron saint, or does it? Should it? - I mean we all know the blessings that flow from invoking a Saint in Heaven. Pippa (talk) 15:35, 22 April 2016 (UTC)
- Donald Drumpf is our patron saint. Petey Plane (talk) 15:39, 22 April 2016 (UTC)
- As an ex-Catholic: the Patron Saint of the US is the Virgin Mary. Yes, really. ikanreed You probably didn't deserve that 15:44, 22 April 2016 (UTC)
- Well we do have a state named after her.--Owlman (talk) (mail) 15:52, 22 April 2016 (UTC) 15:52, 22 April 2016 (UTC)
- I'm pretty sure Madonna is a state. ikanreed You probably didn't deserve that 18:34, 22 April 2016 (UTC)
- What state are you talking about? Virginia and Maryland are both named after Queens of England. WēāŝēīōīďMethinks it is a Weasel 18:28, 22 April 2016 (UTC)
- Really? I was told Maryland was named after Mary from the Bible because they were a Catholic colony.--Owlman (talk) (mail) 18:36, 22 April 2016 (UTC) 18:36, 22 April 2016 (UTC)
- It was named after Henrietta Maria of France, wife of Charles I of England. She was a Catholic so English Catholics at the time probably idolised her. ΨΣΔξΣΓΩΙÐMethinks it is a Weasel 18:46, 22 April 2016 (UTC)
- Actually, the state named after the Virgin Mary is Idaho. - Smerdis of Tlön, LOAD "*", 8, 1. 20:24, 22 April 2016 (UTC)
- You mean the blasphemy incurred from venerating any entity that is not the Supreme God? 142.124.55.236 (talk) 15:45, 22 April 42016 AQD (UTC)
- I like St Herman of Alaska. There's not enough saints called Herman. Annquin (talk) 16:29, 22 April 2016 (UTC)
- What about Reagan? ΨΣΔξΣΓΩΙÐMethinks it is a Weasel 18:37, 22 April 2016 (UTC)
- Reagan is our father Dubya is the son, and Trump is the holy spirit.'Legionwhat do you want from me 19:13, 22 April 2016 (UTC)
- What? It isn't St. Doubting Thomas? Bongolian (talk) 19:16, 22 April 2016 (UTC)
- For any WFAN listeners of there, I would like Congress to vote on making it Jason Giambi. The Blade of the Northern Lights (話して下さい) 20:51, 22 April 2016 (UTC)
- Well what do you know? The Patron saint of the US really is The Virgin Mary - as Our Lady of the Immaculate Conception--Bob"Life is short and (insert adjective)" 21:01, 22 April 2016 (UTC)
Good Yontif everybody.[edit]
Happy Passover.Teurastaja (talk) 20:37, 22 April 2016 (UTC)
- Chag Sameach! Spud (talk) 10:18, 23 April 2016 (UTC)
- Gut moed!--Kugelschreiber (talk) (mail) (block) 14:24, 25 April 2016 (UTC) 14:24, 25 April 2016 (UTC)
- Shalom Jews
Bernie Sanders article[edit]
- This discussion was moved to Talk:Bernie Sanders.
Again... FU22YC47P07470 (talk/stalk) 20:29, 24 April 2016 (UTC)
Bob Beck Blood Electrification Woo[edit]
Anyone have any data on this scam? My grandmother in law, who is a purveyor of all things woo (colloidal silver, alkaline water, plexus slim, etc etc) is suddenly throwing 110% of her resources into it. Apparently my google skills aren't up to snuff. OR - the good doctor Beck has enough folks pumping positive information that I'm struggling to find info explaining why it's BS. Obviously it is, but my word means nothing when trying to talk her out of spending stupid amounts of money on this garbage. — Unsigned, by: Jrock1203 / talk / contribs 14:36, 20 April 2016
- Well, the problem is that a lie makes its way around the world in the time it takes the truth to get its shoes on. Debunking usually takes awhile, but using the same methods help. Does it make impossible promises, does it work in ways that are never clearly stated (or make no sense), "data" is a few testimonials, vague conspiracies, etc... The big gap is that many pray on people who need hope or help where there is little to be found. -EmeraldCityWanderer (talk) 17:23, 20 April 2016 (UTC)
- (EC)Best I can do is a court case where they were held to be making false claims in ads. That's probably not good enough to convince your step-grandmother that it's not effective, but it's really all I can find. ikanreed You probably didn't deserve that 17:30, 20 April 2016 (UTC)
- Ew ew ew. He says that he can cure AIDS, cancer, Epstein-Barr, all for the cost of a pack of gum. oʇɐʇoԀʇɐϽʎzznℲ (talk/stalk) 02:38, 21 April 2016 (UTC)
- Yeah, definitely ratwiki article worthy. ikanreed You probably didn't deserve that 13:51, 21 April 2016 (UTC)
- I asked the science-based medicine people. They pointed me to these articles: and Fuzzy "Cat" Potato, Jr. (talk/stalk) 15:33, 21 April 2016 (UTC)
- Oooh, an update for you all! So after a solid 2 hours of me explaining that it's typical BS - if it sounds too good it likely is type tactics. She explained that she bought one of these "machines". She couldn't order it locally or even in the US - as the government and pharma industries shut it down. She had to order one from...Slovenia. She then went on to explain that Beck offers instructions on how to make one yourself and wants me to build one (which I politely refused). Get this, these "blood electrification" devices are powered by...wait for it....a standard 9v battery. yeesh. Jrock1203 (talk) 15:36, 21 April 2016 (UTC)
- Good news, if you can track down the individual online retailer you got it from, the FDA has the authority to shut them the fuck down ikanreed You probably didn't deserve that 15:40, 21 April 2016 (UTC)
Is there an article yet? If so what's the title? ħuman 23:32, 23 April 2016 (UTC)
so why is it called rational wiki[edit]
when it's religious(non theist) driven?— Unsigned, by: 109.73.3.59 / talk / contribs
- "But I thought this was supposed to be RATIONALWiki!" Drink!
- But seriously, it's because "empirical wiki" wouldn't work. We are about observation and science rather than about dogma. As for "rational", epistemologically, we value empiricism over logic, because if your logic doesn't hold up to the evidence then most likely it's your logic that's wrong. CorruptUser (talk) 05:22, 22 April 2016 (UTC)
- RW isn't "religious(non theist) driven", thus your very question is faulty. Reverend Black Percy (talk) 11:33, 22 April 2016 (UTC)
- For me, it's just a name, nothing more. If you want, I could make a similar criticism of Conservapedia. People who squander the world through extracting unnecessary amounts of natural resources aren't conserving anything. So they can't call themselves conservative. What say you to that? Pbfreespace3 (talk) 11:41, 22 April 2016 (UTC)
- @RBP if you want to get into semantics, the further east you go, the more the definition of religion becomes blurred. To the point where in East Asia, the words for religion and philosophy are the same. So if you hold to a philosophy, you are "religious". Even if that philosophy is logically derived rather than blindly held with faith. Because when you think about it, your philosophy also has some blindly held beliefs such as the assumption that all people have the right to life and so forth. Religions don't necessarily need the mythology component. CorruptUser (talk) 12:46, 22 April 2016 (UTC)
- But the question was, "why is it called rational wiki when it's religious(non theist) driven?". In this question, it's obvious that the word "rational" is the word that is supposed to represent the general philosophical inquiry you describe, and in contrast "religion(non theist)" is supposed to represent Atheism as a religion or Atheism as a similarly arbitrary position of faith as theism is. While it's true that religions don't necessarily need the mythology component, the question being asked was in a sense "Why do you call yourselves rational when you are driven by a religion without the mythology component?". My reply to that is - we're not. Reverend Black Percy (talk) 13:13, 22 April 2016 (UTC)
- Also, I don't pretend I'm being rational unless I'm specifically dealing in observational science, formal logic, or other tools developed to frame things rationally. Outside of those frameworks, I'm both aware and happy to note that I'm not always rational. I sincerely believe that noting that limitation helps me be more rational when it actually matters. (I have no proof of this, and do not consider it a logical deduction) ikanreed You probably didn't deserve that 14:02, 22 April 2016 (UTC)
Is this the same IP who claimed if you call yourself something you can't be that thing? Now it seems that if you are not religious then you are religious. I rather think that this IP is trying to justify something to itself rather than to us, as its arguments are less than convincing.--Bob"Life is short and (insert adjective)" 11:42, 26 April 2016 (UTC)
- Or it might be a troll.--JorisEnter (talk) 11:42, 26 April 2016 (UTC)
- Sure. I suppose it might be anything.--Bob"Life is short and (insert adjective)" 11:46, 26 April 2016 (UTC)
- It's amazing how many fundy loons think that atheism is a religion of Satan though. Like not believing in the Norse mythology and Odin being lord means you believe in Loki. It's not how anything works. -EmeraldCityWanderer (talk) 13:59, 26 April 2016 (UTC)
- That's not true, Atheists worship Athe. StickySock (talk) 14:12, 26 April 2016 (UTC)
Men's rights portal[edit]
- This discussion was moved to Template talk:mrm.
FuzzyCatPotato of the Christian Heros (talk/stalk) 23:43, 26 April 2016 (UTC)
Dragon Age series[edit]
I have been playing Dragon Age: Inquisiton, recently, and seeing as we have articles on bioshock; and deus ex is a highly wanted article, i have to suggest we do an article on the Dragon Age series. The game has serious religious themes that i think would be fairly interesting to explore, as most of the characters in the game are religious, and the religion (the Chantry) goes basically unquestioned, despite physical evidence that their god (The Maker) has abandoned them. Im not talking about prophetic stuff here, you can literally go into a magical dimension and go and look at The Maker's empty throne (not in game however), and the throne itself is a central plot point. Not even to mention that the throne is in a city that has such an evil presence, that not even demons talk about it. I think it would be quite interesting to explore the religious themes of this game series. Though it is just a thought. Bubba41102The place where you can scream at me 02:48, 26 April 2016 (UTC)
- I can't quite see a full article on this; perhaps a funspace article or an essay? :) That said, it would certainly be interesting to have an article about portrayals of religion in popular culture. Cømяade FυzzчCαтPøтαтø (talk/stalk) 02:57, 26 April 2016 (UTC)
- Might i also mention the in game politics are quite interesting, in the fact that they are so chaotic and messy you might think that they were the 2016 US presidential race mixed with
cold war politics.Reagan era Foreign Policy Bubba41102The place where you can scream at me 03:32, 26 April 2016 (UTC)
- One of my several obsessions is the way neopagan pseudohistory (witchcraft as being a surviving pagan religion, the replacement of goddesses by gods, Arthurian legend as pagan myth, an 'old religion' at odds with an official new one) has ensquonked itself as a series of highly recognizable tropes in fantasy fictions. The Dragon Age games are slightly unusual in that regard, in that the Chantry is not protrayed completely unsympathetically, although clerics vs. mages is one of the foundations of the game world. It's even in romance series like Outlander, where an underground coven's ceremony transports the heroine into eighteenth century Scotland. - Smerdis of Tlön, LOAD "*", 8, 1. 03:42, 26 April 2016 (UTC)
- I wouldn't call the chantry fully neopagan, there are very obvious parallels to the chatholic church (only it is run by women, instead of men), they even (used to) have Templars, the parallels are there, though there are definetly neopagan beliefs in characters like Morrigan, and the Witch of the Wilds, who do draw major parallels to the coven witches. I also find it concerning how unquestioned the chantry is, I find one scene in inquisition fairly telling. One of the chantry preists starts singing a religious song, and literally everyone in the camp (basically the entire inquisiton) bar two people (you and an eleven Mage) starts singing along, it is a frighteningly large majority, and nobody seems to qustion any religious figures about the religion, they migh question stuff the chantry does, but never the religion itself, i probably should write an essay on this tomorrow, it could serve as a basis for the religion in pop culture article section on dragon age, because I could seriously go on for a very long time about this, so I'll save the lecture for now. Bubba41102The place where you can scream at me 06:20, 26 April 2016 (UTC)
- One thing fantasy worlds tend not to lack is obvious evidence of the supernatural. It makes sense that an institution like the Chantry would be supported by vast majorities there. Yes, the Chantry is largely modelled on Roman Catholicism, except with a female savior. They lock up anyone with magical talents, and many mages accept that. It isn't the best example of neopagan lore in fantasy fictions, but I would still say that it partially subverts tropes that have become pretty much ubiquitous. - Smerdis of Tlön, LOAD "*", 8, 1. 14:52, 26 April 2016 (UTC)
- Ive started up a sandbox on portrayals of religion in pop culture here feel free to edit Bubba41102The place where you can scream at me 19:24, 26 April 2016 (UTC)
Gitmo[edit]
Y'know the saddest thing about those who have been tortured by the US and those who are still stuck in Gitmo is that we refuse to even move them into a supermax prison. Everyone knows they were innocent, that they were kidnapped, that their confessions were forced, that they were never tried for a crime, that they never had a "fair or speedy trial", or that they will ever have a chance to punish anyone (I know the ACLU could still change, but no officer was punished for Abu Gharib). I know people keep praising Obama for "freeing" them but these people will only end up in countries that they know nothing about and they are most likely going to be watched and deprived of resources until they die. Anyone who justifies this behaviour states that they are now dangerous because we tortured them and they will want revenge which feels like a dark parody of an overly paranoid dictatorship.--Owlman (talk) (mail) 05:07, 26 April 2016 (UTC) 05:07, 26 April 2016 (UTC)
- I think in the future al-Baghdadi could be cited as another reason for not releasing any suspected terrorists because any Muslim "street thug" could become the next self-proclaimed caliph if set free from any of the United States' torture chambers. ∈ NameThatNobodyTakes (✎) 10:00, 26 April 2016 (UTC)
- Looking at al-Baghdadi, that's probably being properly paranoid.--Kugelschreiber (talk) (mail) (block) 10:19, 26 April 2016 (UTC) 10:19, 26 April 2016 (UTC)
- Even if that is so the reality of indefinitely detaining them because we screwed up is insane.--Owlman (talk) (mail) 12:28, 26 April 2016 (UTC) 12:28, 26 April 2016 (UTC)
- What'd be the alternative? Disappearing them?--Kugelschreiber (talk) (mail) (block) 13:16, 26 April 2016 (UTC) 13:16, 26 April 2016 (UTC)
- The alternative is not found in fighting the symptoms but the causes of terrorism.∈ NameThatNobodyTakes (✎) 13:52, 26 April 2016 (UTC)
- The alternative would be trying them and the result would be their release since everything that happened to them was unconstitutional and violated international law. Somtetimes we have to live with the consequences of our actions.--Owlman (talk) (mail) 13:56, 26 April 2016 (UTC) 13:56, 26 April 2016 (UTC)
- Roughly a fifth of the freed inmates have returned to terrorism, which is roughly a sum around 110-120 fighters depending on the sources, which seems like a drop in a bucket compared to the tens of thousands fighting for ISIS. In conclusion you can say that the prison camp hasn't brought the desired results at all, quite the contrary, the faulty intelligence gathered from torture (a word which is too kind in my opinion because the maiming and killing seems more like extrajudicial execution, its cruelty only comparable to ISIS) hasn't made a dent in fundamentalist terrorism which is more widespread than it has ever been and a sizeable fraction of the released prisoners as well as Islamist terrorists have since become probably more radicalized than if the camp wouldn't have existed in the first place. ∈ NameThatNobodyTakes (✎) 15:40, 26 April 2016 (UTC)
- For most penal institutions, a rate of 1/5 recidivism would be considered a banner waving success. - Smerdis of Tlön, LOAD "*", 8, 1. 19:20, 26 April 2016 (UTC)
- ...besides the fact they now reside in other countries that don't send crime data, recidivism counts crimes in general not just the crime of terrorism, and they were innocent people imprisoned and tortured for over a decade. So yeah, wave your banner on that one single point and ignore the rest. *WOOO* /sarcasm -EmeraldCityWanderer (talk) 20:48, 26 April 2016 (UTC)) 19:43, 26 April 2016 (UTC)
- To start, don't refer to terrorists as mujahideen (holy warriors) but as mufsidun (evil doers). Or better yet, replace all media instances of the word jihad (struggle) with crusade (struggle).
- Words have power.StickySock (talk) 19:54, 26 April 2016 (UTC)
- Except these groups are already condemned as kuffar by mainstream ulama...who, of course, agree with pretty much all of their ideals anyway. Just calling them mufsidun won't do anything to defuse the strong theological position held by the Athar'i and Hanbali schools, which are heavily supported by the most stable state in the region - Wahhabi Saudi Arabia. Lord Aeonian (talk) 20:53, 26 April 2016 (UTC)
- They watch the news and see people calling them jihadis and so forth.
- Second thing to do is what the British did to stop Jack the Ripper. He (she?) was never caught, but was stopped by ignoring him. These guys, they see the faces of their brethren on TV and they fill with pride. Stop putting them on tv. Yes report the news but if the person has been caught that person should never become famous. Focus on the victims and the heroes. StickySock (talk) 21:27, 26 April 2016 (UTC)
- Of course there are more factors contributing to terrorism than poverty and colonialism - the hotbeds of terrorist sources have often all these things combined: poverty due to colonialism which has stolen valuable resources for decades, tyranny from compatriots (potentially secular or maybe viewed as such, which makes the mostly devoutly religious population suspicious of it) which keep most of the remaining wealth for themselves, outside forces which either support the tyranny or want to put another one in its place with so-called "Western values" so they can control the resources (which in turn gives the domestic populace another bad taste to our more progressive societies), constant violence over power to control the remaining resources, lacking education because next to no money is spent in building an educational infrastructure and at last fundamentalism around a dogmatic text which has numerous passages proposing violence as a solution when things are not going your way.
- When all of this is added together you have a recipe for disaster. And I do think that only one of these factors can be enough to turn someone into a "holy warrior," (not everyone reacts the same) we also have religious murderous nutcases over here but as our countries (plus some others) do not have all these factors maxed out to the extreme or are not existant at all, these people are luckily few and far between.
- How to defeat the people in Qatar and Saudi Arabia who spread their toxic ideology around the world? Maybe by cutting all economic ties (these places aren't the only ones which sell fossil fuels) and stopping all arm shipments which they immediately ship to Wahabi terrorists anyway.
- I know that getting rid of all these problems require enormous structural changes which could take decades. Do I think by tackling and finding solutions to all of the things I mentioned it will be an antidote to the problem? No, but only delusional people will disagree that how the war on terror has been conducted was an abject failure and has only exacerbated the problem. ∈ NameThatNobodyTakes (✎) 22:03, 26 April 2016 (UTC)
Terrorism is mainly caused by poverty and dissatisfaction with one's social and political circumstances. Take the Sunnis in Syria for example: poor, disenfranchised, and fed up with minority rule. Political and religious reasons often catalyze this disillusionment, leading to violence. Muslim terrorism originally started due to anger over Western involvement in Muslim affairs. The British establishment of Israel, American installment of the Shah in Iran, Soviet invasion of Afghanistan, and the Gulf War drove al-Qaeda to form, Iran to become terroristic, and laid the groundwork for Palestinian and Islamic State terror. Resolution of these circumstances would halt, if not eliminate terrorism. Poverty is one element: if the Levant were transformed into a Germany or a Japan, terrorism would end there. Saudi Arabia and the Gulf states are cases in point. If I were President, I'd also get Israel to withdraw from Palestine, remove American troops from the Middle-East, and end funding to all Middle-East governments (in the long-term). This would help significantly. Pbfreespace3 (talk) 23:48, 26 April 2016 (UTC)
- Did you see my comment above?
- ) 04:49, 27 April 2016 (UTC)
- They live in a world that glorifies the Heroic Sacrifice. The Blaze of Glory. Martyrdom. All the different tropes for giving your life to die.
- It's central to Islam, so short of committing forced conversions and mass murders on a scale that would make Osama look like Mandela, well, all we can do is stop supporting it on our end by not showing terror porn on the news all the time. StickySock (talk) 05:45, 27 April 2016 (UTC)
Philosophy of science icon[edit]
Currently, the icon for
{{philosophyscience}} is a .png square image of a compound microscope. I made some .svg circle pictures:
Any seem fine?:36, 26 April 2016 (UTC)
- Once I can see them I'll let you know. Pbfreespace3 (talk) 23:50, 26 April 2016 (UTC)
- I prefer the one on the left. The one on the right I rate second. My main issue with the one on the right is that it is hard to tell what it is. It's the thinking man statue, I know, but it should be more visible. Pbfreespace3 (talk) 00:59, 27 April 2016 (UTC)
- @Pbfreespace: Thought about doing one without the little bubble, bigger statue.
- Thoughts? Fuzzy. Cat. Potato! (talk/stalk) 02:04, 27 April 2016 (UTC)
- I'd prefer it with the bubble. It needs to be thinner. Is there any way to just decrease the thickness of the svg component? It is more discernible that way. Pbfreespace3 (talk) 11:15, 27 April 2016 (UTC)
- I prefer the one with extra thought bubble too.--JorisEnter (talk) 12:54, 27 April 2016 (UTC)
- Well, not the one in the middle. That seems to say, "Science in the men's toilet". Or maybe, "Laboratory or lavatory?". I'm a bit torn. The image of the Thinker is used in the philosophy template. And it was months before I realized that was what it was supposed to be. So, I'm thinking the one on the left for clarity and the one on the right for consistency. Spud (talk) 13:06, 27 April 2016 (UTC)
- The one on the right is essentially a combination of the science and philosophy icons, it seems. I think it is the most logical icon to use.--JorisEnter (talk) 13:09, 27 April 2016 (UTC)
- The 2nd looks as if it is referring to a guy on the loo thinking about chemistry. The 3rd one is the best IMNSHO, as it contain both references to science and philosophy.--Kugelschreiber (talk) (mail) (block) 13:55, 27 April 2016 (UTC) 13:55, 27 April 2016 (UTC)
Just the cloud, no bloke under it? - David Gerard (talk) 18:38, 27 April 2016 (UTC)
- Nah, that would make it hard to distinguish from the science icon. Besides, this one also has the "philosophy" bit.--JorisEnter (talk) 18:39, 27 April 2016 (UTC)
- I like this one (Icon_philosophy_of_science_test4.svg) the most. Reverend Black Percy (talk) 19:15, 27 April 2016 (UTC)
I put in ; most people seemed to want the icon to include The Thinker, and it lets both icons be bigger. It's easy enough to change later if people want it. oʇɐʇoԀʇɐϽʎzznℲ (talk/stalk) 14:17, 28 April 2016 (UTC)
- i feel the thinker image is too indistinct. It took a couple of minutes with my dodgy eyesight to work out what the fuck that blob was supposed to be. AMassiveGay (talk) 15:32, 28 April 2016 (UTC)
Hastert - biggest political scandal in the history of the Republic?[edit]
Aside from Burr killing Hamilton (which arguably is not as bad as what Hastert did since Hamilton was a voluntary dueler), and undetected cases of masters raping slaves, this is the worst political scandal I can think of in the history of our Republic (:re Hastert). I overcome my opposition to the selective use of federal structuring laws due to the details of this case, and specifically because Speaker designate Livingston had to resign, President Clinton was impeached, and Chairman Hyde and Speaker Gingrich were impugned for consensual affairs back in the 1990s. Even what Senator Vitter or Governor Spitzer did (getting prostitutes) pales in comparison. Objective (talk) 00:14, 28 April 2016 (UTC)
- Maybe it is a bias, but I'm not sure anything will ever surpass Watergate. AyzmoCheers 12:58, 28 April 2016 (UTC)
- Maybe. It's not a scandal in the same sense of Clinton or Watergate -- in both instances, it was an elected official committing the actions. That said, it's a huge fucking deal -- on at least par with the accusations that British officials, up to Thatcher, helped promote pedophilia. FuzzyCatPotato!™ (talk/stalk) 13:55, 28 April 2016 (UTC)
- My vote is for Iran/Contra. While not to diminish what Hastert did, the molestations did occur before he held national public office. Petey Plane (talk) 14:01, 28 April 2016 (UTC)
- all scandals are the worst scandal since the last one. Beyond that, you are comparing Apples and oranges. AMassiveGay (talk) 15:26, 28 April 2016 (UTC)
"But no one who posts RationalWiki as a source should be taken seriously"[edit]
Found this on Facebook. Qscgy (talk) 02:00, 28 April 2016 (UTC)
- Look, every source that fact checks idiots gets the same treatment. I've seen multiple people say the same thing about all of the following
- Snopes
- Politifact
- All media
- Climatology journals
- The simple truth is that people will start saying that the moment they get undercut by a source. We highlight bullshit, and bullshitters hate that. ikanreed You probably didn't deserve that 13:59, 28 April 2016 (UTC)
- It's a classic symptom of confirmation bias.--Bob"Life is short and (insert adjective)" 14:03, 28 April 2016 (UTC)
- To be fair, wikis (regardless of their purpose) aren't good sources for anything other than finding better sources. But yeah, i think the key is that if the sources doesn't reinforce their presuppositions, then the source is wrong. That's pretty basic psychology. Petey Plane (talk) 14:05, 28 April 2016 (UTC)
- I'd say 1 in 25 criticisms of RW as a source include "... and it's a wiki." The other 24, though, tend to imply "it's wrong, so I didn't read it". Fuzzy. Cat. Potato! (talk/stalk) 14:13, 28 April 2016 (UTC)
- It's an easy criticism of Wiki's that very assertively ignores the primary sources that often support statements in Wiki's that often either cannot be debunked or it takes more effort to contend for the lazy nut. -EmeraldCityWanderer (talk) 14:54, 28 April 2016 (UTC)
Animal Rights[edit]
Should we have an animal rights portal? We can include the articles on Pit bulls, Kopi luwak, and animal testing. We can also include the various animal rights groups like PETA, ALF, and ARM.--Owlman (talk) (mail) 16:06, 16 April 2016 (UTC) 16:06, 16 April 2016 (UTC)
Sounds fun. How can I help? B4Xiphos (talk) 12:35, 17 April 2016 (UTC)
- Why not?--Harkinian | Oah! (talk) 12:58, 17 April 2016 (UTC)
- Sorry for the slow response, but I think the best thing we can do is to start creating more articles about animal rights topics. I will add some to the to do list.--Owlman (talk) (mail) 13:33, 20 April 2016 (UTC) 13:33, 20 April 2016 (UTC)
- Just make sure you guys stay nuanced and remember to focus on debunking. Animal rights look different in different parts of the world, and there is a lot of extremism and propaganda on all sides. Especially among ALF-type nuts. Reverend Black Percy (talk) 13:42, 20 April 2016 (UTC)
- Where do we want to start? I am not a fan of the radical "fur/meat is "murder"" crowd. However, I do not support cruelty to animals, nonsensical whaling, sport/trophy hunting/fishing (keep in mind I do hunt and fish, but I use as much of the animal as possible, I don't kill more than I will use, and I don't "catch and release" [i.e. torture small animals for sport]). B4Xiphos (talk) 07:55, 24 April 2016 (UTC)
- A good start would be to focus on animal rights figures who all mostly invoke appeal to nature, naturalistic fallacies, in addition to extreme primitivist and unscientific views. Candidates I propose are Gary Yourofsky who is notorious for being an over-the-top misanthrope and recently has spouted vile racist sentiments towards BLM activists and Palestinians because apparently it is morally reprehensible to focus on your own survival over that of other animals. Then there's "Freelee the banana girl" who has a popular YouTube channel. She once advocated an extreme unhealthy version of raw foodism where you are supposed to only eat dozens of bananas a day only to back out of it and now advocating the equally unhealthy "raw till four" diet. She has also somewhat celebrated last year's earthquake in Nepal because it is justice for the totally unrelated event in India where people sacrifice thousands of animals, going so far as calling it a form of "karma". There's probably way more but these are some of the better examples. ∈ NameThatNobodyTakes (✎) 09:35, 26 April 2016 (UTC)
- ZOMG! I had no idea who "Banana Girl" was, but I stumbled upon a post on Instructables where she was giving "instructions" on how to be a "fruitarian". It was of course DAF, but I read it out of morbid curiosity. Needless to say, the comment section went from talking about eating delicious fruit, to breatharianism pretty quickly. I am going to see what I can look up and start sandboxing an article. B4Xiphos (talk) 09:09, 28 April 2016 (UTC)
- I started sandboxing and suffered some brainbreak... Researching this is going to be torturous because I can only take so much stupid in one day. Also, I have never Wiki before, so it is a learning process. B4Xiphos (talk) 12:51, 28 April 2016 (UTC)
- If you want to cut some of the workload I can assist you in your work (if you so desire that is) as I consider myself somewhat knowledgeable about veganism and I have been planning to write articles about the topic anyway. ∈ NameThatNobodyTakes (✎) 17:37, 28 April 2016 (UTC)
- I started (barely) working on an article about banana girl. I am putting it in the food/diet portal. Sadly, my filter here blocks the banana girl debunked website which I have a feeling would be a like a cliff notes saving me lots of time watching her vapid YouTube channel. I am having a devil of a time finding that Instructables post I first ran across her on. It had some relevant information (in text!, I can't stand videos) because she explained her diet woo and then crossed into some weirdness talking about how people evolved to eat fruit (we should introduce her to ray comfort, she thinks we evolved to eat fruit [and bananas are her fruit of choice], and he thinks fruit [bananas] were created to be eaten by people [never mind that pesky fact of #Horticulture] I think it would be an interesting meeting of the "minds". Who knows? Maybe sparks would fly between Banana Man and Banana Girl, and they would run away together to a remote part of the planet with no internet access. A guy can dream right?). When I find her fruity (yes, pun) comments about animals and those deaths in Nepal I will figure out a way to link that in with the animal rights portion we are supposed to be working on >.> You may help as much or as little as you want. I didn't get much done yesterday because other things came up to distract me. B4Xiphos (talk) 05:03, 29 April 2016 (UTC)
- There's no way she would ever run off to an island to lead a primitivist life, which means voluntarily giving up the glorious internet because she's an absolute narcissist who thrives off the poor souls who adulate her. Could you provide the link which you can't access? Maybe I can access it (as long as the site is not filtered because of scamming). I also did some little research this morning, but I'll start posting them at your sandbox's talk page from now on.∈ NameThatNobodyTakes (✎) 20:14, 29 April 2016 (UTC)
Feel free to edit the sandbox. you don't have to put it on the talk page unless it is something you are unsure of. This is my first stab at a wiki entry, so I know it isn't going to be perfect. freeleeexposed.co.uk/tag/freelee-the-banana-girl/ blocked by my enterprise filter as "uncategorized" B4Xiphos (talk) 03:51, 30 April 2016 (UTC)
Can I make an article on al-Farabi?[edit]
Al-Farabi was a Muslim philosopher who wrote extensively on political theory, he was the first to work from Plato's political ideas and create a variant for an Islamic state and society. He wasn't really an apologist so it doesn't seem missional, but I noticed we have a page on Immanuel Kant and other philosophers which do not debunk anything. I'm also planning to write a page on al-Ghazali, who was an apologist and originated the kalaam argument, along with contributing to the end of the Golden Age of Islam, which would be more missional. Lord Aeonian (talk) 00:24, 22 April 2016 (UTC)
- Al-Farabi is more missional than 75% of current RW articles.:47, 22 April 2016 (UTC)
- I didn't know you were into Schlafly statistics, Fuzzy. ;) That said, I think the wiki could do with a bunch more articles on Islamic scholars, both the 'good' ones as the 'bad' ones. 142.124.55.236 (talk) 00:55, 22 April 42016 AQD (UTC)
Ok, it's settled. Time to create another sandbox which will languish off and on as motivation comes. I still have to update the Dawah Man page with more funny stuff he's done, recently he said that Universities are designed to make people "doubt their faith in Islam." How he doesn't hear himself is beyond me. Lord Aeonian (talk) 01:37, 22 April 2016 (UTC)
- What motivates you? Do insults motivate you? If so, I'll try.
- ahem*
- Dear Sir,
- I wish to inform you in the most ungentlemanly of language that it has come to my attention that your hygiene is rather lacking, due to your apparent allergies to something known as "soap". Your mother was a woman of loose morals and looser clothing, and remains quite popular with the lads for reasons I do not wish to sully this letter going into. Your father always had the distinct aroma of what can only be described as wine of less than commendable quality. Your grade school teachers should be severely punished for having made the misfortune of meeting you. Your more private parts are of an embarrassing shape and/or size for your gender, and your sexual orientation if revealed to your parents, would be quite shameful.
- If your parents were even capable of shame.
- Which is most unlikely, given their utter lack of dignity.
- Speaking of which, please tell them I send my regards, and ask your father if he had ever read the works of Gibson. I did enjoy my most recent discussion of that series with him, and would like to pursue it further. Also he's a real cad and you should be ashamed to have been sired by him.
- Please take these uncouth words to heart.
- With everlasting regards,
- CorruptUser (talk) 05:34, 22 April 2016 (UTC)
- Now please make a good article, that sounds like someone I might be interested in :P.
- I have to make this article, update the Dawah Man article, add the inverse Kalaam to the cosmological article, finish my Surah Like It sandbox...Lord Aeonian (talk) 23:59, 22 April 2016 (UTC)
Alright, it's finished, everyone can read it here.Lord Aeonian (talk) 19:12, 28 April 2016 (UTC)
Trump is a much better advocate for poor citizens compared to Obama[edit]
And I'd lump the Clintons, but not Sanders, with Obama. Obama is a shill for open immigration and permissive work visa policy including H1-B and offshoring. This hurts the poor who don't have significant stock holdings in American corporations (which is the working and non working citizen population under the 50th or or maybe more percentile of wealth). It's no wonder why these people want to vote for Trump over Clinton. They're voting their interests. Obama and the Clintons have decimated the notion that the Democratic Party is of the working class. Sanders' support for illegal immigration, but not offshoring and H1 B visas, shows he is half right on wanting to restrict cheap foreign labor from being used to make American products.
I honestly believe most people who oppose illegal immigration and offshoring/work visas are really worried about economic harm as opposed to increase in crime (e.g. Mexico is sending over their rapists.). Cheap foreign labor benefits American corporations, not American citizens. Thus, only shareholders, who may not even be Americans, benefit from cheap foreign labor. Objective (talk) 22:56, 28 April. 32℉uzzy; 0℃atPotato (talk/stalk) 00:27, 29 April 2016 (UTC)
- . Herr FüzzyCätPötätö (talk/stalk) 00:41, 29 April 2016 (UTC)
- Is really Mexico, as a nation, organizing and literally sending over "their rapists"? Reverend Black Percy (talk) 00:38, 29 April 2016 (UTC)
Global income inequality may have gone down, but not US income inequality. (Without minimising the harm of illegal immigrants perpetrating sex crimes, Trump was engaging in rhetorical hyperbole). Objective (talk) 00:59, 29 April 2016 (UTC)
- Yeah, and how the hell do you blame that on immigration? oʇɐʇoԀʇɐϽʎzznℲ (talk/stalk) 01:03, 29 April 2016 (UTC)
- I think he's trying to point out that when the labor market swells, wages go down...or, in reality instead of theory, wages just never go up. Lord Aeonian (talk) 01:06, 29 April 2016 (UTC)
- This and also when offshoring or plants are moved overseas. Objective (talk) 01:10, 29 April 2016 (UTC)
- @Aeonian: Pft. It's still increasing [12][13], just not fast enough to keep pace with increased expenses. If there's a reason for that, blame the facts that the minimum wage hasn't increased ennough, that education budgets haven't kept pace with GDP, and that healthcare in the US is clusterfuck. Herr FuzzyKatzenPotato (talk/stalk) 01:12, 29 April 2016 (UTC)
- Perhaps, but it's a meaningless endeavor. There won't be a human driven economy in thirty years, provided the markets embrace the most efficient solutions (they will), and neither Trump nor Bernie can stop the violence that will characterize the transition period. Lord Aeonian (talk) 01:15, 29 April 2016 (UTC)
- Pft again. Don't call it 30 years, that's unrealistic. Maybe 50 at soonest. And even then: Who's gonna design the robots? Who's gonna run the buildings that the robots work in? Who's gonna do the research that goes into DoctorBot's heuristics? Humans. Highly educated humans. Hence why we need a fucking hell of a lot more college-educated humans. Sir ℱ℧ℤℤϒℂᗩℑᑭƠℑᗩℑƠ (talk/stalk) 01:35, 29 April 2016 (UTC)
- Repeating the same crap. There are coding algos now that write and bug test themselves and their software, self-driving cars soon, etc. Most forms of work can be broken down into a repetitive or semi-repetitive task that a deep learning computer, linked to the internet, could do much better than a human. Those tasks which couldn't be automated are in highly variable jobs, like that of a buisness CEO. Do you think everyone will become their own CEO? Doubtful. Thirty years. Lord Aeonian (talk) 01:40, 29 April 2016 (UTC)
- Yea, and how common are those algorithms? Who writes those algorithms? And, are you willing to put up with, say, airplanes and cars "debugging", while the descendants of 150 people are suing you? FuzzyCatPotato!™ (talk/stalk) 01:53, 29 April 2016 (UTC)
There are people who aren't mechanically inclined or good at programming. There are people who aren't cut out for college. They still need to have a place to live and work and get by and raise their families too. The problem with all of these trade deals is that they make Western workers compete with workers in Bangladesh and Malaysia. That must stop. And we need to start thinking in terms of why we even endure the economy as it is now constituted. Why do we tolerate markets? Why do we tolerate finance? Why trade? Muster enough political will and they can be abolished. - Smerdis of Tlön, LOAD "*", 8, 1. 02:27, 29 April 2016 (UTC)
- These are quite interesting questions Smerdis which I have been thinking about for a while. Resolving them implies the complete restructuring of the way the world economy works, but I sorta feel that we are approaching the point when resolving these issues may be forced upon us.--Bob"Life is short and (insert adjective)" 09:03, 29 April 2016 (UTC)
- To be replaced with what? -EmeraldCityWanderer (talk) 20:03, 29 April 2016 (UTC)
- I have absolutely no idea. What fun.--Bob"Life is short and (insert adjective)" 14:46, 30 April 2016 (UTC)
- They can work as security or police.
- Also, good news about Bangladesh; they already hit rock bottom wages years ago, and their wages are starting to rise. Really we just need to get people to stop breeding like rabbits and we should be fine. CorruptUser (talk) 05:11, 29 April 2016 (UTC)
Robert Maydole's Ontological argument[edit]
Many theists are claiming that Maydole's version of the ontological argument from the The Blackwell Companion to Natural Theology, which is summarized here, has never been responded to. I was wondering if someone skilled in logic and philosophy could look over it and document this specific variant on the ontological argument page.
Maydole's full 40 page document can be viewed here. Maydole spends a substantial amount of time critiquing the other ontological variants before presenting his own towards the end, which he calls "The Temporal-Contingency Argument."
It would be a great asset to the wiki of anyone skilled in formal logic could put a refutation of this specific variant on our page, as I said. Also, is it the same argument we recently saw in this forum post, by chance? It seems quite similar, but with some words changed around. Lord Aeonian (talk) 23:37, 27 April 2016 (UTC)
- Sure, I would support this endeavour. This particular argument looks atleast as weak as the argument that appeared in our forums. Already at T2, Maydole's proof appears to bluescreen. Reverend Black Percy (talk) 00:54, 28 April 2016 (UTC)
- Maydole's full work in an interested read, at the least. Perhaps someone could do a sandbox where you and some others cooperatively take it apart? This may even deserve its own page, as the fine tuning argument does. I know more than a few people who think the Blackwell Companion, and this argument in particular, are the be all and end all of rational argument. Lord Aeonian (talk) 01:51, 28 April 2016 (UTC)
- His premise T5 "If everything exists for only a finite period of time, and there have been only finitely many beings to date, then there was a time when nothing existed". Suppose time is circular, so that the distant past comes after the far future, and vice versa. If that were true, then everything that has ever or will ever exist will only exist for a finite time, since the total duration of time itself would be finite; furthermore, that would be compatible with there having been "only finitely many beings to date", since if there are finitely many beings back to the next instant (fully around the circle of time), that would be all the beings there has ever been or will ever be. But that does not require that at any particular time nothing exist; there could have been something (whether matter, or energy, or a deity, or whatnot) existing at every moment of time. Hence, T5 is false. (((Zack Martin)))™ 21:36, 29 April 2016 (UTC)
- Wouldn't that just mean the argument requires an A theory of time, like the kalaam? Lord Aeonian (talk) 05:50, 1 May 2016 (UTC)
- I think we need to keep two issues distinct (1) Is the future "open"/"undetermined"? (2) Is the "flow" of time one of its fundamental features, or just something apparent or illusory or confused? The distinction between A and B theories fundamentally speaks to issue (2). But, my suggestion of "circular time" (see e.g. Nietzsche's eternal recurrence), it presumes a negative answer to (1), but it doesn't presume any particular answer to (2). If time is circular, then maybe its apparent "flow" is merely an illusion or confusion (B theory), or maybe its apparent flow is a real and irreducible feature of it, a further feature beyond its circularity (A theory). I agree by adding more premises about time the argument can be at least somewhat saved, but the more premises you add, the more opportunities to challenge those premises. (((Zack Martin)))™ 07:57, 1 May 2016 (UTC)
- The essence of Maydole's argument, is that if there is some possible world in which T1 through T14 are all true, then then a supreme being exists in this world. Now, he classifies some of T1...T14 as merely possible (they are true in some possible world, whether or not they are true in this world, and even though there may be possible worlds in which they are false), and others as necessary (Maydole believes they are true in every possible world). Now T5 he classifies as one of those "self-evident analytic truths which are true in every possible world". Now, I agree that T5 is necessary, in the sense that it is true either in all possible worlds or in none; however, unlike Maydole, rather than necessarily true, I say it is necessarily false. In order to conclude that T5 is necessarily false, we don't need to be convinced that my hypothesis of circular time is true in the actual world, simply that it is true in some possible world. If circular time is true in some possible world, then T5 is necessarily false, hence Maydole's entire argument fails. (((Zack Martin)))™ 08:41, 1 May 2016 (UTC)
- Ah ok, thank you for explaining. Do you think RW should try to make an article on this, since the more educated theists swear by it? Lord Aeonian (talk) 19:21, 1 May 2016 (UTC)
We need you![edit]this new article on how religion is portrayed in pop culture, if you are an obsessive fanboy of a certain series, or are willing to analyze various forms of media, WE WANT YOU! Bubba41102The place where you can scream at me 20:40, 29 April 2016 (UTC)
- Is anything allowed in these articles even ultra obscure Japanese video games? Because this seems like the attempt of making very generalized TVTropes articles, not that I would be against it though.∈ NameThatNobodyTakes (✎) 20:54, 29 April 2016 (UTC)
- It'd be best to limit it to only media where an interesting aspect of religion is portrayed. EG: Warhammer includes a purge of all human religion by an atheistic emperor who ironically becomes a worshipped god himself. Herr FüzzyCätPötätö (talk/stalk) 21:41, 29 April 2016 (UTC)
- Also, those articles definitely need better names. Fuzzy "Cat" Potato, Jr. (talk/stalk) 21:41, 29 April 2016 (UTC)
- Nice picture! Though, I very highly recommend that these articles be merged into one single article. Reverend Black Percy (talk) 21:43, 29 April 2016 (UTC)
- @revThat is what it was originally, but then everyone was like "This is quite a big undertaking, you should probably put it in seperate articles" so i did, and now i am being told it should be back at one article. we should probably vote on this, but right now i am too lazy to make one, so i will do it later. Bubba41102The place where you can scream at me 22:20, 29 April 2016 (UTC)
- @fuzzy yeah i couldn't think of a better name at the time, so for now their names are going to be extremely ugly. Bubba41102The place where you can scream at me 22:23, 29 April 2016 (UTC)
- You thought right before people told you what to do. I can't fathom a good reason to keep these as separate articles, honestly. Reverend Black Percy (talk) 23:28, 29 April 2016 (UTC)
For now, they are merged to: Portrayals of religion in pop culture. Fuzzy. Cat. Potato! (talk/stalk) 00:29, 30 April 2016 (UTC)
- I'm still trying to see exactly what the mission angle is on this.--Bob"Life is short and (insert adjective)" 14:47, 30 April 2016 (UTC)
- Very on mission. It is a documentation of popular media's interpretation and portrayal of the supernatural. It covers 1, 2, and 4 (especially) of our purpose. Petey Plane (talk) 16:02, 30 April 2016 (UTC)
- The missions are: 1.Analyzing and refuting pseudoscience and the anti-science movement. 2 Documenting the full range of crank ideas. 3 Explorations of authoritarianism and fundamentalism. 4.Analysis and criticism of how these subjects are handled in the media.
- The article is just a list which does nothing to further any of them. You might just as well create "Portrayals of homeopathy in science fiction" or "Portrayals of ALT MED in TV Series" or "Portrayals of cryptozoology in comic books".--Bob"Life is short and (insert adjective)" 06:53, 1 May 2016 (UTC)
- The problem I think isn't missionality, it's that it could easily turn into a pile of garbage. Though it hasn't yet - David Gerard (talk) 17:46, 30 April 2016 (UTC)
- I can't see it as anything useful. The subject of religion within popular culture is potentially limitless, what with religion having been a feature of virtually every society & being heavily reflected in societies' cultural output. Meanwhile this listicle establishes its reference points in the opening paragraph as D&D + Star Wars, & the rest of it is minutiae from a few fantasy video games from recent years. I can't see this going anywhere other than as an arbitrary fancrufty trivia list, like a TVTropes page as someone pointed out above. WēāŝēīōīďMethinks it is a Weasel 19:15, 30 April 2016 (UTC)
- Maybe RW could limit the cruft by requiring that each example must be a clear example of a page on religious apologetics and religious tactics that RW has -- eg, the piece shows why god of the gaps is flawed. Sir ℱ℧ℤℤϒℂᗩℑᑭƠℑᗩℑƠ (talk/stalk) 19:24, 30 April 2016 (UTC) | https://rationalwiki.org/wiki/RationalWiki:Saloon_bar/Archive255 | CC-MAIN-2022-21 | refinedweb | 34,834 | 69.52 |
Fl_Window | +----Fl_Gl_Window
#include <FL/Fl_Gl_Window.H>
-lfltk_gl / fltkgl.lib.
If the desired combination cannot be done, FLTK will try turning off FL_MULTISAMPLE. If this also fails the show() will call Fl::error() and not show the window.
You can change the mode while the window is displayed. This is most useful for turning double-buffering on and off. Under X this will cause the old X window to be destroyed and a new one to be created. If this is a top-level window this will unfortunately also cause the window to blink, raise to the top, and be de-iconized, and the xid() will change, possibly breaking other code. It is best to make the GL window a child of another window if you wish to do this!. | http://fltk.org/doc-1.1/Fl_Gl_Window.html | crawl-001 | refinedweb | 129 | 74.59 |
Underscore is a utility-belt library for JavaScript that provides support for functional programming. It is invaluable for writing clear, concise JavaScript in a functional style.
The
underscore package defines the
_ namespace on both the client and the server.
Currently, underscore is included in all projects, as the Meteor core depends on it. _ is available in the global namespace on both the client and the server even if you do not include this package. However if you do use underscore in your application, you should still add the package as we will remove the default underscore in the future.
We have slightly modified the way Underscore differentiates between objects and arrays in collection functions. The original Underscore logic is to treat any object with a numeric
lengthproperty as an array (which helps it work properly on
NodeLists). In Meteor’s version of Underscore, objects with a numeric
lengthproperty are treated as objects if they have no prototype (specifically, if
x.constructor === Object.
© 2011–2017 Meteor Development Group, Inc.
Licensed under the MIT License. | http://docs.w3cub.com/meteor~1.5/packages/underscore/ | CC-MAIN-2017-39 | refinedweb | 175 | 55.74 |
From: Curtis Maloney <[EMAIL PROTECTED]> > What I want to know is, why can't Python Methods refer to anything not > explicitly passed to them? I don't want to have to make everything that > invokes the method have to know to pass it half a dozen objects. > > Isn't the idea of a method to be executed in the namespace of it's parent? I > want my method to be able to access objects in it's own folder... Yep. You just need to make the first parameter of your method 'self', and not have any parameters with default values. For example, method plusX:: <params>self, x</params> return len(self.objectIds()) + x ...can be called like 'folder.plusX(3)'. You can also acquire objects that your method needs from 'self'. Cheers, Evan @ digicool & 4-am _______________________________________________ Zope maillist - [EMAIL PROTECTED] ** No cross posts or HTML encoding! ** (Related lists - )
- [Zope] Something missing in Python Methods Curtis Maloney
- Re: [Zope] Something missing in Python Methods Pierre-Julien Grizel
- Evan Simpson | https://www.mail-archive.com/zope@zope.org/msg13100.html | CC-MAIN-2018-51 | refinedweb | 169 | 72.56 |
/* ** (c) COPYRIGHT MIT 1995. ** Please first read the full copyright statement in the file COPYRIGH. */.
When a Request object is passed to the Library , the core creates a new HTNet object per channel used by the request. In many cases a request only uses a single channel object but, for example, FTP requests use at least two - one for the control connection and one for the data connection.
You can find more information about the libwww pseudo thread model in the Multithread Specifications.
This module is implemented by HTNet.c, and it is a part of the W3C Sample Code Library.
#ifndef HTNET_H #define HTNET_H
The
HTNet object is the core of the request queue management.
This object contains information about the socket descriptor, the input read
buffer etc. required to identify and service a request.
typedef struct _HTNet HTNet; #include "HTEvent.h" #include "HTReq.h" #include "HTResponse.h" #include "HTTrans.h" #include "HTHost.h" #include "HTProt.h" #include "HTChannl.h" #include "HTDNS.h"
Filter functions can be registered to be called before and after a request has either been started or has terminated. The conditions for BEFORE and AFTER filters are not the same, and so we maintain them independently. Filters can be registered globally or locally. The global filters are registered directly by the Net Object (this module) and the local filters are registered by the HTRequest Object. However, both local and global filters use the same regisration mechanism which we provide here.
Filters can be registered by anyone and as they are an often used mechanism
for introducing extensions in libwww, they are videly used to handle
authentication, redirection, etc. Many filters can be registered at once
and not all of the filters may know about the other filters. Therefore, it
is difficult to specify an absolute ordering by which the filters should
be called. Instead you can decide a relative order by which the filters should
be called. The order works pretty much like the Unix priority mechanism running
from
HT_FILTER_FIRST to
HT_FILTER_LAST having
HT_FILTER_MIDDLE being the "normal" case.
typedef enum _HTFilterOrder { HT_FILTER_FIRST = 0x0, /* 0 */ HT_FILTER_EARLY = 0x3FFF, /* 16383 */ HT_FILTER_MIDDLE = 0x7FFF, /* 32767 */ HT_FILTER_LATE = 0xBFFE, /* 49150 */ HT_FILTER_LAST = 0xFFFF /* 65535 */ } HTFilterOrder;
In case multiple filters are registered with the same order then they are called in the inverse order they were registered.
Both BEFORE and AFTER filters can be registered with a URL
template in which case they are only called when the Request URL
matches the template. A template is simply a string which is matched against
the Request URL. The string can be terminated by a single
"
*" in which case all strings matching the template up til the
"*" is considered a match. A template can be as short as the access scheme
which enmables a filter for a specific access method only, for example
"
http//<star>".
A BEFORE filter is called whenever we issue a request and they have been selected by the execution procedure. BEFORE filters are registered with a context and a filter order by which they are to be called and a URL template which may be NULL. In this case, the filter is called on every request. The mode can be used by anybody to pass an extra parameter to a filter. This is not really OO thinking - but hey - this is C ;-)
typedef int HTNetBefore (HTRequest * request, void * param, int mode);
You can add a BEFORE filter in the list provided by the caller. Several filters can be registered in which case they are called with the filter ordering in mind.
extern BOOL HTNetCall_addBefore (HTList * list, HTNetBefore * before, const char * tmplate, void * param, HTFilterOrder order);
You can also unregister all instances of a BEFORE filter from a list using the following function
extern BOOL HTNetCall_deleteBefore (HTList * list, HTNetBefore * before);
You get rid of all BEFORE filters using this function
extern BOOL HTNetCall_deleteBeforeAll (HTList * list);
The BEFORE filters are expected and called if appropriate every time we issue a new request. Libwww calls the BEFORE filters in the order specified at registration time. If a filter returns other than HT_OK then stop and return immediately. Otherwise return what the last filter returns.
extern int HTNetCall_executeBefore (HTList * list, HTRequest * request);
An AFTER filter is called whenever we have terminated a request. That is, on the way out from the protocol module and back to the application. AFTER filters are registered with a context, a status, a filter order by which they are to be called and a URL template which may be NULL. The status of the request may determine which filter to call. The set of possible values are given below. An AFTER filter can be registered to handle one or more of the codes.
A Protocol module can also, in certain cases, return a
HT_IGNORE
in which case no filters are called
typedef int HTNetAfter (HTRequest * request, HTResponse * response, void * param, int status);
You can register a AFTER filter in the list provided by the caller. Several filters can be registered in which case they are called with the filter ordering in mind.
extern BOOL HTNetCall_addAfter (HTList * list, HTNetAfter * after, const char * tmplate, void * param, int status, HTFilterOrder order);
You can either unregister all filters registered for a given status using this function or the filter for all status codes.
extern BOOL HTNetCall_deleteAfter (HTList * list, HTNetAfter * after); extern BOOL HTNetCall_deleteAfterStatus (HTList * list, int status);
You can also delete all AFTER filters in list
extern BOOL HTNetCall_deleteAfterAll (HTList * list);
This function calls all the AFTER filters in the order specified at registration
time and if it has the right status code and it's not
HT_IGNORE.
We also check for any template and whether it matches or not. If a filter
returns other than HT_OK then stop and return immediately. Otherwise return
what the last filter returns.
extern int HTNetCall_executeAfter (HTList * list, HTRequest * request, int status);
Global filters are inspected on every request (they do not have to be called - only if the conditions match). You can also register filters locally in the Request object.
These are the methods to handle global BEFORE Filters.
extern BOOL HTNet_setBefore (HTList * list); extern HTList * HTNet_before (void); extern BOOL HTNet_addBefore (HTNetBefore * before, const char * tmplate, void * param, HTFilterOrder order); extern BOOL HTNet_deleteBefore (HTNetBefore * before);
You can call both the local and the global BEFORE filters (if any)
extern int HTNet_executeBeforeAll (HTRequest * request);
These are the methods to handle global AFTER Filters.
extern BOOL HTNet_setAfter (HTList * list); extern HTList * HTNet_after (void); extern BOOL HTNet_addAfter (HTNetAfter * after, const char * tmplate, void * param, int status, HTFilterOrder order); extern BOOL HTNet_deleteAfter (HTNetAfter * after); extern BOOL HTNet_deleteAfterStatus (int status);
You can call both the local and the global AFTER filters (if any)
extern int HTNet_executeAfterAll (HTRequest * request, int status);
The request queue ensures that no more than a fixed number of TCP connections are open at the same time. If more requests are handed to the Library, they are put into the pending queue and initiated when sockets become free.
Set the max number of simultanous sockets. The default value is HT_MAX_SOCKETS which is 6. The number of persistent connections depend on this value as a deadlock can occur if all available sockets a persistent (see the DNS Manager for more information on setting the number of persistent connections). The number of persistent connections can never be more than the max number of sockets-2, so letting newmax=2 prevents persistent sockets.
extern BOOL HTNet_setMaxSocket (int newmax); extern int HTNet_maxSocket (void);
extern void HTNet_increaseSocket (void); extern void HTNet_decreaseSocket (void); extern int HTNet_availableSockets (void);
extern void HTNet_increasePersistentSocket (void); extern void HTNet_decreasePersistentSocket (void); extern int HTNet_availablePersistentSockets (void);
Returns whether there are active requests. Idle persistent sockets do not count as active.
extern BOOL HTNet_isIdle (void);
Returns the list of active requests that are currently having an open connection. Returns list of HTNet objects or NULL if error.
extern HTList *HTNet_activeQueue (void); extern BOOL HTNet_idle (void);
We have some small functions that tell whether there are registered requests in the Net manager. There are tree queues: The active, the pending, and the persistent. The active queue is the set of requests that are actively sending or receiving data. The pending is the requests that we have registered but which are waiting for a free socket. The Persistent queue are requets that are waiting to use the same socket in order to save network resoures (if the server understands persistent connections).
Returns whether there are requests in the active queue or not
extern BOOL HTNet_idle (void);
Returns whether there are requests registered in any of the lists or not
extern BOOL HTNet_isEmpty (void); extern int HTNet_count (void);
Returns the list of pending requests that are waiting to become active. Returns list of HTNet objects or NULL if error
extern HTList *HTNet_pendingQueue (void);
The Net object is intended to live as long as the request is still active. In that regard it is very similar to the Request Object . However, the main difference is that a Net object represents a "thread" in the Library and a request may have multiple "threads" - an example is a FTP request which has a thread to handle the control connection and one to handle the data connections.
If we have more than HTMaxActive connections already then put this into the pending queue, else start the request by calling the call back function registered with this access method. Returns YES if OK, else NO
extern BOOL HTNet_newClient (HTRequest * request);
You can create a new HTNet object as a new request to be handled. If we have more than HTMaxActive connections already then return NO. Returns YES if OK, else NO
extern BOOL HTNet_newServer (HTRequest * request);
And you can create a plain new HTNet object using the following method:
extern HTNet * HTNet_new (HTHost * host);
Creates a new HTNet object as a duplicate of the same request. Returns YES if OK, else NO.
extern HTNet * HTNet_dup (HTNet * src); extern BOOL HTNet_deleteDup (HTNet * dup);
Start a Net obejct by calling the protocol module.
extern BOOL HTNet_start (HTNet * net);
This functions lets the caller play event manager as it can calls any event handler with the event type and context passed to the function
extern BOOL HTNet_execute (HTNet * net, HTEventType type); extern HTEvent * HTNet_event (HTNet * net); extern BOOL HTNet_setEventParam (HTNet * net, void * eventParam); extern void * HTNet_eventParam (HTNet * net); extern BOOL HTNet_setEventCallback(HTNet * net, HTEventCallback * cbf); extern HTEventCallback * HTNet_eventCallback(HTNet * net);
Deletes the HTNet object from the list of active requests and calls any registered call back functions IF not the status is HT_IGNORE. This is used if we have internal requests that the app doesn't know about. We also see if we have pending requests that can be started up now when we have a socket free. The filters are called in the reverse order of which they were registered (last one first);
extern BOOL HTNet_delete (HTNet * me, int status);
Deletes all HTNet object that might either be active or pending We DO NOT call the call back functions - A crude way of saying goodbye!
extern BOOL HTNet_deleteAll (void);
Let a net object wait for a persistent socket. It will be launched from the HTNet_delete() function when the socket gets free.
extern BOOL HTNet_wait (HTNet *net);
Each HTNet object is created with a priority which it inherits from the Request manager. However, in some stuations it is useful to be to change the current priority after the request has been started. These two functions allow you to do this. The effect will show up the first time (which might be imidiately) the socket blocks and control returns to the event loop. Also have a look at how you can do this before the request is issued in the request manager.
extern HTPriority HTNet_priority (HTNet * net); extern BOOL HTNet_setPriority (HTNet * net, HTPriority priority);
You can set a Net object to handle persistent connections for example using HTTP, NNTP, or FTP. You can control whether a Net object supports persistent connections or not using this function.
extern BOOL HTNet_persistent (HTNet * net);
You can set or disable a Net object supporting persistent connections using this function:
extern BOOL HTNet_setPersistent (HTNet * net, BOOL persistent, HTTransportMode mode);
When pipelining, it is not possible to kill a single request as we then loose track of where we are in the pipe. It is therefore necessary to kill the whole pipeline.
extern BOOL HTNet_killPipe (HTNet * net);
This is not often used anymore, consider using the pipeline version above. Kill the request by calling the call back function with a request for closing the connection. Does not remove the object. This is done by HTNet_delete() function which is called by the load routine. Returns OK if success, NO on error.
extern BOOL HTNet_kill (HTNet * me);
Kills all registered (active as well as pending) requests by calling the call back function with a request for closing the connection. We do not remove the HTNet object as it is done by HTNet_delete(). Returns OK if success, NO on error
extern BOOL HTNet_killAll (void);
You create the input stream and bind it to the channel using the following methods. Please read the description in the HTIOStream module on the parameters target, param, and mode. Both methods return YES if OK, else NO.
#if 0 extern HTInputStream * HTNet_getInput (HTNet * net, HTStream * target, void * param, int mode); #endif extern HTOutputStream * HTNet_getOutput (HTNet * me, void * param, int mode);
Just like the request object, a net object can be assigned a context which keeps track of context dependent information. The Library does not use this information nor does it depend on it but it allows the application to customize a net object to specific uses.
extern BOOL HTNet_setContext (HTNet * net, void * context); extern void * HTNet_context (HTNet * net);
extern BOOL HTNet_setSocket (HTNet * net, SOCKET sockfd); extern SOCKET HTNet_socket (HTNet * net);
A access scheme is defined with a default for using either preemptive (blocking I/O) or non-premitve (non-blocking I/O). This is basically a result of the implementation of the protocol module itself. However, if non-blocking I/O is the default then some times it is nice to be able to set the mode to blocking instead. For example when loading the first document (the home page) then blocking can be used instead of non-blocking.
extern BOOL HTNet_preemptive (HTNet * net);
The Request object is normally set up automatically but can be changed at a later time.
extern BOOL HTNet_setRequest (HTNet * net, HTRequest * request); extern HTRequest * HTNet_request (HTNet * net);
extern BOOL HTNet_setProtocol (HTNet * net, HTProtocol * protocol); extern HTProtocol * HTNet_protocol (HTNet * net);
The transport object is normally set up automatically but can be changed at a later time.
extern BOOL HTNet_setTransport (HTNet * net, HTTransport * tp); extern HTTransport * HTNet_transport (HTNet * net);
extern BOOL HTNet_setChannel (HTNet * net, HTChannel * channel); extern HTChannel * HTNet_channel (HTNet * net);
extern BOOL HTNet_setHost (HTNet * net, HTHost * host); extern HTHost * HTNet_host (HTNet * net);
The DNS object keeps track of the DNS entries that we have already checked out.
extern BOOL HTNet_setDns (HTNet * net, HTdns * dns); extern HTdns * HTNet_dns (HTNet * net);
extern HTStream * HTNet_readStream(HTNet * net); extern BOOL HTNet_setReadStream (HTNet * net, HTStream * stream);
This functions can be used to determine whether bytes count should be managed at the low level read stream or at a higher level. If the data transfer equals the lifetime of a single document like for example in FTP or HTTP/1.0 then this may be a reasonable thing to do.
extern BOOL HTNet_setRawBytesCount (HTNet * net, BOOL mode); extern BOOL HTNet_rawBytesCount (HTNet * net);
#endif /* HTNET_H */ | http://www.w3.org/Library/src/HTNet.html | CC-MAIN-2015-27 | refinedweb | 2,571 | 50.46 |
50 litre plastic bucket mold factory
plastic bucket mold 20 litre for sale - Eden Valley
See more ideas about paint buckets, molding, plastic injection molding. ... factory, square paint bucket mould factory, the capacity from 1L, 3.6L…18L,20L… ...
import plastic bottle mould retailer - Eden Valley
Aluminium 200ml Pet Plastic Water Blow Mould, 50-60 Hrc ₹ 17,000/ Set. Get Quote. Stainless Steel 5 Litre Bottle Mould, For Industrial ₹ 42,000/ Set.
Plastic Buckets Manufacturers and Suppliers in the USA - Thomasnet
Services include precision plastic injection molding, part design, mold design, mold construction, engineering, contract manufacturing, automated & manual ...
20 ltr plastic bucket mold distributor - Shelley Appleton
Results 1 - 48 of 132 ... Visit Alibaba.com for the best 20l bucket mould that are available in many ... Bucket Mould Factory Direct Sales Plastic 18L Bucket Mould.
80 litre bucket mold switzerland - Shelley Appleton
Hot Selling Cheap Price 80 Liter Plastic Bucket Lid Mould. ... Plastic Bucket Lid Mould (JTP-A0023) suppliers and exporters,details:Mould Material:45# 50# ...
H&O Plastics | Plastic Bucket Manufacturer
Whether it's 50 paint kettles or 10,000 sturdy containers for international shipping – H&O Plastics can accommodate your needs. Unlike other UK suppliers, all ...
Plastic Bucket Mould factory, Buy good quality Plastic Bucket Mould ...
China 20 Liter Plastics Buckets Injection Molding Mold , 2 Cavity Plastic Molding Tools factory · China Hot Runner ABS Plastic Bucket Mould High Precision ...
Bucket, plastic, 14L, Heavy duty plastic - IOM|Emergency Manual
Heavy-duty plasticbucket, with handle and lid with attached clip-on cap. Manufacturing process, Injection moulding. Material:
Molds Unlimited
Plastic Machinery,Used Molds,Used Mold,Used Injection Molds,Used Blow Molds,New Machinery,Used Machinery,Chillers ... Set of 4 Molds -Liter Ice Bucket Lid.
We have the right packaging. - Wolf Plastics
That is our world; the world of WOLF PLASTICS. ≤ 1 litre. ... bucket is also impressive as techniques such as in-mould labelling can.
50 liter plastic bucket - Alibaba.com
1986 products ... CNTaizhou Hengming Plastics & Mould Technology Co., Ltd. ... 1L to 50L Large Plastic PP Bucket Plant plastic bucket 1 20 50 100 150 200.
NEXT Post:plastic low table mould manufacturer | https://www.krishnachandracollege.in/plastic/2646-50-litre-plastic-bucket-mold-factory.html | CC-MAIN-2021-49 | refinedweb | 351 | 50.43 |
Real-time Experience at FOSDEM 2018
by Bartłomiej Górny, Michał Piotrowski, Wioletta Dec
This year we took our chance to engage with one of the largest open source software families - by attending FOSDEM. This is a Free Open Source European Developer’s Meeting taking place at the Université Libre de Bruxelles Solbosch campus in Brussels on 3-4 February. FOSDEM is among the world’s largest events focusing on free and open-source software development and its atmosphere is pretty unique.
Fig. 1: Elasticsearch [R]Evolution by Philipp Krenn, Fosdem 2018
FOSDEM 2018 was incredible as always - huge, noisy, crowded, crazy, brimming with energy, joy and never ending excitement. With nearly 14,000 attendees, 653 speakers and almost 700 talks supporting open source innovations, spread across 57 thematic sessions, the event was a hit. Most of the conference rooms were full to bursting, the exhibitors and networking areas were busy from early morning until evening and filled with enormous number of free open source projects and their communities. Github-sponsored free coffee, stalls featuring everything from hardcore Perl hackers to the VLC squad dressed as roadwork cones and LizardFS’ Polish-Irish team treating visitors to their stand with vodka shot!
Fig. 2: Exhibitors Area, FOSDEM 2018
Alessio Fattorini described FOSDEM as “Woodstock for Geeks”. Taking the level of enthusiasm, creative energy combined with tech, innovation and knowledge, we’d say he was right!
As always, organisers did a great job increasing networking and knowledge sharing opportunities through multiple accompanying social events. 2018 is the 20th anniversary of Open Source and it was celebrated at Fosdem.
We were there too, representing our own open source based messaging platform MongooseIM, while hanging out in the Real-Time Lounge.
REAL-TIME LOUNGE
The ‘Real-Time Lounge’ is where various open source, XMPP powered software solutions are presented by their communities, under the umbrella XSF (XMPP Standards Foundation) who are the main hosts of the ‘Real Time Lounge’.
Squeezed between vending machines and a wheel of fortune was our cosy corner, where we brought together the best of open-source instant messaging and real-time communication. XSF, first and foremost, and XMPP-based software - Tigase, Prosody, MongooseIM, OpenFire and more.
Fig. 3: Real Time Lounge, FOSDEM 2018
In addition, our MongooseIM representatives, Michał Piotrowski and Bartłomiej Górny presented their work within the Real Time Communications Devroom. While Michał explored different ways of scaling an open source XMPP server - MongooseIM, Bartłomiej shared his vision of XMPP as the road to innovation.
Michał Piotrowski, “Scaling messaging systems”
“In my talk I described the most frequent scalability limitations when it comes to MongooseIM, showing that, thanks to the Erlang VM, scaling a single node MongooseIM installation or multiple nodes in the same datacenter is easy. The real fun begins when we need to spread the installation between continents. In this case there are two options. XMPP federation where users are bound to a specific datacenter. There is also the new MongooseIM feature called Geo Distribution - in this cases all MongooseIM clusters across the globe serve the same XMPP domain, so users can connect to any datacenter, usually the closest one.”
Scalability depends on many variables for MongooseIM’s or indeed any other XMPP server. It’s hard to say that a particular option will work for every one, as every MongooseIM installation we have had the pleasure to build is unique. When planning how to scale MongooseIM we need to consider things like:
- Machine power (CPU and memory)
- Type of connected users. Using an XMPP server from a web browser or a desktop is different from a mobile device. A mobile device will (re-)connect more often than a desktop client.
- Used and enabled XMPP features. Using only basic one-to-one messages without archiving will place much lighter demands on the server than for instance large group chats with many active users.
When the service popularity grows and there are more and more users generating more and more load on the server, resources may be fully utilised. Typically it’s the memory which runs out first, but depending on your specific use case it may happen that first you will run out of CPU power or maybe your database will start slowing down.
When you hit one of the limits, you need to start scaling MongooseIM. There is several ways to do it.
First of all, thanks to Erlang VM, scaling a single MongooseIM node is as easy as adding more resources (more RAM or more powerful CPU). Every connected device is represented as 2-3 lightweight Erlang processes. These processes are then spread across all available CPU cores thanks to Erlang scheduler.
A single installation, while able to handle millions of users on very powerful machines, is usually a bad idea due to having a single point of failure. Typical production installation consists of at least 3 MongooseIM nodes to be able to survive single node crashes. With multi-node installation we need to remember to keep enough spare resources on all the nodes to be able to handle traffic from a dead node. At some point there may be a need to add more nodes to cluster. This again, thanks to the Erlang VM, is very easy. MongooseIM uses the Erlang distribution layer and Mnesia database to set up the cluster and communicate between nodes in the cluster.
In some cases one cluster is not enough. In this case we can scale MongooseIM beyond a cluster. The simplest solution is XMPP federation. In this approach we setup several MongooseIM clusters, and every cluster serves one XMPP domain. With this setup, users will be bound to a specific domain and will always need to be connected to the same datacenter. Sometimes this is too limiting and we’d like to allow our users to connect to the closest datacenter. And there is answer to this need - it’s MongooseIM’s new extension called Geo Distribution. Thanks to this, many different MongooseIM clusters can serve the same domain and users can connect to any (usually the closest) datacenter.
Watch video recording here.
Bartłomiej Górny, “XMPP as the road to innovation”
“I think the extensibility of XMPP is the best of both worlds: it has a built-in mechanism that makes it really easy to extend, to build stuff on top of it, but it also has the XSF which has a firm grip on it, making sure it grows in a controlled, orderly way. The protocol, with all its official extensions, covers a wide scope of functionalities, but still is clean and tidy. This is what makes it such a good tool for innovative implementations.”
XMPP is designed to be extensible, to serve as a vehicle for innovation. For this purpose, it provides technical means for building solutions on top of the existing protocol. But extensibility alone is nowhere near enough to be truly useful - for example, Drupal, a CMS written in PHP, features over 20k extensions. Bad news for someone trying to find something he needs.
To be a really good platform for innovation, XMPP provides three pillars:
- A solid, stable foundation
- Built-in extension mechanism
- Procedures to verify and share extensions
1. Foundation
Basically, XMPP is for exchanging messages and presence information among clients. It is a client-server protocol, based on XML. Core XMPP documents (RFCs) define the addressing scheme, setting up TCP session and procedures for presence management and exchange and basic messaging.
The base “layer” of the protocol are three XML structures (called “stanzas”), each categorised in a few types:
- IQ (get, set, result, error)
- Presence (available, unavailable, probe, plus a few more specialised types)
- Message (normal, chat, groupchat, …)
Fig. 4: A simple message stanza.
Each stanza has a defined role: IQ (info/query) is basically for communicating with server; presence conveys information about the client’s availability, both to server and to the client’s friends; message is client-client communication and can server a wide variety of purposes.
These stanzas are the core of the protocol, and are not meant to be changed. The rest is extensions, documented in “XMPP Enhancement Proposals” (XEPs). There are quite a few of them, but not too many - just a few hundred, which may still sound scary, but it is just because there is a lot of stuff you can do with XMPP. And here comes the best part: there is a list of officially supported XEPs, maintained by XSF (XMPP Standards Foundation), available on xmpp.org. Everything on this list has been thoroughly scrutinised, discussed, proofread, improved and voted on by people from the foundation. In other words, you can trust them and build your own implementation on top of. It is also easy to choose the one you need, because they usually do not overlap - if you find two XEPs cover similar functionalities, then most likely one of them is already marked as deprecated, or soon will be.
Fig. 5: Part of the list of XMPP extensions
2. Extension mechanism
While the base layer of the protocol is defined by a narrow selection of xml tag names and attributes (message/chat etc), extensions are built around the concept of namespaces. The whole mechanism can be described in just a few bullet points:
- an extension uses a stanza as its transport (message, presence or iq)
- an extension defines its unique namespace
- an extension is documented in its own XEP Therefore there is a one-to-one-to-one mapping between extensions, namespaces and XEPs.
Fig. 6: Namespace identifying protocol extensions
This is the gist of it - namespace uniquely identifies the feature being used, is human-readable, and makes it easy to plug in a dedicated handler for a given extension.
3. Verification
If you design your own extension, the best way to test it is to submit it to XSF. The Foundation is always looking for new ideas, but is also extremely careful and demanding. If you submit your document (the process is described on) it will be really thoroughly evaluated, and you will have to spend lots of time answering questions and making corrections and improvement. Chances it makes it to the official list are rather slim, but you will have your feedback galore. The whole process is time consuming and often frustrating, it also rather taxing from the Foundation’s point of view. It is, though, the only way to make sure the protocol is not getting polluted with half-baked ideas.
The right approach to extending
If you think about extending XMPP, here is a list of steps to take:
Step 1: Read carefully a list of XEPs on xmpp.org. Not just once.
As stated before, there are quite a few of them, covering many areas, and the chances are what you need is already taken care of. It might not be obvious at the first glance, so a close look is highly recommended.
Step 2: Read the list again to see what can be used as the base
An extension is not a fixed take-it-or-leave it thing. It is more like a class in OOP, something you can use as-is or build another class on top of it. Remember: namespaces can be nested, so there is nothing stopping you from implementing extension within extension.
Fig. 7: Nested namespaces - extending an extension
Step 3: Choose stanza carefully
If there is nothing that would suit your purpose and you have to design an extension from scratch, think twice before choosing a stanza. If it is for client-server communication (like getting some data from server, setting parameters, performing administrative action) most likely you will go with IQ. For nearly all other purposes use message. Yes, it is tempting to use presence, sometimes it even seems obvious that it should be a presence. Let me give you an example, then: suppose we want to publish a user’s geographical location in real time. The first idea is “let’s use presence”. It is quite logical, since the user is “present” at a certain location. Let’s design an extension which would add a geolocation element to a presence, and voila, we’re done.
Fig. 8: The wrong way to propagate user state info
It turns out that it is a very bad idea. First, presence goes out to everybody in your roster (contact list), whether he wants it or not. And he can’t get rid of it, unless he unsubscribes, which means he is not going to receive any presence at all, location or no location. Plus, presence info is never archived, which is something you might want. If you must, use message.
By the way, if you consider it at all, it means you haven’t executed step 2 - there is XEP-0163 “Personal Eventing Protocol” which is a perfect tool for the job. It turns every user account to a pub-sub node to which you can subscribe and receive event information, location in this case, as messages. Even worse, it means you haven’t even executed step 1, because if you had, you’d have had discovered XEP-0080 which does exactly what you need.
Step 4 - write a XEP
It is highly recommend to document your extension properly. Of course, it is always highly recommended to properly document anything you do; my advice here is to document it in the same way all other extensions are documented. It is quite verbose, but at least it is consistent; programmers implementing your idea will have to read lots of XEPs AND the one you are writing. Also, consider submitting it to XSF. Even if it is rejected (which it probably will), you will get lots of useful feedback, free of charge.
Watch video recording here.
As this year we are celebrating the 20th anniversary of open-sourced Erlang #OpenErlang, we’ve been glad to be part of FOSDEM, connect with a global open source community and celebrate 20 years of open sourced Erlang together.Go back to the blog | https://www.erlang-solutions.com/blog/real-time-experience-at-fosdem-2018.html?utm_source=ESL%20website&utm_medium=MIM%20twitter&utm_campaign=Fosdem%20blog%20post | CC-MAIN-2018-17 | refinedweb | 2,336 | 59.53 |
Hi. I am pulling my hair out. I have 2 test cases, the 1st one I created a "Properties" test step and I can set and get to that using Groovy within that test case.
I also have also created another "Properties" test step in the 2nd Test case and from within that Test Case (in Groovy) I want to Set a value in the 1st ones "Properties" test step, but cannot figure out how to do this. Any help would be appreciated, please. Thanks, Cliff.
Solved!
Go to Solution.
This will work if both of your test cases are in the same test suite. If they are in different test suites then you will need to define what suite you are working with.
def tCase = testRunner.testCase.testSuite.getTestCaseByName("Global")
def tStep = tCase.getTestStepByName("Global Properties")
tStep.setPropertyValue("Property Name", "newValue")
If you wont need to reuse the test case or test step property then you can do it all in one line.
testRunner.testCase.testSuite.getTestCaseByName("Global").getTestStepByName("Global Properties").setPropertyValue("Property Name", "newValue")
View solution in original post | https://community.smartbear.com/t5/SoapUI-Pro/How-to-Set-or-Get-quot-Test-Step-quot-Properties-from-another/m-p/193695 | CC-MAIN-2019-51 | refinedweb | 181 | 57.47 |
I true for high frequency traders, but not at the sort of timescales that I tend to trade over (holding periods of a couple of weeks up to a couple of months). There I'm using rules that I expect to work over pretty much any instrument I trade, and to perform consistently over long periods of time.
So I've generally advocated pooling information across markets when fitting. My preferred method is to pool gross returns, then apply the costs for each individual instrument, so more expensive instruments will end up trading slower; otherwise everything will look pretty similar.
But... might instrument specific fitting actually work? Or even if that doesn't work, what about pooling together information for similar instruments? Or.... is there some way of getting the best out of all three worlds here: using a blend of instrument specific, globally pooled, and similarity pooled information?
Let's find out.
What exactly is wrong with fitting by instrument?
Let's think about a simple momentum system, where the combined forecast is a weighted average of N different trend signals, each with different speeds. These could be moving average crossovers with some length, or breakouts with some varying window. The only fitting that can be done in this kind of system is to allocate risk weightings differently to different speeds of momentum. Naturally this is a deliberate design decision to avoid 'free-form' fitting of large numbers of parameters, and reduce the issue to a portfolio optimisation problem (which is relatively well understood) with just N-1 degrees of freedom.
The decision we have to make is this: What forecast weights should a given instrument have?
Important note: my trading systems are carefully designed to abstract away any differences in instruments, mostly by the use of risk scaling or risk normalisation. Thus we don't need to estimate or re-estimate 'magic numbers' for each instrument, or calibrate them seperately to account for differences in volatility. Similarly forecasts from each trading rule are normalised to have the same expected risk, so there are no magic numbers required here eithier. This is done automatically by the use of forecast scalars and risk normalisation.
In a simple portfolio optimisation where all assets have the same expected volatility what matters in determining the weights: Basically correlation and relative Sharpe Ratio (equivalent to mean, given the identical volatilities).
But it turns out that when you analyse the different correlation across trading rules for different instruments, you get very similar results.
(There's chunks of pysystemtrade code scattered throughout this post, but hopefully the general approach will be applicable to your own trading system. You may find it helpful to read my posts on optimising with costs, and my preferred optimisation method, handcrafting)
def corr_from(system, instrument):
y = system.combForecast.calculation_of_raw_estimated_monthly_forecast_weights(instrument)
return y.optimiser_over_time.optimiser.calculate_correlation_matrix_for_period(
y.optimiser_over_time.fit_dates[-1]).as_pd().round(2)corr_from(system, "CORN")
momentum16 momentum32 momentum4 momentum64 momentum8
momentum16 1.00 0.88 0.65 0.61 0.89
momentum32 0.88 1.00 0.41 0.88 0.64
momentum4 0.65 0.41 1.00 0.21 0.89
momentum64 0.61 0.88 0.21 1.00 0.37
momentum8 0.89 0.64 0.89 0.37 1.00
corr_from(system, "SP500")
momentum16 momentum32 momentum4 momentum64 momentum8
momentum16 1.00 0.92 0.60 0.79 0.90
momentum32 0.92 1.00 0.40 0.94 0.71
momentum4 0.60 0.40 1.00 0.29 0.85
momentum64 0.79 0.94 0.29 1.00 0.57
momentum8 0.90 0.71 0.85 0.57 1.00
We can see that the results are fairly similar: in fact they'd result in very similar weights (all other things being equal).
This is partly because my handcrafted method is robust to correlation differences that aren't significant, but even a vanilla MVO wouldn't result in radically different weights. In fact I advocate using artifical data to estimate the correlations for momentum rules of different speed, since it will give a robust but accurate result.
(Things are a bit different for carry and other more exotic trading rules, but I'll be bringing those in later)
What about Sharpe Ratio? Well there are indeed some differences....
def SR_from(system, instrument):
y = system.combForecast.calculation_of_raw_estimated_monthly_forecast_weights(instrument)
std = np.mean(list(y.optimiser_over_time.optimiser.calculate_stdev_for_period(y.optimiser_over_time.fit_dates[-1]).values()))
means =y.optimiser_over_time.optimiser.calculate_mean_for_period(y.optimiser_over_time.fit_dates[-1])
SR = dict([
(key, round(mean/std,3)) for key,mean in means.items()
])
return SR
SR_from(system, "CORN")
{'momentum16': 0.39, 'momentum32': 0.296, 'momentum4': -0.25, 'momentum64': 0.102,'momentum8': 0.206}SR_from(system, "SP500")
{'momentum16': 0.147, 'momentum32': 0.29, 'momentum4': -0.207, 'momentum64': 0.359,'momentum8': -0.003}
We can see the well known effect that faster momentum isn't much cop for equity indices, as well as some other differences.
But are they significant differences? Are they significant enough that we should use them in determining what weights to use? Here are the forecast weights with no pooling of gross returns for each instrument:
system.config.forecast_weight_estimates['pool_gross_returns'] = Falsesystem.combForecast.get_forecast_weights("CORN").iloc[-1].round(2)
momentum16 0.39
momentum4 0.00
momentum8 0.13
momentum64 0.16
momentum32 0.32system.combForecast.get_forecast_weights("SP500").iloc[-1].round(2)
momentum16 0.22
momentum4 0.00
momentum8 0.08
momentum64 0.36
momentum32 0.33
The weights are certainly a bit different, although my use of a robust optimisation process (handcrafting) means they're not that crazy. Or maybe it makes more sense to pool our results:
system.config.forecast_weight_estimate['pool_gross_returns'] = True
system.combForecast.get_forecast_weights("CORN").iloc[-1].round(2)
momentum16 0.21
momentum4 0.00
momentum8 0.11
momentum64 0.30
momentum32 0.38
system.combForecast.get_forecast_weights("SP500").iloc[-1].round(2)
momentum16 0.22
momentum4 0.01
momentum8 0.16
momentum64 0.24
momentum32 0.37
(The small differences here are because we're still using the specific costs for each instrument - it's only gross returns that we pool).
There is a tension here: We want more data to get robust fitting results (which implies pooling across instruments is the way to go) and yet we want to account for idiosyncratic differences in performance between instruments (which implies not pooling).
At the moment there is just a binary choice: we eithier pool gross returns, or we don't (we could also pool costs, and hence net returns, but to me that doesn't make a lot of sense - I think the costs of an instrument should determine how it is traded).
And the question is more complex again, because what instruments should we pool across? But maybe it would make more sense to pool across instruments within the same asset class? This effectively is what was done at AHL when I worked there due to the fact that we ran seperate teams for each asset class (I was head of fixed income), and each team fitted their own models (What they do now, I dunno. Probably some fancy machine learning nonsense). Or across everything, regardless of costs?
Really, we have three obvious alternatives:
- Fit by instrument, reflecting the idiosyncractic nature of each instrument
- Fit with information pooled across similar instruments (same asset class? Perhaps)
- Fit with information pooled across all instruments
So the point of this post is to test these alternatives out. But what I also want to try is something else: a method which uses a blend of all three methods. In this post I develop a methodology to do this kind of 'blended weights' (not a catchy name! Suggestions are welcome!).
A brief interlude: The speed limit
In my first book I introduce the idea of a 'speed limit' on costs, measured in annualised risk adjusted terms (so effectively a Sharpe Ratio). The idea is that on a per instrument, per trading rule basis it's unlikely (without overfitting) you will get an average SR before costs of more than about 0.40 on average, and you wouldn't want to spend more than a third of that on costs (about 0.13). Therefore it makes no sense to include any trading rules which breach this limit for a given instrument (which will happen if they trade too quickly, and the instrument concerned is relatively expensive to trade).
Now whilst I do like the idea of the speed limit, one could argue that it is unduly conservative. For starters, expensive rules are going to be penalised anyway since I optimise on after costs returns, and I am taking SR into account when deciding the correct weights to use. In fact they get penalised twice, since I include a scaling factor of 2.0 on all costs when optimising. Secondly, a fast rule might not affect turnover on the entire system once added to a bunch of slower rules, especially if it has some diversifying effects. Thirdly, I apply a buffering on the final position for a given instrument, which reduces turnover and thus costs anyway, so the marginal effect of allocating to a faster rule might be very small.
It turns out that this question of whether to apply the speed limit is pretty important. It will result in different individually fitted instrument weights, different asset groupings, and different results. For this reason I'll be running the results both with, and without the speed limit. And of course I'll be checking what effect this difference has on the pre-cost and after-costs SR.
The setup
- 'momentum4' EWMAC 4,16
- 'momentum64' EWMAC 64,256
- 'carry10' Carry with a 10 day smooth
- 'breakout10' Breakout 10 day window
- 'breakout160' Breakout 160 day window
- 'mrinasset160' Mean reversion within asset classes, 160 day window
- 'relmomentum20' Cross sectional momentum within asset class, 20 day window
- 'assettrend32' Momentum for asset class, EWMAC 32,64
- 'normmom32' Normalised momentum EWMAC 32, 64
- 'relcarry' Relative carry within asset classes
- 'skewabs90' Skew 90 day window
- 'kurtS_abs30' Kurtosis conditioned on skew 30 day window
assettrend32 breakout10 breakout160 carry10 kurtS_abs30 momentum4
assettrend32 1.00 0.16 0.75 0.29 -0.04 0.29
breakout10 0.16 1.00 0.18 0.08 -0.01 0.82
breakout160 0.75 0.18 1.00 0.37 -0.04 0.35
carry10 0.29 0.08 0.37 1.00 -0.05 0.12
kurtS_abs30 -0.04 -0.01 -0.04 -0.05 1.00 -0.02
momentum4 0.29 0.82 0.35 0.12 -0.02 1.00
momentum64 0.73 0.15 0.89 0.46 -0.03 0.28
mrinasset160 0.02 -0.05 -0.38 -0.11 0.03 -0.11
normmom32 0.80 0.18 0.89 0.33 -0.04 0.34
relcarry 0.04 0.00 0.19 0.63 -0.02 0.02
relmomentum20 0.02 0.25 0.19 0.05 0.01 0.42
skewabs90 -0.02 0.01 0.02 0.11 -0.06 -0.03
momentum64 mrinasset160 normmom32 relcarry relmomentum20 skewabs90
assettrend32 0.73 0.02 0.80 0.04 0.02 -0.02
breakout10 0.15 -0.05 0.18 0.00 0.25 0.01
breakout160 0.89 -0.38 0.89 0.19 0.19 0.02
carry10 0.46 -0.11 0.33 0.63 0.05 0.11
kurtS_abs30 -0.03 0.03 -0.04 -0.02 0.01 -0.06
momentum4 0.28 -0.11 0.34 0.02 0.42 -0.03
momentum64 1.00 -0.41 0.87 0.25 0.16 0.08
mrinasset160 -0.41 1.00 -0.45 -0.19 -0.26 -0.01
normmom32 0.87 -0.45 1.00 0.13 0.22 -0.03
relcarry 0.25 -0.19 0.13 1.00 0.03 0.10
relmomentum20 0.16 -0.26 0.22 0.03 1.00 -0.06
skewabs90 0.08 -0.01 -0.03 0.10 -0.06 1.00
There are some rules with high correlation, mostly momentum of similar speeds defined differently. And the mean reversion rule is obviously negatively correlated with the trend rules; whilst the skew and kurtosis rules are clearly doing something quite different.
Here are the Sharpe Ratios (using data pooled across instruments):{'momentum4': 0.181, 'momentum64': 0.627, 'carry10': 0.623,'breakout10': -0.524, 'breakout160': 0.714, 'mrinasset160': -0.271,'relmomentum20': 0.058, 'assettrend32': 0.683, 'normmom32': 0.682,'relcarry': 0.062, 'skewabs90': 0.144, 'kurtS_abs30': -0.600}
Not all of these rules are profitable! That's because I didn't cherry pick rules which I know made money; I want the optimiser to decide - otherwise I'm doing implicit fitting.
As this exercise is quite time consuming, I also used a subset of my full list of instruments, randomly picked mainly to see how well the clustering of groups worked (so there is quite a lot of fixed income for example):'AEX', 'AUD', 'SP500', 'BUND', "SHATZ",'BOBL','US10', 'US2','US5', 'EDOLLAR', 'CRUDE_W', 'GAS_US', 'CORN', 'WHEAT'
Fit weights for individual instrument
Step one is to fit weights for each individual instrument. We'll use these for three different purposes:
- To test instrument specific fitting
- To decide what instruments to pool together for 'pool similar' fitting
- To provide some of the weights to blend together for 'blended' weights
system.config.forecast_weight_estimate['ceiling_cost_SR'] = 9999 # Set to 0.13 to get weights with speed limit
system.config.forecast_weight_estimate['pool_gross_returns'] = False
system.config.forecast_weight_estimate['equalise_SR'] = False
system.config.use_forecast_weight_estimates = True
system.config.instruments = ['AEX', 'AUD', 'SP500', 'BUND', "SHATZ",'BOBL','US10', 'US2','US5', 'EDOLLAR', 'CRUDE_W', 'GAS_US', 'CORN', 'WHEAT']
system = futures_system()
wts_dict = {}
for instrument in system.get_instrument_list():
wts_dict[instrument] = system.combForecast.get_forecast_weights(instrument)
Get instrument groupings
The next stage is to decide which instruments to group together for fitting purposes. Now I could, as I said, do this by asset class. But it seems to make more sense to let the actual forecast weights tell me how they should be clustered, whilst also avoiding any implicit fitting through human selection of what constitutes an asset class. I'll use k-means clustering, which I also used for handcrafting. This takes the wts_dict we produced above as it's argument (remember this is a dict of pandas Data Frames, on per instrument):
import pandas as pd
from sklearn.cluster import KMeans
def get_grouping_pd(wts_dict, n_clusters=4):
all_wts_common_columns_as_dict = create_aligned_dict_of_weights(wts_dict)
## all aligned so can use a single index
all_wts_as_list_common_index = list(all_wts_common_columns_as_dict.values())[0].index
## weights are monthly, let's do this monthly or we'll be here all day
annual_range = range(0, len(all_wts_as_list_common_index), int(len(all_wts_as_list_common_index)/40))
list_of_groupings = [
get_grouping_for_index_date(all_wts_common_columns_as_dict,
index_number, n_clusters=n_clusters)
for index_number in annual_range]
pd_of_groupings = pd.DataFrame(list_of_groupings)
date_index = [all_wts_as_list_common_index[idx] for idx in annual_range]
pd_of_groupings.index = date_index
return pd_of_groupings
def get_grouping_for_index_date(all_wts_common_columns_as_dict: dict,
index_number: int, n_clusters = 4):
print("Grouping for %d" % index_number)
as_pd = get_df_of_weights_for_index_date(all_wts_common_columns_as_dict, index_number)
results_as_dict = get_clusters_for_pd_of_weights(as_pd, n_clusters = n_clusters)
print(results_as_dict)
return results_as_dict
def get_df_of_weights_for_index_date(all_wts_common_columns_as_dict: dict,
index_number: int):
dict_for_index_date = dict()
for instrument in all_wts_common_columns_as_dict.keys():
wts_as_dict = dict(all_wts_common_columns_as_dict[instrument].iloc[index_number])
wts_as_dict = dict([
(str(key), float(value))
for key, value in wts_as_dict.items()
])
dict_for_index_date[instrument] =wts_as_dict
as_pd = pd.DataFrame(dict_for_index_date)
as_pd = as_pd.transpose()
as_pd[as_pd.isna()] = 0.0
return as_pd
def get_clusters_for_pd_of_weights(as_pd, n_clusters = 4):
kmeans = KMeans(n_clusters=n_clusters).fit(as_pd)
klabels = list(kmeans.labels_)
row_names = list(as_pd.index)
results_as_dict = dict([
(instrument, cluster_id) for instrument, cluster_id in
zip(row_names, klabels)
])
return results_as_dict
As an example, here are the groupings for the final month of data (I've done this particular fit with a subset of the trading rules to make the results easier to view):
get_grouping_for_index_date(all_wts_common_columns_as_dict, -1)
{'AEX': 3, 'AUD': 3, 'BOBL': 0, 'BUND': 0, 'CORN': 1, 'CRUDE_W': 3, 'EDOLLAR': 0,
'GAS_US': 3, 'SHATZ': 0, 'SP500': 0, 'US10': 0, 'US2': 2, 'US5': 0, 'WHEAT': 1}
There are four groups (I use 4 clusters throughout, a completely arbitrary decision that seems about right with 14 instruments):
- A bond group containing BOBL, BUND, EDOLLAR, SHATZ, US5 and US10; but curiously also SP500
- An Ags group: Corn and Wheat
- US 2 year
- The rest: Crude & Gas; AEX and AUD
These are close but not quite the same as asset classes (for which you'd have a bond group, an Ags group, Energies, and equities/currency). Let's have a look at the weights to see where these groups came from (remember I'm using a subset here):
get_df_of_weights_for_index_date(all_wts_common_columns_as_dict, -1).round(2)
carry10 momentum16 momentum32 momentum4 momentum64 momentum8
AEX 0.39 0.06 0.08 0.31 0.14 0.02
AUD 0.42 0.16 0.10 0.03 0.11 0.19CRUDE_W 0.40 0.15 0.15 0.05 0.13 0.12
GAS_US 0.42 0.09 0.08 0.12 0.11 0.18carry10 momentum16 momentum32 momentum4 momentum64 momentum8CORN 0.17 0.28 0.23 0.00 0.12 0.20WHEAT 0.28 0.18 0.23 0.00 0.24 0.07
carry10 momentum16 momentum32 momentum4 momentum64 momentum8US2 1.00 0.00 0.00 0.00 0.00 0.00
carry10 momentum16 momentum32 momentum4 momentum64 momentum8
BOBL 0.66 0.10 0.11 0.00 0.13 0.00
BUND 0.64 0.06 0.13 0.01 0.13 0.03
EDOLLAR 0.67 0.00 0.19 0.00 0.14 0.00
SHATZ 0.79 0.00 0.00 0.00 0.21 0.00
SP500 0.64 0.08 0.10 0.04 0.11 0.04
US10 0.60 0.12 0.12 0.00 0.11 0.06
US5 0.56 0.12 0.13 0.00 0.13 0.06
It's a pretty convincing grouping I think! They key difference between the groups is the amount of carry that they have: a lot (bonds, S&P), a little (the Ags markets) or some (Energies and markets beginning with the letter A). (Note that US 2 year can only trade carry in this particular run - which is with the speed limit on rules. The other rules are too expensive, due to US2 very low volatility. Shatz is a tiny bit cheaper and can also trade very slow momentum. This is enough to put it in the same groups as the other bonds for now).
Fit the system by group
- To test group fitting
- To provide weights to blend together
Fit the entire system with everything pooled
system.config.forecast_weight_estimate['pool_gross_returns'] = True # obviously!
system.config.forecast_weight_estimate['ceiling_cost_SR'] = 9999 # ensures all markets grouped
Use a blended set of weights
- The individual weights
- The group fitted weights
- Weights from results pooled across the entire system
What do the weights look like?
Ind Group Entire Blend
assettrend32 0.24 0.24 0.23 0.24
breakout160 0.14 0.06 0.06 0.09
carry10 0.27 0.17 0.17 0.22
mrinasset160 0.00 0.24 0.32 0.14
normmom32 0.11 0.12 0.06 0.11
relcarry 0.24 0.16 0.16 0.20
Ind Group Entire Blend
assettrend32 0.17 0.23 0.21 0.20
breakout160 0.06 0.06 0.06 0.06
carry10 0.33 0.17 0.15 0.24
momentum64 0.06 0.06 0.11 0.06
mrinasset160 0.19 0.21 0.28 0.19
normmom32 0.06 0.12 0.05 0.10
relcarry 0.14 0.15 0.14 0.15
Ind Group Entire Blend
assettrend32 0.09 0.16 0.14 0.13
breakout10 0.02 0.04 0.03 0.03
breakout160 0.02 0.04 0.04 0.04
carry10 0.15 0.09 0.10 0.12
kurtS_abs30 0.18 0.17 0.05 0.18
momentum4 0.06 0.05 0.05 0.05
momentum64 0.02 0.09 0.07 0.06
mrinasset160 0.06 0.07 0.09 0.07
normmom32 0.04 0.04 0.04 0.04
relcarry 0.07 0.06 0.06 0.06
relmomentum20 0.10 0.07 0.07 0.08
skewabs90 0.17 0.12 0.27 0.13
The results!
- Fitting individually
- Fitting across groups
- Fitting across everything
- A blend of the above
def net_costs(system):
return system.accounts.portfolio().gross.sharpe() - system.accounts.portfolio().sharpe()
All rules Speed limit
Hi Rob,
Great post as always! With regard to your last point, I was wondering what you would consider to be a 'regular' correlation structure?
All the off diagonals are equal.
Rob, probably a dumb question. When you go through this process, you are weighting the various rules to produce ONE signal for each instrument, right? Not running all the rules individually and having the weights determine the allocation in the overall portfolio, correct?
". When you go through this process, you are weighting the various rules to produce ONE signal for each instrument, right?"
Right. | https://qoppac.blogspot.com/2021/05/fit-forecast-weights-by-instrument-by.html | CC-MAIN-2021-43 | refinedweb | 3,463 | 50.23 |
After a year or so of solid Alt Dot Net infection (as far as infections go its a pretty awesome one to have), I decided to give Python a try again for more than one off sysadmin tasks, and to actually dive into it as a newly minted “Agilista”.
However, I had a problem..there were no non-painful IoC containers in Python (sorry to the other authors of IoC frameworks in Python like Spring Python and Snake Guice, I know you try and I respect the effort). Ultimately, I could not imagine coding anymore without something to handle all my registration for me, that’d dynamically inject in my dependencies, give me hooks for contextual resolution, and give me rich interception support.
So I built my own, it was painful still, but I had some ideas to move it in an Convention Over Configuration direction, and ultimately get within shooting range of what fancy stuff we’ve come to expect in .Net that Windsor, StructureMap and many others provide.
Now as I got into the fancier aspects of dynamic languages, open classes and the ability to override all behavior easily I get it…a dynamic languages runtime is like a bit IoC container.
Now I’ve heard other people say this many times but rarely with explanation or example, or focus on frankly silly things like “Dependency Injection adds too many lines of code” which is a bit melodramatic. Two arguments to a constructor, two fields ,and then avoiding having to call new is not “adding too many lines of code”, especially with templates, IDE’s, scripting, etc to cut down the actual typing load.Today I’m going to actually try to explain how languages like Python, Ruby etc give us the same awesomeness we’ve come to expect in things like Windsor..but at a much cheaper cost of learning and dev time.
Take a typical resolution scenario where you want to output to a different file format depending on command line switches. With an IoC container you can either:
Change the resolution argument to load a different concrete type:
if(arg == “XML”)
{
container.Register(Component.For<IOutput>().ImpmentedBy<XmlOutput>());
}
else if(arg == “HTML”)
{
container.Register(Component.For<IOutput>().ImpmentedBy<HtmlOutput>());
}
else
{
container.Register(Component.For<IOutput>().ImpmentedBy<NullOutput>());
}
or resolve different arguments or keys using a service locator approach in later client code (thereby depending on the container)
public void output(IKernel container, string key)
{
var output =container.Resolve<IOutput>(key);
output.save();
}
or implement a custom implementation of the resolver system (which I’ll leave out for the sake of brevity, but it’s not instant code). Also to do all this you have to depend on interfaces, add all your interchangeable code to the constructor and life is grand. You do this for many reasons in static languages, its the only way to get easy testability and code that is open to extension. In dynamic languages its always open for extension and easy to test . Let me demonstrate:
import outputlib as o
def outputselect(arg):
if arg == “XML”:
o.Output = XmlOutput
elif arg == “HTML”:
o.Output = HtmlOutput
else:
o.Output = NullOutput
def saveoutput():
o.Output().save() #will save whichever
Contextual resolution in a nutshell, and throughout your code if need be. “Interception” is even easier, take a look at and then start playing you’ll see you can trivially apply logging and security to methods without explicitly adding it. A short logging example follows:
import types
import functools
#applies a cepter to each non-underscored method.
def wrapcls(cls, cepter):
publics = [ name for name in dir(cls) if not name.startswith("_")]
methods = [getattr(cls,method) for method in publics if type(getattr(cls,method)) == types.MethodType ]
for method in methods:
intercepted_method = cepter(method)
setattr(cls, method.__name__, intercepted_method) #attaches intercepted_method to the original class, replacing non-intercepted one
#the magic all happens in the functools.wraps decorator
def loggingcepter(func):
@functools.wraps(func)
def logafter(*args, **kwargs): #for csharp devs view this as an inline delegate
result = func(*args, **kwargs) #invoking function
print “function name: ” + func.__name__
print “arguments were: ”
for a in args:
print repr(a)
print “keyword args were: ”
for kword in kwargs:
print repr(kword) + “ : ” + repr(kwargs[kword])
print “return value was: ” + repr(result)
return result
return logafter
#default boring repository class
class StorageEngine(object):
@property
def connections(self):
pass
def _sessioncall(self):
pass
def create(self,user):
print “running create now from the method”
def delete(self, id):
print “running delete now from the method”
return “deleted from the database”
def get(self, id):
pass
def __init__(self):
pass
#placeholder storage object
class User(object):
pass
wrapcls(StorageEngine ,loggingcepter)
repo = StorageEngine()
print “calling count this should not be intercepted”
cnncount = repo.connections
print “now get should be intercepted”
repo.get(1)
print “we should see keyword arguments here”
repo.delete(id=2)
print “session call should not be intercepted”
repo._sessioncall()
print “create should be intercepted and we should see a User object”
repo.create(User())
Running the above script should result in the following output
So this is all very cool, but what does it mean or why do I care? For those of us used to using a proper IoC container like Windsor or StructureMap, we’ve gotten used to have capabilities like the above easily available to us when we’ve needed them. It’s nice to find that in Python (or really any dynamic language ) we can easily build our own similar functionality that we’ve come to depend on. We’re never coupled and we’re always able to test and mock out behavior. It was a long time coming but I think I finally get it now.
Post Footer automatically generated by Add Post Footer Plugin for wordpress. | http://lostechies.com/ryansvihla/2009/11/16/i-recant-my-ioc-ioc-containers-in-dynamic-languages-are-silly/ | CC-MAIN-2015-11 | refinedweb | 965 | 51.48 |
"The."
All this sounded very promising, so I embarked on the journey of installing and configuring buildbot for the application that Titus and I will be presenting at our PyCon tutorial later this month. I have to say it wasn't trivial to get buildbot to work, and I was hoping to find a simple HOWTO somewhere on the Web, but since I haven't found it, I'm jotting down these notes for future reference. I used the latest version of buildbot, 0.7.1, on a Red Hat 9 Linux box. In the following discussion, I will refer to the application built and tested via buildbot as APP.
Installing buildbot
This step is easy. Just get the package from its SourceForge download page and run "python setup.py install" to install it. A special utility called buildbot will be installed in /usr/local/bin.
Update 2/21/06
I didn't mention in my initial post that you also need to install a number of pre-requisite packages before you can install and run buildbot (thanks to Titus for pointing this out):
a) install ZopeInterface; one way of quickly doing it is running the following command as root:
# easy_install
b) install CVSToys; the quick way:
# easy_install
c) install Twisted; there is no quick way, so I just downloaded the latest version of TwistedSumo (although technically you just need Twisted and TwistedWeb):
# wget
# tar jxvf TwistedSumo-2006-02-12.tar.bz2
# cd TwistedSumo-2006-02-12
# python setup.py install
Creating the buildmaster
The buildmaster is the machine which triggers the build-and-test process by sending commands to other machines known as the buildslaves. The buildmaster itself does not run the build-and-test commands, the slaves do that, then they send the results back to the master, which displays them in a nice HTML format.
The build-and-test process can be scheduled periodically, or can be triggered by source code changes. I took the easy way of just triggering it periodically, every 6 hours.
On my Linux box, I created a user account called buildmaster, I logged in as the buildmaster user and I created a directory called APP. The I ran this command:
buildbot master /home/buildmaster/APP
This created some files in the APP directory, the most important of them being a sample configuration file called master.cfg.sample. I copied that file to master.cfg.
All this was easy. Now comes the hard part.
Configuring the buildmaster
The configuration file master.cfg is really just Python code, and as such it is easy to modify and extend -- if you know where to modify and what to extend :-).
Here are the most important sections of this file, with my modifications:
Defining the project name and URL
Search for c['projectName'] in the configuration file. The default lines are:
c['projectName'] = "Buildbot"
c['projectURL'] = ""
I replaced them with:
c['projectName'] = "App"
c['projectURL'] = ""
where App and are the name of the application, and its URL respectively. These values are displayed by buildbot in its HTML status page.
Defining the URL for the builbot status page
Search for c['buildbotURL'] in the configuration file. The default line is:
c['buildbotURL'] = ""
I changed it to:
c['buildbotURL'] = ""
You need to make sure that whatever port you choose here is actually available on the host machine, and is externally reachable if you want to see the HTLM status page from another machine.
If you replace the default port 8010 with another value (9000 in my case), you also need to specify that value in this line:
c['status'].append(html.Waterfall(http_port=9000))
Defining the buildslaves
Search for c['bots'] in the configuration file. The default line is:
c['bots'] = [("bot1name", "bot1passwd")]
I modified the line to look like this:
c['bots'] = [("x86_rh9", "slavepassword")]
Here I defined a buildslave called x86_rh9 with the given password. If you have more slave machines, just add more tuples to the above list. Make a note of these values, because you will need to use the exact same ones when configuring the buildslaves. More on this when we get there.
Configuring the schedulers
Search for c['schedulers'] in the configuration file. I commented out all the lines in that section and I added these lines:
# We build and test every 6 hours
periodic = Periodic("every_6_hours", ["x86_rh9_trunk"], 6*60*60)
c['schedulers'] = [periodic]
Here I defined a schedule of type Periodic with a name of every_6_hours, which will run a builder called x86_rh9_trunk with a periodicity of 6*60*60 seconds (i.e. 6 hours). The builder name needs to correspond to an actual builder, which we will define in the next section.
I also modified the import line at the top of the config file from:
from buildbot.scheduler import Scheduler
to:
from buildbot.scheduler import Scheduler, Periodic
Configuring the build steps
This is the core of the config file, because this is where you define all the steps that your build-and-test process will consist of.
Search for c['builders'] in the configuration file. I commented out all the lines from:
cvsroot = ":pserver:anonymous@cvs.sourceforge.net:/cvsroot/buildbot"
to:
c['builders'] = [b1]
I added instead these lines:
source = s(step.SVN, mode='update',
baseURL='',
defaultBranch='trunk')
unit_tests = s(UnitTests, command="/usr/local/bin/python setup.py test")
text_tests = s(TextTests, command="/usr/local/texttest/texttest.py")
build_egg = s(BuildEgg, command="%s/build_egg.py" % BUILDBOT_SCRIPT_DIR)
install_egg = s(InstallEgg, command="%s/install_egg.py" % BUILDBOT_SCRIPT_DIR)
f = factory.BuildFactory([source,
unit_tests,
text_tests,
build_egg,
install_egg,
])
c['builders'] = [
{'name':'x86_rh9_trunk',
'slavename':'x86_rh9',
'builddir':'test-APP-linux',
'factory':f },
]
First off, here's what the buildbot manual has to say about build steps:
BuildStepsare usually specified in the buildmaster's configuration file, in a list of “step specifications” that is used to create the
BuildFactory. These “step specifications” are not actual steps, but rather a tuple of the
BuildStepsubclass to be created and a dictionary of arguments. There is a convenience function named “
s” in the
buildbot.process.factorymodule for creating these specification tuples.
In my example above, I have the following build steps: source, unit_tests, text_tests, build_egg and install_egg.
source is a build step of type SVN which does a SVN update of the source code by going to the specified SVN URL; the default branch is trunk, which was fine with me. If you need to check out a different branch, see the buildbot documentation on SVN operations
For different types (i.e. classes) of steps, it's a good idea to look at the file step.py in the buildbot/process directory (which got installed in my case in /usr/local/lib/python2.4/site-packages/buildbot/process/step.py).
The step.py file already contains pre-canned steps for configuring, compiling and testing your freshly-updated source code. They are called respectively Configure, Compile and Test, and are subclasses of the ShellCommand class, which basically executes a given command, captures its stdout and stderr and returns the exit code for that command.
However, I wanted to have some control at least on the text that appears in the buildbot HTML status page next to my steps. For example, I wanted my UnitTest step to say "unit tests" instead of the default "test". For this, I derived a class from step.ShellCommand and called it UnitTests. I created a file called extensions.py in the same directory as master.cfg and added my own classes, which basically just redefine 3 variables. Here is my entire extensions.py file:
from buildbot.process import step
from step import ShellCommand
class UnitTests(ShellCommand):
name = "unit tests"
description = ["running unit tests"]
descriptionDone = [name]
class TextTests(ShellCommand):
name = "texttest regression tests"
description = ["running texttest regression tests"]
descriptionDone = [name]
class BuildEgg(ShellCommand):
name = "egg creation"
description = ["building egg"]
descriptionDone = [name]
class InstallEgg(ShellCommand):
name = "egg installation"
description = ["installing egg"]
descriptionDone = [name]
The two variables that I wanted to customize are description, which appears in the buildbot HTML status page while that particular step is being executed, and descriptionDone, which appears in the status page once the step is finished.
To make master.cfg aware of my custom classes, I added this line to the top of the config file:
from extensions import UnitTests, TextTests, BuildEgg, InstallEgg
Let's look at the custom build steps I added. For the unit_tests step, I'm telling buildbot to run the command python setup.py test on the buildslaves and report back the results. For the text_tests step, the command is /usr/local/texttest/texttest.py, which is where I installed the TextTest acceptance/regression test package. For build_egg and install_egg, I'm running my own custom scripts build_egg.py and install_egg.py on the buildslave, using the BUILDBOT_SCRIPT_DIR variable which I defined at the top of the configuration file as:
BUILDBOT_SCRIPT_DIR = "/home/buildbot/APP/bot_scripts"
As you add more build steps, you need to also add them to the factory object:
f = factory.BuildFactory([source,
unit_tests,
text_tests,
build_egg,
install_egg,
])
The final step in dealing with build steps is defining the builders, which correspond to the buildslaves. In my case, I only have one buildslave machine, so I'm only defining one builder called x86_rh9_trunk which is running on the slave called x86_rh9. The slave will use a builddir named test-APP-linux; this is the directory where the source code will get checked out and where all the build steps will be performed.
Note: the name of the builder x86_rh9_trunk needs to correspond with the name you indicated when defining the scheduler.
Here is again the code fragment which defines the builder:
c['builders'] = [
{'name':'x86_rh9_trunk',
'slavename':'x86_rh9',
'builddir':'test-APP-linux',
'factory':f },
]
We're pretty much done with configuring the buildmaster. Now it's time to create and configure a buildslave.
Creating and configuring a buildslave
On my Linux box, I created a user account called buildbot, I logged in as the buildbot user and I created a directory called APP. The I ran this command:
buildbot slave /home/buildbot/APP localhost:9989 x86_rh9 slavepassword
Note that most of these values have already been defined in the buildmaster's master.cfg file:
- localhost is the host where the buildmaster is running (if you're running the master on a different machine from the one running the slave, you need to indicate here a name or an IP address which is reachable from the slave machine)
- 9989 is the default port that the buildmaster listens on (it is assigned to c['slavePortnum'] in master.cfg)
- x86_rh9 is the name of this slave, and slavepassword is the password for this slave (both values are assigned in master.cfg to c['bots'])
I also created my custom scripts for building and installing a Python egg. I created a sub-directory of APP called bot_scripts, and in there I put build_egg.py and install_egg.py, the 2 scripts that are referenced in the "Build steps" section of the buildmaster's configuration file.
Starting and stopping the buildmaster and the buildslave
To start the buildmaster, I ran this command as user buildmaster:
buildbot start /home/buildmaster/APP
To stop the buildmaster, I used this command:
buildbot stop /home/buildmaster/APP
When I needed the buildmaster to re-read its configuration file, I used this command:
buildbot sighup /home/buildmaster/APP
I used similar commands to start and stop the buildslave, the only difference being that I was logged in as user buildbot and I indicated /home/buildbot/APP as the BASEDIR directory for the buildbot start/stop/sighup commands.
If everything went well, you should be able at this point to see the buildbot HTML status page at the URL that you defined in the buildmaster master.cfg file (in my case this was)
If you can't reach the status page, something might have gone wrong during the startup of the buildmaster. Inspect the file /home/buildmaster/APP/twistd.log for details. I had some configuration file errors initially which prevented the buildmaster from starting.
Whenever the buildmaster is started, it will initiate a build-and-test process. If it can't contact the buildslave, you will see a red cell on the status page with a message such as
In this case, you need to look at the slave's log file, which in my case is in /home/buildbot/APP/twistd.log. Make sure the host name and port numbers, as well as the slave name and password are the same in the slave's buildbot.tac file and in the master's master.cfg file.
If the slave is reachable from the master, then the build-and-test process should unfold, and you should end up with something like this on the status page:
That's about it. I'm sure there are many more intricacies that I have yet to discover, but I hope that this HOWTO will be useful to people who are trying to give buildbot a chance, only to be discouraged by its somewhat steep learning curve.
And I can't finish this post without pointing you to the live buildbot status page for the Python code base.
14 comments:
Can you go into more detail on how you got BuildBot working on RH9? Doesn't RH9 come with an older version of Python that the newer versions of Twisted will not work on?
Anyway.. this was a great post.
More details about my setup on the RH9 box:
- I compiled and installed Python 2.4.2 from the tarball on python.org.
- I used the exact versions of Twisted and other required packages that are mentioned in the post.
Cool.. did you replace the default Python installation or did you install 2.4.2 in parallel the to stock version?
I installed Python 2.4.2 in /usr/local/bin, then I renamed /usr/bin/python to something else, so I didn't have to worry about /usr/bin being in front of /usr/local/bin in PATH.
Thanks you very much for this invaluable guide. It really saved me an headhacke ;)
You can avoid all mentioned installation hassles by switching to our Parabuild - it takes three minutes to install.
If only I came across this guide sooner, I would have saved myself a lot of headache about buildbot. :P Now, I just need to figure out how to get the build master to kick off a build when a change in a repository has been detected
EXCELLENT explanation of the create-slave option to buildbot(version 0.7.5). I never did get a clear explanation from the sourceforge buildbot documentation of just which port number was needed. Thank you so much for clarifying that tidbit of knowledge. They should mimick your presentation on that, at sourceforge, to help novices like me get going quicker.
Regards,
Carl E.
The command
buildbot master /home/buildmaster/APP
should be
buildbot create-master /home/buildmaster/APP
Great stuff. Don't be shy to write more like this ;-)
In 0.7.6 and later, c['slaves'] is used instead of c['bots']
This is to help people who find this in the future. IMHO it's much easier to follow than the buildbot manual.
You should think about updating this. But even as it is, this was very useful. Thank you! :) | http://agiletesting.blogspot.com/2006/02/continuous-integration-with-buildbot.html | CC-MAIN-2019-39 | refinedweb | 2,552 | 61.56 |
Subversion Basic Use
From Ece
This guide covers the basic use of Subversion. For information about creating and merging branches and tagging "snapshots" of the repository, see Subversion Branches and Tags. The basic Subversion tasks are covered in these two articles using command-line examples. They are recommended reading, even if you plan to use TortoiseSVN—a GUI client for Windows—as the TortoiseSVN article may not cover every concept included here.
Also, it is recommended that you first understand some basic concepts before you start. And for a more complete, excellent coverage of Subversion, see the (free) official online book Version Control with Subversion.
Note: Yavin is running Subversion 1.4. You may connect with a v1.4 or v1.5 client. However, some v1.5 features, like merge tracking, will not be supported.
Acquiring the Subversion Client
Linux/UNIX
If you are running a flavor of Linux or UNIX on your personal machine, the best way to get Subversion will depend on your distribution. If your distribution has an established package distribution system, that would probably be your preferred channel. The Subversion website does maintain some links to binary packages produced by third parties.
Of course, you can also run the Subversion client directly on Yavin, using your home directory as your checkout space for storing a local working copy of the repository.
Windows
If you want to follow along with the command-line examples in this guide, you should install the command-line client produced by CollabNet. CollabNet will require you to create an account before allowing you to download.
You might prefer to install TortoiseSVN alongside or instead of the command-line client. TortoiseSVN is a Subversion GUI client that integrates with the Windows shell.
Basic Tasks
The primary client program in Subversion is
svn. To perform an operation, you invoke a subcommand in the form
svn subcommand.
All examples below will use the following base repository URL:
svn+ssh://jdoe@svn.ece.msstate.edu/home/jdoe/repos/
Also, all examples will use a Linux/UNIX syntax form for directories. If you are a Windows user choosing the command-line client over a GUI like TortoiseSVN, you should be savvy enough to correctly specify Windows paths on the command-line as well.
Connecting to a Repository
For a full explanation of repository URLs and connection specifics, see Connecting to a Subversion Repository.
Getting Help
The subcommand
help provides information about
svn or a subcommand. It is invoked in the form
svn help subcommand. For example, to get help on the subcommand
svn help checkout
To get a listing of all available subcommands and their aliases (e.g., you can use
co for
svn help
Importing an Existing File Tree
The
import subcommand can be used to add an entire directory tree to a repository in one step.
For example:
svn import path/to/mytree/ svn+ssh://jdoe@svn.ece.msstate.edu/home/jdoe/repos/desired/path/
Note that this bypasses the usual checkout process, and you will still need to perform a checkout to get a working copy of the project.
Checking out a Working Copy
The
checkout subcommand is used to check out a working copy form a repository. For example:
svn checkout svn+ssh://jdoe@svn.ece.msstate.edu/home/jdoe/repos/ mylocalcopy
will checkout a working copy of the repository into a local directory
mylocalcopy/.
To checkout an older revision, a revision number can be specified.
svn checkout -r 9 svn+ssh://jdoe@svn.ece.msstate.edu/home/jdoe/repos/
For more details on specifying revisions, see revision specifiers in the online Subversion book.
Making Local Changes
Once you have a working copy, you can start making changes in your favorite editor.
Additionally, you can use various commands to make changes to your working copy.
- When you create a new file or place a new file in your working copy folder, the
addsubcommand is used to bring the file under version control, so that the next time you commit, that file will be added to the repository.
- The
deletesubcommand does just what it says. On the next commit, the file will no longer exist in the current repository revision (although it will still exist in previous revisions).
- The
mkdirsubcommand creates a new directory and adds it to version control. It is identical to using the system command
mkdirfollowed by
svn add.
- The
copysubcommand makes a copy of a file and adds it to version control. Subversion will record the fact that a copy took place, so this is not equivalent to using the system command
cpfollowed by
svn add. The
copysubcommand also has more advanced uses, such as creating branches and tags or resurrecting a file deleted in a previous revision.
- The
movesubcommand can move/rename a file, and is identical to a combination of
svn copyand
svn delete.
Examining Local Changes
The
status subcommand uses a list of status codes (see link) to show the status of your files, such as added, modified, etc. By default, it shows only those files with interesting status information. Adding the
--verbose option will list all files.
The
diff subcommand can be used to view the local modifications you've made to a file. For example, after modifying a file
foo.c, look at the changes with:
svn diff foo.c
This will output the contents of the file, including changes.
- Removed lines will be prefaced with
-.
- Added lines will be prefaced with
+.
- A change within a line is represented as a removed line (original state) followed by an added line (current state).
Reverting Local Changes
You can undo all changes made to a file since the last checkout or commit using the
revert subcommand:
svn revert foo.c
Updating the Working Copy
As you edit your working copy of the repository, others in your group may be doing so as well. In fact, in an active development team, it is quite likely that others have committed changes to the repository since your last checkout or commit.
So when you finish making your changes and attempt to commit them, Subversion must handle this carefully. It cannot simply allow you to directly commit your changes, because then the current revision after you commit would not include any of their latest changes. So, Subversion requires that you update your working copy with any new repository changes before it will allow you to commit.
You accomplish this with the
update subcommand. Any changes that have been committed to the repository since your last checkout or commit (i.e. since the revision to which your working copy corresponds) will be merged into your working copy. Generally speaking, if your team is communicating well, than your changes—even if you're working on the same file—will not overlap, and Subversion can seamlessly merge them.
Note: Even if there are no overlapping changes and Subversion quietly merges all changes into your working copy, that does not mean the changes are compatible. It is up to you, the human being, to make sure your teammates changes work with your own.
Resolving Conflicting Changes
Sometimes updating your working copy will result in a state of conflict if your local changes and your teammates committed changes overlap. Depending on your version of the Subversion client (1.4 vs. 1.5), you may be interactively informed of files in a state of conflict, and given the option to immediately deal with the conflict. See the nightly build of the updated manual for more information on interactive conflict resolution.
If you are using Subversion 1.4 (or if you postpone all conflict resolution in v1.5), your working copy is left in a state of conflict, and you will not be allowed to commit until it is resolved. You can recognize a state of conflict by the letter
C next to a filename when you perform
svn update. For each conflicted file, Subversion does the following:
- Places conflict markers inside your document. This would look something like:
Here are some lines that are common to both my working copy and the current revision of the repository, but the next few lines are in conflict. <<<<<<< .mine In my working copy, these lines look just like this, and so I can review them here. ======= These lines belong to my teammate, and I can see them here below the equal signs, ended by a line of >'s and the current repository revision. >>>>>>> .r22 Finally, this is a line that was common to our files.
- Places three extra reference files in your directory. For example, if your last commit produced revision 18, and the current repository revision is 22:
foobar.c.mine— this contains the last revision you committed, plus your local edits.
foobar.c.r18— this contains the last revision you committed.
foobar.c.r22— this contains the current revision of the file, pulled from the repository.
Now, you must resolve the state of conflict. How you do this depends on what client version you are running.
Resolving in Subversion 1.4
You must place your file into a desired state, and then run the
resolved subcommand. Your basic options are:
- Copy one of the temporary files onto the actual file. For our
foobar.cexample,
- To discard your local changes and accept your teammates' changes,
cp foobar.c.r22 foobar.c
- To discard your teammates' changes and use only your local changes,
cp foobar.c.r18 foobar.c
- To discard all changes (local and teammates) and just start over,
svn revert foobar.c
- You will no longer need to run
svn resolvedif you use this option.
- Hand-merge the changes by editing
foobar.c, including removing all conflict markers.
Now, tell Subversion you have put
foobar.c in an acceptable state:
svn resolved foobar.c
This will automatically delete the temporary files.
Resolving in Subversion 1.5
Subversion 1.5 has replaced the
resolved subcommand with
resolve. Your options are essentially the same as in Subversion 1.4, but the
resolve subcommand can do some of the work for you. Still using the foobar.c example:
- To discard your local changes and accept your teammates' changes,
svn resolve --accept theirs-full foobar.c
- To discard your teammates' changes and use only your local changes,
svn resolve --accept mine-full foobar.c
- To discard all changes (local and teammates) and just start over,
svn revert foobar.c
- Hand-merge the changes by editing
foobar.c, including removing all conflict markers, and then run
svn resolve --accept working foobar.c
Committing Local Changes
Once you have brought your working copy up to date, you can commit your changes with the
commit subcommand. Be sure to include a log message with the
-m option, or else your default editor will be opened for you to write one.
svn commit -m "Some useful log message"
Reviewing Commit Logs
You can view the commit log message history with
log subcommand.
Getting Line-By-Line Author and Revision
Subversion provides a very powerful subcommand,
blame, that shows you, line-by-line, what author is responsible for adding or most recently editing the line, and in what revision that line was added or edited.
svn blame foobar.c
Undoing Committed Changes
Undoing a Change from a Previous Revision
Sometimes you might want to undo a committed change to the repository. Unfortunately there is no pure "undo" in Subversion, because Subversion is designed to track and maintain every change made to the repository. The best you can do is to make sure the change is corrected in the HEAD revision.
As an example, consider a file foobar.c, for which an undesired change was committed at revision 22. By the time you realize it, the repository is up to revision 30, and now you want to undo the change that was made at revision 22. You might be tempted checkout or update your working copy to the revision before the regretted changed occurred:
svn checkout -r 21 svn+ssh://jdoe@svn.ece.msstate.edu/home/jdoe/repos/myproj/trunk/ svn update -r 21 svn+ssh://jdoe@svn.ece.msstate.edu/home/jdoe/repos/myproj/trunk/
But this will not work, because Subversion will not allow you to commit this older revision when a newer revision exists in the repository.
The answer is instead to perform a reverse merge. (The
merge subcommand is covered here). You want to get the delta (changes) from revision 22 back to revision 21—this delta would be a description of the "undo"—and apply to a current working copy (i.e. HEAD revision).
svn update svn merge -r 22:21 svn+ssh://jdoe@svn.ece.msstate.edu/home/jdoe/repos/myproj/trunk/ # or you could use svn merge -c -22 svn+ssh://jdoe@svn.ece.msstate.edu/home/jdoe/repos/myproj/trunk/
Note that this compares the entire tree, so if numerous changes occurred from revision 21 to revision 22, you may want to make sure those do not get reversed. Now is a good time to use
svn status and
svn diff to make sure you got what you wanted.
Once you have confirmed the undo operation, just commit your changes with
svn commit.
Resurrecting a Deleted File
If you deleted a file in a previous revision and want to "undelete" it, you cannot undo that committed change. The best you can do is resurrect the file so that it exists again in the HEAD revision. This is accomplished with the
copy subcommand, by copying the file from a previous revision into your working copy, and then committing to the repository.
For example, if you deleted foobar.c in revision 23:
svn copy -r 23 svn+ssh://jdoe@svn.ece.msstate.edu/home/jdoe/repos/myproj/trunk/foobar.c ./foobar.c svn commit -m "Resurrected foobar.c from revision 23, /myproj/trunk/foobar.c."
Keyword Substitution
You might find it useful to see information such as author and modified date directly in your source code files. This can be a maintenance nightmare, as it depends on individuals to update the information as they edit the files. Subversion provides some automated support for this using keyword substitution.
Available Keywords
The following keywords are currently supported by Subversion. Most of them have aliases that perform the exact same substitution, but with a different form of the keyword.
Date— displays the date and time (in local time) of the last change to the file in the repository. Alias:
LastChangedDate
Revision— displays the global revision number at which the file was last changed. Aliases:
LastChangedRevisionand
Rev.
Author— displays the username of the last user who changed the file in the repository. Alias:
LastChangedBy
HeadURL— displays the URL to the head latest version of the file. Alias:
URL
Id— displays a single string containing the filename, revision, last changed date and time (UTC), and author all combined.
Keyword Formats
You can place keywords wherever you like in your source file, but it is probably best to put them near the top.
The simplest form for entering keywords is:
$Rev$ $Author$ $Date$
which will expand to something like:
$Revision: 2341 $ $Author: bully $ $Date: 2006-11-02 12:57:54 -0600 (Thu, 02 Nov 2006) $
You could also add comments to the end, such as:
$Revision$: Revision of last commit $Author$: Author of last commit $Date$: Date of last commit
But note what would happen during substitution:
$Revision: 2341 $: Revision of last commit $Author: bully $: Author of last commit $Date: 2006-11-02 12:57:54 -0600 (Thu, 02 Nov 2006) $: Date of last commit
In order to preserve your spacing, append
:: to the end of the keyword. For example:
$Revision:: $: Revision number $Author:: $: was committed by $Date:: $: on this date
This will be transformed into:
$Revision:: 2341 $: Revision number $Author:: bully $: was committed by $Date:: 2006-11-02 12:57:54 -0600 (Thu, 02 Nov 2006) $: on this date
Some important things to note:
- Make sure these lines are "commented out" in your source files
- Don't edit these lines once they're entered; Subversion will manage them
- Each file individually is updated only when it is changed in the repository, which usually occurs by making local changes and then committing them
- These lines should not lead to a state of conflict on
svn update, but they will show up in
svn diff
Activating Keywords
Keyword substitution will not happen automatically. Each one must be activated by setting the
svn:keywords property on every file that needs substitution to take place.
For example, to activate keyword substitution for
Revision,
Author, and
Date on the file
foobar.c, run the following command:
svn propset svn:keywords "Revision Author Date" foobar.c
Additionally, you can edit the property in your default editor using
svn propedit svn:keywords foobar.c
To see the property's current value,
svn propget svn:keywords foobar.c
To delete the property,
svn propdel svn:keywords foobar.c
See Also
- Subversion
- Subversion Branches and Tags
- Connecting to a Subversion Repository
- Subversion Repository Administration
- TortoiseSVN
External Links
- Subversion (official Web site)
- Version Control with Subversion is the official (online) Subversion book. | http://www.ece.msstate.edu/wiki/index.php/Subversion_Basic_Use | crawl-003 | refinedweb | 2,845 | 55.13 |
The Jest Object
The
jest object is automatically in scope within every test file. The methods in the
jest object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via
import {jest} from '@jest/globals'.
#Mock Modules
jest.disableAutomock()#
Disables automatic mocking in the module loader.
See
automocksection of configuration for more information
After this method is called, all
require()s will return the real versions of each module (rather than a mocked version).
Jest configuration:
Example:.
See
automocksection of configuration for more information
Example:
Note: this method was previously called
autoMockOn. When using
babel-jest, calls to
enableAutomock will automatically be hoisted to the top of the code block. Use
autoMockOn if you want to explicitly avoid this behavior.
jest.createMockFromModule(moduleName)#
#renamed in Jest 26.0.0+
Also under the alias:
.genMockFromModule(moduleName)
Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you.
This is useful when you want to create a manual mock that extends the automatic mock's behavior.
Example:
This is how
createMockFromModule will mock the following data types:
Function#
Creates a new mock function. The new function has no formal parameters and when called will return
undefined. This functionality also applies to
async functions.
Class#
Creates a new class. The interface of the original class is maintained, all of the class member functions and properties will be mocked.
Object#
Creates a new deeply cloned object. The object keys are maintained and their values are mocked.
Array#
Creates a new empty array, ignoring the original.
Primitives#
Creates a new property with the same primitive value as the original property.
Example:
jest.mock(moduleName, factory, options)#
Mocks a module with an auto-mocked version when it is being required.
factory and
options are optional.. This property is normally generated by Babel / TypeScript, but here it needs to be set manually. When importing a default export, it's an instruction to import the property named
default from the export object:
The third argument can be used to create virtual mocks – mocks of modules that don't exist anywhere in the system:
Warning: Importing a module in a setup file (as specified by
setupFilesAfterEnv) will prevent mocking for the module in question, as well as all the modules that it imports.
Modules that are mocked with
jest.mock are mocked only for the file that calls
jest.mock. Another file that imports the module will get the original implementation even if it runs:
Using
jest.doMock() with ES6 imports requires additional steps. Follow these if you don't want to use
require in your tests:
- We have to specify the
__esModule: trueproperty (see the
jest.mock()API for more information).
- Static ES6 module imports are hoisted to the top of the file, so instead we have to import them dynamically using
import().
- Finally, we need an environment which supports dynamic importing. Please see Using Babel for the initial setup. Then add the plugin babel-plugin-dynamic-import-node, or an equivalent, to your Babel config to enable dynamic importing in Node..requireActual(moduleName)#
Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.
Example:
jest.requireMock(moduleName)#
Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.
jest.resetModules()#
Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests.
Example:
Example in a test:
Returns the
jest object for chaining.
jest.isolateModules(fn)#
jest.isolateModules(fn) goes a step further than
jest.resetModules() and creates a sandbox registry for the modules that are loaded inside the callback function. This is useful to isolate specific modules for every test so that local module state doesn't conflict between tests.
#Mock functions
jest.fn(implementation)#
Returns a new, unused mock function. Optionally takes a mock implementation.
jest.isMockFunction(fn)#
Determines if the given function is a mocked function.
jest.spyOn(object, methodName)#);
Example:
Example test:
jest.spyOn(object, methodName, accessType?)#
Since Jest 22.1.0+, the
jest.spyOn method takes an optional third argument of
accessType that can be either
'get' or
'set', which proves to be useful when you want to spy on a getter or a setter, respectively.
Example:
Example()#
Restores all mocks back to their original value. Equivalent to calling
.mockRestore() on every mocked function. Beware that
jest.restoreAllMocks() only works when the mock was created with
jest.spyOn; other mocks will require you to manually restore them.
#Mock timers
jest.useFakeTimers(implementation?: 'modern' | 'legacy')#
Instructs Jest to use fake versions of the standard timer functions (
setTimeout,
setInterval,
clearTimeout,
clearInterval,
nextTick,
setImmediate and
clearImmediate as well as
Date).
If you pass
'legacy' as an argument, Jest's legacy implementation will be used rather than one based on
@sinonjs/fake-timers.
Returns the
jest object for chaining.
jest.useRealTimers()#
Instructs Jest to use the real versions of the standard timer functions. both the macro-task queue (i.e., all tasks queued by
setTimeout(),
setInterval(), and
setImmediate()) and the micro-task queue (usually interfaced in node via
process.nextTick).
When this API is called, all pending macro-tasks and micro-tasks will be executed. If those tasks themselves schedule new tasks, those will be continually exhausted until there are no more().
Note: This function is not available when using modern fake timers implementation
jest.advanceTimersByTime(msToRun)# time frame.advanceTimersToNextTimer(steps)#
Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run.
Optionally, you can provide
steps, so it will run
steps amount of next timeouts/intervals.
jest.clearAllTimers()#
Removes any pending timers from the timer system.
This means, if any timers have been scheduled (but have not yet executed), they will be cleared and will never have the opportunity to execute in the future.
jest.getTimerCount()#
Returns the number of fake timers still left to run.
jest.setSystemTime(now?: number | Date)#
Set the current system time used by fake timers. Simulates a user changing the system clock while your program is running. It affects the current time but it does not in itself cause e.g. timers to fire; they will fire exactly as they would have done without the call to
jest.setSystemTime().
Note: This function is only available when using modern fake timers implementation
jest.getRealSystemTime()#
When mocking time,
Date.now() will also be mocked. If you for some reason need access to the real current time, you can invoke this function.
Note: This function is only available when using modern fake timers implementation
#Misc
jest.setTimeout(timeout)#
Set the default timeout interval for tests and before/after hooks in milliseconds. This only affects the test file from which this function is called.
Note: The default timeout interval is 5 seconds if this method is not called.
Note: If you want to set the timeout for all test files, a good place to do this is in
setupFilesAfterEnv.
Example:
jest.retryTimes()#
Runs failed tests n-times until they pass or until the max number of retries is exhausted. This only works with the default jest-circus runner!
Example in a test:
Returns the
jest object for chaining. | https://jestjs.io/docs/27.0/jest-object | CC-MAIN-2021-43 | refinedweb | 1,222 | 50.43 |
How To Get Started with Jekyll on an Ubuntu VPS
Introduction
Jekyll is a simple static site generator. It takes pages input in Markdown, Textile, Liquid, HTML, and CSS, and outputs complete static HTML pages. Jekyll works well with GitHub Pages, but there are some limitations - for example, it's not particularly easy to work with plugins. Thus, hosting a Jekyll site on your own VPS can be a good idea. Doing so is easy!
In this guide we are going to use the following:
- Jekyll for write our content
- nginx to serve our content
- Capistrano to deploy
Installing Requirements
On your VPS:
Locally:
If you haven't already, install Ruby and RubyGems. The best way to do this is using the Ruby Version Manager (RVM). Use the command from the RVM homepage (rvm.io), which should look something like:
curl -L | bash -s stable --ruby=2.0.0
Follow any other prompts to install Ruby on your system. Once it's installed, you can install the the required gems:
gem install jekyll capistrano
Creating a Blog With Jekyll
Jekyll's website has a quick start guide that steps you through creating a simple Jekyll site and serving it. There's plenty more usage details there. We'll start by creating a simple blog. Switch into the directory you'd like to work from, and run:
jekyll new . cd myblog jekyll serve
You should be able to see your site running at localhost:4000.
Navigate to the "myblog" directory and you should see a few folders. The one we care about is
_site; this one contains the static site generated by Jekyll, which we will be deploying in the next step.
Setting Up the Blog for Deployment With Capistrano
If your Jekyll site is still running (after running
jekyll serve), quit that process. Still in the "myblog" directory, run:
capify .
This creates the necessary files for a Capistrano deployment. Capistrano is "opinionated software" that assumes you'll be deploying via SSH. When you run the command, it should have created a file at
config/deploy.rb; open it, and update it to resemble this:
# replace this with your site's name set :application, "Blog" set :repository, '_site' set :scm, :none set :deploy_via, :copy set :copy_compression, :gzip set :use_sudo, false # the name of the user that should be used for deployments on your VPS set :user, "deployer" # the path to deploy to on your VPS set :deploy_to, "/home/#{user}/blog" # the ip address of your VPS role :web, "123.456.789.10" before 'deploy:update', 'deploy:update_jekyll' namespace :deploy do [:start, :stop, :restart, :finalize_update].each do |t| desc "#{t} task is a no-op with jekyll" task t, :roles => :app do ; end end desc 'Run jekyll to update site before uploading' task :update_jekyll do # clear existing _site # build site using jekyll # remove Capistrano stuff from build %x(rm -rf _site/* && jekyll build && rm _site/Capfile && rm -rf _site/config) end end
The next step is to set up the VPS with the directory structure required by Capistrano. You only need to do this once:
cap deploy:setup
Finally, deploy your VPS:
cap deploy
Capistrano's deploy task will:
- Remove any existing static Jekyll sites
- Build your Jekyll site
- Clean up uneccessary files included in the build (mostly cap files)
- Copy the contents of your static site, via SFTP, to your VPS, dropping them in the specified directory
Hosting Your Blog With nginx
Back on your VPS, switch into the nginx sites-available directory. This is generally located at:
cd /etc/nginx/sites-available
If you run
ls in this directory you should (at least) see a file called "default". If you like, you can use this as a template:
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/example.com
For a static site, you don't need much configuration. The following configuration should work as a bare minimum:
server { # listen on http (port 80) # remove the "default_server" if you are running multiple sites off the same VPS listen 80 default_server; # the IP address of your VPS server_name 123.456.789.10; # see for options # to use your own domain, point a DNS A record at this IP address # and set the server name to (eg.) "blog.example.com" # the path you deployed to. this should match whatever was in your # Capistrano deploy file, with "/current" appended to the end # (Capistrano symlinks to this to your current site) root /home/deployer/blog/current; index index.html # how long should static files be cached for, see for options. expires 1d; }
Alternatively you can use this gist to get the bare essentials. Either way, create a new file in this directory with your desired nginx configuration. Once you've created it, you need to create a symlink to it from the sites-enabled directory:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com
Using symlinks means it's easy to take a site offline by removing the symlink without touching the original configuration file.
Next, make sure nginx is able to read the files it will be serving. Nginx needs to be able to read and execute everything everything in the directory it's hosting, and all parent directories. To do this, we'll give ownership of the site's directory to the nginx user,
www-data. Then we'll give it read and execute access to the required directories:
sudo chown -R www-data:www-data /home/deployer/blog/current sudo chmod 755 -R /home
Finally, you should tell nginx to update its configuration. You can do this by:
# tests the nginx configuration; if this is not successful you should fix any errors raised sudo nginx -t # safely restarts the nginx worker sudo kill -HUP `cat /var/run/nginx.pid`
Alternatively, you can just restart nginx. But the above option is generally considered safer.
sudo service nginx restart
Testing And Going Forward
Navigate to the IP address of your VPS. You should see the homepage of your Jekyll site!
What's next? You can now start writing content and customizing your site with Jekyll. Whenever you have new content you'd like to push online, it's as easy as doing as doing
cap deploy.
15 Comments | https://www.digitalocean.com/community/tutorials/how-to-get-started-with-jekyll-on-an-ubuntu-vps | CC-MAIN-2018-13 | refinedweb | 1,043 | 60.04 |
I need to use the modulous operator on this program. can anyone steer me in the correct direction. I am new to Java and I am trying to understand this language. Please help, my code is as follows
import java.util.Scanner;
public class Remainder {
public static void main (String args[]) {
int hour, min, sec, Total;
Scanner time = new Scanner(System.in);
System.out.print("Enter a number, 4 Digits long to recalculate the time!....");
Total= time.nextInt();
//hour = time.nextInt();
//min = time.nextInt();
//sec = time.nextInt();
min = Total / 60;
hour = min/60;
sec = Total/60;
int i = hour;
int j = min;
int h = sec;
System.out.println("Hours equal " + i);
System.out.println("Minutes equal " + j);
System.out.println("Seconds equal " + h);
int k = i % j;
System.out.println("i%j is " + j + " minutes");
}
}
I'm guessing your input is a number of seconds .... so calculating hours is easy:
int hours = Total / 3600;
Minutes is where you need the modulus operator ... and divide the result by 60:
int mins = (Total % 3600) / 60;
And finally, seconds ... just divide by 60 as you have it.
Forum Rules | http://forums.codeguru.com/showthread.php?533323-can-anyone-help-me-please&p=2101803 | CC-MAIN-2018-26 | refinedweb | 186 | 61.93 |
At 12:32 PM 6/26/2001 +1000, Bernard James POPE wrote: Disclaimer: Sounds like I'm the gloomy guy writing on this list. Don't let that deceive you: I'm actually a happy guy. And excited about Haskell, even if it doesn't sound that way. Really. :-) >I think that many of our students do not >appreciate some of the strong features of declarative programming until >third or fourth >year when they are faced with larger (more difficult) programming tasks. > >There is still a conception amongst some of the students that FP is not really >part of "Real World" programming, and that it is merely of interest to >academics. We try >hard to refute this notion. And it's a good quest. I see three problems that prevent me from seeing Haskell as a "Real World" language. First, compiler support. Yes, if I'm not mistaken, there are several current compilers (4) and interpreters (2) out there, but they all have serious problems in terms of efficiency (of the compiler itself and of the code generated) and logistics (getting compilers to install and work properly, file management, etc...). Hugs is the only one that seems solid enough in most fronts, but it's IMHO only usable for small programs and for testing. GHC... well, I'm still struggling with my own personal quest to get a binary of the latest version to work for my platform (Windows). Second, debugging tools. So far, I haven't been able to figure out why my program (a parser for C++ comments and strings) generates stack overflows. Nothing I've been able to think up has been of any help. Neither has the suggestions I got from the mailing list. GHC is supposed to have nice profiling utilities but it won't work in my installation no matter what I try (the program crashes), and, in any case, I haven't seen in the documentation any stack-debugging options.. A parallel meta-language, even a limited one, would be even better. Better scoping wouldn't hurt either (after C++, I just cannot live without those nifty nested namespaces). And explicit performance-tuning constructs would be a blessing, rather than having to hack them in in some indirect way (i.e. the "force" function for monadic parsers, etc...). Then again, my college background is in Telecommunications Engineering, not CS, and my programming background, although extensive, went through the Assembler->Pascal->C->College->C++ route, so my FP background is indeed limited, and therefore I might "still" be missing some points here. The FP way of thinking has hit hard on me, though. I just coded a bunch of parametric functional parsers in C++ using template metaprogramming (similar to the Haskell monadic parsers, but of course non-monadic). Faster than light, and uglier than sin, but it does work indeed. So, now I repeat my plea for help. At this point, I don't care much if I don't get the program to work. But I _NEED_ to know what was wrong. Maybe one of you teachers might want to use the program as an exercise in diagnosing a program for the students? I can send it in a pinch: it's just 9K.:-( | http://www.haskell.org/pipermail/haskell-cafe/2001-June/001994.html | CC-MAIN-2014-15 | refinedweb | 541 | 71.04 |
Data hiding?
Discussion in 'C++' started by Lorenzo Villari,
Hiding data from screen scrapers and botsBrian W, Jul 16, 2003, in forum: ASP .Net
- Replies:
- 1
- Views:
- 440
- Tian Min Huang
- Jul 18, 2003
hiding groups of data elements on a webform?MDB, May 12, 2004, in forum: ASP .Net
- Replies:
- 3
- Views:
- 531
- Natty Gur
- May 13, 2004
difference between data hiding & watermarkingcoolwarrior, Aug 28, 2004, in forum: C++
- Replies:
- 2
- Views:
- 2,343
- Phlip
- Aug 28, 2004
data hiding/namespace pollutionAlex Hunsley, Oct 31, 2005, in forum: Python
- Replies:
- 12
- Views:
- 629
- Steven Bethard
- Nov 1, 2005
Script for Hiding/Un-Hiding Text On ClickSte, Jul 20, 2007, in forum: Javascript
- Replies:
- 41
- Views:
- 926
- Thomas 'PointedEars' Lahn
- Aug 1, 2007 | http://www.thecodingforums.com/threads/data-hiding.279553/ | CC-MAIN-2015-18 | refinedweb | 123 | 58.45 |
When doing heavy computations involving the Django Object-Relational Mapper to access your database, you might notice Python consuming lots of memory. This will probably not happen during production web server mode, because dealing with lots of data to serve a single request already indicates that something is wrong and at least some preprocessing should be done. So that’s probably why Django isn’t tailored towards such needs, rather favoring speed (both at execution and coding time) at the cost of memory. But at least when you’re in that preprocessing phase or you’re just using the Django ORM for some scientific computation, you don’t want to consume more memory than absolutely necessary.
The first issue to watch out for is debug mode. From the docs:
It is also important to remember that when running with DEBUG turned on, Django will remember every SQL query it executes. This is useful when you are debugging, but on a production server, it will rapidly consume memory.
“Remembering” means that Django stores all SQL queries and their execution times in a list
django.db.connection.queries of the form
[{'sql': 'SELECT ...', 'time': '0.01'}, ]. This is useful when you want to profile your queries (see the docs), but needless overhead when you’re just doing heavy-database-access computations. So either set
DEBUG to
False or clear this list regularly in that case.
Moreover, it is important to understand how Django holds data in memory. Although the resulting objects are constructed “lazily” on the fly, the resulting rows of querysets are kept in memory by default so that multiple iterations on the result can use these cached versions. This can be avoided by using
queryset.iterator(). So while
entries = Entry.objects.all() for entry in entries: print entry for entry in entries: print entry
will receive all entries from the database once and keep them in memory,
for entry in entries.iterator(): print entry for entry in entries.iterator(): print entry
will execute the query twice but save memory.
However, even using
iterator() can still lead to a heavy memory footprint, not directly on Django’s side, but from the database interface (e.g. the Python MySQLdb module). It will receive and store all the resulting data from the database server before even handing bits over to Django. So the only way to avoid this is to use queries that don’t produce too much data at once. This snippet does exactly that:
def queryset_iterator(queryset, chunksize=1000): pk = 0 last_pk = queryset.order_by('-pk')[0].pk queryset = queryset.order_by('pk') while pk < last_pk: for row in queryset.filter(pk__gt=pk)[:chunksize]: pk = row.pk yield row
It basically receives slices (default size 1000) of the queryset ordered by the primary key. As a consequence, any ordering previously applied to the queryset is lost. The reason for this behavior is, of course, that ordering (and especially slicing) by primary key is fast. You can use the function like this:
for entry in queryset_iterator(Entry.objects): print entry
Apart from not being able to order the queryset, this approach does not handle concurrent modification of the data well: When rows are inserted or deleted while iterating over the dataset with
queryset_iterator, rows might be reported several times or never. That should not be a big problem when preprocessing data though.
I modified
queryset_iterator slightly to save the initial primary key query and to allow for non-numerical primary keys and also reverse ordering of primary keys:
def queryset_iterator(queryset, chunksize=1000, reverse=False): ordering = '-' if reverse else '' queryset = queryset.order_by(ordering + 'pk') last_pk = None new_items = True while new_items: new_items = False chunk = queryset if last_pk is not None: func = 'lt' if reverse else 'gt' chunk = chunk.filter(**{'pk__' + func: last_pk}) chunk = chunk[:chunksize] row = None for row in chunk: yield row if row is not None: last_pk = row.pk new_items = True
To sum things up:
- Set
DEBUG = Falsewhen doing lots of database operations.
- Use
queryset_iteratorwhen you deal with millions of rows and don’t care about ordering.
- Still enjoy the convenience of Django! | http://www.poeschko.com/2012/02/memory-efficient-django-queries/ | CC-MAIN-2018-05 | refinedweb | 680 | 54.52 |
Free JSP download Books
Free JSP download Books
Java Servlets and JSP
free download books...-in audience
Demonstrates how to build an EJB system, program with EJB
Free Java Books
Free Java Books
Sams Teach... on servlets, JavaServer Pages (JSP) and Enterprise JavaBean (EJB) technologies... RTF2HTML (you can download a demo of that program) which does quite a good job
Programming Books
books and download these books for future reference. These Free Computer Books...
Free Java Books
Free JSP Books...
Programming Books
A Collection of Large number of
Free
Free JSP Books
Free JSP Books
Download the following JSP books...
servers. A filter is a program that runs on the server before the servlet or JSP page
Free JSP Books
Free JSP Books
Web Server Java: Servlets and JSP
This chapter covers Web Server Java... Libraries is a definitive guide to creating custom JSP tag libraries for server
Free JSP, Free EJB and Free Servlets Hosting Servers
Free JSP, Free EJB and Free Servlets Hosting Servers...;
MediaHost's
Free Servlets Hosting Server - A Free JSP
Hosting...;
MyCGIserver
- Free Hosting server provides
EJB Books
EJB Books
Professional
EJB Books
Written... of the most influential EJB books in the industry. Get ready to jump-start your
JSF Books
.
Books
of Core java Server Faces... Server Faces Books
JavaServer Faces, or JSF, brings a component-based...JSF Books
Free JSP, Free EJB and Free Servlets Hosting Servers
Free JSP, Free EJB and Free Servlets Hosting
Servers
MyCGIserver
- Free Hosting server... Servlets Hosting Server - A
Free JSP Hosting service, offers
Application server to download
Application server to download Which Application server can be downloaded for free to use personally at home to practice JSP,EJB etc
Struts Books
;
Free
Struts Books
The Apache... Servlet and
Java Server Pages (JSP) technologies.
... Servlets, Java
Server Pages (JSP), custom tags, and messaging resources (like
Tomcat Books
and Code Download
Tomcat is an open source web server that processes JavaServer... with Apache. Like Apache, the core Tomcat program is relatively simple...;
Tomcat
Books
Tomcat is an application server built around
Java Programming Books
;
? JavaServer Pages (JSP)
? Enterprise JavaBeans (EJB)
... applications based on servlets, JavaServer Pages (JSP) and Enterprise JavaBean (EJB... download the entire book in PDF format for free, and you will also find
Introduction To Enterprise Java Bean(EJB). WebLogic 6.0 Tutorial.
such as
WebLogic Server 6.0. We will use WebLogic 6.0 Server for testing....
Downloading and Installing
the WebLogic 6.0 server...
Deploying Hello World
Session Bean on WebLogic Server
Weblogic - EJB
Weblogic How can i download the weblogic sever of application develop could u provide the link for that. Hi friend,
Download the weblogic sever of application visit to :
Servlets Books
leading free servlet/JSP engines- Apache Tomcat, the JSWDK, and the Java Web Server... servlet books
Server-side computing is all the rage these days...;
Books : Java Servlet & JSP Cookbook
JSP PDF books
;
The free servlet and JSP Books
Slides and exercises from Marty Hall's world...JSP PDF books
Collection is jsp books in the pdf format
weblogic
weblogic how shud i download wblogic server 9.1 plz tell me step by step i browse for it but it was very confusing
CORBA and RMI Books
CORBA and RMI
Books
Client/Server Programming with Java and CORBA
The standard by which all other CORBA books are judged, Client
JSP Programming Books
JSP Programming Books
... time a CGI program is invoked, the web server has to create a new heavyweight... server: Microsoft ASP, PHP3, Java servlets, and JavaServer Pages? (JSP[1
Introduction to the JSP Java Server Pages
Collection is jsp books in the pdf format. You can download these books and
study it offline.
Free JSP Books
Download the following JSP books.
Free
JSP Download
BooksFree
ejb - EJB
ejb hi
i am making a program in java script with sateful session bean. This program is Loan calculator.In this program three field 1-type... amount & year.
MY QUESTION IS:- I want to that my result is show on jsp page
Weblogic Training
applications using Enterprise Javabeans (EJB),
Servlets, and Java Server Pages (JSP) within BEA?s WebLogic Server. This
course is aimed at those Programmers who... of BEA Weblogic Application Server
BEA WebLogic is a Server
Simple EJB3.0 - EJB
Simple EJB3.0 Hi friends...
I am new user... bean on servlet/jsp.
thanQ Hi Friend,
Please visit the following links:
http Webservice
discussed are:
Create EJB and deployin on the server
Then expose EJB... the client for the EJB Web Service
Client can be created as the the servlet or jsp...EJB Webservies
In this tutorial I
DEVELOPING & DEPLOYING A PACKAGED EJB (WEBLOGIC-7) & ACCESSING IT BY A PACKAGED SERVLET (TOMCAT4.1)
Java server Faces Books
Java server Faces
Books
Java
server Faces... the third free by using code OPC10 in our shopping cart. This deal includes books
ejb - EJB
server. There are many application servers are available both free and commercial... of 3.0 version. Hi friend,
EJB :
The Enterprise JavaBeans architecture or EJB for short is an architecture for the development and deployment
Building a Simple EJB Application Tutorial
Building a Simple EJB Application - A Tutorial
... create a new Session Bean from the Project Explorer (EJB Projects ->
Simple EJB.... This application, while simple, provides a good introduction to EJB
development and some
Swing EJB
would work with EJB application server...Swing EJB Hi everyone !!!
I tried to find wether EJB architecture... as with swing client side, instead
jsp or other web page page(s).
I wondered
Struts integration with EJB in WEBLOGIC7
by the server. The development of the EJB and its deployment in WebLogic server... in the market are:
BEA ..WebLogic Server
JBoss Application server... to a stateless session bean in weblogic7 server through a Struts-based program.
We have
DEVELOPING & DEPLOYING A PACKAGED EJB
searching books
searching books how to write a code for searching books in a library through jsp
Jboss 3.2 EJB Examples
to the list and
thus we can use servlet/jsp in Tomcat and connect to EJB (all types... a classic documentation and also a number of published books and free ebooks... the EJB using servlets through Tomcat for all the Weblogic examples
JSP Tutorials
Collection is jsp books in the pdf format. You can download these books and
study it offline.
Free JSP Books
Download the following JSP books.
Free
JSP Download
Download.
Download. I need a swing program to download a file from the server
FileUpload and Download
FileUpload and Download Hello sir/madam,
I need a simple code for File upload and Download in jsp using sql server,that uploaded file should... be download with its full content...can you please help me... im in urgent i have
Downloading and Installing WebLogic server 6.0
. You can
download the BEA WebLogic Server for
and Installing WebLogic server 6.0... WebLogic Server?, is world class Web
and Wireless Application Server
Weblogic Portal - JSP-Interview Questions
Weblogic Portal Hi,
Can any please give me the details of
1) Weblogic portal interview questions & answers ?
2) Weblogic portal learning step by step websites?
Thanks for your help in advance
Ajax Books
Ajax Books
AJAX - Asynchronous JavaScript and XML - some books and resource links
These books... there have been few books on DHTML and only 2-3 that cover AJAX. But that will change
EJB 3.0 Tutorials
Classes
Interceptors
Simple JNDI lookup of EJB
...;
EJB remote interface
The program given below describes the way... get methods as given below in the program.
EJB Insert data
Deployment steps in weblogic 102 - Development process
Deployment steps in weblogic 102
Hi Friends,
can u give me d deployment steps in weblogic server 10.2(both jsp and servlet ..... how to export war file?) ..Thank u in advance
Simple Bank Application in JSP
Simple Bank Application in JSP
In this section, we have developed a simple bank... on Apache Tomcat Server. To
Download the latest version of Server click
J2ME Books
J2ME Books
Free
J2ME Books
J2ME programming camp... in January, 2005, the best selling book Mastering EJB is now in it?s third
server-jsp - JSP-Servlet
server-jsp how can we implement a simple database(ms access) for storing information about the HTTP requests sent to a web server(database
unable to connect to server - JSP-Servlet
unable to connect to server thank you for the program code... in weblogic/apache servers can any one help me how to do this ? Hi Friend...-application-server/tomcat/install-configure.shtml
Here you will get step by step
Struts integration with EJB in JBOSS3.2
famous EJB-Servers in the market are:
BEA ..WebLogic Server
JBoss....
The development of the EJB and its deployment in JBOSS server is over... we develop the Struts client program for the above EJB
JSP - EJB
JSP scriptlet tag out println What is the JSP scriptlet tag out println
JSP Tutorials Resource - Useful Jsp Tutorials Links and Resources
. You should be able to program in Java.
This tutorial teaches JSP...;
Introduction
To JSP
Java Server Pages... a standard and simple
syntax to access the DOM. JSP pages execute as Java serv
servlet with weblogic
servlet with weblogic hi everyone....
When I'm running this program on weblogic server8.1
import java.io.*;
import java.sql.*;
import...){
System.out.println(e);
}
}
}
this error shown...
Error 500--Internal Server Error
Simple Program Very Urgent.. - JSP-Servlet
Simple Program Very Urgent.. Respected Sir/Madam,
I am R.Ragavendran.. Thanks for your superb reply. I find a simple problem which i have tried my... information.
Workshop for WebLogic 10.1
reporting
This installer also includes: BEA WebLogic Server, and BEA... Workshop for WebLogic 10.1
BEA Workshop for WebLogic 10.1 offers nothing less
Free J2EE Online Training
training. The students are also given training on
JSP (Java Server Pages...Free J2EE Online Training
The Enterprise Edition of Java popularly known... professionals free online J2EE training
there are various websites but the quality
jsp program
jsp program sir
how we can load the data on the server in the on line project
File download from server to client machine - JSP-Servlet
File download from server to client machine hi,
I want to save a pdf file to my client machine from a button provoded in a jsp page.The file... the generated report in server as follow.
exporter.exportIntoPdfFile("c://reports:
Java XML Books
;
Free
Java XML Books...
Java XML Books
Java
and XML Books
One night
|
JSP PDF books
| Free JSP Books
| Free
JSP Download |
Authentication...
uing JDBC in JSP |
Download CSV File from
Database in JSP
JSP... Beans in
JSP | JSP Taglibraries |
Hello World Program in JSP
| Directive... for free use as well as
commercial use allowing you to choose the best server
Free PHP Books
Free PHP Books
...
PHP 5 Simple
PHP has gained a following among non-technical web designers... works with your web server and web browser to the ins and outs of working
Upload and download file - JSP-Servlet
Upload and download file What is JSP code to upload and download............
Now to download the word document file, try the following code...();
response.getOutputStream().flush();
%>
Thanks I want to download a file
Developing Distributed application using Enterprise Java Beans, J2EE Architecture, EJB Tutorial, WebLogic Tutorial.
)
Java Server Pages (JSP)
Java Servlets....
4.
Java Server Pages or JSP for short...-tier applications are also know as
client/server applications. In most
Need E-Books - JSP-Servlet
EJB Container or EJB Server
EJB Container or EJB Server
An EJB container is nothing but the program that runs on the server... less load and sends the request to that
server.
EJB container encapsulates
EL(JSP) - JSP-Servlet
EL(JSP) Dear Sir,
I want to ask that Whether BEA Application server weblogic 8.1 support to Expression language(JSP) or not. Because EL require jsp version 2.0.
Weblogic 8.1 have jsp version 1.2.
J2EE version 1.3 have jsp
Web Sphere Books
standards like Servlets, JSP, and EJB. The more abstract material on the best...
Web Sphere Books
...
This redbook explores in detail IBM's flagship application server offering
Linux Books
and to any other program whose authors commit to using it. (Some other Free...
Linux Books
... reading this book you should understand how to compile a program, and how to use basic
JSP Simple Examples
JSP Simple Examples
Index 1.
Creating a String
In jsp we create a string as we does... in jsp. To make a program on factorial, firstly it must be
clear what
JBoss Application Server
is a free, open source application server under the LGPL license that is widely... that allows the developers to free download, use, embed, and distribute... including EJB, JCA, JSP, JMX, HTTP etc. It provides a bridge for the enterprise Java
Introduction to JSP
?"
Installing JSP
First of all download JavaServer Web... as a small stand-alone server for testing servlets and JSP pages before they are deployed to a full Web server that supports these technologies. It is free
JSP-EL - JSP-Servlet
Application server weblogic 8.1. In weblogic 8.1 allthough execute the JSP... is:
Home.html
A simple JSP application
EL Uisng In JSP
Name...JSP-EL Dear Sir,
I know that this below code run on your
simple java search engine
simple java search engine i have already downloaded the project simple java search engine.but i am not able to run it.can anyone help me.i have....
ABSTRACT
Title : Simple Search Engine
System Specification:
The system on which
JSP
tag to include server state in the jsp page output.
For more information, visit the following link:... language , it is a simple language for accessing data, it makes it possible to easily
WEBSERVICE USING APACHE AXIS TUTORIAL-2 UNDERSTANDING APACHE AXIS (part-2)
;
Creating and testing an EJB in
WebLogic Server.Let...;/enterprise-beans>
</ejb-jar>
//weblogic... weblogic-ejb-jar PUBLIC
"-//BEA Systems, Inc.//DTD WebLogic 7.0.0
EJB Simple Examples
Objects
EL is the JSP 2.0 Expression Language Interpreter from...
Conditional Content on a JSP Page
We make use of the condition... in JSP
An exception can occur if you trying to connect to a database
jsp
jsp
<% out.println("hello");%>
i have writtn this program .but i am not getting way to deploy it.As in ma weblogic at the time of installation web.xml descriptor problem was there so i am doin exploded deployment.so
Roseindia JSP Tutorial
JSP Cookies Example
Disabling Session in JSP
JSP PDF books
Free JSP... - Introducing Java Server Pages Technology
JSP Architecture
Introduction...Roseindia JSP tutorials provides you with a library of best JSP tutorials
Deploying Servlet in Weblogic 9.2 - Servlet Interview Questions
Deploying Servlet in Weblogic 9.2 Hi Friends,
I am new to web... in target server. I am using Struts framework,servlets and hibernate.Jsp for page...
Servlets were designed to allow for extension of a server providing any service
JSP Hello World
through the server side program.
In JSP example also contents HTML code...JSP Hello World
We are going to discus about JSP hello world. In this example we are create
"HelloWold" on web browser. In this program of JSP
Weblogic server - Java Beginners
Weblogic server how can we create connection poolong in weblogic 9.1 application server
JSP-EL - JSP-Servlet
a JSP-EL problem that not solve by me..
Please review that:
That's my program files:
home.html:
A simple JSP application
Name... that program on weblogic 8.1
This is my programming structure:
ELProgram>Home.html | http://www.roseindia.net/tutorialhelp/comment/30127 | CC-MAIN-2015-06 | refinedweb | 2,592 | 67.25 |
Building a Library with RequireJS
RequireJS is an AMD module loader for browsers that can load your script and CSS files asynchronously. You no longer have to deal with the order of script files inside an individual file (e.g. index.html). Instead, you just wrap your code inside module definitions and RequireJS will take care of the dependencies, making your code more structured and well organized. It also has an optimizer tool that uglifies and concatenates the files for production use.
The official site provides extensive documentation about its API, and there are many example repositories to help you. But it has a lot of configuration and it is tricky at first to get started with RequireJS.
In this article we will learn how to use RequireJS by building a library using AMD modules, optimizing it and exporting it as a standalone module using the RequireJS optimizer. Later we will use RequireJS to build an application and consume our library.
Installing RequireJS
RequireJS is available through bower:
bower install requirejs --save
or you can grab the files on github.
There is also a Grunt-based Yeoman generator for RequireJS projects.
Defining an AMD module
We will wrap our code inside
define(), and that will make it an AMD module.
File:
mylib.js
define(['jquery'], function($) { // $ is jquery now. return 'mylib'; });
That’s it. Note that
define() takes an optional first argument of a dependency array, in this case it is
['jquery']. It’s the dependency list for this module. All the modules inside the array will be loaded before this module. When this module is executed, the arguments are the corresponding modules in the dependency array.
So in this case jQuery will be loaded first, then passed into the function as parameter
$, then we can safely use it inside our module. Finally our module returns a string. The return value is what gets passed to the function parameter when this module is required.
Requiring Other Modules
Let’s see how this works by defining a second module and require our first module
mylib.js.
File:
main.js
define(['jquery', 'mylib'], function($, mylib) { // $ is jquery as usual // mylib is the string `mylib` because that's the return value // from the first module return { version: '0.0.1, jQuery version: ' + $.fn.jquery, mylibString: mylib } });
You can require as many dependencies as you like inside the dependency array, and all the modules will be available through the function parameters in the same order. In this second module we required the
jquery and
mylib modules, and simply returned an object, exposing some variables. The user of this library will use this object as your library.
Configuring the RequireJS Optimizer: r.js
You might be wondering, how does RequireJS know what file to load only by looking at the string in dependency array? In our case we provided
jquery and
mylib as strings, and RequireJS knows where those modules are.
mylib is simple enough, it’s
mylib.js with
.js omitted.
How about
jquery? That’s where RequireJS config is used. You can provide extensive configuration through a RequireJS config. There are two ways to provide this config, since we are using the RequireJS optimizer, I will show you the r.js way. r.js is the RequireJS optimizer.
We will provide r.js with a config, and it will optimize all the modules into a single file. The configuration that we provide will make r.js build the modules as a standalone global library that can be used both as an AMD module or as a global export in the browser.
r.js can be run via command line or as a Node module. There is also a Grunt task
grunt-requirejs for running the optimizer.
That being said, let’s see what our configuration looks like:
File:
tools/build.js
{ "baseUrl": "../lib", "paths": { "mylib": "../main" }, "include": ["../tools/almond", "main"], "exclude": ["jquery"], "out": "../dist/mylib.js" "wrap": { "startFile": "wrap.start", "endFile": "wrap.end" } }
The configuration file is really the meat of RequireJS. Once you understand how these parameters work, you can use RequireJS like a pro.
You can do different things, and tweak your project builds with the configuration file. To learn more about configuration and RequireJS in general I recommend referencing the docs and the wiki. There is also an example configuration file, that demonstrates how to use the build system, so make sure to reference that as well.
Finally we actually run the optimizer. As I said before, you can run it via command line, or Node, as well as a Grunt task. See the r.js README to learn how to run the optimizer in different environments.
node tools/r.js -o tools/build.js
This will generate the build file in
dist/mylib.js
build.js
Next, let’s see what the parameters actually mean.
baseUrl – The root path for all module lookups.
paths – Path mappings for module names that are relative to baseUrl.
In our example, “mylib” maps to “../main”, that is relative to
baseUrl, so when we require “mylib” it loads the file “../lib/../mylib/main.js”.
Notice we appended
baseUrl, then the
paths setting, than the module name followed by a
.js suffix. That’s where you specify how modules are mapped to files such as
jquery and
mylib.
include – The modules we want to include in the optimization process. The dependencies that are required by the included modules are included implicitly. In our case,
main module depends on
mylib and
jquery that will get included as well, so no need to include it explicitly. We also include
almond that I will mention later.
exclude – The modules we want to exclude from the optimization process. In our case we exclude
jquery. The consumers of the built library will provide a jQuery library. We will see that when we consume our library later.
out – The name of the optimized output file.
wrap – Wraps the build bundle in a start and end text specified by
wrap. The optimized output file looks like:
wrap.start + included modules +
wrap.end.
wrap.start and
wrap.end are the names of the files in which their contents get included in the output.
almond
The built library does not include require.js in the file, but instead uses almond. almond is a small AMD API implementation, that will replace require.js.
Wrapping our Library
In the r.js config we wrapped our library with
wrap.start and
wrap.end files. We also included almond in our library, those will make our library standalone, so they can be used without RequireJS through browser globals or as an AMD module through requirejs.
File: wrap.start
(function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. define(['jquery'], factory); } else { // Browser globals. root.mylib = factory(root.$); } }(this, function($) {
Our included modules
main,
mylib, and
almond are here in the middle of
wrap.start and
wrap.end.
File: wrap.end
// Register in the values from the outer closure for common dependencies // as local almond modules define('jquery', function() { return $; }); // Use almond's special top level synchronous require to trigger factory // functions, get the final module, and export it as the public api. return require('mylib'); }));
If the consumer uses an AMD loader, then the built file will ask for ‘jquery’ as AMD dependencies. If the consumer just uses browser globals, the library will grab the
$ global variable and use it for jQuery dependency.
Using the Library with RequireJS
We are done with our library, now let’s actually use it by building a requirejs application.
File:
app.js
define(['jquery', 'mylib'], function($, mylib) { // $ is jquery // mylib is mylib that is: // { // version: 'version 0.0.1 jQuery version: xxx', // mylib: 'mylib' // } });
Nothing fancy here, it’s another module that requires jQuery and mylib. When a module is defined with
define it is not immediately executed, that is its callback function (which is passed after the dependency array) is not executed right away. That means our application doesn’t start just by defining this module. Now let’s see how to configure RequireJS and actually execute this module that is our application.
Configuring RequireJS for the Browser
We will configure RequireJS and execute our app module in one file. There are different ways of doing this though.
File:
common.js
requirejs.config({ baseUrl: '../lib', paths: { 'jquery': 'jquery/dist/jquery.min', 'underscore': 'underscore/dist/underscore', 'backbone': 'backbone/backbone', 'mylib': 'mylib/dist/mylib', 'app': '../app' }, shim: { 'jquery': { exports: '$' }, 'backbone': { deps: ['jquery', 'underscore'], exports: 'Backbone', }, 'underscore': { exports: '_' } } }); require(['app/app'], function(App) { // app module is available here // you can start your application now // this is immediately called because // we used `require` instead of `define` // to define this module. });
The
baseUrl and
paths config are the same as before. The additional config value here is:
shim: Configures the dependencies and exports for traditional “browser globals” scripts that do not use
define() to declare the dependencies and set a module value. For example, Backbone is not an AMD module, but it’s a browser global that exports
Backbone into the global namespace that we’ve specified in the
exports. In our example, the module also depends on jQuery and Underscore, so we specify that using
deps. The scripts in the
deps array are loaded before Backbone is loaded, and once loaded, the
exports value is used as the module value.
Note that you can also use r.js in this application project as well, which will require a separate configuration. But don’t get confused by that. I won’t go into detail on how to do that, but it’s similar to what we did for our library. See the example build config for further reference.
require vs define
Later we use
require to load a module and immediately execute it. Sometimes
define and
require can be confused as to which one is used when.
define defines a module, but doesn’t execute it,
require defines a module and executes it – that is, it loads and executes the dependent modules before executing itself. Often you will have one
require as a main entry module that will depend on additional modules that are defined via
define.
Typically you include all your script files in your
index.html. Now that we are using RequireJS, we only have to include RequireJS and specify our
data-main, which is the entry point to our application. There are different ways of setting up the config options, or separating the main module used in
index.html. You can find more information on that here.
<script data-</script>
Conclusion
In this article we have built a library, and an application that uses that library with RequireJS. We learned how to configure the r.js optimizer, and how to configure RequireJS in the browser. Finally we learned how to use RequireJS to define and use AMD modules. That made our code well structured and organized.
I’ve used this example-libglobal repo in this tutorial for the first half (configuring the optimizer), and the second half is not that complicated, so you should be good to roll your own now.
The official RequireJS website is the ultimate documentation, but make sure to check out the example repos on github as well the example projects in that repo, which demonstrate the use of a RequireJS application.
- eguneys | http://www.sitepoint.com/building-library-with-requirejs/ | CC-MAIN-2015-11 | refinedweb | 1,886 | 65.83 |
Asyncio does not work on the UI.
I want to run Asyncio from the UI button, but I get the error "there is no current event loop in thread 'dummy -1'" and cannot run it.
Is there a way to define a loop?
When I define a new loop using new and set, the UI freezes, so I predict that the UI also uses Asyncio and there is a conflict.
Is there any way to avoid it?
def button(sender): loop = asyncio.get_event_loop_policy().new_event_loop() #there is no current event loop in thread 'dummy -1 gather = asyncio.gather( get_pass(target), get_pass(target), get_pass(target) ) loop.run_until_complete(gather) v=ui.load_view() v['imageview1'].image=ui.Image('img/image.png') v['imageview2'].image=ui.Image('img/image2.png') v.present('sheet', hide_title_bar = True)
@Lami this is probably the definitive thread relating to threads and pythonista.
You might consider setting up your thread pool executer outside of the button action. | https://forum.omz-software.com/topic/7197/asyncio-does-not-work-on-the-ui | CC-MAIN-2022-40 | refinedweb | 156 | 58.38 |
On 16/10/2005, at 7:42 PM, Julien Cigar wrote:
> Graham Dumpleton wrote:
>
>> A.
>>
> My directory structure looks like this :
> index.py
> config.cfg
> config.py
> pages/page1.py
> pages/page2.py
> pages/page3.py
> ...
>
> My "pages" directory doesn't contain an __init__.py file (should I ?)
> I don't understand what's wrong with
> apache.import_module(pages/page1.py) .. ? I always done like this :)
> Is it specific to mod_python ? I mean can you import pages/page1.py
> with the classic Pyhon import ?
You can't use '/' when using the "import" statement in classic Python.
Ie., can't do:
import pages/page1
You can use '.', ie.,
import pages.page1
But then this is a package import and the "pages" directory needs to be
set up as a package, ie., it must contain an "__init__.py" file in it,
even if "__init__.py" has nothing in it.
Similarly, if you use the __import__ builtin function, you can't use
'/',
ie., can't do:
page1 = __import__("pages/page1")
but can do:
page1 = __import__("pages.page1")
In other words, that you can specify a '/' like you are is quite
specific
to the current mod_python implementation of apache.import_module().
Well,
that is what I thought ......
At this point I am a bit confused as I can't find anything in the
mod_python
code which would even allow '/' to work. When I even try using it on my
platform, Python throws an exception:
ImportError: No module named pages/page1
What version of mod_python are you using, what version of Python and
what
platform? I don't understand how it could be working for you.
Graham | http://modpython.org/pipermail/mod_python/2005-October/019291.html | CC-MAIN-2018-39 | refinedweb | 271 | 77.13 |
I am trying to find time ranges of the form
12:30 Test
12:30-12:50 Test
((\d+):(\d+)-?)+ (.*)
12:50
import re
print(re.search("^((\d+)(?::|h)(\d+)-?)+ (\w.*)", "12:30-12:50 Test").groups())
You cannot access repeated captures with Python
re, you need to explicitly unwrap the quantified group and make the second part optional:
(\d+):(\d+)(?:-(\d+):(\d+))? (.*) ^^^^^^^^^^^^^^^^^
See the regex demo
import re rx = r"(\d+):(\d+)(?:-(\d+):(\d+))? (.*)" strs = ["12:30 Test", "12:30-12:50 Test"] for str in strs: m = re.search(rx, str) if m: print(m.groups())
Output:
('12', '30', None, None, 'Test') ('12', '30', '12', '50', 'Test')
With PyPi
regex, you can access all the
captures, see an example with your regex:
>>> import regex >>> strs = ["12:30 Test", "12:30-12:50 Test"] >>> for str in strs: m = regex.search(r'((\d+):(\d+)-?)+ (.*)', str) if m: print(m.captures(1)) print(m.captures(2)) print(m.captures(3)) ['12:30'] ['12'] ['30'] ['12:30-', '12:50'] ['12', '12'] ['30', '50'] >>> | https://codedump.io/share/eAJd9idO0RGr/1/regex-for-time-ranges-starting-too-far | CC-MAIN-2018-09 | refinedweb | 172 | 83.05 |
Source code for torchvision.ops.giou_loss
import torch[docs]def generalized_box_iou_loss( boxes1: torch.Tensor, boxes2: torch.Tensor, reduction: str = "none", eps: float = 1e-7, ) -> torch.Tensor: """ Original implementation from Gradient-friendly IoU loss with an additional penalty that is non-zero when the boxes do not overlap and scales with the size of their smallest enclosing box. This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable. Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and ``0 <= y1 < y2``, and The two boxes should have the same dimensions. Args: boxes1 (Tensor[N, 4] or Tensor[4]): first set of boxes boxes2 (Tensor[N, 4] or Tensor[4]): second set of boxes reduction (string, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: No reduction will be applied to the output. ``'mean'``: The output will be averaged. ``'sum'``: The output will be summed. Default: ``'none'`` eps (float, optional): small number to prevent division by zero. Default: 1e-7 Reference: Hamid Rezatofighi et. al: Generalized Intersection over Union: A Metric and A Loss for Bounding Box Regression: """ x1, y1, x2, y2 = boxes1.unbind(dim=-1) x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) # Intersection keypoints xkis1 = torch.max(x1, x1g) ykis1 = torch.max(y1, y1g) xkis2 = torch.min(x2, x2g) ykis2 = torch.min(y2, y2g) intsctk = torch.zeros_like(x1) mask = (ykis2 > ykis1) & (xkis2 > xkis1) intsctk[mask] = (xkis2[mask] - xkis1[mask]) * (ykis2[mask] - ykis1[mask]) unionk = (x2 - x1) * (y2 - y1) + (x2g - x1g) * (y2g - y1g) - intsctk iouk = intsctk / (unionk + eps) # smallest enclosing box xc1 = torch.min(x1, x1g) yc1 = torch.min(y1, y1g) xc2 = torch.max(x2, x2g) yc2 = torch.max(y2, y2g) area_c = (xc2 - xc1) * (yc2 - yc1) miouk = iouk - ((area_c - unionk) / (area_c + eps)) loss = 1 - miouk if reduction == "mean": loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() elif reduction == "sum": loss = loss.sum() return loss | https://pytorch.org/vision/stable/_modules/torchvision/ops/giou_loss.html | CC-MAIN-2022-27 | refinedweb | 322 | 61.93 |
Hi,
Is it possible to use @EJB in JMX / MBean service?
public class HelloService implements HelloServiceMBean{
@EJB
private static Hello hello;
public void start() {
hello.sayHello()
}
}
I have check in JNDI view, and HelloBean is already registered.
And I have set the dependency of the HelloService to HelloBean in jboss-service.xml.
somehow, the injection is not working. hello is always return null
Does anyone know the cause, I try to search in this forum regarding the issue, and found nothing.
Thanks
Regards,
Ferry
The @EJB annotations are part of the EJB 3.0 spec, which is separate from the JMX spec. The @EJB annotation is for use by EJBs, the resource being injected by the EJB container. MBeans have to look up resources in JNDI "manually".
However, if you're not allergic to vendor extensions, you may be interested in the JBoss @Service EJB extension:
Thank you for the explanation.
After some thinking, I guess is it's because MBean was created before the EJBs. And by right, the EJB at the time of MBean creation is not available yet, so it can not be injected.
Though I put dependency on EJBs, it only delay to call the start() method, rather than the create(). | https://developer.jboss.org/thread/52256 | CC-MAIN-2018-05 | refinedweb | 205 | 65.52 |
Hi folks,
Today I’m going to show you how to create a Sigfox mail notifier using Wia and the Pycom SiPy.
This tutorial assumes that you have already connected Sigfox to Wia if you haven’t, please click here to find a tutorial for initial Sigfox setup and publishing data to Wia.
For the HC-SR04 ultrasonic sensor, you'll need to connect the following pins to the Pycom SiPy:
in Atom:
Create a new folder for your project. I'm going to call mine sigfox-mailbox
We'll need three files for our application:
boot.py
main.py
ultrasonic.py
In Atom:
Right click on your project and click New File. Enter boot.py as the filename
Copy and paste the code below into the file
from machine import UART
import machine
import os
uart = UART(0, baudrate=115200)
os.dupterm(uart)
machine.main('main.py')
Right click on your project and click New File. Enter main.py as the filename
import time
import pycom
import socket
from network import Sigfox
from machine import Pin, Timer
import ultrasonic
pycom.heartbeat(False)
echo = Pin(Pin.exp_board.G7, mode=Pin.IN)
trigger = Pin(Pin.exp_board.G8, mode=Pin.OUT)
trigger(0)
# Get the chronometer object
chrono = Timer.Chrono()
# init Sigfox for RCZ1 (Europe))
calibrated_distance = ultrasonic.calibration(chrono, trigger, echo, 1)
mailed_distance = 0
while True:
time.sleep(30)
distance = ultrasonic.getDistance(chrono, trigger, echo)
print("distance: {}, calibration: {}".format(distance, calibrated_distance))
if distance < calibrated_distance:
if distance != mailed_distance:
s.send('') # Send 1 bit
print("you got mail")
mailed_distance = ultrasonic.calibration(chrono, trigger, echo)
Right click on your project and click New File. Enter ultrasonic.py as the filename
from machine import Pin, Timer
import pycom
import time
import socket
def calibration(chrono, trigger, echo, led = False):
if led:
pycom.rgbled(0x7f0000) # red
prev_distance = 0
distance = getDistance(chrono, trigger, echo)
print("calibration distance is {}".format(distance))
count = 0
while True:
prev_distance = distance
distance = getDistance(chrono, trigger, echo)
while prev_distance == distance:
count+=1
print("count: {}".format(count))
if count > 5:
if led:
pycom.rgbled(0x007f00) # green
time.sleep(1.5)
pycom.rgbled(0) # off
return distance
time.sleep(5)
prev_distance = distance
distance = getDistance(chrono, trigger, echo)
else:
count = 0
def getDistance(chrono, trigger, echo):
chrono.reset()
trigger(1)
time.sleep_us(10)
trigger(0)
while echo() == 0:
pass
chrono.start()
while echo() == 1:
pass
chrono.stop()
distance = chrono.read_us() / 58.0
if distance > 400:
return -1
else:
return int(distance)
time.sleep(1)
Your folder structure should now look like this:
Click Upload in the Pymakr plugin at the bottom of your window in Atom and send the code to your Pycom board. Now go to the Wia dashboard and you should see data appearing in the debugger section of your dashboard.
Upload
In order for the sensor to operate correctly, it needs to calibrate the distance inside you mail box.
To calibrate the sensor, place the sensor in the mailbox where its suits best. Power the board; when the LED on the board is red, the sensor is calibrating; once the LED flashes green, the sensor has been calibrated. The sensor needs at-least 2cm of space in order for it to operate correctly.
Now when mail is inserted into your mailbox, the distance will be reduced from the calibrated distance and the code will publish an Event via Sigfox to Wia.
Now for the next step, once we recieve the Sigfox event in Wia, we will send a notification to any connected phones that there is mail. we are going add a notification for the Sigfox Event so we get notified of our inbound mail. To do this, you will require the Wia mobile app. You can download it for iOS here and Android here.
In the Flow Studio editor:
You've got Mail!
Now you should receive Sigfox data to your mobile device. | https://community.wia.io/d/42-build-a-smart-mailbox-with-a-sigfox-and-pycom | CC-MAIN-2019-39 | refinedweb | 640 | 58.28 |
Date: Tue, 24 Oct 2000 12:21:04 +0100 From: "Stephen C. Tweedie" <sct@redhat.com> To: Andreas Gruenbacher <ag@bestbits.at> Subject: Re: [PROPOSAL] Extended attributes for Posix security extensions Hi, On Sun, Oct 22, 2000 at 04:23:53PM +0200, Andreas Gruenbacher wrote: > > This is a proposal to add extended attributes to the Linux kernel. > Extended attributes are name/value pairs associated with inodes. What timing --- we had a long discussion (actually, several!) about this very topic at the Miami storage workshop last week. One of the main goals we had in getting people together to talk about extended attributes in general, and ACLs in particular, was to deal with the API issues cleanly. In particular, we really want the API to be at the same time: * General enough to deal with all of the existing, mutually-incompatible semantics for ACLs and attributes; and * Specific enough to define the requested semantics unambiguously for any one given implementation of the underlying attributes. These points are really important. We have people wanting to add ACL support to ext2 in a manner which Samba can use --- can we do POSIX ACLs with NT SID identifiers rather than with unix user ids? If we mount an NTFS filesystem, it will have native ACLs on disk. How does the API speficy that we want NT semantics, not POSIX semantics, for a given request? There is also the naming issue. There are multiple independent namespaces. For extended attributes, there may be totally separate namespaces for user attributes and for system ones, or there may be a common namespace with per-attribute system status. Again, these different sets of semantics _already exist_ on filesystems which Linux can mount (eg. NTFS, JFS and XFS), so the API has to deal with them. There is already a kernel API which has this flexibility: the BSD socket API handles these issues through the concepts of protocol families and address families. Those same two concepts are perfectly matched to the extended attributes problem.. Obviously the combinations of name types supported for any given attribute family will depend on the underlying implementation, but that's the whole point --- the API is expressive enough to define unambiguously what the application is trying to do, so that if the underlying filesystem doesn't support (say) POSIX ACLs, we get an error back telling us so rather than attempting to do an incomplete map of the POSIX request onto whatever the underlying filesystem happens to support. Before we look at the syscall API in detail, there's one other point to note. It is common to want to read or set one individual attribute in isolation (even if it is an atomic set-and-get which is being performed on that attribute). Sometimes, however, you want to access the entire set of related attributes as an ordered list. ACLs are the obvious case: if you have underlying semantics which allow you to mix both PASS and DENY ACLs on a file, then the order of the ACLs obviously matters. In such cases, you may sometimes want just to query or set the ACL for a specific user, but often you will want to do something more complex such as change the order of ACLs on the list or replace the entire list as a single entity --- and you want to do so atomically. So, the simple "SET" and "GET" operations on named attributes (which correspond to writing and reading the ACLs for specific named users in the ATR_POSIXACL family) need to be augmented with SET variants which append or prepend to the ACL list, or which atomically replace the old ACL list in its entirety. Our proposed kernel API looks something like this: sys_setattr (char *filename, int attrib_family, int op, struct attrib *old_attribs, int *old_lenp, struct attrib *new_attribs, int new_len); sys_fsetattr(int fd, int attrib_family, int op, struct attrib *old_attribs, int *old_lenp, struct attrib *new_attribs, int new_len); where <op> can be ATR_SET overwrite existing attribute ATR_GET read existing attribute ATR_GETALL read entire ordered attribute list (ignores new val) ATR_PREPEND add new attribute to start of ordered list ATR_APPEND add new attribute to end of ordered list ATR_REPLACE replace entire ordered attribute list and where <attribs> is a buffer of length <len> bytes of variable length struct attrib records: struct attrib { int rec_len; /* Length of the whole record: should be padded to long alignment */ int name_family; /* Which namespace is the name in? */ int name_len; int val_len; char name[variable]; /* byte-aligned */ char val[variable]; /* byte-aligned */ }; ATR_SET will overwrite an existing attribute, or if the attribute does not already exist, will append the new attribute (ie. it does not override existing ACL controls, in keeping with the Principle of Least Surprise). If multiple instances of the name already exist, then the first one is replaced and subsequent ones deleted. If supplied with an "old" buffer, all old attributes of that name will be returned. For the PREPEND/APPEND/REPLACE operations, the entire old attribute set is returned. For GET, the <new> specification is read and all attributes which match any items in <new> are returned, in the order in which they are specified in <new>. The actual value in <new> is ignored; only the name is used. For GETALL, <new> is ignored entirely. *old_lenp should contain the size of the old attributes buffer on entry. It will contain the number of valid bytes in the old buffer on exit. If the buffer is not sufficiently large to contain all of the attributes, E2BIG is returned. This is just a first stab at documenting what feels like an appropriate API. It should be extensible enough for the future, but is pretty easy to code to already --- existing filesystems don't have to deal with any complexity they don't want to. Additionally, the use of well-defined namespaces for attributes means that in the future we can implement things like common code for generic attribute caching, or process authentication groups for non-Unix-ID authentication tokens, without having to duplicate all of that work in each individual filesystem. The extended attribute patch currently on the acl-devel group simply doesn't give us the ability to do extended attributes on any filesystem other than ext2, because it has such specific semantics. I'd rather avoid that, and I'd rather do so without adding a profusion of different ACL and attribute syscalls in the process. Cheers, Stephen - To unsubscribe from this list: send the line "unsubscribe linux-fsdevel" in the body of a message to majordomo@vger.kernel.org | http://lwn.net/2000/1026/a/sct-attributes.php3 | crawl-003 | refinedweb | 1,094 | 55.58 |
Module Statement
Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the module comprises.
- attributelist
Optional. See Attribute List.
- accessmodifier
Optional. Can be one of the following:
See Access Levels in Visual Basic.
- name
Required. Name of this module. See Declared Element Names.
- statements
Optional. Statements which define the variables, properties, events, procedures, and nested types of this module.
- End Module
Terminates the Module definition.
A Module statement defines a reference type available throughout its namespace. A module (sometimes called a standard module) is similar to a class but with some important distinctions. Every module has exactly one instance and does not need to be created or assigned to a variable. Modules do not support inheritance or implement interfaces. Notice that a module is not a type in the sense that a class or structure is — you cannot declare a programming element to have the data type of a module.
You can use Module only at namespace level. This means the declaration context for a module must be a source file or namespace, and cannot be a class, structure, module, interface, procedure, or block. You cannot nest a module within another module, or within any type. For more information, see Declaration Contexts and Default Access Levels.
A module has the same lifetime as your program. Because its members are all Shared, they also have lifetimes equal to that of the program.
Modules default to Friend (Visual Basic) access. You can adjust their access levels with the access modifiers. For more information, see Access Levels in Visual Basic.
All members of a module are implicitly Shared.
Classes and Modules. So only classes can be instantiated as objects. For more information, see Classes vs. Modules.
Rules
Modifiers. All module members are implicitly Shared (Visual Basic). You cannot use the Shared keyword when declaring a member, and you cannot alter the shared status of any member.
Inheritance. A module cannot inherit from any type other than Object, from which all modules inherit. In particular, one module cannot inherit from another.
You cannot use the Inherits Statement in a module definition, even to specify Object.
Default Property. You cannot define any Default Properties in a module.
Behavior
Access Level. Within a module, you can declare each member with its own access level. Module members default to Public (Visual Basic) access, except variables and constants, which default to Private (Visual Basic) access. When a module has more restricted access than one of its members, the specified module access level takes precedence.
Scope. A module is in scope throughout its namespace.
The scope of every module member is the entire module. Notice that all members undergo type promotion, which causes their scope to be promoted to the namespace containing the module. For more information, see Type Promotion.
Qualification. You can have multiple modules in a project, and you can declare members with the same name in two or more modules. However, you must qualify any reference to such a member with the appropriate module name if the reference is from outside that module. For more information, see Resolving a Reference When Multiple Variables Have the Same Name. | https://msdn.microsoft.com/en-US/library/aaxss7da(v=vs.80).aspx | CC-MAIN-2017-30 | refinedweb | 530 | 58.69 |
I have coded a simple program and would like to see if I can put it on a webpage so others can try it, but after following the guides on java.sun I still get the "Applet notinited" problem. I have looked for solution on the Internet but I just don't get it.
Where could I possibly go wrong? I have even tried the example code on sun.java:
package betaTest; import javax.swing.JApplet; import java.awt.Graphics; /** * * @author Raymond */ public class testApp extends JApplet { @Override public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); g.drawString("Hello world!", 5, 15); } }
And in the web page source I've written:
<html> <body> <applet code=testApp.class </applet> </body> </html>
Did I miss anything or do anything wrong?
Thanks for help > <" | http://www.dreamincode.net/forums/topic/67477-applet-problems/ | CC-MAIN-2016-22 | refinedweb | 138 | 71.21 |
Description
EXPERIENCE THE WORLD'S FIRST TAXI APP Order a taxi with one tap, track your driver in real time and pay your trips cashless by app. One app, one account, 40+ cities in Europe! And all this for FREE! Available in Barcelona, Berlin, Cologne, Cracow, Dortmund, Düsseldorf, Essen, Frankfurt, Hamburg, Hanover, Lisbon, Madrid, Milan, Munich, Stuttgart, Valencia, Vienna, Warsaw and many more (full list bellow). FEATURES OVERVIEW: • Pay by App: Save time with cashless & cardless payment by app. • Collect vouchers: Give away free tours to friends to get thank-you vouchers in return (not available in Germany). • One Touch Order: Order a taxi to your current location with one tap. • Live Trip: Track your approaching driver in real time. • Advance Order: Request a taxi up to 4 days in advance. • Favorite Drivers: Save drivers you know and like. • 5 Star Taxis: Request the best rated taxis as default. • Taxi Radar: Map nearby taxis in real time. ----- IT WORKS WITH ONE TAP ONLY: 1. Allow the app to locate your current position as your pickup location. 2. Tap on "Order a Taxi"". Once a driver is found, you'll be able to see your driver's name, photo, mobile number, estimated arrival time, vehicle class, license plate and ratings. You can always preselect your preferred options (favorite drivers, taxi van, wheelchair) for orders with one tap. ----- MYTAXI IS AVAILABLE IN: • Austria: Graz, Vienna • Germany: Berlin, Bonn, Bremen, Cologne, Dortmund, Dresden, Düsseldorf, Essen, Frankfurt, Hamburg, Hanover, Leipzig, Lübeck, Mainz, Munich, Nuremberg, Osnabrück, Stuttgart and Sylt • Italy: Milan • Poland: Crakow, Warsaw • Portugal: Lissabon • Spain: Barcelona, Madrid, Sevilla, Valencia ----- Reviews & Feedback: If you need help or if you have any suggestion, email us at customerservice@mytaxi.com. We'd love to hear from you. Follow us on Facebook (fb.com/mytaxi.us) and on Twitter (@mytaxiUS).
What's new in this version
Welcome to the brand new mytaxi app! Ordering a taxi is now easier, faster and more intuitive than ever. WHAT'S NEW: • Refer friends and earn credit • Bug fixes. We've been very busy lately and we seriously hope you like the new app. Tell us your experience! We'd love to hear from you! Email us at customerservice@mytaxi.com and/or follow us on Facebook (fb.com/mytaxi.us) and on Twitter (@mytaxiUS).
Additional information
Published byIntelligent Apps GmbH
Developed byIntelligent Apps GmbH
Approximate size8.01 MB
Language supportedDeutsch (Deutschland)
English (United States)
Català (Català)
Español (España, Alfabetización Internacional)
Polski (Polska)
Publisher Infomytaxi website
mytaxi support
Additional termsmytaxi privacy policy
Terms of transaction
mytaxi license terms | https://www.microsoft.com/en-us/p/mytaxi/9wzdncrdfrhq?rtc=1 | CC-MAIN-2019-39 | refinedweb | 427 | 58.58 |
This article describes software I’m not really familiar with. Take this with a pinch of salt. For all I know, tomorrow I may realize the error of my ways and change my tune.
I recently found out that there’s this open-source OCR software called Tesseract, and decided to give it a try. I’m going to show you how you can set up something really quickly, and some initial results I’ve seen.
First, install Tesseract via NuGet:
Second, to use Tesseract’s OCR facility, you need some language data, which Tesseract provides. Go to the tessdata project and download it. Technically, you only need the files starting with eng* if you’re going to OCR English text. If you download the whole repo, be patient – it’s a few hundred megabytes zipped. Make sure you put the files in a folder called tessdata, or it won’t work.
Third, get yourself some test images you can feed to the OCR. You can find some online, or scan something from a book.
Fourth, you’ll need to add a reference to System.Drawing, because the Tesseract package depends on the Bitmap class:
Finally, we can get some code in. Let’s use this (needs
using Tesseract;):
static void Main(string[] args) { Console.Title = "Trying Tesseract"; const string tessDataDir = @"tessdata"; const string imageDir = @"image.png"; using (var engine = new TesseractEngine(tessDataDir, "eng", EngineMode.Default)) using (var image = Pix.LoadFromFile(imageDir)) using (var page = engine.Process(image)) { string text = page.GetText(); Console.WriteLine(text); Console.ReadLine(); } }
This is enough to set up Tesseract, load a file from disk, and OCR it (convert it from image to text). It may take a few seconds for the processing to happen. Now, you may be wondering what a
Pix class is, or what is a
page. And I’m afraid I can’t quite answer that, because there doesn’t seem to be any documentation available, so that doesn’t exactly help.
So, when trying this out, I first scanned a page from The Pragmatic Programmer and fed it to Tesseract. I can’t reproduce that for copyright reasons, but aside from some occasional incorrect character, the results were actually pretty good.
The next thing I did was feed it the Robertson image from this page. It looked okay at first glance, until I actually bothered to check the result:
Good heavens. What on Earth is a “sriyialeeeurreneeseenu”? Shocked by these results, I read some tips about improving the quality of the output. Because it’s true, you can’t blame the OCR for mistaking a ‘c’ for an ‘e’ when they look very similar, and the image has some noise artifacts (see top of image, where there’s some faint print from another page).
To make sure I give it some nice, crisp text, I took a screenshot of the Emgu CV homepage (shown below), and fed it to the program.
See the results for yourself:
That’s quite an elaborate mess. It may be because I’m new to this software, but that doesn’t give me a very good impression. Maybe it’s my fault. But I can’t know that if there’s no documentation explaining how to use it. | https://gigi.nullneuron.net/gigilabs/2015/12/18/ | CC-MAIN-2020-05 | refinedweb | 542 | 74.19 |
I created a simple Apache Cordova app and got it working on my iOS and Android emulators in the last article. My hope was to convert the app to ECMAScript 2015 (the new fancy name for what we have been calling ES6 for the past year) and work on Browserify for the app packaging. However, the initial bits took too long. So let’s remedy that now. I’m starting from the basic app template that the cordova tool produced.
Let’s start by looking at the code that the basic app template includes (in ./www/js); } }; app.initialize();
This is basically a class for handling events together with a method that handles the application code. I think I can abstract the event handling and use the EventEmitter class from the NodeJS package. I like the semantics of EventEmitter a little better. Let’s take a look at my new code (which I’ve placed in src/js/index.js):
import DeviceManager from './lib/device-manager'; var app = new DeviceManager(); app.on('deviceready', function () { var parentElement = document.getElementById('deviceready'); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); });
I could have used an arrow-function for the callback in app.on(), but I like the callback semantics when I’m not in a class and have no parameters. I believe it is more readable. I now need a DeviceManager class. This is stored in the file src/js/lib/device-manager.js:
import {EventEmitter} from 'events'; /** * A class for handling all the event handling for Apache Cordova * @extends EventEmitter */ export default class DeviceManager extends EventEmitter { /** * Create new DeviceManager instance */ constructor() { super(); document.addEventListener('deviceready', this.onDeviceReady.bind(this), false); } /** * Handle the deviceready event * @see * @emits {deviceready} a deviceready event * @param {Event} the deviceready event object */ onDeviceReady(e) { console.debug('[DeviceManager#onDeviceReady] event = ', e); this.emit('deviceready', e); } }
I’m preparing this for conversion into a library by include esdoc tags for documentation. There is more to do in this class. I want to trap all the Apache Cordova events so that I can re-emit them through the EventEmitter module, for example. However, this is enough to get us started.
Note that there is a little extra work needed if you want to use Visual Studio Code to edit ES2015 code. Add the following jsconfig.json file:
{ "compilerOptions": { "target": "ES6" } }
Now that I have the code written, how does one build it? First step is to bring in npm, which I will use as the package manager for this project:
npm init --yes
I like to answer yes to everything and then edit the file directly. In this case, I’ve set the license to MIT, added a description and updated the author. However all of these are optional, so this single line lets me start working straight away.
A Diversion: Babel 6
My next step was to download the tool chain which includes gulp, browserify and babelify. I always browse the blog before adding a module to a project and it was lucky I did that in the case of Babel as there were major changes. Here is the short short version:
- Babel is just a transpiler framework now
- You must create a .babelrc file for it to work
Fortunately, getting ES2015 compilation working with the .babelrc file is simple. Here it is:
{ "presets": [ "es2015" ] }
If you are using Babel on the command line, I highly recommend you read the introductory blog post by the team.
Build Process: Gulp
As I pretty much always do nowadays, gulp is my go-to build process handler. To set it up:
npm install --save-dev gulp gulp-rename vinyl-source-stream browserify babelify babel-preset-es2015
The first five modules are from my prior experience with Browserify. The last one is a new one and brings in the ES2015 preset for Babel6. The Gulpfile.js is relatively simple right now:
var babelify = require('babelify'), browserify = require('browserify'), gulp = require('gulp'), rename = require('gulp-rename') source = require('vinyl-source-stream'); gulp.task('default': [ 'build' ]); gulp.task('build': [ 'js:bundle' ]); gulp.task('js:bundle', function () { var bundler = browserify({ entry: './src/js/index.js', debug: true }); return bundler .add('./src/js/index.js') .transform(babelify) .bundle() .pipe(source('./src/js/index.js')) .pipe(rename('index.js')) .pipe(gulp.dest('./www/js')); });
This is the exact same recipe I have used before, so the semantics haven’t changed. However, you need to uninstall old-babel and install the new packages for this to work. Of course, this is a new project, so I didn’t have to uninstall old-babel. To build the package, I now need to do the following:
gulp build
To make it even easier, I’ve added the following section to the npm package.json:
"scripts": { "build": "gulp build" },
With this code, I can now run npm run build instead of gulp directly. It’s a small level of indirection, but a common one.
Wrapping up
The build process overwrites the original www/js/index.js. Once the build is done, you should be able to use cordova run browser to check it out. You should also be able to build the iOS and Android versions and run those. There isn’t any functional change, but the code is now ES2015, and that makes me happy.
In the meantime, check out the code! | https://shellmonger.com/2015/11/24/apache-cordova-es2015-and-babel/ | CC-MAIN-2017-51 | refinedweb | 902 | 57.77 |
Hi ,
I'm just a beginner in java programming and I would like to ask how to manage the reading from file to class.
I mean, I have a file containing this kind of information:
Abbiati%goalkeeper%MILAN%2
....
....
the 1st string before the % is a name of the player (in a soccer team) the 2nd is his role, the 3rd is his team and the last is the credits of his quotation.
Well, what I want to do is to read these infos from file and save them in a class by using some arrays.
For example I will create:
String name[]
String role[]
String team[]
String credits[]
and I want that :
String name[0] = Abbiati
String role[0] = goalkeeper
String team [0] = MILAN
String credits[0] = 2
And so on for each rows of my file which contains all the players of MILAN team.
I simply don't know how realize this thing in java...
Can someone suggest me the java code?
Thanks in advance for your cooperation!!
bye!
Hi,
thats quite a task you have taken for a java beginner
First clarify if you are using java application or applet. By default applications have more priviliges in terms of reading/writing to local disks as compared to applets.
You will have to use java.io.* package that contains various classes for input/output streams.
Given belowis one example of java code that read its own file:
import java.io.*;
public class readsource{
public static void main(String args[]){
try{
FileReader file=new FileReader ("readsource.java");
BufferedReader buff=new BufferedReader(file);
boolean eof=false;
while(!eof){
String line=buff.readLine();
if(line==null)
eof=true;
else
System.out.println(line);
}
buff.close();
}catch(IOException e){
System.out.println("Error Pankaj:"+e.toString());
}
try{
Thread.currentThread().sleep(15*1000);
}catch(InterruptedException e){}
}
}
For the remaining part of your desired functionality you need to get hands on string parsing, vectors or suitable data set for holding the data.
bye
Pankaj
Hi!
Many thanks for your support!!
You're right, I didn't specify if I have to do an application or an Applet ....
I have to do an application!
Well, I've read your code and I think to have caught the meaning of everything a part of the last few lines:
try{
Thread.currentThread().sleep(15*1000);
}catch(InterruptedException e){}
}
what does it mean?
I have also to say that I know only C language so I can't use the Vector class you suggested me. With C language I would have used a struct, but I think that Java doesn't support this kind of data... I'm a VERY beginner you know
Other thing: can I use a similar code to do the opposite task? that means to write infos from array to file?
many thanks again!
bye!!
Hi,
Sorry that piece of code was a copy and paste problem. There is no thread defined in this code but for your information that code when executed will stop the thread for specified milliseconds (15 in the given case) thus if you are designing an animation of images and you want each image to be displayed for specified time then you will need this kind of code with sleep() method. But in the example I posted it was not required and it is a mistake on my part - this is good observation
Yes you can write the array back to the file with the only difference that istead of FileReader class you will have to create instance of FileWriter class
For your code you will have to create one generic class (data type ) like this:
public class player(){
String name;
String role;
String team;
String credits;
public player(String s1,String s2,String s3,String s4)
name=s1;
role=s2;
teams3;
credits=s4;
}
}
The above class only contains a constructor that assigns values to four variables as defined above.
Now in your main code or application you will have to create an instance for each line of data in your file thus an example can be:
player player1= new player("Abbiati","goalkeeper","Milan","2");
You will have to create as many "player" objects as the number of players in your data file - you can also create an array of players like
teamplayer[] =new player[team_size];
This is a static method of creating an array and you will have to ensure that the size does not exceed the array limit. Alternately you can also create a dynamic array but "vectors" have the advantage of expanding/shrinking as required and you do not have to worry about the size of the array required or for cleaning up allocated memory when the object is no longer in use. All these things are automaticlly taken care of in vectors.
BTW java has mutitude of data structures to suit your requirements.
bye
Pankaj
Hi!
The idea to create a class (like the player class you have suggested) that simulates the struct data of C language is very great. I think I can manage it quite good!
Well, I used the code you gave me few times ago to read datas from file and I also added a piece of code to share my line in tokens. I used the symbol of percentage (%) as delimit's mark since the blank spaces were not usefull to my purpose.
Here below you see the code:
while(!eof)
{
String line = buff.readLine();
if(line==null)
eof=true;
else
{
StringTokenizer st=newStringTokenizerline, "%");
int i=0;
while (st.hasMoreTokens())
{
vector[i] = st.nextToken("%");
System.out.println(vector[i]);
i++;
}
}
}
Notice that it works!!!
Ok, after this I run into another problem...
Instead of print these tokens with a System.out.println I should visualize them into a table consists in 30 rows (number of player per team) and 5 columns (name and surname, role, team, credists.. ).
I try to use a JTable to accomplish this task, but I must say that it's appeared to me a little bit complicate....
Can you suggest me some about it?
Thanks again for your availability!!!
PS: don't worry for your copy/paste error, as a matter of fact I learned more about java!!
Forum Rules
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center | http://forums.devx.com/showthread.php?137756-from-file-to-class&p=407350&mode=linear | CC-MAIN-2015-22 | refinedweb | 1,050 | 62.38 |
Get it done fast’n’easy
[UPDATE February 13, 2011]
PLEASE NOTE!
DI Commander has been embedded to DI Construction Kit, which supports also MS SQL 2008 and SAP B1 8.8.
You can download DI Construction Kit with documentation and full source code from these sites:
Please Note! A new patch version (released on September 21, 2007) of DIC is now available on the DIC download page. The new version fixes the login problem with B1 2007 & MSSQL 2005 as well as introduces a new helper object..
The most usual alternatives available to the consultant (ordered by hairyness factor, not by preference) to handle these tasks are:
- The Monkey Method: brute force
Just do it manually using the B1 client. Don’t get me wrong: despite the name, this method should not be overlooked. If the number of records to modify is small enough, the Monkey Method may well give the best effort/result ratio. I use it all the time, with good results. Especially during the implementation project, typing in a bunch of customer or item records might be an excellent excercise for the users of the new system.
- The Layman Method I: B1 Import
SAP Business One client includes a rough but easy-to-use tool for importing some of the basic stuff such as items, business partners etc. Performancewise, this is by far the fastest method as it seems to bypass the DI API and import the data directly into the database. I haven’t used this tool so much, but I’ve found it rather useful in doing massive pricelist updates. The main problem with B1 import is that there are so few objects it can manipulate and even for those objects, a limited subset of fields are exposed.
- The Layman Method II: Data Transfer Workbench
DTW is most often used in the initial master data migration, but it can also be used to modify data in a production database. One appealing feature of DTW is that the import files can be built with spreadsheet tools such as Open Office Calc or MS Excel, which are familiar to both end users and ERP consultants. While DTW is more flexible than B1 import, there are still lots of areas it leaves uncovered. Perhaps the most notable limitation is that while you can add and modify records with DTW, you cannot delete records. Sometimes doing a reimport also results in kinky stuff that you really want to avoid in a production environment (such as double invoicing addresses in a customer record).
- The Geek Method: DI API
When it comes to handling masterdata or transactions in the B1 database, the Data Interface API can do ‘almost’ everything that can be done via the B1 client. It is implemented as a COM object and thus can be accessed with any language and development tool that supports COM. The most typical languages used are Visual Basic and C#, but you could even use VBA from inside MS Office.
Unlike the notorious UI API, DI API is actually a rather solid and stable piece of software. Interestingly enough, Data Transfer Workbench is actually built on top of DI API and just adds the possibility to map CSV files or SQL resultsets to the fields of DI API objects. This means that anything that can be done in DTW can also be done in DI API, but not necessarily vice versa.
With DI API, the biggest problem is not the API itself, but the fact that it’s pretty much targeted only for people with a developer background – that is, the ‘geeks’. To use DI API directly, you need to have a good grasp of elementary programming concepts and you need to be able to read API documentations. The tools required (such as Visual Studio or Delphi) for writing and debugging code are not always available (not installed and/or no license bought) in the customer’s production environment.
For a single-shot data modification task, there’s quite an overhead having to do the full cycle of writing, compiling, testing, deploying and finally running the code in the customer’s environment. There is also quite a lot of ‘plumbing code’ involved in order for such basic stuff as initiating the B1 session. Of course, the basic plumbing stuff can be copied from another project, but it’s still a bit messy.
For those things that DI API cannot do, one might try some even hairier kludges such as the SendKeys method in either the UI API or from .NET Framework. However, these are even less approachable to the wider audience than the DI API.
None of the methods discussed above are intrinsically superior over each other. Sometimes a Caterpillar is better than a shovel and a shovel is better than a spoon, but not always. The selection of the most optimal tools depends on several variables, such as:
- The number of records that need to be modified
- The kind of modification required (create/change/delete)
- The overall complexity of the task
- The skills of the people available for the job
- The tools available in the customer’s environment
- Recurrence: will this task be executed just once or perhaps repeated later ?
For instance, if you only need to delete 20 items once, the fastest method is obviously just to do it manually. However, when the number of items rises or the task is more complex and needs to be repeated over time (for instance, monthly contract invoicing), quite soon we are in a situation where taking the time to write a small application to do the task might save you valuable time and effort. That is, of course, if you have a developer available. While there are a big number of B1 consultants out there that do have a developer background, I think it’s safe to assume that most of them don’t.
Introducing DI Commander
Wouldn’t it be nice to have a tool that had the full power of DI API but was about as easy to use as the Data Transfer Workbench or SQL queries ? Something that could be learned and used by a non-developer who is somewhat familiar with such tools as spreadsheet formulas/macros, SQL queries and/or command line shells. This is where DI Commander (DIC) comes into picture. DIC makes it easier, faster and more flexible to execute data modification tasks such as those mentioned above, but simultaneously remain within the safe boundaries provided by DI API. While the main target audience is consultants who are not developers, I think there are lots of developers who also might find some use for DIC.
Get straight to the business
With DIC, you don’t need to care about initiating B1 sessions, as DIC does it for you. DIC supports multiple simultaneous sessions, so that you can for example read stuff from one B1 instance and write to another. The most interesting part of DIC is however the command host. My aim was to hide the complexities of “traditional” languages such as C# and VB in order to provide a more business logic -oriented user experience. While you can’t totally avoid writing code when using DIC, there are obvious quantitative and qualitative differences. In the quantitative sense, there is a lot less code to be written in order to get a job done. While the quantity of the code has been reduced, the code is also much more transparent, revealing what is happening on the business logic level. This should make it much more approachable for non-developers. DIC has a code editor window, but it also has a shell window that imitates a command prompt. For many potential users, the command prompt may be more familiar than a developer-oriented IDE.
I am not endorsing DIC as a replacement for real task-specific business applications. However, if you just want a job done quick’n’dirty, it will provide you with the tools of the trade.
DIC = IronPython with extensions
When I was reflecting on all the stuff I had previously done with C# and DI API, I realized that it was pretty much always variations from the same theme:
- Get a handle of one or several B1 business objects
- Run a query or read a file
- Based on the results of step 2 and using the handle retrieved in step 1, either create new records or modify/delete existing ones (or perhaps transfer the retrieved. data into another system).
- Repeat your selected mixture of steps 1-3 until you’re done.
Based on these findings, I decided to equip DIC with some extras in order to get the much needed performance boost for the mentioned tasks. To be more precise, I added the following functions to DIC by modifying the embedded IronPython engine:
get()
The get function is used for retrieving existing objects from the database or handles for creating new objects. It has four different variants:
- get(objecttype) ==> this will retrieve a handle for the specified objecttype from the default session.
- get(objecttype, key) ==> this will retrieve the instance of the specified objecttype with the specified key, if it exists in the database.
- get(objecttype, session) ==> this will retrieve a handle for the specified objecttype from the specified session.
- get(objecttype, key, session) ==> this will retrieve the instance of the specified objecttype with the specified key from the specified session, if it exists in the database.
For instance, to get a handle to the order nr. 50 that exists in the database, all you need to type is:
myOrder=get(ORDER, 50)
Now that you’ve got the handle, you could access the values like this:
myOrder.CardCode
…or perhaps update some value in the order:
myOrder.Comments="Just testing"
update(myOrder)
The objecttype parameter is a member of the BoObjectTypes enumeration. DIC generates a helper constants for each BoObjectType in DI API as follows:
- oInvoices ==> INVOICE
- oItems ==> ITEM
- oBusinessPartners ==> BUSINESSPARTNER
- oAccountSegmentationCategories ==> ACCOUNTSEGMENTATIONCATEGORY
- etc.
If you are familiar with DI API documentation or DTW, you perhaps noticed that the helper constants are without the ‘o’ prefix and in singular form for clarity. If you prefer to use the original DI API notation for BoObjectTypes, you can do that as well. Just remember to type the whole namespace (for instance, SAPbobsCOM.BoObjectTypes.oInvoices instead of INVOICE).
By far the most important of the added functions is browse. Because DI API has been implemented as a COM object, its enumeration support in .NET environment leaves a lot of room for improvement. The browse function is used to create a multipurpose .NET enumeration wrapper for a variety of B1 objects:
- Objects that have the Browser property that can be mapped to a resultset
- “Line” objects that have the property Count and method SetCurrentLine. For Instance, Document_Lines and BPAddresses.
- Resultsets
With the enumeration interface in place, these object collections can be treated as any list in Python. With remarkable ease, that is.
There are five variants of browse():
- browse(objectinstance) ==> The specified object instance must have the property Count and the method SetCurrentLine (for instance, Document_Lines and BPAddresses). It will return an enumeration of all the line instances of the given object instance.
- browse(objecttype, recordset) ==> Gets a handle of the specified object type and returns an enumeration of the object instances specified by the recordset (using the default session).
- browse(objecttype, recordset, session) ==> As above, but uses the specified session instead of the default session.
- browse(recordset) ==> Returns an enumeration of the first column in each line contained in the recordset.
- browse(recordset, columnname) ==> Returns an enumeration of the specified column in each line contained in the recordset.
For instance, to iterate the items in an order, you might type:
myOrder=get(ORDER, 50)
for myline in browse(myOrder):
print myline.ItemCode
print ","
query()
The query function is used to retrieve a Recordset from DI API according to the specified query. It has two variants:
- query(querystring) ==> this will retrieve a Recordset object from the default session using the specified query.
- query(querystring, session) ==> this will retrieve a Recordset object from the specified session using the specified query.
The Resultset retrieved by the query function can then be enumerated using the browse function.
add()
The only reason for the existence of the add function is syntactical consistency with the other new functions. All is does is call the Add() method of the specified object instance):
- add(objectinstance)
update()
As with the add function, the only reason for the existence of the update function is syntactical consistency with the other new functions. All is does is call the Update() method of the specified object instance):
- update(objectinstance)
remove()
The remove method can be used to removing any object that has the Remove() method. Naturally, the object can only be deleted if the consistency rules of B1 allows it to be deleted.
There are three variants of remove:
- remove(objecttype, key) ==> Removes the object instance of the specified type if found by the key using the default session.
- remove(objecttype, key, session) ==> Removes the object instance of the specified type if found by the key using the specified session.
- remove(objectinstance) ==> Added only for syntactical consistency. Simply calls the Remove() method of the given object instance.
The DIC user interface
As you can see from the image above, the current user interface of DIC is rather spartan.
Top of the screen
Shell tab
The shell window imitates a typical command prompt. It includes such functions as command history that can be accessed using the arrow keys. Currently, the shell window does not support statements that span several lines. However, you can combine multiple commands on a single line by separating them with semicolons.
Trace tab
The shell window will only show a short error message when an internal exception is caught. The Trace window will contain more details (stack traces etc). Normally you should not need to use the trace tab at all.
Bottom of the screen
B1 Sessions tab
DIC can do the standard Python tricks even without logging in. However, in order to use the DI API, you need to initiate at least one B1 session by using the login screen (To be precise, you could do it straight from the code, but why bother?). DIC also supports the promiscuous mode, in which you can initiate multiple simultaneous sessions into different databases and do cross-database operations. For each session you initiate, you need to select a handle that can be used to refer to the session from the code. If you only have one session open, you don’t need to use the handle (as the single session is automatically defined as the default session), but even then you need to give the handle when logging in. The system suggests “session1” as the handle, but you can change it if you wish.
Code tab
This is an alternative to the Shell window. It works like a typical text editor: in addition to typing text, you can for instance copy and paste stuff around. Executing the code works a bit like the Query Analyzer window in MS SQL 2000: if nothing is selected, the application tries to execute every bit of code on the screen. If something is selected, the application will only execute the selected commands. Even when using the code window, the executed commands will be added to the command history of the shell.
Compared with the shell, the code window has a couple of bonuses. First of all, it supports multiple-line statements (just remember the indentation). Second, it also provides colour coding for the standard Python commands as well as for the functions added in DIC. Sorry folks, there’s currently no IntelliSense function in DIC. However, in the Shell window you can get a list of the available fields and methods of any object by using the dir() function (please see the image below). I guess you could call that poor man’s IntelliSense.
Working with Python
I will only scratch the surface of Python here. If you wish to get more thorough overview of the language, check out the Python.org website for a description of Python.
I chose Python as the language of DIC because Python has a very clear, human-readable syntax and it also lets you interact with live objects as you build your code.
As there are loads of excellent documents on Python out there in the web, I don’t want to write another Python tutorial here. Instead, I will just give a couple of pointers to some of the available tutorials:
- The ‘official’ Python tutorial provided by the Python Software Foundation
- A beginner’s Python tutorial by Steven Thurlow
If you prefer real books, I warmly recommend Learning Python by Mark Lutz and David Ascher (publiched by O’Reilly).
Learning to program Python is not really required in order to benefit from DIC. Basically you just need to know the new functions added in DIC and some very basic commands in Python to get by. That’s definitely not any harder than learning SQL.
I hope to be able to establish a public library of well-written DIC snippets in the future. This would make DIC even more approachable by the Layman.
Playing around with DIC
Before diving deeper into the sample scripts, there’s a few issues and conventions you should be aware of.
First of all, indentation (spaces and tabs) matter a lot in Python. They are used for identifying blocks of code that span several lines but belong to a single statement. These include for loops, function and class definitions etc. When you see an indentation in the sample code, it is there for a purpose. Omitting it will cause the code to fail (Please see the following image for an example on incorrect and correct indentation)
If you are a seasoned Python developer, you should also notice that there are a couple of Python conventions that are not currently supported by DIC (although they are supported in IronPython):
- While line spanning is supported in def and class statements, DIC does not currently support spanning lines ending with backslash (/)
- The ‘open pairs’ rule is not supported. Thus:
MyList = ["A","B","C"]
…is valid but the following isn’t (although it is valid according to Python conventions):
MyList = ["A",
"B",
"C"]
I apologize for these limitations. I was forced to skip some cleaning up in order to get DIC out in a decent amount of time. After all, remember that I’m distributing DIC for free and doing it just for fun.
Adding stuff
Let’s add a new order (with two lines) to the system:
myorder=get(ORDER)
myorder.CardCode='CUSTOMER1'
myorder.DocDate=System.DateTime.Now
myorder.DocDueDate=System.DateTime.Now
myorder.Lines.ItemCode='DEMOITEM1'
myorder.Lines.Quantity=10
myorder.Lines.UnitPrice=5.5
add(myorder.Lines)
myorder.Lines.ItemCode='DEMOITEM2'
myorder.Lines.Quantity=8
myorder.Lines.UnitPrice=3.7
add(myorder)
Modifying existing stuff
To update a couple of fields for a single Business Partner with the CardCode ‘CUSTOMER1’, you might type something like this:
bp1=get(BUSINESSPARTNER, 'CUSTOMER1')
bp1.Cellular="+358 50 4324 1332"
bp1.Notes="Just testing."
update(bp1)
To do a similar change for all the business partners who belong to the default customer group:
for customer in browse(BUSINESSPARTNER, query("select cardcode from ocrd where groupcode=100")):
customer.Notes="Testing batch."
customer.Freetext="Testing batch."
update(customer)
To change the password for all users in the database (for instance after making a copy of the production database for testing purposes):
for user in browse(USER, query("select user_code from ousr")):
user.UserPassword="test"
if update(user)==0:
print user.UserName + ":OK "
else:
print user.UserName + ":Update failed "
To lock the warehouse 01 on all items in the database:
for itm in browse(ITEM, query("select itemcode from oitm")):
for whs in browse(itm.WhsInfo):
if whs.WarehouseCode=="01":
print " Locking warehouse 01 for item "+itm.ItemCode+":"
whs.Locked=SAPbobsCOM.BoYesNoEnum.tYES
update(itm)
Deleting stuff
The following examples focus on deleting items from the database. This is something you cannot do with the DTW.
To delete a single item with ItemCode ‘DEMOITEM1’ from the database, just type:
remove(ITEM,'DEMOITEM1')
...you may also build the list of items by defining a list such as this:for itemcode in['A123','B124','C125']:
remove(ITEM,itemcode)
The above samples are nice for testing, but in a real world scenario you might perhaps want to read the itemcodes from a textfile with one itemcode per line:for itemcode in open("c:\\itemstodelete.txt"):
remove(ITEM, itemcode)
…OR you might wish to use a resultset from a query as a source for the item codes:rs=query("select itemcode from oitm where qrygroup64='Y'")
for itemcode in browse(rs):
remove(ITEM, itemcode)
Function calls can be nested for a more compact expression:for itemcode in browse(query("select itemcode from oitm where qrygroup64='Y'")): remove(ITEM, itemcode)
(As the above can be expressed on a single line, you can use it in the shell window)
Naturally, any of the above samples could just as well have been done for any DI API object types (BusinessPartners, Quotation documents etc). Simply replace the value of the objecttype parameter with the one you need. of the box (as long as the objecttype in question has the Remove() method in DI API).
For instance:for cardcode in browse(query("select cardcode from ocrd where cardtype='L'")):
remove(BUSINESSPARTNER, cardcode)
…this will remove all the BP’s with type ‘Lead’ from your database (Please note! The same limitations apply as for the Remove() method in DI API. Thus, if there are transactions linked to a BP, it cannot be deleted).
Installing DIC
Click here to get the latest version (R1.0 PL 3) of DIC. Currently only the binary version is available. I have not yet decided whether to publish the source code.
Installation is about as quick’n’dirty as you might expect: just unzip it and you’re ready to rock’n’roll.
System Prerequisites
In order to get DIC up and running, you need to have a correct version of DI API installed. DIC was compiled against DI API 2005 SP1 PL23, but hopefully it will work fine against any version of DI API 2005.
In addition to DI API, you also need to have version 2.0 of the .NET Framework installed.
UPDATE: Are there safety issues with DIC ?
I’ve recently received comments and warnings from several people who’ve assumed that DIC is poking the database directly using SQL queries. I thought it would become clear from all that’s written above, but obviously it wasn’t: ALL THE DATA MANIPULATION OPERATIONS DONE WITH DIC ARE EXECUTED VIA THE DI API CALLING THE Update(), Add() and Remove() METHODS PROVIDED BY THE DI API OBJECTS. Thus, DIC is safe as milk. Or at least as safe as the DI API.
UPDATE 2: The name is lame, but the tool works all the same (Jan 18, 2008)
Recently, I was contacted by the moderators of this portal. It turned out that some people had somehow associated the acronym formed from the previous name (B1 Turbo Command Host) with some kind of an insult. Well, I apologize for that.
Still, if we start going down that road, it quickly becomes a slippery slope. There are simply too many words with several meanings and too many acronyms that may give wrong impressions when pronounced as a word. Try replacing “1” with “i” and pronouncing some of the most common acronyms used in the B1 Forum, then look up those words in Wikipedia. You might be surprised by what you find.
Anyway, I decided that it’s better to change the name than to be totally censored. Thus, B1 Turbo Command Host is now DI Commander. I sincerely hope that this new name does not aggravate anyone. If it does, then the Beauty is certainly in the Eye of the Beholder..
Regards, Runar W.
Could you please send me the script you executed? I’m sure we can work it out if I see the script.
I am currently working on the second release of DI TCH and it will contain a wizard (or perhaps “witch” is a more appropriate name) that makes generating scripts easier.
Henry
Sorry for the late respons to your answer regarding my trouble with updating BPs. The code I used is a stripped down version of one of the examples in the blog.
for customer in browse(BUSINESSPARTNER, query(“select cardcode from ocrd”)): customer.Notes=”Testing batch.”
update(customer)
This affected only my suppliers. But, never mind, because what I really was going to do (eventually) was adding and updating the PaymentMethod for all BPs in my system.
Is it possible for you to provide some syntax on how to do this?
for customer in browse(BUSINESSPARTNER, query(“select TOP 10 cardcode from ocrd”)): customer.Notes=”Testing batch.”
update(customer)
and
then i executed
bp1=get(BUSINESSPARTNER,’C000004′)
bp1.Cellular=’555-555′
update(bp1)
the result is FALSE and i can’t executed please help!
My code i executed from tab CODE.
Could you try this:
bp1=get(BUSINESSPARTNER)
bp1.GetByKey(“C000004”)
bp1.Cellular=”555-555″
update(bp1)?
Without seeing your script, I could imagine that the problem lies within the query that it’s using as the key source. Most likely your query contains something that blocks the suppliers out.
For instance, the sample query mentioned in the blog will only process business partners with BP group code 100. It is worth noticing that supplier and customer group codes are stored in the same table (OCRG). Normally, code 100 refers to a customer group.
Henry
When I try updating with a standard B1 field like Cellular everything works fine, but when trying to work with a User Defined Field I always get error message “A general error occurred. See the trace tab for details.” Will the program allow you to update a UDF?
To recreate, I did the following:
>>>bp1=get(BUSINESSPARTNER, ‘C30000’)
>>>bp1.Cellular=”+358 50 4324 1332″
>>>bp1.Notes=”Just testing.”
>>>update(bp1)
This worked fine and updated both the Mobile Phone and Remarks field.
I then Added a UDF called udf to the Master Data Business Partner. System information shows this as OCRD.U_udf. When I edited the sample to:
bp1=get(BUSINESSPARTNER, ‘C30000’)
bp1.U_udf=”55″
update(bp1)
It fails.
The DI API handles UDFs in a slightly different way than the ‘normal’ fields.
Try this:
bp1=get(BUSINESSPARTNER, ‘C30000’)
bp1.UserFields.Fields.Item(‘U_udf’).Value=”55″
update(bp1)
This is definitely something that could be done in a more user-friendly way in DI TCH. I’ll put it on my tasklist.
Henry
That worked. I had read about the formating in the SAP SDK help, but couldn’t quite figure out that syntax. I’d definately look forward to an update, but I’ll keep going with the corrected syntax. Thanks for the help.
One other piece of feedback, I know that when working with DTW, being case sensative is required, but I would love to see the code tab not be case sensative in DI TCH.
Thanks for putting this out there, it is a cool tool.
I want to try di tch, but I can’t login (SBO-Common Error -111) on SBO 2007.
Am I doing something wrong or does the tool not work on 2007) version?
Best regards,
Wim Kleinsman
I guess you are using MSSQL 2005 ?
This is something that I’ve run into after releasing DI TCH 1.0: with B1 2007 and MSSQL 2005, the db server type field can no longer be omitted in the login procedure, otherwise the login will fail.
I hope to be soon able to release a new version of DI TCH that would among other things also accommodate the selection of db server type (MSSQL, MSSQL2005, Sybase, DB2).
Henry
Thanks for this tool. It looks very useful. But unfortunately it can’t be used with SAP B1 2007A and MSSQL2005. Do you know when will be available version with support for these?
Thank very much
Lukasz Chomin.
Please see the download page. Now there is a patch that fixes the problem.
Henry
Unfortunately I couldn’t download the new patch as there was a message:
The requested URL /public/DITCH1.0PL3.zip was not found on this server.
Can you check if the URL is correct or the file is uploaded?
Thank you very much once again,
Lukasz Chomin.
I’m sorry, there was a typo in the name of the zip file. Now it’s corrected and you should be able to download it.
Henry
I would like some help in updating the avgprice field for a certain item say x0004 in warehouse 01.
for item in browse(ITEM, query(“select itemcode from oitw where whscode=01” and itemcode=x0004)):
item.avgprice=”100.”
update(item)
I have used whs.avgprice as well but still it does not work.
Any suggestions??
Thanks in advance.
Jacques
There a couple of typos in your script. I will not go into detail with them, but here’s a couple of syntactically correct versions. Anyway, please pay attention that the fieldnames are case sensitive when calling the DI API objects (on the other hand, it doesn’t matter so much with the queries).
As you are only updating a single item, you don’t need call browse. Instead, you can do it like this:
item=get(ITEM,’x0004′)
item.AvgStdPrice=100
update(item)
The above sample will work if your item’s valuation method is standard and you *don’t* manage stock by warehouse (thus the avprice is set on the header level).
As I could imagine from the query you were trying to run that you *do* manage stock by warehouse, it will be slightly more complicated
item=get(ITEM,’x0004′)
item.WhsInfo.StandardAveragePrice=100
update(item)
…this one will set the std price for the first warehouse linked to the item. If you have several, you need to either browse them or call SetCurrentLine one by one. Please note that in the DI API the field for std avg price has a different name on header level and on warehouse level.
Regards,
Henry
Congratulation, this is a very good tool, and it is a very good idea to use Python for this.
I just have a question:
How do you have registered the SAPbobsCOM dll in Python?
Do you use the ctypes library or IronPython ? I have tried with ctypes, but it does not work.
Thank you.
It’s as simple as this:
import clr
clr.AddReferenceToFile(“Interop.SAPbobsCOM.dll”)
import SAPbobsCOM
In this case, you need to have the Interop.SAPbobsCOM.dll in the same directory with the executable. Otherwise, you could make a strongnamed version of SAPbobsCOM and place it in the Global Assembly Cache.
Henry
Great tool, already saved me hours from the Monkey Method.
I have a number of ITEMS I wish to cancel.
Can you tell me if the Cancel method has been implemented?
I would have expected the following to work:
itm=get(ITEM,’A00023′)
cancel(itm)
I can see Cancel is listed from dir(itm) and so I tried:
itm.Cancel
But still the item record is not cancelled.
Any ideas or pearls of wisdom.
Gary.
I’m glad you like DI TCH.
Regarding your problem, could you try this:
itm=get(ITEM,’A00023′)
itm.Cancel()
This is good input for the next version. I will add direct support for the cancel method.
Also, I will change all the implemented methods so that they will return a boolean value (true/false) instead of a number. This will make the scripts a bit more elegant.
I think this tool is just great. Is there a way to use the BeginTransaction – EndTransaction methods?
If not, I know that you don’t have much time for this, but could you include this in the next version? It’d be very helpful.
Congrats!
Ian
Thanks for the feedback. I’m glad there are people out there who’ve found this tool useful.
Regarding your question about transactions: yes, surely you can do that with DI TCH. Actually all the functionality of DI API is available to you in DI TCH, although the more obscure functions have to be accessed with a bit more complex syntax.
Here are two samples on using transactions: the first one is ended with a commit and the second one with a rollback. Thus only the first item ends up really being added to the database.
session1.StartTransaction()
itm=get(ITEM)
itm.ItemCode=”ABCTEST”;
add(itm)
session1.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)
session1.StartTransaction()
itm=get(ITEM)
itm.ItemCode=”ABCTEST2″;
add(itm)
session1.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
= = = =
I think I might add these simplified commands in a future version:
starttransaction
rollback
commit
…these would be using the default session.
For other sessions, the syntax would be:
startransaction(sessionhandle)
rollback(sessionhandle)
commit(sessionhandle)
Thanks, actually things have a little more sense now 😛 . I tried to push it a little more a tried to add a UserDataField (you know a metadata operation), and got the error -1120 (no error message). I thinks that’s the typical for the instanced recordset, so I guess you have an instanced recordset (maybe for the search function?). In .Net the oRecordSet = null; GC.Collect(); works fine. Can please tell me how to do it in DI TCH?
You know, scripting the add of UDF is better than monkey doing it, plus you can add fields to not exposed tables in the SBO client (currencies, transaction codes, banks, and a LARGE etc).
Congrats again and thanks a lot,
Ian
Please suggest.
Regards,
Pankaj Mathur
Yes it is. It goes like this (assuming you used the default session handle):
session1.XmlExportType=SAPbobsCOM.BoXmlExportTypes.xet_ExportImportMode
Henry
Thanks a lot for this great tool,i downloaded the new version (DITCH1.0PL3) and i’m facing a problem while after refreshing:
I entered the Session handle, username, password, Server,DB userid and after i press the Refresh Button i got:
“Fail to get company list(perhaps you should try DB direct):Connection to SBO-Common has failed”
well i tried the DB direct and it isn’t working. Also i tried to change from MSSQL2005 to MSSQL and also it’s not working.
I didn’t faced this kind of problem with the older version.
what i should now?
Thanks a lot
here is my email(johnny.aboughannam@medialog.biz)
When you check the DB Direct checkbox, you should type the name of the SQL Server database instead of the name of the company in the database field (for instance, SBODemo_US instead of the name of the demo company).
I hope this helps.
Henry
Thank you for this usefull tool.
I have a problem. I wish I could change the cardtype value of various BusinessPartner. I tried this code with one of them but it didn’t work.
bp=get(BUSINESSPARTNER,’003282′)
bp.CardType=’cLid’
update(bp)
DI TCH returns : ‘__ComObject’ object has no attribute ‘CardType’
Can you help me ?
Guillaume
This should do the trick:
bp=get(BUSINESSPARTNER,’003282′)
bp.CardType=SAPbobsCOM.BoCardTypes.cLid
update(bp)
However, keep in mind that you can only change the CardType if there are no transactions linked to the business partner.
Henry
Guillaume
I would like to know if it is possible to write into file from DI TCH.
Thanks a lot for your answer.
Cheers,
Sure you can. The easiest way to do this is by using the standard Python syntax.
Try this:
filename = “c:\DITCHtest.txt”
file = open(filename, ‘w’)
file.write(“Hello from DI TCH !”)
file.close()
Just for information, DI TCH has full support for .NET 2.0. Thus, you can use any .NET 2.0 library such as System.IO from DI TCH. However, the above mentioned Python-oriented way is more in line with the basic idea of DI TCH (with emphasis on compact syntax that lets you do lots of things with just a few lines of code).
Thanks again for your very useful tool.
I have such problem. I update items group code in that way:
for item in browse(ITEM, query(“select * from oitm where itmsGrpCod = 100”)):
item.ItemsGroupCode=113
update(item)
It works great but from time to time I get return code -5002 for some items and these items group code is not changed. Changing the group code by SAP B1 Client Application is working without any problems.
Where can be the problem? Is it related to your tool or DI API?
I try to remove one of the assigned Warehouses from Item Master Data but I couldn’t achieve this.
I tried in different ways but no luck e.g:
for itm in browse(ITEM, query(“select itemcode from oitm where itemcode = ‘0125420517MB'”)):
for whs in browse(itm.WhsInfo):
if whs.WarehouseCode==”PL”:
remove(SAPbobsCOM.BoObjectTypes.oWhsInfo,itm.WhsInfo)
Is it possible? How to do this?
Thank you very much in advance for any help.
Unfortunately this is a major shortcoming of the DI API: there is no Remove() method for the ItemWarehouseInfo class. As DI TCH is using DI API to get things done in the database, it thus has the same problem.
In fact there is no Remove() method for any of the “lines” objects that are accessed through a parent object (for instance, Document_Lines and EmployeeRolesInfo).
The problem of not being able to remove ItemWarehouseInfo records is especially painful. I’ve seen lots of cases where the system has been set up to automatically link all items to all warehouses. Then, a user accidentally adds a new warehouse (the code of which is quite often ‘*’ :-). In a few seconds, a whole bunch of new ItemWarehouseInfo records has been created. It’s not a funny thing to remove them manually if you have a few thousand items or more.
You Said we cannot remove warehouse from item information, but is it possible to update one warehouse insted of another.
Example:
I have item with code FR0008.
And warehouses as A,B,C.
This item is Assigned to Warehouse A and B. Now I want to Update this item by assigning to A and C warehouse only and i want to Remove B. Is it possible to do like this.
Or is it possible to change the code of warehouse from B to C.
Thanks & Regards
P Siva Reddy
miOrden=get(ORDER, 19946)
misLineas = miOrden.Lines
misLineas.SetCurrentLine(2)
misLineas.Delete()
update(miOrden)
With SBO 2007 PL46 and newest B1TCH version
Greetings,?
I’m a fan of python language and now of SAP/B1.
We are trying to create some automated processes and we are trying to do it with your tool. Writing the script in the tool, all it’s ok, but doing from outside it’s so dificult/easy than with di-api, can you show us a little example of these, perhaps only for us, functionality?
For example: c:\> b1tch.exe importInvoice.py
Inside importInvoice.py, manage connection, instantiate classes, etc…
First of all, i’m not sure if it’s possible!? or even if you see thats it’s a good idea.
I have problem updating invoices:
rs=query(“Select T0.DocEntry AS DocEntry FROM OINV T0 INNER JOIN ORCT T1 ON T0.ReceiptNum = T1.DocEntry INNER JOIN OSLP T2 ON T0.SlpCode = T2.SlpCode WHERE T0.CANCELED = ‘N’ AND AND T2.SlpCode = ‘1’ “))
for DocEntry in browse(rs):
myinvoice=get(INVOICE, DocEntry)
myinvoice.UserFields.Fields.Item(‘U_I_Prov’).Value = “2”
update(myinvoice)
I don’t know why, but it doesn’t work. I tried it without the get-part, but it doesn’t work, too.
Maybe you can give me a hint where my mistake lies.
Thanks,
Thomas
Could you give me more details regarding your problem, such as:
– The error message that you receive ?
– The version of DIC that you are using? (I warmly recommend version 2.0)
– The type of your user-defined field (U_I_Prov)
Best Regards,
Henry
This tool is really useful and I have already used it to remove numerous inactive items by writing a simple query.
I have another issue at the moment and I was wondering whether this can be used. Basically I have an excel spreadsheet containing an Item Code and UserText (this is the Item Remarks field) and I need to update the UserText field for over 2000 items.
I used to be able to import the UserText using DTW but now this is a 10 character field and I cannot update them.
Can I use this tool? If so what would the command be? the file is located in c:\usertext.xls and the spreadsheet has 1 header row but this can be removed (or a 2nd header row added) if needed.
Please advise, many thanks,
Adrian
I tried to Cancel Sales Orders with the following:
myorder=get(ORDER)
myorder.Cancel()
but I receive ‘-2028’
Any Idea?
You need to retrieve the order by key, which in this case is the docentry of the order. The script for canceling an order with docentry 667 would be:
myorder=get(ORDER)
myorder.GetByKey(667)
myorder.Cancel()
Best Regards,
Henry
I am very happy to found out this tool today.I am trying to test it if i can update the status of the order . Can you please help me on this .
Could you please give me more details in which way you wish to update the status? Do you want to close it or do something else ?
Henry
I’m trying to change the GL Determination method of an Item (set it to Item Level) and then set the various accounts for that item but when I run the code: MyItem.GLMethod = ‘glm_ItemLevel’ I get a general error. The trace window gives me this:
at B1TCH.frmMain.ProcessCommands(String input, Boolean echo)System.MissingMemberException: ‘__ComObject’ object has no attribute ‘GLMethod’
Any ideas on how to do this and also how to set the various GL Accounts?
Thanks for the tool though, its mighty handy. Best suggestion I can make is to add more examples of how to use it: maybe some of the other users can just paste in examples of their working code/queries.
Regards
Edu
how can I do this task?
I’m afraid I have to disappoint you with this one. Removing warehouse links from items is one of those rare things that you cannot do with DI API. Therefore you neither can do this with DI Commander, as it is dependent on DI API.
The phenomenon you’re experiencing is a well known irritation in B1. If you have the setting “link all items to all databases” active when you accidentally create a new warehouse, B1 really creates a link from all items to that warehouse. I really think this should be fixed so that these links would only be created for *new* items that are added after the warehouse was created.
I guess you don’t want to revert to a backup copy. Then the only “officially supported” way to get rid of the extra warehouse is to manually eliminate all those links from OITW table to the new warehouse and then finalln delete the warehouse itself.
Best Regards,
Henry
Thanks again for this very useful tool.
I have strange message when I try to update UDF for item. I run this code which I think should be correct:
for item in browse(ITEM,query(“select ItemCode FROM OITM WHERE ItemCode=’A-001′”)):
item.UserFields.Fields.Item(‘U_ThermDecomp’).Value=”Test”
update(item)
unfortunatelly I always get the error message:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Do you maybe have any idea what’s wrong with my code?
Thanks in advance.
Lukasz Chomin
Login failed: Failed to connect to SBOCommon(-111)
Have any solution?
Thanks
In order to add support for SQL 2008, I will need to tweak the source code a bit and recompile the application against DI API 2007. I will try to do this ASAP.
Has this been done?
Working version for SQL2008
Thanks,
Wynand.
I have integrated B1TCH (it’s now known as Python Console) to a new toolkit that I’ll be releasing shortly. It is called DI Construction Kit and it’s compatible with MSSQL 2008 as well as B1 8.8. (as well as the previous db/B1 versions).
Send me your email address (for instance via LinkedIn) and I’ll deliver you a pre-release version of the new toolkit.
Now the first official release (R2.01) of DI Construction Kit is finally available free of charge with full source code at
It is licensed under GNU Lesser GPL 3.0
The Python tool that was previously known as DI Commander / B1 Turbo Command Host is now fully integrated to DI Construction Kit. Naturally, it supports both B1 8.8 (as well as 2007) and MS SQL 2008.
I will start a new series of blogs about the ways in which the toolkit can be used. The first blog is already submitted to SDN but still pending for approval. Anyway, you can download the blog as a pdf document together with the toolkit from the mentioned link.
Thank you and keep up the good work!
It would be great if DIC could be updated to work with MSSQL 2008. Please let us know if this is in planning.
I’m not a Python expert but if you’re not planning to update it would it be possible to get the source code so that I can take a shot at the update. This tool is way too handy to live without…
Regards
Edu
I surely am planning to release a new version of DI Commander, with some nice new features and support for B1 2007/SQL 2008. I cannot give any promises about the schedule, though.
Regarding the source code, did you notice from the more recent DI Commander blog that the full source code for DIC 2.0 is already available. You will find the link to the source code from here:
Best Regards,
Henry
A few hours after I asked for the source code I stimnbled onto your other weblog where the source code is stored.
I downloaded it, added SQL 2008 to the options list, added a reference to the latest version of SAPbobsCom and recompiled.
Not sure how many things I’ve broken buy doing this but so far all functions I’ve tried have worked. The best thing was that you can now delete Warehouses through DI. DIC probably saved me 2 days of pain.
I can upload the compiled version (if you think its wise and if I can figure out how/where to upload it).
You mentioned in your other blog that you’re working on something called myBolt. Is this a private project or is there somewhere where we can get more information on it (and I’m assuming it has something to do with integration).
Thanks again for this amazing tool.
Edu
Is there any news about a version supporting SQL2008. Thank you for the tool that is very useful.
BR
I tried using the example of item delete to delete drafts.
My code (simple when this works I will change to delete all CLOSED DRAFTS):
for docentry in browse(query(“select docentry from odrf where docentry =282”)): remove(DRAFT,docentry).
Error:
Invalid argument: expected BoObjectTypes, got int
Kind Regards
Eric Walker
Regards
Shankar
Dear Henry,
How If I want to remove data from an UDT ?
I try command :
is there any new update for this app ??
As an equivalent you can script over B1 DI API with Microsoft Powershell.
What Henry did is great but needs to be updated.
With Powershell you can use it with any version of B1.
Hi Henry ,
Do we have a supported version for SAP 9.1 and SQL 2012 . This is one of the great tools i have used over the years to remove /clean up data . Please update if there is one available to use
thank you | https://blogs.sap.com/2007/08/19/get-your-kicks-with-di-commander/ | CC-MAIN-2019-04 | refinedweb | 8,069 | 63.9 |
Custom Media attached to Conversations
With Flex and call recording enabled you can drill down from Flex Insights Historical Reporting directly to calls and chat transcripts. You can listen to a call recording related to call conversation. You can read a chat transcript related to chat conversation done via Twilio Programmable Chat.
You can attach a list of custom media can point to additional media or other resources related to a conversation or its segments. Custom media can be used to:
- Attach call recordings stored in an external system
- Attach related CRM records
- Attach related ticketing system items
There can be multiple media attached to each conversation and users can switch between in the user interface.
Adding media links overrides the references to default call recording and default chat transcript. To reference the original call recording or the original chat transcript together with custom media you need to list the original recording and chat transcript in the media links yourself.
Add Media Links
Each segment can have multiple media links related to it.
You can provide links on task level and/or on reservation level:
- Task-level media links. The media links are attached to all segments related to the task.
- Reservation-level media links. The media are attached to all segments related to the reservation. Reservation-level media links override task-level media links. If a reservation has related media links no media links from the task level are attached.
Example TaskRouter attributes structure for task-level media links:
"task_attributes": { "conversations": { "media": [ // media links list goes here ] } }
Example TaskRouter attributes structure for reservation-level media links:
"task_attributes": { "reservation_attributes": { "<reservation_sid_1>": { "media": [ // media links list goes here ] } } }
Raw Media Link
Raw media link is passed as-is to Historical Reporting.
This means that on drill down either the link is opened in a new browser tab or you can respond to clicks on that link and create custom drill down behavior in Flex.
"task_attributes": { "conversations": { "media": [ { "type": "Raw", "url": "", "title": "CRM Conversation Record" } ] } }
Embedded Media Link
Embedded media link enables you to show custom webpage in an iframe on Conversation Screen. This type of media links is useful for referencing tickets, CRM records and similar content related to conversations. The application that you embedd has to support unique and URLs for records that you are interested it so you can point to th content directly relateed to a conversation.
"task_attributes": { "conversations": { "media": [ { "type": "Embedded", "url": "", "title": "Support Ticket" } ] } }
Some web applications do not enable to embed their content or require configuration on their side to enable embedding. In case a web application does not enable embedding use the referenced media link type.
Referenced Media Link
Referenced media link is useful for pointing to external web pages related to a conversation. Referenced media links are shown as links in Conversation Screen.
"task_attributes": { "conversations": { "media": [ { "type": "Referenced", "url": "", "title": "External Ticket" } ] } }
Voice Recording Media Link
VoiceRecording references a voice call recording that users can playback and listen to in case they drill down to a conversation. VoiceRecording media are also processed by Speech Analytics Essentials to detect silences, agent talk and customer talk.
"task_attributes": { "conversations": { "media": [ { "type": "VoiceRecording", "url": "", "start_time": 1574350320000, "channels": [ "customer", "others" ], "Title": "Dual channel recording" } ] } }
When call recording is enabled in Flex you do not typically have to provide link to a voice recording.
The start_time attribute needs to be in miliseconds (i.e. 1574350320000).
Chat Transcript Media Link
Chat Transcript media link references a chat transcript made by Twilio Programmable Chat.
"task_attributes": { "conversations": { "media": [ { "type": "ChatTranscript", "sid": "CHxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } ] } }
Multiple Media Links
Media links list can have multiple items in them. When users drill down to a conversation with multiple media attached to them they can switch between them.
In the following cases there is a specific behavior for media links:
- When Raw media link is on the first position in the list then when customers drill down to a conversation Conversation Screen does not open. The Raw media link is open in a new browser window/tab. The other media links are not accessible from Flex user interface.
- Only the first VoiceRecording media link in the list will be procced by Speech Analytics Essentials for silences, agent and customer talk time.
The following example shows multiple media links in a conversation. The Conversation Screen will offer users to switch between the chat transcript and the embedded content. Also the voice recording will be analyzed by Speech Analytics essentials and available for playback.
"task_attributes": { "conversations": { "media": [ { "type": "Embedded", "url": "", "title": "Support Ticket" }, { "type": "ChatTranscript", "sid": "CHxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, { "type": "VoiceRecording", "url": "" } ] } }
Respond to Drilldowns in Historical Reporting
When users click on a conversation in Flex Insights Flex shows either a call, chat transcript or a list of custom media provided via TaskRouter attributes. Users can change this behavior. The primary use of custom response to drill downs is to respond to Raw media links.
import { Actions } from "@twilio/flex-ui" Actions.replaceAction("HistoricalReporting:view", async (url, original) => { // implement your own handling of URL or call original(url) to use the original handler })
Developers can decide whether they want to handle each drill down themselves or pass it to Flex to handle the drill down. This can be based on the URL that a user clicked or based on any other conditions.
Need some help?
We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow. | https://www.twilio.com/docs/flex/wfo/custom-media-attached-conversations | CC-MAIN-2020-40 | refinedweb | 911 | 51.68 |
Reinforcement Learning – The Multi Arm Bandit Problem using TensorFlow
Introduction
The n-arm bandit problem is a reinforcement learning problem where the agent is given n bandits/arms slot machine. Each of the arms of a slot machine has a different success probability. Pulling any one of the arms rewards the agent i.e., success or a failure.
The agent’s objective is to pull the bandits/arms one at a time such that it maximizes the total reward collected as the process ends. Moreover, the problem statement defines that the agent does not know the probability of success of the arms. It gradually learns through the process of trial and error and also by estimation of value.
Methodology
In this blog, we learn to use the policy gradient method which uses TensorFlow and creates a simple neural network that consists of weights corresponding to each of the possible arms’ probability of fetching the reward of the slot machine. In this method, the agent chooses an arm of a machine based on an e-greedy approach. It means that mostly the agent would choose the action that corresponds to the largest expected value, but sometimes it also chooses randomly.
In this way, the agent tries out each of the different arms to continue to learn more about them. Once the agent has taken an action i.e., chooses an arm of the slot machine, it then receives a reward of either 1 or -1.
Practical Code Implementation
Below is a short implementation of the n-arm/multi-arm bandit problem implemented in Python programming language:
We take n=6 for our code implementation (6 arms of slot machine) and their numbers as [2,0,0.2,-2,-1,0.8].
We will gradually find out that the agent learns and successfully chooses the bandit which fetches the largest reward.
Import necessary libraries
import numpy as np import tensorflow.compat.v1 as tf tf.disable_v2_behavior()
The function tf.disable_v2_behavior (as the name suggests) switches all global behaviors that are different between TensorFlow 1.x and 2.x to behave as intended for 1.x.
Finding rewards for the arms
We create a slot_arms array that defines our bandits. len_slot_arms stores 6 i.e length of array. The function finds reward() generates a random number from a normal distribution with a mean 0.
The lower the arm/bandit number it is, the more likely the agent returns a positive reward (1).
slot_arms = [2,0,0.2,-2,-1,0.8] len_slot_arms = len(slot_arms) def findReward(arm): result = np.random.randn(1) if result > arm: #returns a positive reward return 1 else: #returns a negative reward return -1
Our neural agent
tf.reset_default_graph() weights = tf.Variable(tf.ones([len_slot_arms])) chosen_action = tf.argmax(weights,0)
The function tf.rese_default_graph of the TensorFlow library clears the default graph stack and resets the global default graph. Lines 2 and 3 define the weights of the particular bandits as 1 and then do the actual choosing of the arm.
reward_holder = tf.placeholder(shape=[1],dtype=tf.float32) action_holder = tf.placeholder(shape=[1],dtype=tf.int32) responsible_weight = tf.slice(weights,action_holder,[1]) loss = -(tf.log(responsible_weight)*reward_holder) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001) update = optimizer.minimize(loss)
The above lines of code do the training. It first feeds the reward and the chosen action(arm) to the network. The neural network then computes the loss by the formula given below. This loss is then used to update the network for better performance.
Loss = -log(weight for action)*A(Advantage from baseline(here it is 0)).
Training our agent and finding the most probable arm/bandit
total_episodes = 1000 total_reward = np.zeros(len_slot_arms) #output reward array e = 0.1 #chance of taking a random action. init = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init) i = 0 while i < total_episodes: if np.random.rand(1) < e: action = np.random.randint(len_slot_arms) else: action = sess.run(chosen_action) reward = findReward(slot_arms[action]) _,resp,ww = sess.run([update,responsible_weight,weights], feed_dict={reward_holder:[reward],action_holder:[action]}) total_reward[action] += reward if i % 50 == 0: print ("Running reward for the n=6 arms of slot machine: " + str(total_reward)) i+=1 print ("The agent thinks bandit " + str(np.argmax(ww)+1) + " has highest probability of giving poistive reward") if np.argmax(ww) == np.argmax(-np.array(slot_arms)): print("which is right.") else: print("which is wrong.")
We train the agent by taking random actions and therefore receiving rewards. The above lines of code launch a TensorFlow graph, then a random action is chosen to which reward is picked out of one of the arms. This reward helps in updating the network and is also outputted on the screen.
Sample Output
Yet another very Informative post! 😊
Looking forward to many more Reinforcement Learning problems! 💯 | https://valueml.com/reinforcement-learning-the-multi-arm-bandit-problem-using-tensorflow/ | CC-MAIN-2021-25 | refinedweb | 799 | 51.75 |
This class handles threaded delivery of datagrams to various TCP or UDP sockets.
More...
#include "connectionWriter.h"
List of all members.
This class handles threaded delivery of datagrams to various TCP or UDP sockets.
A ConnectionWriter may define an arbitrary number of threads (0 or more) to write its datagrams to sockets. The number of threads is specified at construction time and cannot be changed.
Definition at line 38 of file connectionWriter.h.
string()
Creates a new ConnectionWriter with the indicated number of threads to handle output.
If num_threads is 0, all datagrams will be sent immediately instead of queueing for later transmission by a thread.
Definition at line 60 of file connectionWriter.cxx.
References ConnectionManager::add_writer(), and Thread::is_threading_supported().
[protected]
This should normally only be called when the associated ConnectionManager destructs.
It resets the ConnectionManager pointer to NULL so we don't have a floating pointer. This makes the ConnectionWriter invalid; presumably it also will be destructed momentarily.
Definition at line 371 of file connectionWriter.cxx.
References shutdown().
Returns the current number of things in the queue.
Definition at line 141 of file connectionWriter.cxx.
References DatagramQueue::get_current_queue_size().
Returns a pointer to the ConnectionManager object that serves this ConnectionWriter.
Definition at line 253 of file connectionWriter.cxx.
Returns the maximum size the queue is allowed to grow to.
See set_max_queue_size().
Definition at line 131 of file connectionWriter.cxx.
References DatagramQueue::get_max_queue_size().
Returns the number of threads the ConnectionWriter has been created with.
Definition at line 275 of file connectionWriter.cxx.
Returns the current setting of the raw mode flag.
See set_raw_mode().
Definition at line 305 of file connectionWriter.cxx.
Returns the current setting of TCP header size.
See set_tcp_header_size().
Definition at line 330 of file connectionWriter.cxx.
Returns true if the writer is an immediate writer, i.e.
it has no threads.
Definition at line 264 of file connectionWriter.cxx.
Returns true if the datagram is small enough to be sent over a UDP packet, false otherwise.
Definition at line 242 of file connectionWriter.cxx.
References Datagram::get_length().
false
Enqueues a datagram for transmittal on the indicated socket.
Since the host address is not specified with this form, this function should only be used for sending TCP packets. Use the other send() method for sending UDP packets.
Returns true if successful, false if there was an error. In the normal, threaded case, this function only returns false if the send queue is filled; it's impossible to detect a transmission error at this point.
If block is true, this will not return false if the send queue is filled; instead, it will wait until there is space available.
Definition at line 166 of file connectionWriter.cxx.
References Connection::get_socket(), DatagramQueue::insert(), and TypedObject::is_exact_type().
Referenced by DatagramSinkNet::put_datagram().
This form of the function allows the specification of a destination host address, and so is appropriate for UDP packets. Use the other send() method for sending TCP packets.
Definition at line 206 of file connectionWriter.cxx.
References Datagram::get_length(), Connection::get_socket(), DatagramQueue::insert(), TypedObject::is_exact_type(), NetDatagram::set_address(), and NetDatagram::set_connection().
Limits the number of packets that may be pending on the outbound queue.
This only has an effect when using threads; if num_threads is 0, then all packets are sent immediately.
Definition at line 120 of file connectionWriter.cxx.
References DatagramQueue::set_max_queue_size().
Sets the ConnectionWriter into raw mode (or turns off raw mode).
In raw mode, datagrams are not sent along with their headers; the bytes in the datagram are simply sent down the pipe.
Setting the ConnectionWriter to raw mode must be done with care. This can only be done when the matching ConnectionReader is also set to raw mode, or when the ConnectionWriter is communicating to a process that does not expect datagrams.
Definition at line 294 of file connectionWriter.cxx.
Sets the header size of TCP packets.
At the present, legal values for this are 0, 2, or 4; this specifies the number of bytes to use encode the datagram length at the start of each TCP datagram. Sender and receiver must independently agree on this.
Definition at line 319 of file connectionWriter.cxx.
Stops all the threads and cleans them up.
This is called automatically by the destructor, but it may be called explicitly before destruction.
Definition at line 342 of file connectionWriter.cxx.
References DatagramQueue::shutdown().
Referenced by clear_manager(). | http://www.panda3d.org/reference/1.7.2/cxx/classConnectionWriter.php | CC-MAIN-2013-20 | refinedweb | 724 | 51.44 |
Using a Raspberry Pi with MotorBee
The following details show how to control a
MotorBee using a program
written in Python running under the Raspbian operating system on a
Raspberry Pi model B single board Computer.
( If you are not familiar with basic Motor Bee functionality, more details can be found here )
The Raspberry Pi has two standard USB sockets. One of them is usually dedicated to the keyboard (or keyboard and mouse where a small USB hub has been used). It is assumed the MotorBee is connected via a standard USB lead to one of these ports or to a free USB port on a hub if one is connected.
The following simple example of Python Code is all that is required to turn on motor1, set it to half speed, set the servo to centre position, set the digital outputs and read the digital inputs on the MotorBee. Have a look at this code and then see the explanation that follows for detailed description of each of the lines.
import usb.core
dev = usb.core.find(idVendor=0x04d8, idProduct=0x005b)
if dev is None:
raise ValueError('Device not found')
else:
try:
dev.detach_kernel_driver(0)
except:
pass
dev.set_configuration()
speed1 = 128
speed2 = 0
speed3 = 0
speed4 = 0
motoronoff = 0b11110001
enable = 0x30
servo = 128
data=[4, speed1, speed2, speed3, speed4, motoronoff, enable, servo]
dev.write(2,data)
outputs = 0b11000011
data=[8, outputs]
dev.write(2,data)
inputs = dev.read(0x81,1)
print "Inputs = {}".format(inputs[0])b)
This uses one of the PyUSB functions to "find" the attached MotorBee. The way it finds the MotorBee is by checking all available USB ports to find the one with a device that has the unique identifier associated with the MotorBee. This identifier is made up to two parts: the Vendor ID and the Product ID. For the MotorBee this is the two hexadecimal numbers 0x04d8 and 0x005b respectively. If the device is found, the "dev" object is created for the MotorBee and can then be used for susequent operations on the MotorBee. It is only necessary to use this statement once in your program, but obviously, it needs to be before any other use of the "dev" functions.
if
dev
is
None:
raise ValueError('Device not found')
It is always good programming practice to check if the Motor MotorBee. When the MotorBee is first plugged into the USB port the operating system tries to be helpful and associates one of its standard drivers to deal with all operations to the board. We don't want this, but, with it "attached" to the MotorBee it won't then allow any other direct operations. This line "detaches" this driver from the MotorBee allowing us to access it directly. Note that this only needs to be done the first time the program is run after connecting the Motor MotorBee, it simply has one configuration which is it's default. However, this still needs to be "set" as the active one using the statement shown. This only needs to done once in your program and before any other code that communicates with the MotorBee.
speed1 = 128
speed2 = 0
speed3 = 0
speed4 = 0
motoronoff = 0b11110001
enable = 0x30
servo = 128
data=[4, speed1, speed2, speed3, speed4, motoronoff, enable, servo]
The Motor MotorBee consists of a message type number and seven 8-bit numbers that correspond to the required settings for motors etc.. The message type number is simply '4'. This indicates to the MotorBee that it should use the following 7 numbers to set its outputs (motor speed, servo position etc...). Each number has been given a named variable above but it could just as easily have been entered as simple numbers into the data array. For example the above is equivalent to .....
data=[4, 128, 0, 0, 0, 0b11110001, 0x30, 128]
The "speed" variables hold the speed of each motor output (motor 1 to 4). The speed is in the range 1 to 255. Note that a speed of 0 is not allowed: To turn off the motor, you should use the on/off controls (described later).
When the motorbee outputs are being used to drive a motor in bi-directional mode, two outputs are used per motor and the numbers then correspond to the speed in a given direction. For example: If a motor is connected to the first two outputs so that it can be used in bi-directional mode the following example illustrates the principle ...
speed1=255, speed2=0 --> this produces maximum speed in the forward direction
speed1=0, speed2 =128 --> this produces half speed in the reverse direction
etc.. etc...
Note that in bi-directional configuration one of the pair of motor outputs MUST be set to 0, otherwise the motor will be trying to drive in both directions at the same time and will probably just stall or overheat.
The "motoronoff" variable uses the four least significant bits to turn the corresponding motor on or off (regardless of its speed). The bits associated with these outputs are shown below. Please note that the unused bits (bit4 - bit7) MUST be set to logic '1' as shown.
Motor On/Off Control Bits
A logic '1' corresponds to the associated motor being ON and logic '0' for OFF.
The "enable" variable is not used but is reserved for future releases of the board firmware. For now, it should simply be set to 0x30 to ensure the board is fully enabled.
The value of the "servo" variable specifies the position that the servo should go to and is in the range 1 to 255. Note: it depends on the servo used how this corresponds to the actual range of movement. Typically, the centre position is specified with a value of 128, -90degrees with 64 and +90 degrees with 192 .
dev.write(2,data)
Once the data sequence has been specified it is simply sent to the MotorBee using the "write" function within the "dev" object as shown. The number '2' used, is just the name of the internal buffer to use within the MotorBee, or , as previously mentioned, the USB "endpoint" number. For the MotorBee this is always set to 2. The MotorBee motor speeds, directions and servo position will now be set accordingly.
In the above description its worth noting that the first few lines may look slightly complicated but, once your program has "found" the MotorBee, detached the kernel driver (if necessary) and set the MotorBee configuration, the control of the MotorBee motors and servo is simply a case of using the "dev.write" function (with the appropriate data in the data array) as often as you like.
outputs = 0b11000011
data=[8, outputs]
dev.write(2,data)
inputs = dev.read(0x81,1)
The Motorbee also has some digital inputs and outputs which may be controlled. It has 4 digital outputs which are specified using a single byte of data with appropriate bits set. See diagram below....
Setting Motorbee Digital Outputs
This is then used as part of a message to be sent to the motorbee in the same way as the motors and servo were set previously. i.e. the message is simply two bytes in the data array...
data = [8,outputs]
The '8' is once again the message type which will be recognised by the motorbee as the command to set the outputs. The second byte being the output pattern to be used as already mentioned. The actual sending of the message is once again done using...
dev.write(2,data)
However, unlike the previous sending of the message to set the motors, this message has two functions. The first is to set the digital outputs as described. The second is to tell the MotorBee to read its digital inputs into a buffer and make that reading available to be read across the USB interface by a subsequent command. Even if the input data is not required, it is necessary to read the inputs data buffer every time the outputs are set !!. The command that actually reads this data from the MotorBee is next....
inputs = dev.read(0x81, MotorBee reads. The number '1' is the number of bytes of data to read from the MotorBee. i.e. since the MotorBee only has 5 digital inputs it only requires one 8-bit byte to hold the data.. The variable which we have called "inputs" will then hold the returned data. i.e. inputs is a Python array with inputs[0] holding the returned data. Details of the bits corresponding to the inputs is shown below....
A logic '1' corresponds to the input being HIGH (+5v), logic '0' corresponds to LOW (0v)
print "Inputs = {}".format(inputs[0])
This is not really required, but shows motor1 to 1/3 full speed (approx) and
servo to -90 degrees
data=[4, 84, 0, 0, 0, 0b11110001, 0x30, 64]
dev.write(2,data)
# set motors 2 and 4 to full speed and
the servo to centre position
data=[4, 0, 255, 0, 255, 0b11111010, 0x30, 128]
dev.write(2,data)
# set digital output 1 on then read and
display the current inputs
data=[8, 0b00000001]
dev.write(2,data)
inputs = dev.read(0x81, 1)
print inputs
See the article below for an example of using the Motor Bee with a Raspberry Pi ........
13515 | https://pc-control.co.uk/control/raspi/raspi-motorbee.php | CC-MAIN-2018-13 | refinedweb | 1,544 | 61.36 |
This chapter covered some of the basics of XML, including the differences between elements and attributes. It also delved into what makes an XML document well formed and not well formed. In addition, I covered how to make script elements in XHTML from both an XML and JavaScript point of view, as well as entities.
The subject of namespaces was covered along with their purpose. This included a brief look at both Document Type Definitions and schemas, and the role that they play in validation. Finally, this chapter covered the role that XML Data Islands can play within an HTML document. | http://www.yaldex.com/ajax_tutorial_2/ch06lev1sec9.html | CC-MAIN-2021-25 | refinedweb | 101 | 71.34 |
To follow on from my previous post I've found that in RTClib.h reference to RTC_millis which defines static function DateTime now(); which in turn is explained for those more experienced in coding in C++ in RTClib.cpp lots of good late night reading if your so inclined :)
In RTClib.h is also a note which explains a problem I've noticed as follows:
// note in RTClib.h says: RTC using the internal millis() clock, has to be initialized before use NOTE: this clock won't be correct once the millis() timer rolls over (>49d?)
My seconds count crazy on an LCD after 59 09 19 29 39 up to 99 then back on track to 10. This does not happen on the Serial Monitor
To get over the problem of the RTC not being set precisely I found this way to do it from Visual Basic & arduino sketch ... ck#Summary.
Following for those who may be interested is the original code at the top of this post modified to display both on Serial Monitor & 2x16 LCD
Enjoy
/*
The circuit:
* LCD RS pin to digital pin 8 (J3/1 or PB0)
* LCD Enable pin to digital pin 9 (J3/2 or PB1)
* LCD D4 pin to digital pin 4 (J1/5 or PD4)
* LCD D5 pin to digital pin 5
* LCD D6 pin to digital pin 6
* LCD D7 pin to digital pin 7 (J1/8 or PD7)
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
*/
// include the library code:
#include <LiquidCrystal.h>
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;
//("About to Start...");
delay(1000); // time to see display
Serial.begin(57600); // for Serial Monitor
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled - load off PC Time
// RTC.adjust(DateTime(__DATE__, __TIME__)); // only use if you need to reload time from PC with
// slight error of maybe 2 minutes
}
} // end of setup
void loop() {
DateTime now = RTC.now();
// Display Date
lcd.setCursor(0,0); // lcd.setCursor(col, row)
lcd.print("DATE: ");
Serial.print("DATE: ");
Serial.print(now.day(), DEC); // to serial port
lcd.print(now.day(), DEC); // to lcd
Serial.print('/');
lcd.print('/');
Serial.print(now.month(), DEC); // to serial port
lcd.print(now.month(), DEC); // to lcd
Serial.print('/');
lcd.print('/');
Serial.print(now.year(), DEC); // to serial port
lcd.print(now.year(), DEC); // to lcd
// Display Time
lcd.setCursor(0,1); // lcd.setCursor(col, row)
lcd.print("TIME: ");
Serial.print(" TIME: ");
Serial.print(now.hour(), DEC); // to serial port
lcd.print(now.hour(), DEC); // to lcd
Serial.print(':');
lcd.print(':');
Serial.print(now.minute(), DEC); // to serial port
lcd.print(now.minute(), DEC); // to lcd
Serial.print(':');
lcd.print(':');
Serial.print(now.second(), DEC); // to serial port
lcd.print(now.second(), DEC); // to lcd
// note in RTClib.h says: RTC using the internal millis() clock, has to be initialized before use
// NOTE: this clock won't be correct once the millis() timer rolls over (>49d?)
Serial.println(); // provides line feed on Serial
delay(1000);
} // end of loop - that's all folks... | http://forums.adafruit.com/viewtopic.php?f=25&t=23744&p=173489 | CC-MAIN-2015-18 | refinedweb | 549 | 66.33 |
later a later chapter).:
Typo line 7 Vector3f in Solution to 1.c
Fixed. Thanks!
!"
This so if I make 4 separate files for Storage and Display class (2 each, a .h and a .cpp) I'll have to include both header files in both .cpp files right? So then would the order of inclusion matter in the case? Or is it ok to just include both headers regardless of the order.
Also do I need to include Storage.h in my Display.h and vice versa? I'm a bit confused by this...
So I just saw the solution for quiz 1.c, and I kind of get how it needs to be done, but won't it be ok to not include "Point3d.h" in the main.cpp and Point3d.cpp since we are including the "Vector3d.h" and it includes "Point3d.h"
Do we include it because it'll make things clear when the program is in maintenance phase? or is there any other reason to do so?
You `#include` header files that you use even if the header files `#include` each other for clarity. It makes it obvious what headers are being used.
It also isn't a great idea to rely on your headers `#include`-ing other headers - if you change `Vector3d.h` later not to `#include "Point3d.h"` and your `main.cpp` doesn't, it could break. This is more an issue if you're `#include`-ing someone else's headers (eg the standard library often `#include`s itself, but might not on every installation)
(At least this is my understanding, I'm just going through these tutorials like you :D )
Unsure why but although
compiles fine, Vector3d:: does not bring up any members of the class. The error is ":: must be followed by a namespace a class". It is as if VS IDE is not detecting the constructor prototype in Vector3d.h. Why is this? The code DOES compile fine! Just feeling uncomfortable that the IDE is flagging an error when none exists?
Two small suggestions:
First, because printWeather is a friend of both classes, ...
instead of
First, because PrintWeather is a friend of both classes, ...
..., the compiler would tell us it doesn’t know what a Humidity is when parsing the prototype for printWeather() inside the Temperature class.
instead of
..., the compiler would tell us it doesn’t know what a Humidity is when parsing the prototype for PrintWeather() inside the Temperature class.
Name (required)
Website
Save my name, email, and website in this browser for the next time I comment. | https://www.learncpp.com/cpp-tutorial/friend-functions-and-classes/ | CC-MAIN-2021-17 | refinedweb | 429 | 77.33 |
Got?@...
Hi All,
After hunting through the list. I couldn't find a patch
that cleanly applies to 2.6.3 (on top of latest uml patch)
to re-enable skas host support.
So after merging parts of Paulo's and Ingo's skas patches
for 2.6.0 and 2.6.2, I now have a single patch that cleanly
applies and runs for me both as a host and guest with 2.6.3
rediffed against the latest uml patch.
First apply 2.6.3-rc2.1 uml patch (cleanly applies to 2.6.3)
Then apply the skas patch:
It includes the following changes:
* PROC_MM Kconfig
* add back skas ptrace support
* export ldt functions with mm argument
* export do_mmap2 with mm argument
* compatibility wrapper for do_mmap_pgoff
* proc_mm now uses __init_new_context
Use at your own risk - it boots and runs skas mode guest here ;)
~mc
rocombs@... said:
> The boot messages look like this when it dies:
> Checking for the skas3 patch in the host...not found
> Checking for /proc/mm...not found
> make_umid - mkstemp failed, errno = 13
> tracing thread pid = 22242
> Segmentation fault
Copy /proc/cpuinfo into the jail. I added a dependency on that when doing
the RTC change, but forgot to make it behave well when cpuinfo isn't available.
Jeff
On Thu, Feb 26, 2004 at 10:26:55PM +0100, Gerd Knorr wrote:
> Hi,
>
> recent gcc versions need this one ...
Another one of this kind (without this gcc may optimizes away the static
declared but unreferenced stuff, resulting in initrd= and --help options
not working any more for example ...).
Gerd
--- linux-um-2.6.3/arch/um/include/init.h.used 2004-02-27 09:34:57.874205081 +0100
+++ linux-um-2.6.3/arch/um/include/init.h 2004-02-27 09:44:32.415275725 +0100
@@ -40,9 +40,9 @@
typedef int (*initcall_t)(void);
typedef void (*exitcall_t)(void);
-#define __init __attribute__ ((__section__ (".text.init")))
+#define __init __attribute__ ((used,__section__ (".text.init")))
#define __exit __attribute__ ((unused, __section__(".text.exit")))
-#define __initdata __attribute__ ((__section__ (".data.init")))
+#define __initdata __attribute__ ((used,__section__ (".data.init")))
#endif
@@ -94,11 +94,11 @@
* Mark functions and data as being only used at initialization
* or exit time.
*/
-#define __uml_init_setup __attribute__ ((unused,__section__ (".uml.setup.init")))
-#define __uml_setup_help __attribute__ ((unused,__section__ (".uml.help.init")))
-#define __uml_init_call __attribute__ ((unused,__section__ (".uml.initcall.init")))
-#define __uml_postsetup_call __attribute__ ((unused,__section__ (".uml.postsetup.init")))
-#define __uml_exit_call __attribute__ ((unused,__section__ (".uml.exitcall.exit")))
+#define __uml_init_setup __attribute__ ((used,__section__ (".uml.setup.init")))
+#define __uml_setup_help __attribute__ ((used,__section__ (".uml.help.init")))
+#define __uml_init_call __attribute__ ((used,__section__ (".uml.initcall.init")))
+#define __uml_postsetup_call __attribute__ ((used,__section__ (".uml.postsetup.init")))
+#define __uml_exit_call __attribute__ ((used,__section__ (".uml.exitcall.exit")))
#endif /* _LINUX_UML_INIT_H */
I've been trying to debug an early boot crash with 2.4.25 (x86 with
UML running on Red Hat 7.3 with kernel 2.4.20-28.7.
The boot messages look like this when it dies:
Checking for the skas3 patch in the host...not found
Checking for /proc/mm...not found
make_umid - mkstemp failed, errno = 13
tracing thread pid = 22242
Segmentation fault
If I keep everything the same except not call chroot() in my startup
script it boots fine (until mounting the root fs which would need
modified paths to work without chroot). The messages look like this
when it works:
Checking for the skas3 patch in the host...not found
Checking for /proc/mm...not found
make_umid - mkstemp failed, errno = 13)
make_umid - mkstemp failed, errno = 13
Linux version 2.4.25-1um (nospam@...) (gcc version 3.3.3 20040125 (prerelease) (Debian)) #11 Fri Feb 27 02:23:25 EST 2004
On node 0 totalpages: 16384
zone(0): 16384 pages.
zone(1): 0 pages.
...
The mkstemp permission problem with the pidfile has always been there
because there is only one writable place in the chrooted environment,
but it has never caused a problem before.
It looks like the /dev/anon checks are somehow skipped when using
chroot and it jumps directly to starting the tracing thread which then
dies after receiving a SIGUSR1.
I've tried adding more debug messages to the boot sequence. They
didn't tell me a whole lot but here is the sequence when it dies:
...
Postsetup completed
tracing thread pid = 21888
after clone
after ptrace
after debug
ready to loop
after waitpid
got sig 10
before do_proc_op
before switch
got REBOOT or HALT
Segmentation fault
I really have no clue what is causing this and the only factor I have
found to make a difference doesn't make sense.
Has anyone else seen this? Do you have any ideas?
Thanks,
-Ross
* BlaisorBlade <blaisorblade_spam@...> [2004-02-26 19:39]:
> > copy_thread : pipe failed, err = 24
>
> This is EMFILE. Either you "ulimit"ed your UML's (and one UML needs a lot of
> filehandles) or you need to increase the filehandle limit where it is
> happening.
Yes, it was the ulimit, I increased the file handles now
> > This error appears first after a few hours of running and the boxes
> > with this error is no longer reachable.
>
> *Very* strange. If you mean that you can no longer login / do anything that
> needs to create a new process inside UML, I understand it.
Yes, that's the problem. :)
> > The following other errors
> > also appear:
> >
> > flush_thread : new thread failed, errno = 1
> > copy_thread : clone failed - errno = 11
> > copy_thread : clone failed - errno = 1
> > copy_thread : clone failed - errno = 1
>
> EPERM (very strange) and EAGAIN (too many processes running). Checking the
> source for sys_clone could be needed to diagnose EPERM (unless you have
> something as GrSecurity active).
No, vanilla 2.4.25 Kernel.
Greetings, Sebastian | https://sourceforge.net/p/user-mode-linux/mailman/user-mode-linux-devel/?viewmonth=200402&viewday=27 | CC-MAIN-2018-13 | refinedweb | 932 | 67.04 |
painter(3i) [bsd man page]
Painter(3I) InterViews Reference Manual Painter(3I) NAME
Painter - graphics output SYNOPSIS
#include <InterViews/painter.h> DESCRIPTION
Painter is a class that provides ``immediate-mode'' graphics operations for drawing on a canvas. The state of a painter defines the graph- ics context for the drawing operations and includes a brush, foreground and background colors, a fill pattern and mode, a text font, a text style, an output origin and current position, and a transformation matrix. STATE OPERATIONS
Painter(Painter* = stdpaint) Create a new painter and copy its state from the given painter. void SetBrush(Brush*) Brush* GetBrush() Set or return the painter's brush. Default is the predefined brush ``single''. void SetColors(Color* fg, Color* bg) Color* GetFgColor() Color* GetBgColor() Set or return the painter's colors. If either argument to SetColors is nil, then the corresponding color is not changed. Defaults are ``black'' for foreground and ``white'' for background. void SetFont(Font*) Font* GetFont() Set or return the painter's text font. Default is the predefined font ``stdfont''. void SetStyle(int style) int GetStyle() Set or get the painter's text style. A text style is a bit vector that can be assembled from the predefined constants Plain, Bold- face, Underlined, and Reversed. Default is Plain. void SetPattern(Pattern*) Pattern* GetPattern() void FillBg(boolean mode) boolean BgFilled() Set or return the painter's fill pattern and mode. If the mode is true, fill operations will set pixels corresponding to ones in the current fill pattern to the foreground color and pixels corresponding to zeros to the background color. If false, then only foreground pixels will be set. Default pattern is ``solid''; default mode is true. void SetOrigin(int x0, int y0) void GetOrigin(int& x0, int& y0) Set or return the origin by which all coordinates are offset. Default is (0, 0). void Translate(float dx, float dy) void Rotate(float angle) void Scale(float x, float y) void SetTransformer(Transformer*) Transformer* GetTransformer() Coordinates passed to drawing operations are transformed according to the current origin, translation (cumulative), rotation, and scale factor. Internally, a transformation matrix is stored that can be directly set and accessed using SetTransformer and Get- Transformer. The default transformer is nil, meaning no transformations are performed. void SetPlaneMask(int mask) Set which bit planes are affected by drawing operations. If the Kth bit of mask is set, then display operations will draw on plane K. void SetOverwrite(boolean) Set whether a painter is allowed to write in subcanvases. If true, drawing operations will be able to write over the canvases of component interactors. If false, drawing operations will be clipped by any subcanvases. The default is false. void Clip(Canvas*, Coord x1, Coord y1, Coord x2, Coord y2) void NoClip() Clip restricts output operations to the specified region of the canvas. NoClip removes the restriction so that operations affect the entire canvas. Only one clipping region may be in effect at a time. void MoveTo(Coord x, Coord y) Set the current output position. The output position is used and updated by Text and CurveTo. DRAWING OPERATIONS
void Curve(Canvas*, Coord x0, y0, x1, y1, x2, y2, x3, y3) void CurveTo(Canvas*, Coord x1, y1, x2, y2, x3, y3) Paint a Bezier curve on the canvas from the first point to the last point (but not going through the intermediate control points). The curve will lie within the polygon formed by the four points. CurveTo uses the current position for the first point. void BSpline(Canvas*, Coord x[], y[], int n) void ClosedBSpline(Canvas*, Coord x[], y[], int n) void FillBSpline(Canvas*, Coord x[], y[], int n) Draw the B-spline defined by the n control vertices. If closed or filled, the last point is connected to the first point. void Circle(Canvas*, Coord x, y, int r) void FillCircle(Canvas*, Coord x, y, int radius) Draw a circle with center (x, y) and radius r. void Ellipse(Canvas*, Coord x, y, int xr, int yr) void FillEllipse(Canvas*, Coord x, y, int xr, int yr) Draw an ellipse with center (x, y), horizontal radius xr, and vertical radius yr. void Line(Canvas*, Coord x1, y1, x2, y2) void MultiLine(Canvas*, Coord x[], y[], int n) void Polygon(Canvas*, Coord x[], y[], int n) void FillPolygon(Canvas*, Coord x[], y[], int n) Draw a path using the current brush and colors. The Line operation draws a vector between two points (inclusive); MultiLine draws a number of connected vectors; Polygon draws a closed set of vectors; FillPolygon fills the area inside a polygon using the current fill pattern and colors. void Point(Canvas*, Coord x, y) void MultiPoint(Canvas*, Coord x[], y[], int n) Set a point or set of points to the current foreground color. void Rect(Canvas*, Coord x1, y1, x2, y2) void FillRect(Canvas*, Coord x1, y1, x2, y2) void ClearRect(Canvas*, Coord x1, y1, x2, y2) Draw a rectangle with opposite corners specfied by (x1, y1) and (x2, y2). FillRect fills the rectangle using the current pattern and colors; ClearRect fills the rectangle with the background color. void Text(Canvas*, const char* str, Coord x, Coord y) void Text(Canvas*, const char* str, int n, Coord x, Coord y) void Text(Canvas*, const char* str) void Text(Canvas*, const char* str, int n) Draw a string or substring of text using the current Font and text style. The (x, y) coordinates specify the lower-left corner of the bounding box of the text. The width of the bounding box is the width of the string as reported by the Font::Width operation, and the height of the bounding box is the Font height. Most fonts will result in output which only affects pixels within the bound- ing box. The current transformation matrix is applied to both the positions and the shapes of characters drawn. If the matrix specifies a transformation involving rotation or scaling, the resulting operation may proceed much more slowly than normal. If background fill mode is on, then the characters are drawn in the foreground color, and other pixels within the bounding box are set to the background color. If background fill mode is off, only the foreground pixels are set. If no coordinates are specified, then the current position (defined by MoveTo) is used and updated to reflect the lower-right corner of the bounding box. void Stencil(Canvas*, Coord x, Coord y, Bitmap* image, Bitmap* mask = nil) Paint foreground and background colors through a stencil formed by positioning the image and mask Bitmaps with their origins at the point (x, y). Foreground color is painted where the image Bitmap has a true value and background color where image is false. How- ever, only pixels corresponding to a true value in the mask Bitmap are affected. A nil mask is equivalent to a mask of the same size and shape as image and containing all true values. The current transformation matrix is applied to both the image and mask Bitmaps. If the matrix specifies a transformation involving rotation or scaling, the resulting operation may proceed much more slowly than normal. void RasterRect(Canvas*, Coord x, Coord y, Raster*) Render the Raster with its lower-left corner at the position (x, y). The current transformation matrix is applied to the Raster. If the matrix specifies a transformation involving rotation or scaling, the resulting operation may proceed much more slowly than normal. void Read(Canvas*, void*, Coord x1, y1, x2, y2) void Write(Canvas*, const void*, Coord x1, y1, x2, y2) void Copy(Canvas* src, Coord x1, y1, x2, y2, Canvas* dst, Coord x0, y0) Read copies a region of a canvas into memory. Write copies data from memory to a region of a canvas. Copy reads a region of one canvas and writes the data into a region of another canvas (or within a canvas if src and dst are the same). The point (x0, y0) is the lower-left corner of the destination region. Note that Read and Write are superceded by operations that use Rasters. SEE ALSO
Bitmap(3I), Brush(3I), Canvas(3I), Color(3I), Font(3I), Pattern(3I), Raster(3I), Transformer(3I) InterViews 15 June 1987 Painter(3I) | https://www.unix.com/man-page/bsd/3i/painter | CC-MAIN-2022-40 | refinedweb | 1,366 | 61.16 |
IRC Client freezing up
Hello,
I'm writing an IRC client(just to learn C#), and I'm using class/namespace I found on the web:
that one, I tried to take it from a console application to a windows form application, I removed the cIrc class, and just used the base class IRC.
My problem is, when I connect, the windows form freezes up, but the applicaiton continues to run, and the application connects to the IRC Server. The form doesn't respond, and I have to alt-ctrl-delete it.
I'm really new to C# (Coming from PHP), so I don't really understand what's going on behind.
Can someone explain a way to keep the windows form responding? I'm using multicast delegates (learned the term from my C# book).
Heres my code:
the form using the IRC class
then I have the class here:
I have no clue how to solve this problem.
Thanks for your help
Jerome Gagner
Thursday, September 16, 2004
The reason is that your IRC client is doing blocking network I/O on the thread that the user interface also relies upon for functioning.
The easiest, although perhaps most dangerous thing, is that you could thread the IRC client code.
Brad Wilson (dotnetguy.techieswithcats.com)
Friday, September 17, 2004
Recent Topics
Fog Creek Home | https://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&ixPost=4334&ixReplies=1 | CC-MAIN-2018-26 | refinedweb | 224 | 69.01 |
By: Davide Prati and Hubris
In this chapter we will build the planet Earth from scratch. With a sphere and a texture is much more easier than what its sound. We will work with the
ofTexture class, and after this chapter you will be able to apply any kind of texture to a 3d primitive. And you will be ready to dig further using shaders and textures together.
To add a texture to a sphere we need to save the image that we want to apply in the
bin/data folder. Let's assume that we have saved this image and we want to apply it to a sphere. In order to do this, you need to setup a basic 3D scene, with a sphere and a texture object. Your app.h file should look like this:
#pragma once #include "ofMain.h" mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); ofSpherePrimitive sphere; ofLight light; ofTexture mTex; ofEasyCam cam; };
And your App.cpp file like this:
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofDisableAlphaBlending(); ofEnableDepthTest(); light.enable(); light.setPosition(ofVec3f(100,100,200)); light.lookAt(ofVec3f(0,0,0)); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ cam.begin(); sphere.draw(); cam.end(); }
If you run the App, you will see a sphere without any texture. To add the texture, the
ofTexture object has to load in memory the
earth.jpg file. In the setup method, add these lines:
ofDisableArbTex(); ofLoadImage(mTex,"earth.jpg");
The call to
ofDisableArbText() is there for backward compatibility reasons, if you want to know more about these reasons, read this thread on the forum.
The second step is to tell to openFrameworks to apply this texture whenever we want to draw a sphere. Change the
draw() method as follow:
cam.begin(); mTex.bind(); sphere.draw(); mTex.unbind(); cam.end();
And voila', the Earth is done.
A mipmap is something clever, it makes possible that our sphere looks good from far away and also looks good when we look at it really close. Basically, a mipmap is an image that contains our image at different resolutions, from an high resolution version of the image to a lower resolution version. When we look at the planet earth from far away, the lower resolution version of that image will be used to render the sphere, when we look at the sphere closer, the higher resolution image will be use instead. This solution avoid antialiasing effects and increase speed. The wikipedia page about Mipmaps is really interesting, have a look if you want to know more.
This means that we have to resize our planet earth image at different resolutions and to decide which one to render depending on the case? no, openFrameworks comes in our help with a simple method,
generateMipmap() that will do all this work for us. Change the setup method as follow:
ofDisableArbTex(); ofLoadImage(mTex,"earth.jpg"); mTex.generateMipmap();
Alternatively, you can call
enableMipmap before loading the texture:
ofDisableArbTex(); mtex.enableMipmap(); ofLoadImage(mTex,"earth.jpg");
Now, there are different ways on which these images with different resolutions are used internally by openGL. By default, in openFrameworks, these images are linearly interpolated using
GL_LINEAR. To change the default behaviour, there is a method called
setTextureMinMagFilter().
If we add this line after
mTex.generateMipmap()
ofTexture.setTextureMinMagFilter(GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST)
The image will change as follow:
As you can see, we get the perks of the mipmap, but because we set the magnitude to
GL_NEAREST, on where the texture is closer, we'll get that pixelated look.
If we change the code as follow
ofTexture.setTextureMinMagFilter(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR)
we obtain an image like the following one:
Sometimes you need to repeat a texture all over a mesh. To repeat the texture of the planet Earth around a sphere is weird, but to repeat the texture of a bark over a tree makes sense. Let's see how to do this and how the texture repetition and the mipmaps change the aspect of the meshes. For the sake of clarity, I will skip the code to load the mesh of a tree and to load the texture, and I've also used as texture an image containing a black ball on a red background, to make the artifacts more visible.
The new method that we see in the following code is
setTextureWrap(). It takes two argument, the first one defines if the texture should repeat on the x, the second one if the texture should repeat y.
Let's observe this image containing the same three with different texture's usage.
The example A is created with the following code:
// assuming that in App.h you have // ofTexture bark ofLoadImage(bark, "bark.png");
No texture repetition nor minMag filter is set
The example's B code looks like:
ofLoadImage(bark2, "bark.jpg"); bark2.setTextureWrap(GL_REPEAT, GL_REPEAT); bark2.setTextureMinMagFilter(GL_NEAREST, GL_NEAREST);
As you can see, the texture is repeated correctly, without scaling it, but the final part of the tree looks really pixelated. Let's fix this in the example's C code
ofLoadImage(bark3,"bark.jpg"); bark3.setTextureWrap(GL_REPEAT, GL_REPEAT); bark3.generateMipmap(); bark3.setTextureMinMagFilter(GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST);
Of course this tree looks more like a leopard than a tree, try out different texture to obtain a more realistic effect. | http://openframeworks.cc/ofBook/chapters/textures.html | CC-MAIN-2018-05 | refinedweb | 891 | 62.98 |
On Wed, Sep 28, 2011 at 11:58 AM, Paul Moore <p.f.moore at gmail.com> wrote: > On 28 September 2011 16:38, Guido van Rossum <guido at python.org> wrote: >> Of course once there's different syntax, the nonlocal declaration in >> the function is redundant. And clearly I'm back-peddling. :-) > > If we're back to syntax proposals on the def statement, how about > > def fn() with i=1, lock=Lock(): > whatever > > ? This is basically another bikeshed to paint, though... The PEP 3150 discussion on keywords is relevant to that kind of keyword-based proposal (there's a reason the statement local namespaces proposal suggests 'given' rather than 'with' or 'where') Cheers, Nick -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia | https://mail.python.org/pipermail/python-ideas/2011-September/011936.html | CC-MAIN-2017-17 | refinedweb | 123 | 67.76 |
A journey on the Android Main Thread — PSVM
From PSVM to loopers and handlers
Written by Pierre-Yves Ricau.
There is an article on coding horror about why we should learn to read the source. One of the great aspects of Android is its open source nature.
When facing bugs that were related to how we interact with the main thread, I decided to get a closer look at what the main thread really is. This article describes the first part of my journey.
PSVM
public class BigBang { public static void main(String... args) { // The Java universe starts here. } }
All Java programs start with a call to a public static void main() method. This is true for Java Desktop programs, JEE servlet containers, and Android applications.
When the Android system boots, it starts a Linux process called ZygoteInit. This process is a Dalvik VM that loads the most common classes of the Android SDK on a thread, and then waits.
When starting a new Android application, the Android system forks the ZygoteInit process. The thread in the child fork stops waiting, and calls ActivityThread.main().
According to Wikipedia, a zygote is a fertilized biological cell.
Loopers
Before going any further, we need to look at the Looper class.
Using a looper is a good way to dedicate one thread to process messages serially.
Each looper has a queue of Message objects (a MessageQueue).
A looper has a loop() method that will process each message in the queue, and block when the queue is empty.
The Looper.loop() method code is similar to this:
void loop() { while(true) { Message message = queue.next(); // blocks if empty. dispatchMessage(message); message.recycle(); } }
Each looper is associated with one thread. To create a new looper and associate it to the current thread, you must call Looper.prepare(). The loopers are stored in a static ThreadLocal in the Looper class. You can retrieve the Looper associated to the current thread by calling Looper.myLooper().
The HandlerThread class does everything for you:
HandlerThread thread = new HandlerThread("SquareHandlerThread"); thread.start(); // starts the thread. Looper looper = thread.getLooper();
Its code is similar to this:
class HandlerThread extends Thread { Looper looper; public void run() { Looper.prepare(); // Create a Looper and store it in a ThreadLocal. looper = Looper.myLooper(); // Retrieve the looper instance from the ThreadLocal, for later use. Looper.loop(); // Loop forever. } }
Handlers
A handler is the natural companion to a looper.
A handler has two purposes:
- Send messages to a looper message queue from any thread.
- Handle messages dequeued by a looper on the thread associated to that looper.
// Each handler is associated to one looper. Handler handler = new Handler(looper) { public void handleMessage(Message message) { // Handle the message on the thread associated to the given looper. if (message.what == DO_SOMETHING) { // do something } } }; // Create a new message associated to that handler. Message message = handler.obtainMessage(DO_SOMETHING); // Add the message to the looper queue. // Can be called from any thread. handler.sendMessage(message);
You can associate multiple handlers to one looper. The looper delivers the message to message.target.
A popular and simpler way to use a handler is to post a Runnable:
// Create a message containing a reference to the runnable and add it to the looper queue handler.post(new Runnable() { public void run() { // Runs on the thread associated to the looper associated to that handler. } });
A handler can also be created without providing any looper:
// DON'T DO THIS Handler handler = new Handler();
The handler no argument constructor calls Looper.myLooper() and retrieves the looper associated with the current thread. This may or may not be the thread you actually want the handler to be associated with.
Most of the time, you just want to create a handler to post on the main thread:
Handler handler = new Handler(Looper.getMainLooper());
Back to PSVM
Let’s look at ActivityThread.main() again. Here is what it is essentially doing:
public class ActivityThread { public static void main(String... args) { Looper.prepare(); // You can now retrieve the main looper at any time by calling Looper.getMainLooper(). Looper.setMainLooper(Looper.myLooper()); // Post the first messages to the looper. // { ... } Looper.loop(); } }
Now you know why this thread is called the main thread :) .
Note: As you would expect, one of the first things that the main thread will do is create the Application and call Application.onCreate().
In the next part, we will look at the relation between the Android lifecycle and the main thread, and how this can lead to subtle bugs. Pierre-Yves Ricau (@Piwai) | Twitter The latest Tweets from Pierre-Yves Ricau (@Piwai). Android baker @Square. Paris / San Franciscotwitter.com | https://developer.squareup.com/blog/a-journey-on-the-android-main-thread-psvm/ | CC-MAIN-2021-43 | refinedweb | 769 | 58.79 |
Variable size/Set
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Demonstrate how to specify the minimum size of a variable or a data type.
Contents
- 1 360 Assembly
- 2 Ada
- 3 AutoHotkey
- 4 BASIC
- 5 BBC BASIC
- 6 C
- 7 C++
- 8 D
- 9 Erlang
- 10 ERRE
- 11 Fortran
- 12 FreeBASIC
- 13 Go
- 14 Haskell
- 15 Icon and Unicon
- 16 J
- 17 Kotlin
- 18 Mathematica
- 19 Modula-3
- 20 Nim
- 21 ooRexx
- 22 PARI/GP
- 23 Pascal
- 24 Perl
- 25 Perl 6
- 26 PL/I
- 27 PicoLisp
- 28 PureBasic
- 29 Python
- 30 Racket
- 31 REXX
- 32 Tcl
- 33 Ursala
- 34 XPL0
- 35 zkl
- 36 ZX Spectrum Basic
360 Assembly[edit]
The 360 architecture data specifications are:
* Binary interger (H,F)
I2 DS H half word 2 bytes
I4 DS F full word 4 bytes
* Real (floating point) (E,D,L)
X4 DS E short 4 bytes
X8 DS D double 8 bytes
X16 DS L extended 16 bytes
* Packed decimal (P)
P3 DS PL3 2 bytes
P7 DS PL7 4 bytes
P15 DS PL15 8 bytes
* Zoned decimal (Z)
Z8 DS ZL8 8 bytes
Z16 DS ZL16 16 bytes
* Character (C)
C1 DS C 1 byte
C16 DS CL16 16 bytes
C256 DS CL256 256 bytes
* Bit value (B)
B1 DC B'10101010' 1 byte
* Hexadecimal value (X)
X1 DC X'AA' 1 byte
* Address value (A)
A4 DC A(176) 4 bytes but only 3 bytes used
* (24 bits => 16 MB of storage)
Ada[edit]
type Response is (Yes, No); -- Definition of an enumeration type with two values
for Response'Size use 1; -- Setting the size of Response to 1 bit, rather than the default single byte size
AutoHotkey[edit]
The documentation explains how the built-in function VarSetCapacity() may be used to do so.
BASIC, strings are allocated in single characters (bytes), so C$(12) in the following example is stored as 12 bytes + additional bytes used for the header in the variable table. In some implementations of basic (such as those that support the storage of variable length strings in arrays), additional terminator characters (such as a trailing Ascii NUL) may also be included. In traditional basic, integers are typically 2 bytes each, so A%(10) contains 10 lots of 2 bytes (20 bytes in total) + additional bytes used for header data in the variable table. Floating point values are typically 8 bytes each, so B(10) holds 10 lots of 8 bytes (80 bytes in total) + additional bytes for header in the variable table:
10 DIM A%(10): REM the array size is 10 integers
20 DIM B(10): REM the array will hold 10 floating point values
30 DIM C$(12): REM a character array of 12 bytes
BBC BASIC[edit]
The only way to 'set' the size of a scalar numeric variable is to declare it with the appropriate type suffix:
var& = 1 : REM Variable occupies 8 bits
var% = 1 : REM Variable occupies 32 bits
var = 1 : REM Variable occupies 40 bits
var# = 1 : REM Variable occupies 64 bits
If the task is talking about setting the size of a variable at run time that is only possible with strings, arrays and structures.
C[edit]
#include <stdint.h>
int_least32_t foo;
Here foo is a signed integer with at least 32 bits. stdint.h also defines minimum-width types for at least 8, 16, 32, and 64 bits, as well as unsigned integer types.
C++[edit]or
#include <boost/cstdint.hpp>
boost::int_least32_t foo;
D[edit]
In D, any variables of static array of zero length has a size of zero. But such data is useless, as no base type element can be accessed.
typedef long[0] zeroLength ;
writefln(zeroLength.sizeof) ; // print 0
NOTE: a dynamic array variable's size is always 8 bytes, 4(32-bit) for length and 4 for a reference pointer of the actual storage somewhere in runtime memory.
The proper candidates of minimum size variable are empty structure, 1-byte size data type variable (include byte, ubyte, char and bool), and void, they all occupy 1 byte.
byte b ;
ubyte ub ;
char c ;
bool t ;
bool is logically 1-bit size, but it actually occupy 1 byte.
void can't be declared alone, but void.sizeof gives 1.
An empty structure is logically zero size, but still occupy 1 byte.
struct Empty { }
writefln(Empty.sizeof) ; // print 1
Erlang[edit]
Variables and data type sizes are outside of the programmers control, with one exception: binary data. Here you can say exactly how many bits you want. Default is 8 bits so below the 0 is 8 bits and the 1 is 3 bits.
15> <<1:11>>. <<0,1:3>>
ERRE, in ERRE strings are allocated in single characters (bytes), so C$[12] in the following example is stored as 12 bytes + additional bytes used for the header in the variable table. Integers are typically 2 bytes each, so A%[10] contains 10 numbers of 2 bytes (20 bytes in total) + additional bytes used for header data in the variable table. Floating point values are typically 4 bytes each, so B[10] holds 10 numbers of 4 bytes (40 bytes in total) + additional bytes for header in the variable table:
DIM A%[10] ! the array size is 10 integers
DIM B[10] ! the array will hold 10 floating point values
DIM C$[12] ! a character array of 12 bytes</lang>
There is also "double" floating point values (8 bytes). Variables of this type use the suffix #.
Fortran[edit]
Since Fortran 90 each intrinsic data type (INTEGER, REAL, COMPLEX, LOGICAL and CHARACTER) has a KIND parameter associated with it that can be used to set the required level of precision. The actual values which these KIND parameters can take are not specified in the standard and are implementation-dependent. In order to select an appropriate KIND value that is portable over different platforms we can use the intrinsic functions SELECTED_REAL_KIND and SELECTED_INT_KIND.
The syntax of these functions are as follows:-
selected_real_kind(P, R), where P is the required number of significant decimal digits and R is the required decimal exponent range. At least one argument must be present. The return value is the kind type parameter for real values with the given precision and/or range. A value of -1 is returned if P is out of range, a value of -2 is returned if R is out of range and a value of -3 is returned if both P and R are out of range.
selected_int_kind(R), where R is the required decimal exponent range. The return value is the kind type parameter for integer values n such that -10^R < n < 10^R. A value of -1 is returned if R is out of range.
program setsize
implicit none
integer, parameter :: p1 = 6
integer, parameter :: p2 = 12
integer, parameter :: r1 = 30
integer, parameter :: r2 = 1000
integer, parameter :: r3 = 2
integer, parameter :: r4 = 4
integer, parameter :: r5 = 8
integer, parameter :: r6 = 16
integer, parameter :: rprec1 = selected_real_kind(p1, r1)
integer, parameter :: rprec2 = selected_real_kind(p2, r1)
integer, parameter :: rprec3 = selected_real_kind(p2, r2)
integer, parameter :: iprec1 = selected_int_kind(r3)
integer, parameter :: iprec2 = selected_int_kind(r4)
integer, parameter :: iprec3 = selected_int_kind(r5)
integer, parameter :: iprec4 = selected_int_kind(r6)
real(rprec1) :: n1
real(rprec2) :: n2
real(rprec3) :: n3
integer(iprec1) :: n4
integer(iprec2) :: n5
integer(iprec3) :: n6
integer(iprec4) :: n7
character(30) :: form
form = "(a7, i11, i10, i6, i9, i8)"
write(*, "(a)") "KIND NAME KIND NUMBER PRECISION RANGE "
write(*, "(a)") " min set min set"
write(*, "(a)") "______________________________________________________"
write(*, form) "rprec1", kind(n1), p1, precision(n1), r1, range(n1)
write(*, form) "rprec2", kind(n2), p2, precision(n2), r1, range(n2)
write(*, form) "rprec3", kind(n3), p2, precision(n3), r2, range(n3)
write(*,*)
form = "(a7, i11, i25, i8)"
write(*, form) "iprec1", kind(n4), r3, range(n4)
write(*, form) "iprec2", kind(n5), r4, range(n5)
write(*, form) "iprec3", kind(n6), r5, range(n6)
write(*, form) "iprec4", kind(n7), r6, range(n7)
end program
Output
KIND NAME KIND NUMBER PRECISION RANGE min set min set ______________________________________________________ rprec1 1 6 6 30 37 rprec2 2 12 15 30 307 rprec3 3 12 18 1000 4931 iprec1 1 2 2 iprec2 2 4 4 iprec3 3 8 9 iprec4 4 16 18
FreeBASIC[edit]
FreeBASIC variables have a fixed size (depending on their type) with four exceptions:
1. The size of the Integer and UInteger types depends on the underlying platform - 4 bytes for 32-bit and 8 bytes for 64-bit platforms.
2. The size of individual characters of the WString type depends on the operating system - 2 bytes for Windows and 4 bytes for Linux.
3. The length of variable length strings is determined at run time and can be changed.
4. The bounds of dynamic arrays are determined at run time and can be changed (using ReDim). However, the number of dimensions (which can be up to 8) must be specified at compile time and cannot be changed.
Variables of types 3. and 4. don't hold their data directly but instead contain a fixed length descriptor - 24 bytes for a string and between 64 and 232 bytes for an array depending on the number of dimensions. The descriptor contains, amongst other things, a pointer to where the actual data is stored.
Go[edit]
For task interpretation this follows the spirit of the Ada example included by the task author. In it, an enumeration type is defined from enumeration values, then a storage size--smaller than the default--is specified for the type. A similar situation exists within Go. Defining types from values is called duck-typing, and the situation where a type smaller than the default can be specified exists when a variable is duck-typed from a numeric literal.
package main
import (
"fmt"
"unsafe"
)
func main() {
i := 5 // default type is int
r := '5' // default type is rune (which is int32)
f := 5. // default type is float64
c := 5i // default type is complex128
fmt.Println("i:", unsafe.Sizeof(i), "bytes")
fmt.Println("r:", unsafe.Sizeof(r), "bytes")
fmt.Println("f:", unsafe.Sizeof(f), "bytes")
fmt.Println("c:", unsafe.Sizeof(c), "bytes")
iMin := int8(5)
rMin := byte('5')
fMin := float32(5.)
cMin := complex64(5i)
fmt.Println("iMin:", unsafe.Sizeof(iMin), "bytes")
fmt.Println("rMin:", unsafe.Sizeof(rMin), "bytes")
fmt.Println("fMin:", unsafe.Sizeof(fMin), "bytes")
fmt.Println("cMin:", unsafe.Sizeof(cMin), "bytes")
}
Output:
i: 4 bytes r: 4 bytes f: 8 bytes c: 16 bytes iMin: 1 bytes rMin: 1 bytes fMin: 4 bytes cMin: 8 bytes
Haskell[edit]
import Data.Int
import Foreign.Storable
task name value = putStrLn $ name ++ ": " ++ show (sizeOf value) ++ " byte(s)"
main = do
let i8 = 0::Int8
let i16 = 0::Int16
let i32 = 0::Int32
let i64 = 0::Int64
let int = 0::Int
task "Int8" i8
task "Int16" i16
task "Int32" i32
task "Int64" i64
task "Int" int
- Output:
Int8: 1 byte(s) Int16: 2 byte(s) Int32: 4 byte(s) Int64: 8 byte(s) Int: 8 byte(s)
Icon and Unicon[edit]
Icon and Unicon values are self-descriptive types subject to automatic garbage collection. As a result the opportunities for setting the sizes of the variables are limited.
- strings are always variable in length with some fixed overhead
- csets are a fixed size
- tables and sets are variable in size and start empty
- integers and reals are fixed sizes
- records are a fized size
- co-expressions vary in size based on the environment when they are created
- file, window, and procedure references are all fixed in size
- lists can be specified with a minimum size (see below):
L := list(10) # 10 element list
J[edit]
v=: ''
Here, v is specified to have a minimum size. In this case, the minimum size of the content is zero, though the size of the representation is somewhat larger.
Kotlin[edit]
In Kotlin (or any other language targetting the JVM) the size of variables is outside the programmer's control. The primitive types are either fixed in size or (in the case of Boolean) implementation dependent and the size of objects will depend not only on the aggregate size of their fields but also on any overhead or alignment padding needed.
If one wants a numeric type to be able to accomodate a certain size of number, then one can of course declare a variable of the appropriate type (up to 8 bytes) or use the BigInteger or BigDecimal types where more than 8 byte precision is required.
The following program shows the range of numbers which the primitive numeric types can accomodate to enable one to choose the appropriate type:
// version 1.0.6
fun main(args: Array<String>) {
/* ranges for variables of the primitive numeric types */
println("A Byte variable has a range of : ${Byte.MIN_VALUE} to ${Byte.MAX_VALUE}")
println("A Short variable has a range of : ${Short.MIN_VALUE} to ${Short.MAX_VALUE}")
println("An Int variable has a range of : ${Int.MIN_VALUE} to ${Int.MAX_VALUE}")
println("A Long variable has a range of : ${Long.MIN_VALUE} to ${Long.MAX_VALUE}")
println("A Float variable has a range of : ${Float.MIN_VALUE} to ${Float.MAX_VALUE}")
println("A Double variable has a range of : ${Double.MIN_VALUE} to ${Double.MAX_VALUE}")
}
- Output:
A Byte variable has a range of : -128 to 127 A Short variable has a range of : -32768 to 32767 An Int variable has a range of : -2147483648 to 2147483647 A Long variable has a range of : -9223372036854775808 to 9223372036854775807 A Float variable has a range of : 1.4E-45 to 3.4028235E38 A Double variable has a range of : 4.9E-324 to 1.7976931348623157E308
Mathematica [edit]
Mathematica stores variables in symbols : e.g. variable 'A' containing integer 0 requires 24 bytes under Windows.
Modula-3[edit]
TYPE UByte = BITS 8 FOR [0..255];
Note that this only works for records, arrays, and objects. Also note that the size in bits must be large enough to hold the entire range (in this case, 8 bits is the correct amount for the range 0 to 255) or the compiler will error.
Nim[edit]
var a: int8 = 0
var b: int16 = 1
var c: int32 = 10
var d: int64 = 100
ooRexx[edit]
ooRexx variables are all references to object instances, so the variables themselves have no settable or gettable size.
PARI/GP[edit]
default(precision, 1000)
Alternately, in the gp interpreter,
\p 1000
Pascal[edit]
Ordinal and floating point types of FreePascal are listed here: [[1]] and here: [[2]]
var
a: byte; // 1 byte
b: word; // 2 byte
c: cardinal; // 4 byte
d: QWord; // 8 byte
x: real; // 4 byte
y: double; // 8 byte
Perl[edit]
I suppose you could use vec() or similar to twiddle a single bit. The thing is, as soon as you store this in a variable, the SV (the underlying C implementation of the most simple data type) already takes a couple dozen of bytes.
In Perl, memory is readily and happily traded for expressiveness and ease of use.
Perl 6[edit]
In Perl 6, normal user-facing types (Int, Rat, Str, Array, Hash) are all auto-sizing, so there is no need to specify a minimum size for them. (Floating point, known as "Num", defaults to a machine double.) For storage declarations, native storage types (starting with a lowercase letter) may also be specified, in which case the required bit size is part of the type name: int16, uint8 (aka "byte"), num32 (a "float"), complex64 (made of two num64's), etc. More generally, such types are created through an API supporting representational polymorphism, in this case, the NativeHOW representation, when provides methods to set the size of a type; the actual allocation calculation happens when such generic types are composed into a class instance representing the semantics of the effective type to the compiler and run-time system. But mostly this is not something users will concern themselves with directly.
By spec, arrays may be declared with dimensions of fixed size, but as of this writing, such arrays not yet implemented. An array of fixed size that returns elements of a native type will be stored compactly, and uses exactly the memory you'd think it should, (modulo alignment constraints between elements and any slop at the end due to your memory allocator).
PL/I[edit]
declare i fixed binary (7), /* occupies 1 byte */
j fixed binary (15), /* occupies 2 bytes */
k fixed binary (31), /* occupies 4 bytes */
l fixed binary (63); /* occupies 8 bytes */
declare d fixed decimal (1), /* occupies 1 byte */
e fixed decimal (3), /* occupies 2 bytes */
/* an so on ... */
f fixed decimal (15); /* occupies 8 bytes */
declare b(16) bit (1) unaligned; /* occupies 2 bytes */
declare c(16) bit (1) aligned; /* occupies 16 bytes */
declare x float decimal (6), /* occupies 4 bytes */
y float decimal (16), /* occupies 8 bytes */
z float decimal (33); /* occupies 16 bytes */
PicoLisp[edit]
In PicoLisp, all variables have the same size (a single cell). But it is possible to create a data structure of a given minimal size with the 'need' function.
PureBasic[edit]
EnableExplicit
Structure AllTypes
b.b
a.a
w.w
u.u
c.c ; character type : 1 byte on x86, 2 bytes on x64
l.l
i.i ; integer type : 4 bytes on x86, 8 bytes on x64
q.q
f.f
d.d
s.s ; pointer to string on heap : pointer size same as integer
z.s{2} ; fixed length string of 2 characters, stored inline
EndStructure
If OpenConsole()
Define at.AllTypes
PrintN("Size of types in bytes (x64)")
PrintN("")
PrintN("byte = " + SizeOf(at\b))
PrintN("ascii = " + SizeOf(at\a))
PrintN("word = " + SizeOf(at\w))
PrintN("unicode = " + SizeOf(at\u))
PrintN("character = " + SizeOf(at\c))
PrintN("long = " + SizeOf(at\l))
PrintN("integer = " + SizeOf(at\i))
PrintN("quod = " + SizeOf(at\q))
PrintN("float = " + SizeOf(at\f))
PrintN("double = " + SizeOf(at\d))
PrintN("string = " + SizeOf(at\s))
PrintN("string{2} = " + SizeOf(at\z))
PrintN("---------------")
PrintN("AllTypes = " + SizeOf(at))
PrintN("")
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf
- Output:
Size of types in bytes (x64) byte = 1 ascii = 1 word = 2 unicode = 2 character = 2 long = 4 integer = 8 quod = 8 float = 4 double = 8 string = 8 string{2} = 4 --------------- AllTypes = 52
Python[edit]
For compatibility with the calling conventions of external C functions, the ctypes module has functions that map data types and sizes between Python and C:
Racket[edit]
Like many other highlevel languages, Racket doesn't have direct control on object sizes. More than that, objects are almost always references, so holding a vector or a list still starts from some object with pointers to the rest. It is possible, however, to create random ffi structs with some given length, by using something like (_array _byte N) and it's possible to add that to some other ffi type by wrapping it with such an array in a struct. But to create and manage chunks of memory, it's much better to just use malloc (which is also available via the ffi).
REXX[edit]
In REXX, there are no minimums for variables holding character literals, so you just simply assign (set)
character strings (or numbers) to REXX variables.
Note that REXX stores all the values of variables as characters, and that includes numbers (all kinds),
booleans (logical), and labels (including subroutine/function names).
However, to insure that REXX can store numbers with a minimum size (amount of decimal digits),
the NUMERIC DIGITS nnn REXX instruction can be used. This will ensure that the decimal
number can be stored without resorting to exponential notation (although exponential notation
can be forced via the format BIF (Built In Function).
The default for numeric digits is 9 (decimal) digits.
There's effectively no limit for the precision [or length] for REXX numbers (except for memory),
but eight million is probably the practical limit.
/*REXX program demonstrates on setting a variable (using a "minimum var size".*/
numeric digits 100 /*default: 9 (decimal digs) for numbers*/
/*── 1 2 3 4 5 6 7──*/
/*──1234567890123456789012345678901234567890123456789012345678901234567890──*/
z = 12345678901111111112222222222333333333344444444445555555555.66
n =-12345678901111111112222222222333333333344444444445555555555.66
/* [↑] these #'s are stored as coded. */
/*stick a fork in it, we're all done. */
Tcl[edit]
In Tcl, most values are (Unicode) strings. Their size is measured in characters, and the minimum size of a string is of course 0. However, one can arrange, via write traces, that the value of a variable is reformatted to bigger size. Examples, from an interactive tclsh session:
% proc format_trace {fmt _var el op} {upvar 1 $_var v; set v [format $fmt $v]}..or limit its size to a certain length:
% trace var foo w {format_trace %10s}
% puts "/[set foo bar]/"
/ bar/
% trace var grill w {format_trace %-10s}
% puts "/[set grill bar]/"
/bar /
% proc range_trace {n _var el op} {upvar 1 $_var v; set v [string range $v 0 [incr n -1]]}
% trace var baz w {range_trace 2}
% set baz Frankfurt
Ursala[edit]
There is no way to set the minimum size of natural, integer, or rational numbers, but no need because they all have unlimited precision.
For (mpfr format) arbitrary precision floating point numbers, there are several mechanisms for setting the minimum precision, although not the exact amount of real memory used.
- If it's initialized from a literal constant, the compiler infers the intended precision from the number of digits in the constant (or 160 bits, whichever is greater).
- The library function
mpfr..grow(x,n)returns a copy of
xwith its precision increased by
nbits (padded with zeros).
- The library function
mpfr..shrink(x,n)returns a copy of
xwith its precision reduced by
nbits, or to
MPFR_PREC_MIN, whichever is greater.
- Library functions such as
mpfr..piand
mpfr..const_catalantake a natural number specifying the precision as an argument and return a constant with at least that precision.
- If two numbers of unequal precision are combined using any binary operation from the mpfr library, the result is computed and allocated using the greater precision of the two.
The last feature eliminates the need for explicitly setting the precision of numbers having exact representations, albeit contrary to the convention in physical sciences.
p = mpfr..pi 200 # 200 bits of precision
x = mpfr..grow(1.0E+0,1000) # 160 default precision, grown to 1160
y = mpfr..shrink(1.0+0,40) # 160 default shrunk to 120
z = mpfr..add(p,y) # inherits 200 bits of precision
a = # 180 bits (not the default 160) because of more digits in the constant
1.00000000000000000000000000000000000000000000000000000E0
XPL0[edit]
include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
char S,
A(1), \sets up an array containing one byte
B(0); \sets up an array containing no bytes
int I;
[S:= ""; \a zero-length (null) string
A:= Reserve(1); \sets up a 1-byte array at runtime
B:= Reserve(0); \sets up a 0-byte array at runtime
I:= I ! 1<<3; \stores a single 1 bit into an integer
I:= I & ~(1<<29); \stores a 0 bit into bit 29 of the integer
IntOut(0, I>>3 & 1); \displays value of bit 3
]
Other than arrays and strings, variables are a fixed size. Integers are four bytes and reals are eight bytes.
zkl[edit]
It is up to the object to decide on size. For example, Ints and Floats are 8 bytes, Strings are immutable and are sized when created. Mutable lists and dictionaries grow and shrink as needed. Some mutable types (such as Lists and Dictionaries) can take [programmer supplied] hints as to how big they might become.
ZX Spectrum Basic[edit]
10 DIM a$(10): REM This array will be 10 characters long
20 DIM b(10): REM this will hold a set of numbers. The fixed number of bytes per number is implementation specific
30 LET c=5: REM this is a single numerical value of fixed size
- Programming Tasks
- Type System
- 360 Assembly
- Ada
- AutoHotkey
- BASIC
- BBC BASIC
- C
- C++
- D
- Erlang
- ERRE
- Fortran
- FreeBASIC
- Go
- Haskell
- Icon
- Unicon
- J
- Kotlin
- Mathematica
- Modula-3
- Nim
- OoRexx
- PARI/GP
- Pascal
- Perl
- Perl 6
- PL/I
- PicoLisp
- PureBasic
- Python
- Racket
- REXX
- Tcl
- Ursala
- XPL0
- Zkl
- ZX Spectrum Basic
- AWK/Omit
- Clojure/Omit
- E/Omit
- Gnuplot/Omit
- Groovy/Omit
- GUISS/Omit
- J/Omit
- Java/Omit
- JavaScript/Omit
- LaTeX/Omit
- Logtalk/Omit
- Make/Omit
- Maxima/Omit
- NetRexx/Omit
- PlainTeX/Omit
- PureBasic/Omit
- Ruby/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- TPP/Omit
- XSLT/Omit
- M4/Omit
- Unlambda/Omit
- UNIX Shell/Omit | http://rosettacode.org/wiki/Variable_size/Set | CC-MAIN-2017-22 | refinedweb | 4,067 | 55.98 |
#include <gromacs/utility/directoryenumerator.h>
Lists files in a directory.
If multiple threads share the same DirectoryEnumerator, they must take responsibility for their mutual synchronization, particularly with regard to calling nextFile().
Opens a directory for listing.
Opens a directory for listing.
Convenience function to list files with certain extension from a directory.
dirname.
Gets next file in a directory.
falseif there were no more files.
If all files from the directory have been returned (or there are no files in the directory and this is the first call), the method returns
false and
filename is cleared. Otherwise, the return value is
true and the first/next file name is returned in
filename.
filename will not contain any path information, only the name of the file.
If
bThrow passed to the constructor was
false and the directory was not successfully opened, the first call to this function will return
false.
This method is not thread safe when called on the same object by multiple threads. Such use requires external synchronization. | https://manual.gromacs.org/current/doxygen/html-full/classgmx_1_1DirectoryEnumerator.xhtml | CC-MAIN-2021-17 | refinedweb | 169 | 58.58 |
I am learning about descriptors in python. I want to write a non-data descriptor but the class having the descriptor as its classmethod doesn't call the
__get__
__set__
class D(object):
"The Descriptor"
def __init__(self, x = 1395):
self.x = x
def __get__(self, instance, owner):
print "getting", self.x
return self.x
class C(object):
d = D()
def __init__(self, d):
self.d = d
>>>c = C(4)
>>>c.d
4
__get__
__set__
class D(object):
"The Descriptor"
def __init__(self, x = 1395):
self.x = x
def __get__(self, instance, owner):
print "getting", self.x
return self.x
def __set__(self, instance, value):
print "setting", self.x
self.x = value
class C(object):
d = D()
def __init__(self, d):
self.d = d
C
>>> c=C(4)
setting 1395
>>> c.d
getting 4
4
__get__, __set__
__get__, __set__
You successfully created a proper non-data descriptor, but you then mask the
d attribute by setting an instance attribute.
Because it is a non-data descriptor, the instance attribute wins in this case. When you add a
__set__ method, you turn your descriptor into a data descriptor, and data descriptors are always applied even if there is an instance attribute.
From the Descriptor Howto:.
and.
If you remove the
d instance attribute (never set it or delete it from the instance), the descriptor object gets invoked:
>>> class D(object): ... def __init__(self, x = 1395): ... self.x = x ... def __get__(self, instance, owner): ... print "getting", self.x ... return self.x ... >>> class C(object): ... d = D() ... >>> c = C() >>> c.d getting 1395 1395
Add an instance attribute again and the descriptor is ignored because the instance attribute wins:
>>> c.d = 42 # setting an instance attribute >>> c.d 42 >>> del c.d # deleting it again >>> c.d getting 1395 1395
Also see the Invoking Descriptors documentation in the Python Datamodel reference. | https://codedump.io/share/XhOh84w7iHdC/1/writing-non-data-descriptor-in-python | CC-MAIN-2018-17 | refinedweb | 308 | 69.58 |
XAML can be confusing - especially if you think it is a markup language like HTML - it isn't. XAML is a general purpose object instantiation language and to find out what this means - read on.
XAML is a, mostly declarative, object instantiation language – that is it’s a way of describing using XML what objects should be created and how they should be initialised before your program starts running.
If you keep this in mind then XAML is becomes a lot more transparent and easier to understand.
Its use in conjunction with WPF is just one of its many possible applications and indeed it has started to appear in other places – Windows Workflow for example and of course it is the UI design language for Windows Store apps i.e. WinRT apps.
To explain exactly what XAML is this article works with custom classes that have nothing to do with WPF so that we can find out about XAML in a completely general context that will help you understand all of its uses potential and current.
We could start with a non-WPF project to prove how general XAML is we but this would waste a lot of time adding references and “usings”.
So let’s start with a simple WPF Application using Visual Studio Community Edition say.
You don’t need to modify any of the generated code but you do need to add a simple custom class with which to try out XAML:
public class MyClass{ public MyClass() { }}
All that is necessary for a class to be instantiable by XAML is that it has a parameterless constructor and it can’t be a nested class.
It can have other constructors but these play no part in its working with XAML. Notice that as structs have a default parameterless constructor provided automatically by the system you can instantiate structs in XAML.
Now that we have our minimal class we can write some XAML to create an instance of it. However first there has to be some way of making the link between the XAML document and the class definition.
This is achieved by importing the class’s namespace into XAML.
You can import the namespace of any assembly and use namespaces to indicate exactly which class you are referring to. In this case we need to import the namespace of the assembly that the XAML file is part of, i.e. the current project.
So moving to the XAML editor we need to add a single line to the <Window> tag:
<Window x:
The “clr-namespace” is a special token which is interpreted to mean “get the namespace from the named CLR runtime”.
In general you might also need an “assembly=” token to supply the location of the assembly but in this case it’s assumed to be the current project.
Following this any name prefixed by m: is taken from the namespace of the current project - which is assumed in this case to be WpfApplication1.
The next thing we have to do is to get rid of the <Grid> tags as we cannot nest a general class within a grid – it needs a class that can be displayed.
To create the instance of our class all we have to enter is:
<m:MyClass> </m:MyClass>
between the <Window> and </Window> tag.
The project should now run without errors. If you do see any errors then it will be due to loss of synchronisation between namespaces – simply run the project again. The need to keep namespaces and other generated files in sync is one of the problems of splitting instantiation from the runtime.
So we have a working program that creates an instance of MyClass but this does us very little good as the instance is dynamic and goes out of scope as soon as the main form is loaded!
To keep the instance in scope, and to allow us to work with it within the C# code, we need to give the instance a name.
Standard WPF components are generally given a name via the NAME property but a more direct mechanism for custom classes is to use the facilities provided by the XAML “x” namespace. The “x:Name” attribute can be used to set the name used by XAML to create the instance:
<m:MyClass x:</m:MyClass>
With this change you can now run the program and, with the help of a breakpoint and the debugger, you can confirm that there it really does create MyObject1. Put a breakpoint in the MainWindow constructor after the call to InitializeComponent(). You will see MyObject1 listed in the Locals window:
If you would like to see the generated C# code that does the instantiation then load the file called MainWindow.g.cs - click on the Show All files icon in the Solution Explorer:
Navigate to the obj\Debug directory - where you will find MainWindow.g.cs.
If you look at the code you will discover that what happens boils down to:
internal WpfApplication1.MyClass MyObject1;
followed a few lines later by:
System.Uri resourceLocater=new System.Uri( "/WpfApplication1;component/mainwindow.xaml", System.UriKind.Relative); System.Windows.Application.LoadComponent( this, resourceLocater);
This creates the objects defined in the XAML file and then the instruction:
this.MyObject1 = ((WpfApplication1.MyClass)(target));
makes the connection between the object and the variable referencing it.
As already mentioned, WPF classes inherit a Name property which can be used in place of x:Name. If a class doesn’t have a Name property then use x:Name.
To assign a name property to a class you simply use the RuntimeNameProperty Attribute to designate a property that will store the name of the instance. For example:
[RuntimeNameProperty("MyName")] public class MyClass { public MyClass(){}
[RuntimeNameProperty("MyName")] public class MyClass { public MyClass(){}
public string MyName { get { return _MyName; } set { _MyName= value; } } private string _MyName= string.Empty;}
public string MyName { get { return _MyName; } set { _MyName= value; } } private string _MyName= string.Empty;
}
However this only works if the class belongs to another assembly and not the one actively being edited in Visual Studio say.
Notice also that the XAML compiler will create an instance with the name you specify and store the name in the property in case you need to make use of it.
As with WPF objects in XAML we can set properties on custom objects.
For example, if we add a trivial int property to MyClass:
public int MyProperty{ get{return m_MyProperty;} set{m_MyProperty=value;}} private int m_MyProperty;
we can set this to “20” within XAML using:
<m:MyClass x:</m:MyClass>
Now if you run the program and examine it after an early breakpoint you will see that the object has been created with the property set to 20.
You can also modify the property using the Property window:
Notice that the property type implied by XAML is string but the conversion to int is automatically taken care of – essentially by XAML asking the Convert object to convert the string to the type of the property.
This is fine as long as Convert has definitions for the appropriate ToType.
In addition to converting to the usual primitives, XAML will also try to convert a string to a suitable value of an enumeration by performing string matching against its values.
<ASIN:0735619573>
<ASIN:0672330318>
<ASIN:0596526733> | http://www.i-programmer.info/programming/wpf-workings/446-how-xaml-works.html | CC-MAIN-2015-22 | refinedweb | 1,218 | 56.29 |
Upgrading code to RoboFont 3 ↩
- Running RF 1 code in RF 3
- Running RF 3 code in RF 1
Developers are kindly advised to upgrade their code for RoboFont 3.
In practice, this means:
- upgrading from the RoboFab API to the FontParts API
- see RoboFab vs. FontParts APIs
- upgrading from Python 2 to Python 3 syntax
- see Writing Python 2-3 compatible code
Running RF 1 code in RF 3
RoboFab → FontParts
Using the RoboFab API in RoboFont 3.
- What happens?
- A deprecation warning will be raised, with an example of the new syntax.
Warnings can be configured with the Preference setting
warningsLevel. See Preferences Editor.
- Does the script work?
- YES.
- What to do?
- Please update your code to the FontParts API.
- Example
g = CurrentGlyph() g.move((100, 100)) g.update()
/Applications/RoboFontPy3.app/Contents/Resources/lib/python3.6/fontParts/base/deprecated.py:45: DeprecationWarning: 'RGlyph.move()': use RGlyph.moveBy() /Applications/RoboFontPy3.app/Contents/Resources/lib/python3.6/fontParts/base/deprecated.py:28: DeprecationWarning: 'RGlyph.update': use RGlyph.changed()
Change to:
g = CurrentGlyph() g.moveBy((100, 100)) g.changed()
Python 2 → Python 3
Using Python 2 syntax in RoboFont 3.
- What happens?
- A
SyntaxErroris raised.
- Does the script work?
- NO.
- What to do?
- Please update your code to Python 3.
- Example
print 'hello world'
Traceback (most recent call last): File "<untitled>", line 1 print 'hello world' ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')?
Change to:
print('hello world')
Running RF 3 code in RF 1
RoboFab ← FontParts
Using the FontParts API in RoboFont 1.8.
- What happens?
An error message is raised.
If the oneToThree extension is installed, RoboFont will try to map the newer FontParts API to the older RoboFab API automatically. However, not all possible differences between the RoboFab and FontParts APIs are covered.
- Does the script work?
- MAYBE.
- Example
g = CurrentGlyph() g.moveBy((100, 100)) g.changed()
Without oneToThree:
Traceback (most recent call last): File "<untitled>", line 2, in <module> AttributeError: 'RobofabWrapperGlyph' object has no attribute 'moveBy'
With oneToThree installed, this particular code snippet would work fine in RoboFont 1.
Here’s an example which oneToThree is not able to handle:
g = CurrentGlyph() g.rotateBy(30, origin=(100, 100))
Traceback (most recent call last): File "<untitled>", line 2, in <module> TypeError: rotate() got an unexpected keyword argument 'origin'
- What to do?
As a first step, give the oneToThree extension a try.
If your code includes syntax which is not covered by oneToThree, and you need to have your code working in both versions of RoboFont at the same time, you’ll need to use conditionals as a last resort. Simply ask RoboFont for its version, and run different bits of code for RF1 and RF3.
from mojo.roboFont import version # RF3 if version >= "3.0.0": g.rotateBy(30, origin=(100, 100)) # RF1 else: g.rotateBy(30, offset=(100, 100))
Python 2 ← Python 3
Using Python 3 syntax in RoboFont 1.
- What happens?
RoboFont 1 supports some of the newer Python 3 syntax automatically, thanks to the
__future__module. However, not all possible differences between the Python 2 and Python 3 are supported.
- Does the script work?
- PROBABLY.
- Example
Add example of Python 3 code which does not work in RF1.
- What to do?
Make sure your Python 3 code is compatible with Python 2.
See Writing Python 2-3 compatible code for reference. | https://doc.robofont.com/documentation/building-tools/recommendations-upgrading-RF3/ | CC-MAIN-2020-29 | refinedweb | 562 | 60.51 |
#include <apr_buckets.h>
A bucket referring to data allocated from a pool
The block of data actually allocated from the pool. Segments of this block are referenced by adjusting the start and length of the apr_bucket accordingly. This will be NULL after the pool gets cleaned up.
The pool bucket must be able to be easily morphed to a heap bucket if the pool gets cleaned up before all references are destroyed. This apr_bucket_heap structure is populated automatically when the pool gets cleaned up, and subsequent calls to pool_read() will result in the apr_bucket in question being morphed into a regular heap bucket. (To avoid having to do many extra refcount manipulations and b->data manipulations, the apr_bucket_pool struct actually contains the apr_bucket_heap struct that it will become as its first element; the two share their apr_bucket_refcount members.)
The freelist this structure was allocated from, which is needed in the cleanup phase in order to allocate space on the heap
The pool the data was allocated from. When the pool is cleaned up, this gets set to NULL as an indicator to pool_read() that the data is now on the heap and so it should morph the bucket into a regular heap bucket before continuing. | http://apr.apache.org/docs/apr/trunk/structapr__bucket__pool.html | CC-MAIN-2018-43 | refinedweb | 205 | 54.15 |
I'm writing a small web portal which will enable users to annotate some text, for a computational linguistics project, and save their annotations to file.
I'm having trouble getting the modified text to be saved.
My page is:
from bottle import template
from project import app
from bottle import request
from bottle import redirect
import random
@app.route('/')
def index():
notices = 'This is a placeholder text for StackOverflow'
return template('annotator/index', package=notices)
@app.route('/annotator/submit', method=['GET'])
def submit():
with open('output.txt', 'w') as outfile:
package = str(request.GET.get('package'))
outfile.write(str(package))
redirect('/')
<!doctype html>
<head>
<link rel="stylesheet" type="text/css" href="/css/style.css">
<title>My App</title>
</head>
<body>
<div class="page">
<h1>NM Annotator Demo V 0.1</h1>
% if package is not '':
<form action='annotator/submit',
<textarea name="package" ROWS=20 COLS=70>{{package}}</textarea>
<td><INPUT TYPE=SUBMIT</td>
</form>
%end
%include
</div>
</body>
<form action="annotator/submit" method="post">
<dl>
Thank you
</dl>
</form>
%rebase layout/layout
Your textarea and your submit form items are both named "package".
Change your button to this and see if that helps:
<INPUT TYPE=SUBMIT
EDIT: Explanation
The problem with having two form items that have the same name is that your application receives them both, on the query string. For example,
In your app, you'll effectively get a dict of the query args, and it will either look like
{'package': 'sometext'} or
{'package': 'Submit'}. Which one you get depends entirely upon the application (Bottle), but the most likely implementation--to process the query args in order--would result in the second value taking precedence, as it overwrites the first.
Most web frameworks expose a way to get all query args for a given name; in Bottle, it's request.query.getall. So
request.query.getall('package') would return
['sometext', 'Submit']. But in your case it makes much more sense to avoid the name collision in the first place, rather than keep it and then retrieve multiple values.
Hope that helps! | https://codedump.io/share/JbpSjlG3vMRE/1/saving-the-content-of-a-lttextareagt-to-file-with-bottle | CC-MAIN-2018-51 | refinedweb | 344 | 53.1 |
Updated to 2.8
Search Criteria
Package Details: sir 3.1-1
Dependencies (7)
- exiv2
- qt5-base (qt5-base-dev-git, qt5-base-git)
- qt5-imageformats (qt5-imageformats-git)
- qt5-svg (qt5-svg-git)
- cmake (make)
- qt5-tools (qt5-tools-git) (make)
- dcraw (optional) – RAW images support
Required by (0)
Sources (1)
Latest Comments
szlachar commented on 2015-03-09 19:38
Alister.Hood commented on 2014-09-15 04:45
The "upstream url" is dead. Looks like it should be changed to:
kzoli429 commented on 2014-09-01 17:28
Unfortunately cannot build any more:
==> Validating source files with sha1sums...
sir_2.7.2.tar.gz ... FAILED
==> ERROR: One or more files did not pass the validity check!
==> ERROR: Makepkg was unable to build sir.
szlachar commented on 2014-04-17 22:23
Updated to 2.7.1 with cmake in makedepends.
metak commented on 2014-03-16 01:48
It also needs 'cmake' in makedepends.
metak commented on 2014-03-16 01:47
Shouldn't there also be cmake in makedepends?
szlachar commented on 2012-11-14 21:00
updated to 2.5.1
Marvn commented on 2012-07-31 11:04
updated to 2.4
Marvn commented on 2012-05-17 16:57
updated to 2.3
Anonymous comment on 2011-10-23 18:23
src/metadatautils.h:4:27: fatal error: exiv2/exiv2.hpp: No such file or directory
compilation terminated.
#include <exiv2/exiv2.hpp> ← Here's the problem
Please add exiv2 to the dependencies ! | https://aur.archlinux.org/packages/sir/ | CC-MAIN-2016-30 | refinedweb | 248 | 61.43 |
23 November 2011 16:43 [Source: ICIS news]
LONDON (ICIS)--Coal to oil and chemicals producer Sasol estimates that earnings per share in the first half of its 2012 financial year, which ends on 31 December 2011, will be 45% higher than the year earlier comparable period, it said on Wednesday.
?xml:namespace>
The company made no other financial projections but said it was required to inform the market of the expected profits increase under the terms of its Johannesburg Stock Exchange (JSE) listing requirements.
The comparison is made against the first half 2011 performance and not the stronger second half fiscal 2011 results. It also takes into account lower synfuels production in the current reporting period which, it said, is expected to range between 7.0m and 7.2m tonnes.
Earnings per share for the first half of 2011, which ended on 31 December 2010, were rand (R) 12.97, and for the full year, which ended on 30 June 2011, R33.85.
Synfuels production from coal in
The coal conveyor system is in the process of being repaired, Sasol said.
Sasol’s CFO will review operations and the progress being made on capital projects in an update on 30 November 2011 to be posted on the company’s website.
Sasol’s financial results for the first six months of the 2012 fiscal year, ending 30 December 2011, will be posted on 12 March 2012.
For more on Sas | http://www.icis.com/Articles/2011/11/23/9511018/sasol-expects-45-higher-first-half-fiscal-2012-earnings.html | CC-MAIN-2014-41 | refinedweb | 240 | 58.72 |
Seam + Facelets: use of JSTL and if testsPÃ¥l Oliver Kristiansen Jun 23, 2006 4:54 AM
Hello !
I've posted this to the Facelets list aswell but if anyone in here have any ideas to help me solve this problem, I can tell you that my weekend would look quite different ;)
I have a seam component called "node" with a method
called "isNodeHaveSubNodes" hardcoded to return true.
Now, take this xhtml snippet:
Outputtext says: <h:outputText<br/> <c:ifIf test says its true</c:if> Resulting evaluation: <h:outputText<br/>
This prints:
Outputtext says: true Resulting evaluation: false
What im I missing ? Is this a configuration issue with regards to JSTL jars and so forth ? I see that in the examples (like DVD store) uses the "choose when"-tags extensively but that too generates the same problem for me.
Any ideas ?
This content has been marked as final. Show 3 replies
1. Re: Seam + Facelets: use of JSTL and if testssonja löhr Jun 23, 2006 7:11 AM (in response to PÃ¥l Oliver Kristiansen)
If something is wrong with your declaration of the standard core library, you should see the unresolved <c:if> tags in the html source of your output. How does your namespace-declaration for the core library look like?
2. Re: Seam + Facelets: use of JSTL and if testsPÃ¥l Oliver Kristiansen Jun 23, 2006 7:42 AM (in response to PÃ¥l Oliver Kristiansen)
They are like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xmlns:
However after further investigation I've found out that this only happens with within the ui:repeat (since the "node" object in question is within a collection).
The facelets manual says something about JSTL support: "."
I too new to all of this to really understand what that meant.
Strickly speaking this dont seem to be a Seam issue so I wont post anymore on that issue. Thanks anyway.
3. Re: Seam + Facelets: use of JSTL and if testsJim Hazen Jun 23, 2006 11:29 AM (in response to PÃ¥l Oliver Kristiansen)
You might want to try a c:if c:set combo.
Outputtext says: <h:outputText<br/> <c:if <c:set If test says its true </c:if> Resulting evaluation: <h:outputText<br/>
I haven't tested this, but I think it's your next best shot.
-Jim | https://developer.jboss.org/message/453795 | CC-MAIN-2018-26 | refinedweb | 396 | 66.88 |
fmt_human - Man Page
write a human readable ASCII representation of a long integer
Syntax
#include <fmt.h>
size_t fmt_human(char *dest,unsigned long long source);
Description
fmt_human writes a human readable ASCII representation of source to dest and returns the number of bytes written. The result resembles the file size output of "ls -H"; 1000 becomes "1.0k", 1000000 becomes "1.0M" and so on for "G" and "T".
fmt_human does not append \0.
If dest equals FMT_LEN (i.e. is zero), fmt_human returns the number of bytes it would have written.
The output of fmt_human can not exceed 11 (assuming unsigned long long has 64 bits).
See Also
fmt_humank(3), scan_human(3)
Referenced By
fmt_humank(3). | https://www.mankier.com/3/fmt_human | CC-MAIN-2021-49 | refinedweb | 117 | 68.97 |
This tutorial is a starting point for developing Android apps. It will explain the very basics of the Android SDK (Software Development Kit) and how to use it with Eclipse. To understand this tutorial, you don't need to have any knowledge about programming in Java, but it might be helpful for further programming to understand the basics of object orientated programming. This tutorial explains Android beginners how to create an Android Project in Eclipse, work with resources, and create some first code.
If you don't already have a running environment to develop Android apps, follow the instructions at this link.
Hint: PATH means the Path Environment Variable. In Windows, you will find it under "Control Panel/System/Advanced System Settings/Environment Variables" in the lower list box. You can check what version of Java is installed, by going in the command line and typing java -version.
Now we want to create our first application, which is (as always) a Hello World application. First of all, start Eclipse. Then select "File/New/Project". In the "New Project" dialog, select "Android/Android Project" and click "Next".
Here you can set up the project. First of all, we need to give the project a name, so type "Hello World" in the name box. Next you have to select the Android version you want to use. Here we choose version 2.2. As we see in the last column, we need the API Version 8 for this Android version, so we type an "8" in the Min SDK Version box. Also, the project requires an application name. (Notice that this name is also used in code, so the name should have no whitespaces). Usually, you use the project name and delete all whitespaces (e.g., "helloworld" for this project). Next, you have to define the package of the project. We will use "com.test.helloworld" here (a package can group multiple classes; for more information, see here). At least, you need a name for the activity (one App might have multiple Activities; they are like a single part/screen of the app). In this example, we simply use "HelloWorldApp".
Before we can finally start our first project, we need to create a configuration. This configuration specifies under which circumstances the app will be started. E.g., you can control the network speed the emulator/app can use. Also, you can choose different emulators to test the app with different versions of Android or in different screen sizes. To create the configuration, go to "Run/Run Configurations". Now click the "Android Application" tab at the side and then the New button above the tabs. Call the new configuration "HelloWorldConfig" and select our project over the Browse button. Now move on to the target tab. Here you can select the network speed and which emulator will be used.
Since we haven't created an emulator till now, we need to do that first. Click the automatic control to enable the buttons at the side and then click on the manager-button. Here, click the new button to the right to create a new emulator. In the following screen, you can enter a name for the emulator (I have used "DefaultAndroidEmulator") and specify the details (like Android version, SD card size, and much more). You can control every little detail of the emulator over the hardware section.
Once you are done with that, click "Create AVD" and close the manager window. Now we have successfully created the run configurations. Click "Apply" and close the configurations. At least run your first Android project.
Notice: It may take the emulator some time to get started, so be patient! Also, I have cropped the image so that you can't see the keyboard or the D-pad.
Congratulations! You just created your first App!
After we have set up everything, it's (finally) time to actually getting started with the code, because we all know: Coding is fun!
But before we can actually jump into the Java code, we need to understand the structure of an Android Application. Go to your Package Explorer and enlarge the "Hello World" project. You will see five folders and two files. Let's get started with the one of these two files, the AndroidManifest file. This file contains all the information about your project, like the icon, the name of the author. To open it, make a right click on it and choose "Open With/Android Manifest Editor". In the upcoming tab, you can specify the package name and the version of your project. At the bottom, you will find additional tabs. I think most of the settings you will find are pretty much self-explanatory. Note the @ in front of some attributes. This shows that the following string is a reference to a resource. You can find the resources in the "res" folder of your project. If you enlarge it, you will notice that it has some subfolders. To be specific, the res folder can have seven types of subfolders: values, drawable, layout, animations, xml, styles, and raw.
Let's focus on the values folder first. Here you can store all kinds of simple resources (like strings, colors, numbers, dimensions, arrays, etc.). By default, you will find the strings.xml file in there. When you open it (with right click, "Open with/Android Layout Editor"), you will see that it contains two values. The first is the message you see when you run your project, and the second is the name of your app. You can add new values if you want to use them later on in code (or in the Manifest or Layout files). You can also create specific resources using quantifiers. If you add a - to the folder's name, you can add a quantifier to the name. E.g., you can rename the values folder to values-en which means that the content of the folder is only used by Android phones with English language activated. If you do not add a quantifier, the resources are default. The default resources are used if no specific resources for the current system are found. If the project is started, all resources will be compiled as efficiently as possible and added to the package. Also, a reference will be created (called R) which allows you to access the resources in code. Since this is only a tutorial, I will not focus on all the types of resources here. You can find more information on resources and quantifiers here.
At last, it is time to start coding! Go to the "src" folder. In the folder, you will find the package folder, open the HelloWorld.java file. You will see the default code for an Android Activity:
package com.test.helloworld; //the package we are working in
//some android packages we need to import
import android.app.Activity;
import android.os.Bundle;
//our activity class (extendes the default activity class)
public class HelloWorldApp extends Activity {
/** Called when the activity is first created. */
@Override
//the function called when activity is created
public void onCreate(Bundle savedInstanceState) {
//call the create fct. Of the base class
super.onCreate(savedInstanceState);
//load the layout specified in the layout.xml
setContentView(R.layout.main);
}
}
As you can see, we create a new activity by extending the default Android activity class. Then we override the default onCreate function, which is called when the project is created. In there, we load our own layout from the resources and also call the onCreate function of the base class. Now let's take a closer look at the layout file. You find it in the layout folder under resources. When you open it, it should look like this:
onCreate
<linearlayout android:layout_height="fill_parent"
android:layout_width="fill_parent" android:orientation="vertical"
xmlns:
<textview android:layout_height="wrap_content"
android:
</linearlayout />
You see the root node is called LinearLayout. As you you might already have figured out, there are different types of layouts:
LinearLayout
FrameLayout
RelativeLayout
TableLayout
AbsoluteLayout
Once you have chosen a layout type, you can add child elements. In the code given, there is already a TextView, which is used to display text on the screen. The current content is a reference to a resource defined in the values.xml file. As you will see, it uses the whole width of the screen, but is only as long as it needs to, to display the content. We might start with some small changes. Let's change the text color of the TextView to green:
TextView
<textview android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="@string/hello"
android:
Now, launch the project and see the changes. Next, let's add a new control called EditText:
EditText
<linearlayout android:layout_height="fill_parent"
android:layout_width="fill_parent" android:orientation="vertical"
xmlns:
<edittext android:layout_height="wrap_content"
android:layout_width="fill_parent" android:textcolor="#FF0000FF"
android:
<textview android:layout_height="wrap_content" android:layout_width="fill_parent"
android:
</linearlayout />
When we want to access the controls in code, they need to have an ID. Next we create some code for the controls. Go to the helloworld.java file.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get the two controls we created earlier, also with the resource reference and the id
final TextView tv_View = (TextView)findViewById(R.id.tv_View);
final EditText et_Text = (EditText)findViewById(R.id.et_Text);
//add new KeyListener Callback (to record key input)
et_Text.setOnKeyListener(new OnKeyListener()
{
//function to invoke when a key is pressed
public boolean onKey(View v, int keyCode, KeyEvent event)
{
//check if there is
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
//check if the right key was pressed
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
//add the text to the textview
tv_View.setText(tv_View.getText() + ", " +
et_Text.getText());
//and clear the EditText control
et_Text.setText("");
return true;
}
}
return false;
}
});
}
We will analyze the code line by line. First of all, as before, we load the layout. Then we create a TextView and a EditText variable and load our interface objects in them (that's what we need the ID for). Finally, we add a new OnKeyListener to the EditText control. In this OnKeyListener, we create the method onKey, which is called when a key is pressed, when the control is active. In the method, we perform two checks: the first to be sure that a key is pressed down (and not released), and the second to specify the key (in this case, the center key of the D-pad). If both checks are passed, we add the text of the EditText control to the TextView, and finally the text of the EditText control is deleted. Run and test the application. Great, you created your first real Android app.
OnKeyListener
onKey
As with every platform, Android has its own design challenges. Always keep in mind that you are developing for a mobile platform with limited memory, disk space, and processing power. Therefore, Android automatically kills processes (each app runs in its own process) to keep the system responsive. Processes are sorted after importance. The most important is the currently active process, followed by visible and stated service processes. The bottommost types of processes in hierarchy are background and empty processes. Keep that in mind when you design your application, because you don't want its process to be killed in the middle of something. Also, you can use whatever hardware is built into the Android phone. But notice that not all phones might have this hardware, and so not all might be able to run your app.
That's it for this tutorial. Hopefully, you understood the basics of Android development. Since this is my first article on CodeProject, I would really appreciate. | http://www.codeproject.com/Articles/102065/Android-A-beginner-s-guide?fid=1583614&df=90&mpp=10&sort=Position&spc=None&tid=4419797 | CC-MAIN-2015-22 | refinedweb | 1,939 | 65.83 |
Clean Code
Practical Clean Code 1: Variables Methods Classes
Practical guide for applying and evolving clean code, design patterns to domain driven. This series will highlight each of the steps and then connect all of them into the big picture so everything can make more sense. This article being the first, focusing on clean code at class level and below.
Overview
By no means this article is comprehensive. This article highlights items which in my experience would help start off. Readers should expand further by reading books on the subject.
Clean code here, means that the code has qualities that can make developers / programmers understand and change it easily such as (but not limited to):
- Conveys clear intention
- Easy to understand (the flow, logic, at every abstraction level)
- Easily update-able and make changes (changing one thing doesn’t cause a chain reaction, )
- Testable
Having clean code means you easily update your code to match you current understanding, design and model of the system. To safe guard your refactoring efforts, tests must be in place.
Tests
One of the things that enables you to convey clear intention is to ensure that the code models the problem domain closely and up to date as it the design becomes clearer. This will ensure the code is self documented and the basic assumptions of the code are as expected. What better ways than to test your “assumptions” via tests :P.
You can choose between unit tests, integration tests (test containers, embedded db, etc.) within your project by deciding how much value / test coverage vs the effort. Building an in house product would be ideal to have test at all levels (unit, integration and system) but for projects that’s one off with tight dateline, it’s better to choose something high value vs effort IE. integration test (though trade off tests run much slower).
More details on tests will be shared on separate article:), but at the very least you can do in the beginning, is to separate object construction and its usage.
Construction vs Usage
To improve test-ability and re-usability, we need to separate object construction and usage. Without separation, both construction and usage will be intertwined at the same place / class. Example:
public class SomeClass { public void someMethod() {
final Object something = new Object(); // construction
object.something(); // usage
}}
The “object” should be instantiated somewhere else and not within the class that is using it. Perhaps it can be constructed in the main class, factory or if you are using DI framework in it’s registry mechanism (for Spring case would be as the bean). Then the class that’s using the object should have a mechanism to pass the constructed object either via constructor, setter or in Spring case (if you choose to) reflection.
Continuing on from the example above, the object can be passed to the SomeClass via constructor.
public class SomeClass {
private final Object thatObjectYouWantToUse; public SomeClass(final Object thatObjectThing) { this.thatObjectYouWantToUse = thatObjectThing;
}public void someMethod() {
final Object something = new Object(); // construction
thatObjectYouWantToUse.something();
}}
This gives few benefit:
- Test-ability by allowing you to substitute the “Object ”with something else (mocking it for example) for testing via dependency injection.
- Re-usability, by allowing to reuse existing implementation with different behavior (IE: you have a class that uses another object, you can pass a different object here that does something different)
- Flexibility, by giving you path ways for expand-ability, 1 instance, through multiple implementation of the same concrete class via interface (design patterns, hint* strategy pattern for example hint*, more details on this later)
There’re more subjects like how to make test less fragile, clean tests, test smells, patterns, but we are not get into that for now. The points above would be somewhat enough to get you started.
Just that, I can’t stress enough how important test is in making your code clean.
We are going to use a web gallery application for back-end for some of the examples to illustrate the points below. For other cases I would use generic naming scheme to illustrate the intention of applying cleaner implementation.
Variable
Be Generous in Giving the Name
Don’t be stingy with the number of character. Try to give a name that reveal the intention of storing the data in the variable.
You have a URI for un-edited and un-resized image.
private final String uri;// not thisprivate final String image;// not thisprivate final String rawImageUri; // use this
Use variable to add clarity
Let’s say you have a situation where you have the thumbnails URI.
- Then this URI will be prefixed with the CDN server.
- This CDN server will depend on some condition within Thumbnail.
- If thumbnail has has large sized url link (I will use simple boolean flag to illustrate), use the default CDN server.
- If not append the CDN based on the region passed.
- Finally convert it to another type, response for example.
If you are > java 8, you might have something like the following:
You can assign in between to a variable before proceeding to the next step. This variable you can use a name that illustrate the intention. Line 6, using the variable we are showing the steps are to build a list of “thumbnailWithCdn”. Line 12, we are building the “responseData ”for downstream consumption.
The same idea should also be used to illustrate methods.
Method
Your Intent in Action
Method name would be doing something with the intention of doing it.
getSomething()
resizeAndCompressImage()
prefixImageWithCorrectCdn();
removeItemIfNeeded() // the item is removed if the condition is met.
Method name should be a concise description on the steps within the method, and the end result should be the reader should have a general idea what the method is doing just by glancing the method’s name.
The need to comment is the need to rename
If you feel you need to write a comment to clarify the method’s intention then it’s a sign you should rename your method to something else. Comments should be reserved for whys and context of the method implementation and should not be used to clarify your intention.
Long Method Name (too long)
Might be an indicator you need to break the method further. Try to think at which abstraction level you should break and see it makes sense.
checkValidityAndBuildUrlIfNecessary() // you can break to belowfinal Map<String, Validity> objectIdValidityMapping = checkValidity();
final List<Object> objectWithUrl = buildUrlIfNecessaryWithValidity(objectIdValidityMapping);
Choose Proper Abstraction Level
For example you have the following steps you need to do.
- Get some data from the database
- Based on the data check on an external system (REST endpoint perhaps) to verify something (legit or not, authorize or not, anything)
- Then after that, based on verified items you need to access another external system to get additional data (REST perhaps)
- Finally merge both data and return.
Below you can see 3 methods, first without any abstraction whatsoever. Second with mixed abstraction (one of the step is extracted as method). Finally, last one, all encapsulated in methods at proper abstraction level.
SomeData being just an example data structure for the initial call, SomeData2 is used as ab example to represent the data from external system. You can imagine SomeData could be your profiles, accounts, books some entity as basis. SomeData2 could be your data extension, address, authors, supplement accounts etc.
Do One Thing in a method (Same Abstraction Level)
After understanding a bit on proper abstraction, next, is to ensure that each method do one thing at a given abstraction level.
Looking above, “getVerifiedSomeData()” method line 82, it’s consist of few steps,
- Getting the raw data from database
- Converting the SomeData to just the ids for next step usage.
- Converting map of the id and the verification (just a boolean)
- Returning verified SomeData, meaning filtering our the false verification in step 3.
All the above steps can be abstracted at 1 level in the method “getVerifiedSomeData()”.
If… else… then?
Having too many if elses (and nested ones) increases the cyclomatic complexity (simpler term, complexity of the code :P),. Try to cut it down by making the conditions simpler, or thinking a simpler logic. If not, encapsulate each branch in a method.
If the if then elses are part of checking mechanism for null or empty, you can reduce it by:
- Using optional.orElse return default value (java > 8 ),- (line 4)
- Apache’s ObjectUtils comes in handy to minimize if else,-. Will use the default if it’s null. (line 6)
- You could also use switch by identifying the proper flag for the switch to trigger. (quite straightforward for this one)
- Encapsulate the decision making in another method. (line 8)
The above just to check nulls and empty value. You can replace this with something that fits your case. If that can’t be done, there’s a cleaner way to go, the chain of responsibility for example :). We will get to there later.
Consistency
If you are using a variable call image and a method doing something on it should also refer to the image in the method name.
private final String imageUri;private void selectCdnForImageUri () {..};// NOT
private void selectCdnForPictureUri() {..};
Another point for consistencies, is the term use in discussions either business or technical in nature. That term should be the same when discussing with Analyst, Product Owners, business stakeholders, developers, architects and other technical stakeholders. If there’s a translation or mapping required from business to technical model or vice versa, then there’s a gap that has a high chance of causing miss-communication and confusion.
Consistencies, consistencies, consistencies…
Class
Naming
Should use noun or noun phrase that concisely describe the concept. This is important because from the name, if it’s define correctly, it will help you in making the class cohesive. In software engineering we strive in maximizing cohesiveness and minimizing coupling.
Cohesiveness
If you’re able to name the concept concisely, then the class should only do what it suppose to do within the boundary of its concept definition. This basically “centralized” the concern of the concept and ensure if changes are needed (at least for that concern),only 1 location are needed to be modified.
From understanding perspective, it’s easier to get the mental picture of what’s going on. Having mix bag of things in the class makes it harder to have the bigger picture.
Use Class (Data Type) in Conjunction with Variable
You could use class name to provide more context for the variable. One example is for thumbnail. You have thumbnails which have many sizes and maybe a caption to represent it.
You can put loosely in a class,
private final String thumbSmallMainPageUS;
private final String thumbMediumMainPageUS;
private final String thumbLargeMainPageUS;
private final String thumbCapMainPageUS;private final String thumbSmallSubPageAsia;
private final String thumbMediumSubPageAsia;
private final String thumbLargeSubPageeAsia;
private final String thumbCapSubPageAsia;
which is rather messy.
Or you can put everything in a class that encapsulate the concept and the intention.
public class Thumbnail {
private final String region;private final String thumbSmall;
private final String thumbMedium;
private final String thumbLarge;
private final String thumbCap;
}//usageprivate final Thumbnail mainThumbnail;
Generalization with interfaces
To improve the cohesiveness of the module, you can proceed to generalize the class. This involves abstracting similar classes by distilling its common behaviors. This in turn (at least in java world for classes) gets you interfaces.
The interface makes it clear that the classes (concrete, implementations) can be used and accessed similarly. In other words, interface makes the intention clear that these classes has explicit contract which states what it has and what it must do (behaviors).
Technically speaking, classes with the same implementation will have to implement the methods in the interface. This allow the class to be substituted with other class that implements the same interface. Looking back at construction vs usage, you can use in conjunction with interface to improve re-usability and clarity of your intention in the implementation.
final ThumbnailBig thumbnailBig = new ThumbnailBig();
final ThumbnailSmall thumbnailSmall = new ThumbnailSmall();
thumbnailBig.resizeMedium();
thumbnailSmall.resizeMedium();
Without interface, the above example ThumbnailBig and ThumbnailSmall will be disconnected by concept. Both of them will be un-related as both are different class. However, conceptually and semantically both are the same. Weeks or months passed, and you look at the code again and wonder, are both of them different to warrant different implementation and contracts?
Utilizing interface, we explicitly make both ThumbnailBig and Small are a type of Thumbnail. Since both implements the same interface (let’s call it GeneralThumbnail), both will have the interface’s method (let’s call it resizeMedium). All types of thumbnail implements this interface and all of them can do resizeMedium. This implementation conveys the idea that the concept of thumbnail is able to be resized to medium which bridges the understanding of the implementation.
Moreover, this is useful in terms of re-usability and test-ability because you can model a concept with multiple implementations and then reuse this in other place as long it has the same contract. That applies for tests as well.
Peer Review
So you put hours, if not days (not weeks :P, we don’t want to annoy your team with a huge PR lol), and now you want to raise a PR and let your team have a look.
Due to mental fatigue or familiarity of your code, you won’t see from perspective of someone with a pair of fresh eye. So things like maintaining method at proper abstraction level or the naming things may be missed in your review. Something that may seem clear to you might be convoluted to others ;).
Someone else may catch this and the team may collective improve the code through feedback and discussion. If you are working alone, then having a break and doing other things then coming back after 2- 5 hours may help you review the code with a fresh mind.
Wrap Up
The above are the basics. Practice it on multiple projects. As it becomes apart of your instinct, you began applying more on what you’ve read and learn.
Making code clean and simple is an evolution process. Step by step, variables, methods and classes being re-defined based on new understanding and models. Tests are the mechanism to ensure refactoring process and changes doesn’t cause regression or unexpected changes in its existing behavior.
Based on above you can see it’s a fundamental block where the code could be evolved to something more structured. Design Patterns for example. The if.. else branches can be improved into chain of responsibility pattern and the construction vs usage into factories.
Key point here is that, intention should be made clear and strive to lower coupling and increase cohesion between all levels of components in a step by step manner.
Reference
- Clean Code, Robert C Martin
- Clean Architecture, Robert C Martin
- Refactoring, Martin Fowler
- Effective Java, Joshua Bloch | https://maziz88.medium.com/practical-clean-code-variables-methods-classes-f470eeffb98e | CC-MAIN-2021-04 | refinedweb | 2,484 | 52.7 |
Installation¶
SpiceyPy is currently supported on Mac, Linux, FreeBSD, and Windows systems.
If you are new to python, it is a good idea to read a bit about it first. For new installations of python, it is encouraged to install and or update: pip, setuptools, wheel, and numpy first before installing SpiceyPy
pip install -U pip setuptools wheel pip install -U numpy
Then to install SpiceyPy, simply run:
pip install spiceypy
If you use anaconda/miniconda/conda run:¶
conda config --add channels conda-forge conda install spiceypy
If no error was returned you have successfully installed SpiceyPy. To verify this you can list the installed packages via this pip command:
pip list
You should see spicepy in the output of this command. Or you can start a python interpreter and try importing SpiceyPy like so:
As of 04/10/2021, spiceypy has experimental support for 64bit ARM processors for linux and macos (linux-aarch64 & osx-arm64) via the conda-forge distribution.
import spiceypy # print out the toolkit version installed print(spiceypy.tkvrsn('TOOLKIT'))
This should print out the toolkit version without any errors. You have now verified that SpiceyPy is installed.
Offline installation¶
If you need to install SpiceyPy without a network or if you have a prebuilt shared library at hand, you can override the default behaviour of SpiceyPy by using the CSPICE_SRC_DIR and CSPICE_SHARED_LIB environment variables respectively.
For example, if you have downloaded SpiceyPy and the CSPICE toolkit, and extracted CSPICE to /tmp/cspice you can run:
export CSPICE_SRC_DIR="/tmp/cspice" python setup.py install
Or if you have a shared library of CSPICE located at /tmp/cspice.so, you can run:
export CSPICE_SHARED_LIB="/tmp/cspice.so" python setup.py install
Both examples above assume you have cloned the SpiceyPy repository and are running those commands within the project directory.
A simple example program¶
This script calls the spiceypy function ‘tkvrsn’ and outputs the return value.
File tkvrsn.py from __future__ import print_function import spiceypy def print_ver(): """Prints the TOOLKIT version """ print(spiceypy.tkvrsn('TOOLKIT')) if __name__ == '__main__': print_ver()
From the command line, execute the function:
$ python tkvrsn.py CSPICE_N0066
From Python, execute the function:
$ python >>> import tkvrsn >>> tkvrsn.print_ver() CSPICE_N0066
SpiceyPy Documentation¶
The current version of SpiceyPy does not provide extensive documentation, but there are several ways to navigate your way through the Python version of the toolkit. One simple way is to use the standard Python mechanisms. All interfaces implemented in SpiceyPy can be listed using the standard built-in function dir(), which returns an alphabetized list of names comprising (among) other things, the API names. If you need to get additional information about an API parameters, the standard built-in function help() could be used:
>>> import spiceypy >>> help(spiceypy.tkvrsn)
which produces
Help on function tkvrsn in module spiceypy.spiceypy: tkvrsn(item) Given an item such as the Toolkit or an entry point name, return the latest version string.. html :param item: Item for which a version string is desired. :type item: str :return: the latest version string. :rtype: str
As indicated in the help on the function, the complete documentation is available on the CSPICE toolkit version. Therefore it is recommended to have the CSPICE toolkit version installed locally in order to access its documentation offline.
Common Issues¶
SSL Alert Handshake Issue¶
Attention
As of 2020, users are not likely to experience this issue with python version 3.7 and above, and for newer 3.6.X releases. Users running older operating systems are encouraged to update to newer versions of python if they are attempting to install version 3.0.0 or above. See other sections of this document for more information.
In early 2017, JPL updated to a TLS1.2 certificate and enforced https connections causing installation issues for users, in particular for macOS users, with OpenSSL versions older than 1.0.1g. This is because older versions of OpenSSL still distributed in some environments which are incompatible with TLS1.2. As of late 2017 SpiceyPy has been updated with a strategy that can mitigate this issue on some systems, but it may not be totally reliable due to known deficiencies in setuptools and pip.
Another solution is to configure a new python installation that is linked against a newer version of OpenSSL, the easiest way to do this is to install python using homebrew, once this is done spiceypy can be installed to this new installation of python (IMHO this is the best option).
If your python 3.6 distribution was installed from the packages available at python.org an included command “Install Certificates.command” should be run before attempting to install SpiceyPy again. That command installs the certifi package that can also be install using pip.
Alternatively, installing an anaconda or miniconda python distribution and installing SpiceyPy using the conda command above is another possible work around.
Users continuing to have issues should report an issue to the github repository.
Supporting links:
How to install from source (for bleeding edge updates)¶
Attention
If you have used the pip or conda install commands above you do not need to do any of the following commands. Installing from source is intended for advanced users. Users on machines running Windows should take note that attempting to install from source will require software such as visual studio and additional environment configuration. Given the complexity of this Windows users are highly encouraged to stick with the releases made available through PyPi/Conda-Forge.
If you wish to install from source, first simply clone the repository by running the following in your favorite shell:
git clone
If you do not have git, you can also directly download the source code from the GitHub repo for SpiceyPy at
To install the library, simply change into the root directory of the project and then run:
python setup.py install
The installation script will download the appropriate version of the SPICE toolkit for your system, and will build a shared library from the included static library files. Then the installation script will install SpiceyPy along with the generated shared library into your site-packages directory. | https://spiceypy.readthedocs.io/en/v4.0.1/installation.html | CC-MAIN-2021-43 | refinedweb | 1,016 | 52.6 |
Add CSS for tab components and color schemes.
Review Request #10387 — Created Jan. 22, 2019 and submitted — Latest diff uploaded
This introduces common CSS for defining tab navigation for content.
It's meant to be generic enough to be used in a variety of cases, but
also to be extendable for additional presentation modes going forward.
Tabs are defined by creating a
ul.rb-c-tabselement, with
li.rb-c-tabs__tabelements inside of it. Each has a label, which can
optionally have a short version for mobile devices.
On mobile devices, tabs are also horizontally scrollable, keeping the
tabs from wrapping around awkwardly.
Mixin functions are available to customize tab presentation.
.set-color-scheme()defines the colors used by the tabs, and
.set-flush-with-border()makes the tabs flush with a border of a
content container.
Tabs make use of another new CSS addition, color schemes. We constantly
define colors throughout our UI, rarely making use of centralized
variables for them. In an effort to both standardize colors and to make
it easy to apply them, the beginnings of a set of namespaced color
definitions and pre-defined color schemes (grouping together
backgrounds, borders, etc.) now exist in
colors.less. Color schemes
can be passed currently to
.set-color_scheme(), and other functions
down the road, to give a standard way of customizing components.
Made use of this with the Issue Summary Table.
Tested the full and short labels in mobile/desktop modes, and tested
the horizontal scrolling in mobile mode.
Tested the mixins in different conditions. | https://reviews.reviewboard.org/r/10387/diff/?expand=1 | CC-MAIN-2020-10 | refinedweb | 257 | 51.44 |
As you've seen in recent lessons, data science leans on data visualizations to draw inferences about our data, and to make sense of the math we use in making sense of this data. We saw how plotting data with a bar chart can be used to show the relationship between $x$ and $y$ variables.
In this lesson, we'll explore more of the functionality of the Plotly library. As we do so, pay careful attention to the data type that our methods require: whether they are dictionaries or lists, or lists of dictionaries. Ok, let's go!
As you know, to get started with Plotly, we first install the library on our computer. Let's do so in Jupyter by executing the cell below.
!pip install plotly
If plotly is already on your computer, pip will tell you that the requirement is already satisfied. That's ok, we can happily proceed.
The next step is to import the plotly library.
import plotly from plotly.offline import iplot, init_notebook_mode init_notebook_mode(connected=True)
If we plot offline, we do not need to provide a login. So we plot offline, while plotting our first plot with the below line.
plotly.offline.iplot([ {} ])
Let's take another look at that line of code.
plotly.offline.iplot([ {} ])
We reference the
plotly library, which we imported above. Then we pass a list containing a dictionary to the
iplot method. That dictionary can represent a scatter trace, a line trace, or other types of traces.
We pass the trace into a list because we can have more than one trace in the same graph - for example two bar traces displayed side by side or a scatter trace underneath a line trace.
Now let's discuss how a trace represents data. In the
trace in the code below, we plot four points. Notice that we provide the $x$ and $y$ coordinates in two separate attributes of the dictionary. Change around the data to get a feel for how it works.
trace = {'x': [1, 2, 3, 4], 'y': [1, 2, 3, 4]} plotly.offline.iplot([ trace ])
The plot above has one trace which is a line trace. However, this type of trace is just the default. Note, that we did not specify any particular type.
trace = {'x': [1, 2, 3, 4], 'y': [1, 2, 3, 4]}
We can change it by changing the mode to
markers. While we are at it, let's also change the color of the markers.
trace = {'x': [1, 2, 3, 4], 'y': [1, 2, 3, 4], 'mode': 'markers', 'marker': {'color': 'rgba(255, 182, 193, .9)'}} plotly.offline.iplot([ trace ])
Cool! So we changed the code to markers and changed the colors of those markers by setting the rgb (red, green, blue) value.
trace = {'x': [1, 2, 3, 4], 'y': [1, 2, 3, 4], 'mode': 'markers', 'marker': {'color': 'rgba(255, 182, 193, .9)'}}
Now let's add more than one trace to a given graph. We'll keep the first trace largely the same by using the same data, and color of markers. We'll name our trace 'Some dots' by adding the name attribute and set it equal to the corresponding string.
trace0 = {'x': [1, 2, 3, 4], 'y': [1, 2, 3, 4], 'mode': 'markers', 'marker': {'color': 'rgba(255, 182, 193, .9)'}, 'name': 'Some dots'}
In the second trace, we have some new data, and set the color as blue. Because we did not specify a mode, it defaults to connecting the points as a line. And we name our trace as "Our nice line".
trace1 = {'x': [1.5, 2.5, 3.5, 4.5], 'y': [3, 5, 7, 9], 'marker': {'color': 'blue'}, 'name': 'Our nice line'}
Finally, we create a plot of the two traces.
plotly.offline.iplot([ trace0, trace1 ])
So far, we have only worked with either scatter charts or line charts. The two charts are really quite similar -- connecting lines versus no connecting lines -- and plotly treats them as such. However, there are other ways of viewing the world beyond dots and lines. Now let's see how.
For example, we can make a bar chart, simply by specifying the in our dictionary that the
type is
bar for a
bar trace.
bar_trace = {'type': 'bar', 'x': ['bobby', 'susan', 'eli', 'malcolm'], 'y': [3, 5, 7, 9], 'marker': {'color': 'blue'}, 'name': 'Our nice bar trace'} plotly.offline.iplot([ bar_trace ])
Another way to create a bar chart is to use the constructor provided by plotly. It's not too tricky to do so. First, we import our
graph_objs library from Plotly. And then we call the bar chart constructor.
from plotly import graph_objs bar_trace_via_constructor = graph_objs.Bar( x=['bobby', 'susan', 'eli', 'malcolm'], y=[3, 5, 7, 9] ) bar_trace_via_constructor
We refer to the function
graph_objs.Bar as a constructor because it literally constructs python dictionaries with a key of
type that equals
bar. Then, we can pass this dictionary to our
iplot method to display our bar chart.
bar_trace_via_constructor = graph_objs.Bar( x=['bobby', 'susan', 'eli', 'malcolm'], y=[3, 5, 7, 9] ) plotly.offline.iplot([ bar_trace_via_constructor ])
Now let's look at some constructors for make other traces.
graph_objs.Scatter()
graph_objs.Pie()
And of course, we can always use the dictionary constructor to create our dictionaries.
pie_trace = dict(type="pie", labels=["chocolate", "vanilla", "strawberry"], values=[10, 5, 15]) plotly.offline.iplot([ pie_trace ])
So far we have seen how to specify attributes of traces or charts, which display our data. Now let's see how to modify the overall layout in our chart.
Note that the format of our traces will not change.
trace_of_data = {'x': [1.5, 2.5, 3.5, 4.5], 'y': [3, 5, 7, 9], 'marker': {'color': 'blue'}, 'name': 'Our nice line'}
However, instead of passing to our
iplot function a list of traces, we pass our
iplot function a dictionary with a
data key, which has a value of a list of traces. The
layout key points to a dictionary representing our layout.
layout = {'title': 'Scatter Plot'} trace_of_data = {'x': [1.5, 2.5, 3.5, 4.5], 'y': [3, 5, 7, 9], 'marker': {'color': 'blue'}, 'name': 'Our nice line'} figure = {'data': [trace_of_data], 'layout': layout} plotly.offline.iplot(figure)
So above we used the
layout to name our plot's title. Now that we have used
layout to specify our chart's title, let's also use it to specify the range of our x axis and y axis. Previously, we were allowing Plotly to automatically set the range. We can also adjust the range to meet our specifications.
layout = {'title': 'Scatter Plot', 'xaxis': {'range': [1, 10]}, 'yaxis': {'range': [1, 10]}} trace_of_data = {'x': [1.5, 2.5, 3.5, 4.5], 'y': [3, 5, 7, 9], 'marker': {'color': 'blue'}, 'name': 'Our nice line'} figure = {'data': [trace_of_data], 'layout': layout} plotly.offline.iplot(figure)
We can see how adjusting the range changes our perspective of the plotted x and y values.
In this section we explored more of Plotly's library to create different data visualizations. We created different traces to represent our data, with each trace represented as a dictionary passed to our
iplot method. We saw how to display multiple traces in a chart by wrapping the traces in a list. We learned how to use constructors like
graph_objs.Bar to create a chart. The constructor creates a dictionary that we can pass to our
iplot method. Finally, we moved onto modifying the layout of our charts with another python dictionary. | https://learn.co/lessons/plotly-basics | CC-MAIN-2019-43 | refinedweb | 1,236 | 73.88 |
General) or processing units (PUs)) data?
Azure Event Hubs standard and dedicated tiers store metadata and data in regions that you select. When geo-disaster recovery is set up for an Azure Event Hubs namespace, metadata is copied over to the secondary region that you select. Therefore,.
What client IPs are sending events to or receiving events.
Note
Currently, it's not possible to determine the source IP of an individual message or event.
Apache Kafka integration? (Applied to **standard** tier only)).'t changeable in all tiers except the dedicated tier,. throughput unit is used up to the maximum ingress allowance.?
Troubleshooting.: | https://docs.microsoft.com/it-it/azure/event-hubs/event-hubs-faq | CC-MAIN-2021-25 | refinedweb | 102 | 60.31 |
libffi has been updated, so llvm-minimal-git needs a rebuild .
After that rebuild has finished you will need to rebuild this pacakge also .
libffi has been updated, so llvm-minimal-git needs a rebuild .
After that rebuild has finished you will need to rebuild this pacakge also .
Patch added to solve a build failure, see
clover patch has also been commited now:
Thanks for the alert, Xenu.
Patch edited & renamed, working on lib32-mesa-minimal-git now. .
MR 12715 has been commited to main:
Though this only fixes "src/amd/llvm/ac_llvm_helper.cpp". Patching "src/gallium/frontends/clover/llvm/codegen/common.cpp" was not part of this MR.
Thank you for your work Lone_Wolf.
Patch as posted by xenu applied.
Thanks for creating it.
Created a short patch for current build issue with llvm14 (based on)
--- a/src/amd/llvm/ac_llvm_helper.cpp +++ b/src/amd/llvm/ac_llvm_helper.cpp @@ -60,7 +60,7 @@ llvm::Argument *A = llvm::unwrap<llvm::Argument>(arg); llvm::AttributeList AS = A->getParent()->getAttributes(); unsigned ArgNo = A->getArgNo(); - return AS.hasAttribute(ArgNo + 1, llvm::Attribute::InReg); + return AS.hasParamAttr(ArgNo, llvm::Attribute::InReg); } --- a/src/gallium/frontends/clover/llvm/codegen/common.cpp +++ b/src/gallium/frontends/clover/llvm/codegen/common.cpp @@ -233,8 +233,8 @@ namespace { } } else { - const bool needs_sign_ext = f.getAttributes().hasAttribute( - arg.getArgNo() + 1, ::llvm::Attribute::SExt); + const bool needs_sign_ext = f.getAttributes().hasParamAttr( + arg.getArgNo(), ::llvm::Attribute::SExt); args.emplace_back(module::argument::scalar, arg_api_size, target_size, target_align,
until that MR gets added.
I had an issue with opengl games freezing after a short time and causing a GPU reset (Radeon 6900XT). Same game run with zink worked fine. Downgrading llvm/clang to version 12 and rebuilding this package resolved the issue. Anyone else run into this?
Depends on which functionality you need.
libunwind is for debugging
lmsensors adds graphics related sensors to lmsensors database
gallium-opencl enables opencl through libclc, but mainly works on polaris (like RX 580) and earlier cards.
If you feel you don't need / want that functionality, you can disable them and simplify dependencies a bit .
Oops! you're right. I cloned that one instead!
Thanks for maintaining this really! Now I want to go more minimal with only AMD stuff, should I only edit the
vulkan-drivers and
gallium-drivers or are there extra stuff to modify in PKGBUILD as well?
Pinned Comments
Lone_Wolf commented on 2021-01-22 18:36
Why does this package hard depend on llvm-minimal-git ?
performance
archlinux repo packages are build with
-march=x86-64 -mtune=genericwhich works on lots of machines but makes limited use of modern processor capabilities. For many packages this has little impact, but with llvm my experience is different.
My local builds for llvm / mesa are done with
-march=nativeand this has a noticeable effect on their performance.
How big the benefit of this is depends heavily on the exact hardware you use. Worse, the software setup also impacts this. The only way to find out if it benefits your system/software setup is to try it out yourself.
easier maintenance and troubleshooting
Since i started my first mesa trunk package late in 2010 I have maintained versions without any llvm, one llvm implementation, split versions, singular versions, versions supporting multiple llvm implementations , switch from libgl hacks libglvnd to allow mesa & nvidia to cooperate etc.
Depending on one llvm variant in a non-splitted singular version results in a simple PKGBUILD that is easy to maintain.
Troubleshooting is also much easier if maintainer uses the same llvm variant as users.
If people feel those reasons are not good enough to hard depend on llvm-minimal-git , maybe I should transfer ownership .
Lone_Wolf commented on 2021-01-09 15:02
Why does this exist ?
Basically mesa/mesa-git build almost everything they can build.
This package tries to build just enough so everyone can use it, but disables older and/or unused components.
Check for a discussion about this package. | https://aur.tuna.tsinghua.edu.cn/packages/mesa-minimal-git/ | CC-MAIN-2022-05 | refinedweb | 659 | 50.23 |
I have a fixed-width text file I'd like to use with Azure Data Lake Analytics (ADLA). ADLA reads files using extractors. As of today, ADLA comes out of the box with three extractors: one for comma-delimited text, another for tab-delimited text and a general purpose extractor for delimited text. Examples on GitHub demonstrate the mechanics for writing custom ADLA extractors and include working versions of JSON and XML extractors. Using these examples as a starting point, I've managed to hack together a custom extractor for fixed-width text files. I'll use this post to walk you through the code I've assembled in hopes that this helps someone else who needs to build a custom ADLA extractor of their own.
First, I'll walk you through my scenario in a bit more detail. I've setup an ADLA account (called brysmi) and have associated it with an Azure Data Lake Store (ADLS) account (also called brysmi). In the ADLS account, I've created a folder off the root called fixedwidth and in it I've placed my fixed-width file. (Details on creating an ADLS account and loading files to it are found here.) This file (downloadable here) consists of three lines of fixed width text:
12345678 12345678 12345678
Admittedly, this isn't the most exciting file out there but the simple structure allows me to very easily verify my extractor is working correctly. To do that, I need to submit a U-SQL script to ADLA which calls up my custom extractor, telling it how to read the fixed-width lines into columns, and then send that data to an output file using a delimited format. The U-SQL code I'll use looks like this:
USE DATABASE [master]; REFERENCE ASSEMBLY [FixedWidthExtractor]; @tbl = EXTRACT col1 int, col2 float, col3 decimal, col4 byte[] FROM "/fixedwidth/input.txt" USING new MyCustomExtractors.FixedWidthExtractor ( new SQL.MAP<string, string> { {"col1","3"}, {"col2","2"}, {"col3","1"}, {"col4","2"} } ); OUTPUT @tbl TO "/fixedwidth/output.txt" USING Outputters.Csv();
The first line of this script tells ADLA to USE objects referenced in its master database. You can think of this as a structure for keeping logical reference to objects in the ADLA/ADLS environment. In that master database, I've registered an assembly (DLL) which holds the extractor code - I'll cover that part towards the bottom of this post - so that the REFERENCE statement points ADLA at that registered object.
In the next block, I tell ADLA to extract four fields FROM my input file USING an extractor class that's defined in my referenced assembly. To that class, I am passing a parameter typed as an ADLA type called a SQL.MAP which holds ordered key-value pairs identifying the columns to read from a line of text and the number of characters associated with each. Note that the columns in map are ordered the same as those in the EXTRACT statement's column list. Note also that column widths are passed in as strings; while SQL.MAP appears to accept integer values for the value part of its pairs, passing anything other than a string was causing errors.
In the last block of U-SQL script, I have ADLA send the parsed data to a comma-delimited text file. Nothing fancy here; I just want to see how the parsing worked.
If all that made sense, then let's take a look at the code for the assembly. I've written this using the Azure Data Lake Tools for Visual Studio 2015, leveraging the Class Library (For U-SQL Application) project type:
Before going any further, I need to point out that I am not even a mediocre C# developer. I'm going to screw up terminology and probably point out things that no true developer would either need pointing out or find interesting. And, yes, there are probably a bazzilion ways the code could be written more efficiently. With that out of the way, let's proceed.
The first thing I want to point out is the namespace and class definitions. It's important to note these because when you call the extractor in the EXTRACT statement, you need to instantiate the extractor using the new keyword followed by namespace.class.
namespace MyCustomExtractors { public class FixedWidthExtractor : IExtractor { … //coding magic happens here } }
Under the class definition, I define the method by which the class is instantiated. I have three parameters, two of which are optional. The optional parameters, encoding and row_delim, are used to identify the encoding and row-delimiter for the text file. These receive default values of UTF8 and carriage-return+line-feed if not otherwise specified. The SqlMap, i.e. col_widths, is the only required parameter and hopefully it is pretty well understood given the explanation earlier in this post.
public FixedWidthExtractor(SqlMap<string, string> col_widths, Encoding encoding = null, string row_delim = "\r\n") { this._encoding = ((encoding == null) ? Encoding.UTF8 : encoding); this._row_delim = this._encoding.GetBytes(row_delim); this._col_widths = col_widths; }
The class we're defining implements the IExtractor interface. As such it exposes an IEnumerable method that ADLA depends upon to send file contents to it and receive structured data back. By overriding this method, we now have the means to insert the custom logic needed to process the fixed-width file.
public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output) { ... //more code magic here }
The input variable passed into IEnumerable by ADLA is a reference to our input file. To read data from that file, a stream is opened and information passing over that stream is split using our specified row-delimiter. Each row is interpreted as a string using the specified encoding and assigned to the variable line.
public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output) { foreach (Stream currentline in input.Split(this._row_delim)) { using (StreamReader lineReader = new StreamReader(currentline, this._encoding)) { string line = lineReader.ReadToEnd(); … //the good stuff is coming here } } }
With a line of text now assigned to the line variable, it can be parsed into columns. Iterating over the SqlMap holding the column names and widths, each column is parsed from the line. Based on data types read from the column-list in the U-SQL EXTRACT statement and imposed on the output object passed to the IEnumerable method by ADLA, strings parsed from the line are cast to appropriate types and assigned to the output. Once the last column is parsed, the row in the output object is made read-only, freeing it to send data to ADLA.
//read new line of input int start_parse = 0; //for each column int i = 0; foreach (var col_width in this._col_widths) { //read chars associated with fixed-width column int chars_to_read = int.Parse(col_width.Value); string value = line.Substring(start_parse, chars_to_read); //assign value to output (w/ appropriate type) switch (output.Schema[i].Type.Name) { case ("String"): output.Set(i, value); break; case ("Int32"): output.Set(i, Int32.Parse(value)); break; ... //shortened for readability default: throw (new Exception("Unknown data type specified: "+output.Schema[i].Type.Name)); } //move to start of next column start_parse += chars_to_read; i++; } //send output yield return output.AsReadOnly();
With all the needed code in place, I build the project as I would any other. Now I come to the challenge of registering it with ADLA. To do this, I open Server Explorer in Visual Studio (found under the View menu if not already visible). I connect to my Azure account, expand the Data Lake Analytics node, and locate the ADLA account I've already created.
Expanding the ADLA account and then the U-SQL Databases node under it, I come to the master database. Expanding that database, I find a folder for Assemblies. Right-clicking that folder and selecting Register Assembly, I launch a dialog for registering the assembly I just compiled.
In the dialog, I click on the button next to the Load assembly from path: textbox. In the pop-up, I select local click on the associated button to locate the DLL compiled with my project. By default, this will be under the bin\Debug subfolder under the project folder. The .pdb file as well as the Microsoft.Analytics.Interfaces.dll and Microsoft.Analytics.Types.dll files are ignored.
Once the file is located, I click OK to return to the original dialog and then Submit to upload the assembly and register it with ADLA. The process takes a little time to complete but I encounter a Job View screen displaying all green marks when successfully completed.
Refreshing and then expanding the Assemblies folder in Server Explorer, I now see the assembly registered. Note the name as displayed in Server Explorer as this is the name used in the REFERENCE ASSEMBLY U-SQL statement.
At this point, everything is in place for a test run of the extractor. To run the U-SQL script leveraging the Visual Studio interface, I simply create a new U-SQL project. In the U-SQL Script view, I double check the script is pointed to my ADLA account (as highlighted in the image below) and click Submit.
As before, I receive a Job View screen but this one will display a bit more info. Once successfully completed, I use the Server Explorer to return to my ADLA account. I expand the Storage Accounts item, right-click the ADLS storage account and select Explorer. In the Explorer window, I navigate to the folder holding the output file. Right-clicking the output file and selecting Preview opens a window where I can see the file is parsed per my instructions. (Note, I asked the extractor to parse the last two characters in the string as a byte array. Converting this back to text results in the characters shown in the screenshot below.) | https://blogs.msdn.microsoft.com/data_otaku/2016/10/27/a-fixed-width-extractor-for-azure-data-lake-analytics/ | CC-MAIN-2017-30 | refinedweb | 1,629 | 55.03 |
Persian Calendar
This book meant to collect data about Jalali/Persian Calendar, which is currently used by Iranian. I wish others help me to complete the historical information, but what I want to share is some functions about how to calculate the leap years of this calendar.
Leap Years[edit]
The year was computed from the vernal w:equinox, which is take 365.24219 days (The actual value is 365.2422464 days)[1]. In order to evaluate the length of one year, Khayyam made a 2820-year cycle rule to find the leap years. Leap years have 366 days and others have 365 days. Here we explain the rule and write its algorithm. The 2820-year cycle is divided into 21 subcycles of 128 years each, and a 132-year subcycle at the end of each 2820-year cycle. A 128-year subcycle consists of a 29-year sub-subcycle, followed by 3 sub-subcycles of 33 years each. Finally, the 132-year subcycle consists of one sub-subcycle of 29 years, followed by two 33-year sub-subcycles and a final sub-subcycle of 37 years. The years are numbered within each cycle. Writing n for the number of a year within a cycle, this year is a leap year if n > 1 and n mod 4 = 1.[2] This algorithm in python3 programming language is[3]
# This is the implementation of Khayyam rules. year is an integer parameter. def isLeapYearReal(year): # The 2820-year cycle includes 21 128-year subcycles, and a 132-year subcycle cycle2820 = ((21,128),(1,132)) # The 128-year subcycle includes a 29-year sub-subcycles, and three 33-year sub-subcycle cycle128 = ((1,29),(3,33)) cycle132 = ((1,29),(2,33),(1,37)) cycle29 = ((1,5),(6,4)) cycle33 = ((1,5),(7,4)) cycle37 = ((1,5),(8,4)) if year > 0: realYear = (year + 37) % 2820 # realYear includes zero elif year < 0: # 38 years separating the beginning of the 2820-year cycle from Hejira realYear = (year + 38) % 2820 else: return None # There is no zero year!! wi = whereIs(cycle2820, realYear) # find what subcycle of 2820-year cycle includes the realYear if(wi[0] == 128): # if realYear is inside of 128-year subcycle wi1 = whereIs(cycle128, wi[1]) # find what subcycle of 128-cycle includes the wi[1] if(wi1[0] == 29): # if realYear is inside of 29-year sub-subcycle wi2 = whereIs(cycle29, wi1[1]) if wi2[1] == wi2[0] - 1: # if wi2[1] mod wi2[0] becomes wi2[0] - 1 (wi2[0] is 4 or 5) return True elif(wi1[0] == 33): # if realYear is inside of 33-year sub-subcycle wi2 = whereIs(cycle33, wi1[1]) if wi2[1] == wi2[0] - 1: return True elif(wi[0] == 132): # if realYear is inside of 132-year subcycle wi1 = whereIs(cycle132, wi[1]) if(wi1[0] == 29): wi2 = whereIs(cycle29, wi1[1]) if wi2[1] == wi2[0] - 1: return True elif(wi1[0] == 33): wi2 = whereIs(cycle33, wi1[1]) if wi2[1] == wi2[0] - 1: return True elif(wi1[0] == 37): wi2 = whereIs(cycle37, wi1[1]) if wi2[1] == wi2[0] - 1: return True return False def whereIs(cycle, year): # a function to find what subcycle includes the year y = year # for example p is (21,128), which means this cycle have 21 of 128-year subcycles for p in cycle: if y < p[0]*p[1]: # if y is inside one of subcycles # p[1] is the length of subcycle # y % p[1] is y mod p[1], which gives the position of y inside one of p[1]s return (p[1], y % p[1]) y -= p[0]*p[1] # if y is not inside of p[1] subcycle prepare for next subcycle
where 38 represents the years separating the beginning of the 2820-year cycle from Hejira - the year of Mohammed's flight from Mecca to Medina, corresponding to 621-622 AD, which the Jalali panel of scientists chose as the first year of the Iranian calendar.[4] As you can see this algorithm is too long and slow. To improve the calculation here is an extrapolation of above function
# a function to extrapolate leap years just like isLeapYearReal(year) def isLeapYear(year): a = 0.025 # a and b are two parameters. which are tuned b = 266 if year > 0: # 38 days is the difference of epoch to 2820-year cycle leapDays0 = ((year + 38) % 2820)*0.24219 + a # 0.24219 ~ extra days of one year leapDays1 = ((year + 39) % 2820)*0.24219 + a elif year < 0: leapDays0 = ((year + 39) % 2820)*0.24219 + a leapDays1 = ((year + 40) % 2820)*0.24219 + a else: # In case of using isLeapYear(year - 1) as last year. Look FixedDate function return True frac0 = int((leapDays0 - int(leapDays0))*1000) # the fractions of two consecutive days frac1 = int((leapDays1 - int(leapDays1))*1000) # 242 fraction, which is the extra days of one year, can happened twice inside # a 266 interval so we have to check two consecutive days if frac0 <= b and frac1 > b : # this year is a leap year if the next year wouldn't be a leap year return True else: return False
where a and b are two parameters, which are tuned. Another function that is so useful in programming is how to extrapolate the days that passed from the epoch (FARVARDIN 1, 1) to the first day of each year (FARVARDIN 1, year).
# find the interval in days between FARVARDIN 1 of this year and the first one def FixedDate(year): if year > 0: realYear = year - 1 # realYear includes zero elif year < 0: realYear = year else: return None # There is no zero year!! cycle = (realYear + 38) % 2820 # cycle is (realYear + 38) mod 2820 base = int( (realYear + 38) / 2820) if realYear + 38 < 0: base -= 1 days = 1029983 * base # 1029983 is the total days of one 2820-year cycle days += int((cycle - 38) * 365.24219) + 1 if cycle - 38 < 0: days -= 1 extra = cycle * 0.24219 # 0.24219 ~ extra days of one year frac = int((extra - int(extra))*1000) # frac is the fraction of extra days if isLeapYear(year - 1) and frac <= 202: # 202 is a tuned parameter days += 1 return days
There is no limitation for these functions as long as Kayyam rules are correct. To become convinced anyone can use this test function.
def test(): days = 1 # The first day of calendar, FARVARDIN 1, 1 for year in range(1,2850): # check if the estimated function is the same as the real one if isLeapYear(year) != isLeapYearReal(year): print("wrong!!") if FixedDate(year) != days: print("wrong!!") if isLeapYear(year): # add 366 days for leap years days += 366 else: days += 365 days = 1 # The first day of calendar, FARVARDIN 1, 1 for year in range(-1,-2850,-1): # do the same for negative years if isLeapYear(year) != isLeapYearReal(year): print("wrong!!") if isLeapYear(year): days -= 366 else: days -= 365 if FixedDate(year) != days: print("wrong!!")
- ↑ Kazimierz M. Borkowski, "The tropical year and solar calendar", The Journal of the Royal Astronomical Society of Canada 85/3 (June 1991) 121–130.
- ↑
- ↑ The repository for main functions..
- ↑ | https://en.wikibooks.org/wiki/Persian_Calendar | CC-MAIN-2020-40 | refinedweb | 1,175 | 60.89 |
Here's an overview picture showing all the major components. Go ahead and plug in your powered USB hub, mouse, keyboard, speakers, and either ethernet or WiFi connection.
Connecting the RGB LED StripFirst, cut back the plastic sleeve from the RGB strip and solder 4 wires. Note that there's an Input and Output end of the strip, and it's important to connect to the input end. You can also use some JST connectors if you don't want to solder..
RGB Strip Software
Grab the software and follow the instructions on that page for getting the Pi able to output to SPI. Do install spidev. It's important that you use the hardware SPI because any bit-banging approach won't be fast enough.
sudo raspi-config to enable hardware SPI (follow instructions at git page). While you're there, set the audio output to be out the 3.5mm jack rather than the HDMI connector.
I added the install directory to my PYTHONPATH in bashrc so I could call the functions from anywhere.
nano ~/.bashrc:
export PYTHONPATH=$PYTHONPATH:/home/pi/RPi-LPD8806
(you could also add PYTHONPATH=$PYTHONPATH:/home/pi/RPi-LPD8806 to /etc/environments, but this will require a reboot to register on new terminal windows)
Test out that the strip works by running the example code:
python example.py
The xmas light code we're going to download later wants to run as root, and when you run things with a sudo in front, the environment variables, specifically, PYTHONPATH aren't transferred.
To keep those environment variables around, edit /etc/sudoers by typing
sudo visudo
and then add to the bottom
Defaults env_keep=SYNCHRONIZED_LIGHTS_HOME
Defaults env_keep+=PYTHONPATH
the first line is something we'll need for the xmas light package to be installed later.
To test that you have it setup right and can run things as root, close the terminal and re-open, then type
sudo python
from bootstrap import *
led.fill(Color(50,50,50),0,10)
led.update()
that should turn on the first 10 LEDs. You might need to restart a terminal window to make sure the environment variables get loaded.
Mount the LED Strip
I looped my strip back and forth on a baby gate with twist ties, but this wastes LEDs at the bends. A cleaner route would be to cut the strip into 5 even segments and solder 4-wire jumpers between each segment. You'll just need to adjust the address of the LEDs for the columns. | https://learn.adafruit.com/raspberry-pi-spectrum-analyzer-display-on-rgb-led-strip/led-strip-and-rgb-led-software | CC-MAIN-2019-09 | refinedweb | 420 | 70.02 |
alright I made this code to try and get a grid of cells across the screen to try and make a cellular automata as I am quite new to programming but when I run this all of my cells are in one place near the bottom center on my screen (I know this because I set them to always display as white to check where they where as it wasn’t working. you may notice a logic function that generally isn’t being called but I just wanted to see if there was something I was missing that is obvious.
import java.util.ArrayList; boolean paused = false; int x = -10; int y = -10; final static ArrayList<cell> cells = new ArrayList(); class cell { boolean state; float xpos, ypos; float age; int identify; cell (float x, float y, int ident) { xpos = x; ypos = y; identify = ident; } void colour() { if (state == true) { fill(255); } else { fill(0); } } void DrawAndPress() { if (mouseX > x && mouseX < x+10 && mouseY > y && mouseY < y+10 && mousePressed) { state = !state; } rect(x, y, 10, 10); } void Logic() { } } void setup() { fullScreen(); background(0); noStroke(); for (int i = 0; i < (width*height)/10000; i = i+1) { x = x+10; if (x > width) { y = y+10; x = 0; } cells.add( new cell(x, y, i)); } } void draw() { for (cell c : cells) c.colour(); for (cell c : cells) c.DrawAndPress(); if (!paused) { for (cell c : cells) c.Logic(); } } | https://discourse.processing.org/t/why-does-my-for-loop-create-cells-in-one-specific-area-instead-of-in-a-grid/14197 | CC-MAIN-2022-27 | refinedweb | 234 | 66 |
Automatically get default value for "current_app", for easier namespace support.
Showing 1-3 of 3 messages
Automatically get default value for "current_app", for easier namespace support.
Tai Lee
5/20/14 1:01 AM
Right now it seems that for a generic app to support the possibility of being installed in a URLconf with a namespace, the app author will need to take care to explicitly define a `current_app` for every call to `reverse()`, `TemplateResponse`, `RequestContext`, `Context` and `{% url %}`.
Django already adds a `ResolverMatch` object to every request. Shouldn't Django just use this to get a default value for "current_app", whenever users don't explicitly define one?
This should make it almost a non-issue to define the current app for every case except explicit calls to `reverse()`, `Context` and templates that are rendered without a `RequestContext` object (as none of these have access to the request).
We could even get a sensible default in those cases as well by storing the current app in thread local storage, and using that as a default in `reverse()`.
I've made a ticket for this, but it was closed as wontfix because thread local storage is global state and Django is at war with global state.
As suggested, I'm bringing this to django-developers to ask for any alternative suggestions that don't involve global state, and also to try and make my case for the ticket as originally described.
Django already uses `threading.local()` in a number of places such as `urlresolvers._prefixes`, `urlresolvers._urlconfs`, `CacheHandler._caches`, `ConnectionHandler._connections`, `trans_real._active`, `timezone._active`.
The most notably similar use case is probably for timezone support, which allows users to call `activate()` to tell Django what timezone they are in, and then other parts of the code call `get_current_timezone()` to get the value stored in thread local storage.
I think it would be along the same lines to have the ability to set a current app and have other parts of the code get the current app, without having to pass an object around as an argument every step of the way, which is practically impossible.
For example, models with a `get_absolute_url` method (or perhaps multiple `get_foo_url` methods) that are rendered in templates. These functions can't take arguments when rendered as context variables in a template, and have no way to obtain the current namespace from the `request` object.
This would make it super easy for users (via middleware) or Django itself to inspect the `request.resolver_match` object and set the current app early in the request/response cycle, and then `reverse()` and `{% url %}` would just work without generic app authors having to explicitly build in support for multiple instances of their app being deployed within a single project.
Does anyone else think this would be a good idea, or does anyone have an alternative suggestion?
Cheers.
Tai.
Re: Automatically get default value for "current_app", for easier namespace support.
George Ma
10/25/15 9:44 PM
That's exactly what I'm thinking about. Unfortunately, it's not brought to the attention among Django developers so far.
Re: Automatically get default value for "current_app", for easier namespace support.
Marten Kenbeek
10/26/15 5:15 AM
Hi George,
The behaviour for {% url %} has since been changed when used with
a RequestContext. It will now default to the current namespace when
one is available. This change will be available in 1.9.
This change doesn't cover the thread-local storage for calls to reverse(),
or for {% url %} without a RequestContext. That is still marked as wont-fix.
Marten | https://groups.google.com/forum/?_escaped_fragment_=topic/django-developers/mPtWJHz2870 | CC-MAIN-2016-07 | refinedweb | 599 | 50.26 |
Settings for the size, location, and opacity of graphics that you want Elastic Transcoder to overlay over videos that are transcoded using this preset. You can specify settings for up to four watermarks. Watermarks appear in the specified size and location, and with the specified opacity for the duration of the transcoded video.
Watermarks can be in .png or .jpg format. If you want to display a watermark that is not rectangular, use the .png format, which supports transparency.
When you create a job that uses this preset, you specify the .png or .jpg graphics that you want Elastic Transcoder to include in the transcoded videos. You can specify fewer graphics in the job than you specify watermark settings in the preset, which allows you to use the same preset for up to four watermarks that have different dimensions.
public class PresetWatermark
Assembly: AWSSDK (Module: AWSSDK) Version: 1.5.60.0 (1.5.60.0)
Inheritance Hierarchy
| http://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/T_Amazon_ElasticTranscoder_Model_PresetWatermark.htm | CC-MAIN-2017-47 | refinedweb | 157 | 57.57 |
The Community Technology Preview for BizTalk 2006 R2 just came out and Beta 2 is coming soon.
In parallel with the R2 RTM, we will also be releasing a new version of the Accelerator for HL7, the successor to the v1.3 release currently available and dubbed v2.0.
This is a good time to start talking about the new features and enhancements that will be included in this new release based on the feedback we got from customers and partners.
The first new feature I want to talk about is the Schema Generation Tool. This tool will be available as an MSDN download. This is the same tool that we used internally to generate the schemas that ship with the current version of the Accelerator. The tool takes the HL7 message definition from the database that HL7 publishes on their web site and generates schemas in a format that the BizTalk HL7 parser can understand. These schemas are used by the parser in the process of translating from the flat file format of HL7 v2.x to XML.
The HL7 message definitions are stored in a Microsoft Access database and include definitions for all the approved versions (2.1, 2.2, 2.3, 2.3.1, 2.4 and 2.5). You can have a peek at what's in the database here. The HL7 message definition database will not ship with the Accelerator or the Schema Generation Tool as it is part of the HL7 standard and has to be acquired directly from HL7.org.
By customizing the database and the generated schema namespace, you will be able to create your own library of message definitions for your own integration purposes or for versions of HL7 that we do not ship schemas for (e.g. the Dutch localization of HL7, the Australian localization...).
The Schema Generation Tool will also come with full source code as a shared source project. That way it can be adapted to generate the schemas from *any* repository or from tools such as the HL7 Messaging Workbench.
The objective of the Schema Generation Tool is to make it easier to manage libraries of HL7 message definitions by working at the model level instead of dealing with schema customization. Every time you need to generated a custom message or segment, you can modify the repository (or a copy of it) and generate new schemas.
That's all for today. I'll be back soon discussing other new features and changes in the upcoming BizTalk Accelerator for HL7 v2.0.
Update: the Schema Generation Tool as well as BizTalk 2006 R2 Beta 2 and the Accelerator for HL7 v2 Beta 2 *are not available yet*. Once we release them, you'll be the first to know. Consider this a teaser :-) | http://blogs.msdn.com/b/rruggeri/archive/2007/03/13/biztalk-accelerator-for-hl7-v2-0-schema-generation-tool.aspx | CC-MAIN-2015-22 | refinedweb | 464 | 70.23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.