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
|
|---|---|---|---|---|---|
1
Off Topic discussions / Re: Slowing Down But Not Hitting the Brakes« Last post by mauro on Today at 10:13:57 am »
Condolence. Most of our fathers-mothers made us the kind of person we now are, also wherever not directly wanting that.
OS2World.com Forum is back !!!
Remember to visit OS2World at:
Are you using a multiprocessor system? - Just wondering if using markexe.exe (from os/2 toolkit) to "mark" the executable (dux.exe ?) as mpunsafe will help...Hi Pete, It' s a VirtualBox system, one processor in the configuration. I' ll check that anyway, but I remember my "real" system in the early 2000s, a P4 (hence without multiprocessing), showed the same problem.
Loaded fine here as it's basic and I would prefer like this if it worked basically well. Thing is that is the only one among other browser on same system unable to translate URL string into IP address, it's not a matter of happening in both cases. Probably reinstalling it would be the only attempt to try fixing. Boh.... (from an italian slang :"who ever knows?)
Dooble is pretty simple and doesn't seem to try alternative domain names unlike Mozilla which will make a few attempts http vs www. or not and .com added
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/select.h>
#include <unistd.h>
#include <termios.h>
int term_fd = -1;
int get_key(int do_delay, char *val)
{
fd_set r;
struct timeval t;
t.tv_sec=0;
t.tv_usec=(do_delay) ? 1000 : 0;
FD_ZERO(&r);
FD_SET(term_fd,&r);
int n = select(term_fd+1,&r,NULL,NULL,&t);
if(n > 0 && FD_ISSET(term_fd,&r) && read(term_fd,val,1) == 1)
return 1;
return 0;
}
int main(int argc, char **argv)
{
if(argc >= 2)
term_fd = open("/dev/tty", O_RDONLY);
else
term_fd = STDIN_FILENO;
if(term_fd < 0)
{
perror("failure opening terminal input");
return 1;
}
fprintf(stderr, "terminal fd: %d\n", term_fd);
struct termios old_tio;
int termsetup = 0;
if(!tcgetattr(term_fd, &old_tio))
{
fprintf(stderr, "proper terminal setup\n");
struct termios tio = old_tio;
tio.c_lflag &= ~(ICANON|ECHO);
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 0;
tcsetattr(term_fd,TCSANOW,&tio);
termsetup = 1;
}
char val = 0;
while(val != 'q')
{
if(get_key(1, &val))
fprintf(stderr, "got key: %c\n", val);
}
if(termsetup)
tcsetattr(term_fd,TCSAFLUSH,&old_tio);
if(term_fd > 0)
close(term_fd);
return 0;
}
Hi GlennUnfortunately the remedy is worse than the problem: instead of just not starting the application, applying these patches causes the app to somehow start minimized (can see the program in lSwitcher) but also to hang the WPS - I have to use TOP to kill the app AND reset the WPS before I can regain control on the system...
I don't have the American Heritage Dictionary by DUX, but the only thing I had seen is that there are two patches at hobbes, but I'm not sure if those are for the same thing you are using? Those are patches for DUX.EXE.
Regards
The readme is out of date as well as the libc DLL's that come with the additions.Dave,
You want to remove any in \os2\dll and only use the ones in \usr\lib.
Also note that the latest is libcn0.dll and the other libc06*.dll's are forwarders and need to be at the same level.
Thanks for the additional information. I was not aware of the connection between libcn0.dll and libc06*.dll. Since the Guest Additions for OS2 do not include libcn0.dll, then we shouldn't be using the libc06*.dll files from the Guest Additions CDROM image.
Bennie
|
https://www.os2world.com/forum/index.php?PHPSESSID=c9q7m2mtra1qdh5uckrafeljft&action=recent
|
CC-MAIN-2022-21
|
refinedweb
| 596
| 67.25
|
We incremental compilation for Kotlin/JS by default
- Brings improvements to Kotlin/Native
As always, we’d like to thank our numerous external contributors. The complete list of changes for this release can be found in the change log. Let’s dive in!
Faster Gradle builds by parallelizing tasks
The Kotlin Gradle plugin can now run tasks in parallel within a project. Parallel execution is supported by using the Gradle Worker API. To make use of this feature, add the following setting to
gradle.properties or
local.properties file:
This feature is beneficial for projects defining custom source sets, since the compilation of independent source sets can be parallelized. In the case of multiplatform projects, targets for different platforms can also be built in parallel. For Android, the debug and release build types can be compiled in parallel.
We plan to enable the parallel task compilation by default at a later date, so we kindly ask for your feedback. Do let us know if you face any issues.
Multiplatform projects update
We continue working on multiplatform projects and improve different aspects based on your feedback.
Support for Kotlin Gradle DSL
You can now use Kotlin Gradle DSL to build multiplatform projects:
You can check many examples in both Groovy and Kotlin in the documentation.
DSL improvements
The DSL to set up a multiplatform project has been greatly improved and simplified. This blog post contains some highlights in comparison to the previous version. We recommend you read the updated guide for more details and complete samples.
You can now use shorthand for Kotlin dependencies. That is, instead of
'org.jetbrains.kotlin:kotlin-stdlib' you write simply
kotlin('stdlib').
In addition, supported targets can be specified directly instead of using the
fromPreset function:
Note that if you need it, the previous functionality still exists, using
targetFromPreset(...).
You can also independently configure Kotlin/Native binaries like executable files or native libraries. For instance, you can use this to export symbols of certain dependencies to an Objective-C framework.
For more information, please refer to the documentation.
Finally, we’ve also made
kotlinOptions available, allowing for easier compiler configuration
All improvements are available both in Groovy and Kotlin DSL.
Android Library (AAR) can be a part of a multiplatform library
You can now publish Android libraries (AAR) as a part of a multiplatform library. This functionality is disabled by default; to enable it, specify the list of the variants that you want to publish in the scope of the Android target:
You can read more about publishing libraries in the documentation.
Improvements for inline classes
Support for inline classes has been significantly improved, and some constraints have been mitigated. For instance, you can now define an inner class inside an inline class. There are also improvements for non-trivial cases, like using inline functions inside inline classes or passing references to inline classes as arguments to inline functions.
You can now also use reflection with inline classes and have access to class literals and
javaClass property
There’s also support for
call and
callBy for functions that have inline class types in their signature. For more information, refer to the corresponding section on the KEEP.
Kotlin/Native
Code contracts
Some time ago we introduced experimental support for contracts, which allows a function to describe its behaviour in a way that the compiler understands. This functionality is now also available in Kotlin/Native.
Better interop
Improved interop including support for more C constructions such as enums with forward declarations, as well as better error reporting for cases of inheritance in Objective-C.
Native frameworks from libraries
With this release, we can now produce Apple frameworks not only from source files but also from Kotlin libraries (i.e.
.klib files). This is possible using the
-Xexport-library command line option or via Gradle plugins
Performance
Apart from reducing the memory footprint and improving runtime performance, this release also brings compiler optimizations for looping over ranges, making iterations much faster.
IntelliJ IDEA support
This release adds new refactorings, inspections, and intentions to the IntelliJ IDEA plugin. We’ll highlight some of them.
Template to generate
main without parameters
Since Kotlin 1.3, you can use the
main function without parameters. Now, the default ‘main’ live template adds this new version of
main.
If you need to pass some arguments, use ‘maina’ live template.
Inspections to improve coroutines code
When working with coroutines, you usually follow certain conventions. For instance, you would add an “Async” suffix to a function returning ‘Deferred’, or define a function either as a
suspend one or as an extension to
CoroutineScope, but never both at the same time (for more details, check this talk from KotlinConf). IntelliJ IDEA is now aware of these conventions and offers intentions to fix potential issues:
New intention for converting SAM as lambda to an anonymous object
A new intention allows to convert constructs using lambdas with SAM to anonymous objects. For instance
can now be converted automatically by the IDE to
String conversion improvements
‘Convert concatenation to template’ intention is now smarter, meaning
will be converted to
removing the unnecessary
.toString() calls on each parameter.
Kapt improvements
Using Kapt from the command line has been simplified, allowing for direct use as a separate command line tool as opposed to having to use it via the compiler:
All kapt-related arguments are now passed as top-level arguments instead of using the verbose syntax:
Note that a new option that shows processor timings (-Kapt-show-processor-timings`) has also been introduced in this release.
Compile avoidance for kapt
We’ve added support for Compile Avoidance for
kaptKotlin tasks in Gradle, improving build performance times. It skips annotation processing completely when there are no changes in kapt stubs and only method bodies are changed in dependencies. Setting
in
gradle.properties enables it. Note, however, that this setting also turns off the AP discovery in compile classpath, but if you add AP to
kapt* configuration, that shouldn’t affect you.
Other notable mentions
In addition to the above, a few more fixes and improvements worth mentioning:
- Incremental compilation for Kotlin/JS is now stable enough and is enabled by default. If you encounter any issues, we’d appreciate if you report it to us, and in the meantime, you can disable the option:
- In a Gradle project, add
kotlin.incremental.js=falseto
gradle.propertiesor
local.properties
- In an IntelliJ IDEA project, go to Settings | Build, Execution, Deployment | Compiler | Kotlin Compiler | Kotlin to JavaScript and uncheck Enable incremental compilation.
- We now provide a Kotlin BOM (Bill of Materials) file that lists the dependencies used from the
org.jetbrains.kotlingroup.
- Stable sorting is now available on all targets. Previously this was an issue when targeting JavaScript.
- Numerous fixes and improvements in scripting support.
- Support for MethodHandle and VarHandle in JVM code generation.
- Modularized artifacts for Kotlin JVM libraries are included.
- Kotlin/Native will embed bitcode by default for iOS frameworks targets in Gradle projects.
- Kotlin/Native annotations
@ThreadLocaland
@SharedImmutableare now accessible from common code (declared as
optional expect).
How to update
To update your IntelliJ IDEA or Android Studio plugin, use Tools | Kotlin | Configure Kotlin Plugin Updates and click the “Check for updates now” button. The Eclipse IDE plugin can be installed or updated via the Eclipse Marketplace (Help | Eclipse Marketplace and search for the Kotlin plugin).
Also, don’t forget to update the compiler and standard library versions!
External Contributions
Thank you once again to all community contributions for this release. In particular:
- Kenji Tomita
- Xavi Arias Seguí
- Ivan Gavrilovic
- Cuihtlauac Alvarado
- Matthew Runo
- Takayuki Matsubara
- Ting-Yuan Huang
- Vitaly Khudobakhshov
- Aleksei Semin
- Alex Saveau
- Bernhard Posselt
- Corey
- Dave Leeds
- Bradley Smith
- Fabian Mastenbroek
- Fedor Korotkov
- Ingo Kegel
- Itsuki Aoyagi
- James Wald
- John Eismeier
- Juan Chen
- Karen Schwane
- Keita Watanabe
- Lukas Welte
- Mikhail Levchenko
- Monchi
- Piotr Krzeminski
- Raluca Sauciuc
- Ricardo Meneghin Filho
- Timo Obereder
- Yuki Miida
- shiraji
- takattata
- technoir
- ymnder
Updates
We previously stated that it is necessary to enable parallel builds in Gradle using
This is in fact not required, as this would enable cross-project parallelism. Thank you to Cédric Champeau and Eric Wendelin for pointing this out.
Kudos for the superb release. I can’t wait to update all the projects to it and get serious with multiplatform libraries, so I’ll start the former now, and the latter as soon as I can.
Sweet! I’ve been waiting for multiplatform to be available in the Kotlin DSL for a while now. Thanks for the update guys!
I want to make one quick clarification regarding
org.gradle.parallel=trueeven though most of you probably already know: this is completely unrelated to the Worker API.
org.gradle.parallel=truetells Gradle to build separate Projects of a multi-project build in parallel. The worker API is much finer-grained. I’m sorry the Gradle Worker API docs at didn’t do a better job making this distinction clear.
I for one am super excited for Kotlin compilation to be executed in parallel.
TL;DR — Unless the Kotlin team coded it into the Kotlin Gradle Plugin somehow that
org.gradle.parallel=trueneeds to be on, you don’t need it. Just
kotlin.parallel.tasks.in.project=true.
with 1.3.20 I’m seeing the following warning lines when invoking the kotlin-maven-plugin compile goal in mostly kotlin project (see no such lines with 1.3.11):
Thanks for the report! We’ve identified the issue and will fix it in 1.3.21:
Is it now possible to release Kotlin native libraries to e.g. bintray and then consume them via Gradle, like I would do on the JVM? That would be great!
You seems to add lot of complexity around building
All you have to do is ditch Java and fix the compiler using AOT compiled language
When not warmed up, the process takes an eternity to compile
This is so annoying that made out company use GO instead of java for backend services
Kotlin is only used for our Android app, and god knows how slow it is…
We have huge hopes for Kotlin Native, please make programming fun again!
Android builds are very slow but I would bet the Kotlin compilation part is only a small part of it. To profile this, you should use the build scan and post the URL
I’m not seeing any of the class=”kotlin-code” sections in this article…they all have their visibility style set to hidden.
FWIW, I’m on a Mac. Tried both Safari and Chrome with the same results.
Possibly related: returned a 404.
Same here, on Chrome of Windows 10
me2
Array.from(document.querySelectorAll(‘pre.kotlin-code’)).forEach(x=>x.style.visibility=”)
What does the roadmap ahead look like?
I’m really looking forward on when the team’s focus can start to shift away from the multi-platform stuff and get back to core Kotlin language innovation.
Badly missing:
– tuples
– guard statements (with proper forced ‘returns’)
– conditional statements (if expressions are ugly as it gets… common guys)
– optional binding (ie: ‘if let x = expression… { . }’ –> the .let library approach was fine for a beta stage of the language, but there really needs to be language-level support for something as fundamental as this)
– array/dictionary initialization literals (not library-level ‘listOf(..)/mutableListOf(..), mapOf(..) etc.)
– language-level async support (not library again)
There is a big theme here where the language has been leading with libraries to prove concepts out (that’s great)…. but lacking the follow-up on adopting what works back into the language itself – so over time Kotlin has been turning into a library bloat instead of continually simplifying, beautifying and advancing. Feels like a big time for a 2.0 push to reel all these things in.
#constructivelove
Thanks for your feedback! We don’t have a roadmap that we can share at the moment, sorry.
def theJsTarget = js('nodeJs')
^^^^
defshould be
val, right?
No. This is written in Groovy.
I have Error Too
This is already fixed in 1.3.21, see comments above.
Sweet! I’ve been waiting for multiplatform to be available in the Kotlin DSL for a while now. Thanks for the update guys!
the settings in files ‘gradle.properties’ and ‘local.properties’ are blank , is anyone happens ?Errors might be here—-visible = hidden—— ”
“
What is “AP” mentioned in the kapt part where the opt-in property can speed compilation up?
“AP” stands for annotation processor/processing.
To disable annotation processor discovery in compile classpath (so processors would be discovered only in annotation processing classpath) and enable Java compile avoidance for “kaptKotlin*” tasks, add:
to your
gradle.propertiesfile.
The expected effect is that when you only change a method body in a dependency, annotation processing is skipped. Note, that
kaptGenerateStubs*tasks are unaffected by this change.
|
https://blog.jetbrains.com/kotlin/2019/01/kotlin-1-3-20-released/?replytocom=47103
|
CC-MAIN-2019-13
|
refinedweb
| 2,140
| 54.32
|
Now that we have written a few programs let us look at the instructions that we used in these programs. There are basically three types of instructions in C:
- Type Declaration Instruction
- Arithmetic Instruction
- Control Instruction
The purpose of each of these instructions is given below:
(a) Type Declaration Instruction
This instruction is used to declare the type of variables being used in the program. Any variable used in the program must be declared before using it in any statement. The type declaration statement is written at the beginning of main( ) function.
int bas; float rs, grosssal; char name, code;
There are several subtle variations of the type declaration instruction. These are discussed below:
(a) While declaring the type of variable we can also initialize it as shown below.
int i = 10, j = 25; float a = 1.5, b = 1.99 + 2.4 * 1.44;
(b)The order in which we define the variables is sometimes important sometimes not. For example,
int i = 10, j = 25;
is same as
int j = 25, j = 10;
However,
float a = 1.5, b = a + 3.1;
is alright, but
float b = a + 3.1, a = 1.5;
is not. This is because here we are trying to use a even before defining it.
(c) The following statements would work.
int a, b, c, d ; a = b = c = 10 ;
However, the following statement would not work
int a = b = c = d = 10 ;
Once again we are trying to use b (to assign to a) before defining it.
(b) Arithmetic Instruction
A C arithmetic instruction consists of a variable name on the left hand side of = and variable names & constants on the right hand side of =. The variables and constants appearing on the right hand side of = are connected by arithmetic operators like +, -, *, and /.
int ad ; float kot, deta, alpha, beta, gamma ; ad = 3200 ; kot = 0.0056 ; deta = alpha * beta / gamma + 3.2 * 2 / 5 ;
Here,
*, /, -, + are the arithmetic operators.
= is the assignment operator.
2, 5 and 3200 are integer constants.
3.2 and 0.0056 are real constants.
ad is an integer variable.
kot, deta, alpha, beta, gamma are real variables.The variables and constants together are called ‘operands’ that are operated upon by the ‘arithmetic operators’ and the result is assigned, using the assignment operator, to the variable on left-hand side. A C arithmetic statement could be of three types. These are as follows:
(a)Integer mode arithmetic statement – This is an arithmetic statement in which all operands are either integer variables or integer constants. Example
int i, king, issac, noteit ; i = i + 1 ; king = issac * 234 + noteit - 7689 ;
(b)Real mode arithmetic statement – This is an arithmetic statement in which all operands are either real constants or real variables. one often commits mistakes in writing them. Let us take a closer look at these statements. Note the following points carefully.
(a) C allows only one variable on left-hand side of =. That is, z = k * l is legal, whereas k * l = z is illegal.
(b) In addition to the division operator C also provides a modular division operator. This operator returns the remainder on dividing one integer with another. Thus the expression 10 / 2 yields 5, whereas, 10 % 2 yields 0. Note that the modulus operator (%) cannot be applied on a float. Also note that on using % the sign of the remainder is always same as the sign of the numerator. Thus –5 % 2 yields –1, whereas, 5 % -2 yields 1.
(d) Arithmetic operations can be performed on ints, floats and chars.
Thus the statements,
char x, y ; int z ; x = 'a' ; y = 'b' ; z = x + y ;
are perfectly valid, since the addition is performed on the ASCII values of the characters and not on characters themselves. The ASCII values of ‘a’ and ‘b’ are 97 and 98, and hence can definitely be added.
(e) No operator is assumed to be present. It must be written explicitly. In the following example, the multiplication operator after b must be explicitly written.
a = c.d.b(xy) usual arithmetic statement
b = c * d * b * ( x * y ) C statement
Unlike other high level languages, there is no operator for performing exponentiation operation. Thus following statements are invalid.
a = 3 ** 2 ; b = 3 ^ 2 ;
If we want to do the exponentiation we can get it done this way:
#include <math.h> main( ) { int a ; a = pow ( 3, 2 ) ; printf ( “%d”, a ) ; }
Here pow( ) function is a standard library function. It is being used to raise 3 to the power of 2. #include
(c) Control Instructions in C
As the name suggests the ‘Control Instructions’ enable us to specify the order in which the various instructions in a program are to be executed by the computer. In other words the control instructions determine the ‘flow of control’ in a program. There are four types of control instructions in C. They are:
- Sequence Control Instruction
- Selection or Decision Control Instruction
- Repetition or Loop Control Instruction
- Case Control Instruction
The Sequence control instruction ensures that the instructions are executed in the same order in which they appear in the program. Decision and Case control instructions allow the computer to take a decision as to which instruction is to be executed next. The Loop control instruction helps computer to execute a group of statements repeatedly. In next tutorials we are going to learn these instructions in detail.
|
http://www.loopandbreak.com/c-instructions/
|
CC-MAIN-2021-17
|
refinedweb
| 898
| 65.32
|
As enterprises move workloads to the cloud, transparency and visibility across development and operations (DevOps) teams are really important. The real power of the Slack messaging platform is to help teams collaborate and coordinate their work no matter where they are located, in the field office, at home, or anywhere around the globe. This tutorial shows you how to set up a toolchain of IBM Cloud services that uses a continuous integration and continuous delivery (CI/CD) stack to maintain and deploy applications running on a Kubernetes cluster. Then, it shows how you can enhance the collaboration experience within your DevOps team by integrating the toolchain with the Slack platform so your Slack channel receives notifications about deployment activities.
Prerequisites
You need the following tools to complete the steps in this tutorial:
- IBM Cloud account.
- Access to the IBM Cloud Kubernetes Service to create a Kubernetes cluster. If needed, you can create one free cluster for 30 days to get familiar with Kubernetes capabilities.
- Slack workspace.
- Visual Studio Code or another integrated development environment (IDE) for local development.
- A GitHub account and some knowledge of Git commands.
Estimated time
It will take you less than one hour to complete this tutorial.
Steps
- Fork and clone the GitHub repository
- Create a Kubernetes cluster
- Create the container registry
- Configure a toolchain
- Verify the application is running
- Activate the Slack API
- Integrate your Slack app with your toolchain
- Change the toolchain and check updates on Slack
Step 1. Fork and clone the GitHub repository
- Open the GitHub repository that contains the sample code for this tutorial.
- Click Fork from the menu bar to copy the repository into your GitHub account. You will use the URL of your forked repository in Step 4.
- Open your terminal and change your directory by using the
cd downloadscommand (or any other directory in which you want to clone the project).
- Run the
git clone.
- Move into the cloned folder and run the
npm installcommand to install the dependencies.
- Run the
node app.jscommand to check that the application runs successfully on you local device.
Note: The project contains the Dockerfile and deployment files that you use in the next few steps, so please go through the files. This tutorial does not focus on how to write these two files.
Step 2. Create a Kubernetes cluster
- Log into your IBM Cloud account and navigate to the Kubernetes Cluster page.
Create a Kubernetes cluster. If you need assistance, refer to the steps in the Getting started with IBM Cloud Kubernetes Service documentation.
It may take 10 to 15 minutes for your Kubernetes cluster to provision.
Step 3. Create the container registry
- Go to the Container Registry page within IBM Cloud.
- Click the Create button.
- Within the Location drop box, select the region that is closest to you geographically.
- Click the Namespaces tab.
- Click Create.
- In the Create namespace pane, enter a unique name for your registry within the Name field.
- Click Create.
Note: Although you could skip this step and directly integrate the container registry within Step 4, it could cause an error if your registry name is not unique.
Step 4. Configure a toolchain
Toolchains provide an integrated set of tools to build, deploy, and manage your apps. By creating a toolchain on IBM Cloud, you can develop and deploy an application securely into a Kubernetes cluster managed by the IBM Cloud Kubernetes Service. The toolchain includes Vulnerability Advisor to provide a secure container.
After you create the toolchain in this step and push the changes to your repository, the delivery pipeline will automatically build and deploy the code. Learn more about creating toolchains on IBM Cloud.
Perform the following tasks:
- Go to the Create a Toolchain dashboard within IBM Cloud.
- There are many ready-made toolchains are available on the dashboard. Select Develop a Kubernetes app.
- Enter any name you want within the Toolchain Name field.
- In the Select Region field, choose the same location as the one you chose in Step 3.
- In the Select a source provider field, choose Git Repos and Issue Tracking.
- Within the Tool Integrations section, in the Source repository URL field, enter the URL of the forked repository that you created in Step 1.
- Click the Delivery Pipeline tab.
- In the App name field, enter
mypipeline.
- In the IBM Cloud API key field, click the New button.
- In the Create a new API key with full access window, select OK.
- In the Container registry region and Cluster region fields, select the region where you created your services earlier.
- Click the Create button.
After the Delivery Pipeline status box indicates that it is configured successfully, click it to open the Delivery Pipeline status page.
The screen capture of the Delivery Pipeline page shows the three pipeline stages:
- Build: If a
manifest.ymlfile exists in the root folder, it is used to determine which buildpack to use.
- Containerize: This stage checks for the Dockerfile in your root folder, creates a container registry after the image is successfully built, and deploys the image in the registry. This stage also checks for any vulnerabilities in the image, and if there are any, then images with high warnings will not deploy.
- Deploy: This stage checks for cluster readiness and namespace existence, configures the cluster namespace, updates the
deployment.ymlmanifest file, and grants access to the private image registry.
Note: The screen capture image displays a warning because we did not activate the SSL certificate.
Step 5. Verify the application is running
- Within the Deploy stage, click View logs and history.
- Select Deploy to Kubernetes.
- Scroll to the end of the logs, until you reach
VIEW THE APPLICATION AT:followed by a URL.
Open your browser and run the URL to check whether the application is running.
Now you will verify if the services are running on your Kubernetes cluster.
- Go to the Resource list in IBM Cloud.
- Expand Cluster and click on the Kubernetes cluster service that you created in Step 2.
- Within your cluster service page, select Kubernetes dashboard from the menu bar.
- Within the side panel of the Kubernetes dashboard, click Namespaces.
- Select default from the Namespaces list.
- Check the services running as
hello-app.
Step 6. Activate the Slack API
If you do not already have a Slack account, create one before starting the following tasks to activate the Slack API.
- Within your browser, go to.
- Click Create an App.
- Within the Create a Slack App window, enter
IBM Toolchainin the App Name field.
- In the Development Slack Workspace drop down list, select the workspace that you identified or created to fulfill the Prerequisites for this tutorial.
- Click Create App. After your app is created, you will be redirected to the settings page for your new app.
- Select Incoming Webhooks.
- Set Activate Incoming Webhooks to On.
- Click Add New Webhook to Workspace.
- Pick a channel from the list that you want the app to post notifications to.
- Click Allow.
- Back on the Incoming Webhooks page, there is a new entry within the Webhook URL section for the channel you selected. Click the Copy button to save the URL for an upcoming task.
Step 7. Integrate your Slack app with your toolchain
Now that your Slack app is set up, you can integrate it with your toolchain in IBM Cloud.
- Go to the Toolchains dashboard within IBM Cloud.
- In the Location list, choose the region where you created your toolchain in Step 4.
- Select your toolchain from the list.
- On you toolchain overview page, click the Add tool button.
- Type
Slackin the search box and click the Slack integration option that appears.
- On the Configure Slack page, paste the webhook URL that you copied at the end of Step 6 into the Slack webhook field.
- Within the Slack channel field, enter the name of the channel that you selected in Step 6 to post notifications to.
- In the Slack team name field, enter the name of your Slack team. (To find your team name, open your Slack workspace, expand your workspace name located in the side panel, and copy the word or phrase that appears before
.slack.com.)
Click the Create Integration button. Your toolchain overview page will now display your Slack integration within a Culture section of the pipeline.
Open your Slack workspace. Inside the configured channel will be a message stating that your Slack service has been bound to your toolchain.
Step 8. Change the toolchain and check updates on Slack
- From your toolchain overview page, click the Delivery Pipeline status box to open the Delivery Pipeline status page.
- Within the Deploy stage, click the Run Stage icon.
The stage will start running and verification messages will appear in your Slack workspace channel. In a real world scenario, everyone on your team would have better visualization of the project changes through these types of automated deployment messages.
Conclusion
In this tutorial, you learned how to work with toolchains to manage applications running on a Kubernetes cluster with automated stages that replace the manual interaction of development and operations teams. In addition, this tutorial demonstrated how the Slack platform can enhance DevOps collaboration by integrating it with an IBM Cloud toolchain to verify executions performed by a specific role. Teams could use DevOps toolchains for multi-staging strategies as part of their best practices. For example, before deploying a complete workload to a production Kubernetes cluster, it could be deployed in the test environment stage and not affect the production environment if there are any failures.
|
https://developer.ibm.com/devpractices/devops/tutorials/integrate-a-cicd-pipeline-to-a-kubernetes-cluster-with-slack/
|
CC-MAIN-2020-50
|
refinedweb
| 1,583
| 64.41
|
Simple HTTP server
I repurposed some generic micropython HTTP server code to run on the gpy
import machine; from machine import Pin pins = [machine.Pin(i, machine.Pin.IN) for i in ('P23', 'P22', 'P21')] print (pins) ()
It's supposed to show the status of the pins in a table but when I run it & try to login I get
[Pin('P23', mode=Pin.IN, pull=None, alt=-1), Pin('P22', mode=Pin.IN, pull=None, alt=-1), Pin('P21', mode=Pin.IN, pull=None, alt=-1)] listening on ('0.0.0.0', 80) client connected from ('192.168.4.2', 58649) Traceback (most recent call last): File "<stdin>", line 26, in <module> ValueError: invalid argument(s) value
I can't find any docs on makefile so I was wondering if anyone can tell me what the problem is with
cl_file = cl.makefile('rwb', 0)
Spot on with the cl.makefile('wb') Eric, although I can't tell how you figured that out from that doc page. No matter it works now! If I change 'import socket' to 'import usocket as socket' it runs the same so the pycom library must have both?
According to documentation () makefile seem have only one argument and not two. Logically i don't know any system where when you have write acces you haven't read access, so i propose you to try
cl_file = cl.makefile('wb')
Please note that's "import usocket" and not "import socket" as in your code with pycom library, if you use a different lib have a look at your provider's library documentation
|
https://forum.pycom.io/topic/4625/simple-http-server
|
CC-MAIN-2022-33
|
refinedweb
| 265
| 72.05
|
I need to install a package from PyPi straight within my script.
Maybe there’s exists module or distutils (distribute, pip) ability which allows me just execute something like
pypi.install('requests') and requests will be installed into my virtualenv, and I should not type
pip install requests in my shell?
You can also use something like:
import pip def install(package): pip.main(['install', package]) # Example if __name__ == '__main__': install('argh')).
This should work:
import subprocess def install(name): subprocess.call(['pip', 'install', name])
I hope this question is still valid.
I did the above something like this:
import sys import os import site try: import pip except ImportError: print "installing pip" cmd = "sudo easy_install pip" os.system(cmd) reload(site) try: import requests except ImportError: print "no lib requests" import pip cmd = "sudo pip install requests" print "Requests package is missing\nPlease enter root password to install required package" os.system(cmd) reload(site)
the second try block can be written in the else part of the first try block as well, however in my problem statement I has to write two seperate blocks.
you could always download
import os
then right all the terminal commands to download it from there.
like
while True: code = input("") os.system("code")
whatever it is i’m not sure but if you don’t even know how to do it in terminal how are you gonna do it in python.
Tags: laravelpython
|
https://exceptionshub.com/installing-python-module-within-code.html
|
CC-MAIN-2022-05
|
refinedweb
| 241
| 62.78
|
Protocol Buffers, for data exchange with a server beyond JSON
Protocol Buffers is a data definition language created by Google that can be compared to IDL, but is much simpler. Its syntax, based on the C language, evokes that of JSON, with the difference of the use of typed variables.
Google has defined this language for use on its own servers that store and exchange big quantities of structured data, and in 2008 decided to make it open source. It is used in Android to speed up exchanges with the server (in Marketplace for example).
The proto files have a dual format, the human readable source and the binary that can be handled quickly by the machine.
It may be used for three reasons among other:
- It is an alternative to XML, much more compact, with a processing time considerably decreased.
- It is a means of storing structured data and exchange them between software, possibly written in different programming languages, and between a server and a client.
A library of functions is included to assist in the use of Web services.
- It allows a cross-language serialization of classes. The serialization produces compact and easy to process binary code.
A simple format with advanced tools
First, some definitions to see more clearly:
Protocol Buffers: name of the language and name of units of data encapsulated into a proto file.
Proto: a data definition file in the PB language, with the .proto extension.
Protoc: name of the compiler that produces classes or binaries.
Features of the language
- Object oriented language, each message inherits the Message class.
- Typed data language.
- Textual and binary formats.
- The Protoc compiler generates, from the data definition, a class in the choosen language.
- The compiler provides C++ or Java classes and is intended to be compatible with all languages.
- The class is serialized into a binary file. Protoc can also produce the binary file from the PB language.
- A unit is called "message". A .proto file can contain several messages.
- Supports namespaces.
- The structure of a message is recursive, a proto structure may have elements that are other proto structures.
- repeated fields, as in XML, their definition can be reused in the same message.
- Dynamically extensible.
Syntax
Each source has the form:
message name { ...list of data fields... }
The main scalar types are string, int32, int64, float, double, bool.
Variables may be declared with a modifier: required, optional, repeated.
A sequence number is assigned to each variable, which is a directive to the compiler and not a value for the variable.
required string x = 1 // 1 is not a value
An initial value may be assigned with the default directive:
required string x = 1 [default="Some text"];
In addition to primitives, nested types are added by embedding a message into another message:
message container { required int32 number = 1; message contained { repeated string x = 1; } }
The "contained" object and its variables can be accessed through a string as container.contained.x
Enumerations with the type enum can be included in messages.
When we defined the structure of a message, it is used in a program by creating an instance. To it are associated methods specific to the class and produced by the compiler int C++ or Java generated files.
container myinstance; myinstance.set_number(18);
Sample code
Simple message.
message hello { required string = 1 [default="the message"]; optional int32 = 2; }
See the definition of the PB programming language for more details.
Download the Protoc compiler and get the full documentation included in the archive.
See also...
- Protocol Buffers tutorial, A short manual for a first use.
- JSON. A simpler format for JavaScript and server-side languages.
- FlatBuffers. By Google again a very fast serialization framework, enabling the use of data stored without loading the file into memory. An example of use is the data used by a game such as maps, sprites, etc.
|
http://www.scriptol.com/programming/protocol-buffers.php
|
CC-MAIN-2016-40
|
refinedweb
| 644
| 55.74
|
Ant 1.6 introduces support for XML namespaces. This page tries to show what this means, how it can be used, and where potential problems exist in the current implementation (as of 1.6 beta 3).
History
All releases of Ant prior to Ant 1.6 do not support XML namespaces. No support basically implies two things here:
- Element names correspond to the "qname" of the tags, which is usually the same as the local name. But if the build file writer uses colons in names of defined tasks/types, those become part of the element name. Turning on namespace support gives colon-separated prefixes in tag names a special meaning, and thus build files using colons in user-defined tasks and types will break.
Attributes with the names 'xmlns' and 'xmlns: IIRC, and using any attribute starting with "xml" is actually strongly discouraged by the XML spec to reserve such names for future use.
Motivation
In build files using a lot of custom and third-party tasks, it is easy to get into name conflicts. When individual types are defined, the build file writer can do some name-spacing manually (for example, using "tomcat-deploy" instead of just "deploy"). But when defining whole libraries of types using the <typedef> 'resource' attribute, the build file writer has no chance to override or even prefix the names supplied by the library.
Assigning Namespaces
Adding a 'prefix' attribute to <typedef> might have been enough, but XML already has a well-known method for name-spacing..
Namespaces and Nested Elements>
Namespaces and Attributes
Attributes are only used to configure the element they belong to if:
they have no namespace (note that the default namespace does not apply to attributes)
- they are in the same namespace as the element they belong meta data, such as RDF and XML-Schema (whether that's a good thing or not). The same is not true for elements from unknown namespaces, which result in a error.
Mixing Elements from Different Namespaces
Now comes the difficult part: elements from different namespaces can be woven together under certain circumstances. This has a lot to do with the NewAntFeaturesInDetail/NewIntrospectionRules: Ant types and tasks are now free to accept arbritrary where the builtin Ant conditions and selectors are not really types in 1.6. This is expected to change in Ant 1.7.
Namespaces and Antlib
The new NewAntFeaturesInDet.
More TBD
Namespaces and DynamicConfigurator
TBD
|
http://wiki.apache.org/ant/NewAntFeaturesInDetail/XmlNamespaceSupport?action=diff
|
CC-MAIN-2016-40
|
refinedweb
| 404
| 60.24
|
iPath Struct Reference
[Geometry utilities]
#include <igeom/path.h>
Detailed Description
A path in 3D.
An object or camera can use this object to trace a path in 3D. This is particularly useful in combination with csReversibleTransform::LookAt().
Definition at line 40 of file path.h.
Member Function Documentation
Calculate internal values for this spline given some time value.
Get the index of the current point we are in (valid after Calculate()).
Get one forward vector.
Get the interpolated forward vector.
Get the interpolated position.
Get the interpolated up vector.
Get one position vector.
Get one time value.
Get one up vector.
Return the number of points defining the path.
Calling this GetPointCount as in the real classes causes MANY ambiguous function call errors in msvc7.
Set one forward vector.
Set the forward vectors (dimensions 6 to 8).
Set one position vector.
Set the position vectors (first three dimensions of the cubic spline).
Set one time value.
Set one up vector.
Set the up vectors (dimensions 3 to 5).
The documentation for this struct was generated from the following file:
Generated for Crystal Space 1.4.1 by doxygen 1.7.1
|
http://www.crystalspace3d.org/docs/online/api-1.4.1/structiPath.html
|
CC-MAIN-2016-40
|
refinedweb
| 192
| 55.5
|
Code. Collaborate. Organize.
No Limits. Try it Today.
In this article we show how odeint can be adapted to work with VexCL.
odeint is a library for solving ordinary differential equations (ODE) numerically with C++. ODEs are important in many scientific areas and hence numerous applications
for odeint can be found. VexCL is a high-level C++ library for OpenCL. Its main feature are expression templates which significantly simplify the way one writes code
for numerical problems. By using OpenCL the resulting code can run on a GPU or can be parallelized on multiple cores. Both libraries have been introduced here on the CodeProject:
Note: This article does not give an introduction to the odeint and ordinary differential equations. If you are unfamiliar with those read the odeint article first!
Note: VexCL needs C++11 features! So you have to compile with C++11 support enabled.
odeint provides a mechanism which lets the user change the way how the elementary numerical computations (addition, multiplication, ...) are performed. This mechanism consist of a combination of state_type, algebra and operations. state_type represents here the state of the ODE and it is usually a vector type like std::vector, std::array. An example is:
std::vector
std::array
std::array< double , 3 > x1 , x2;
// initialize x1, x2
odeint::range_algebra algebra;
double dt = 0.1;
algebra.for_each2( x1 , x2 , default_operations::scale_sum1( dt ) );
// computes x1 = dt * x2 for all elements of x1 and x2
The algebra is responsible for iterating of all elements of the state whereas the operations are responsible for the elementary operation.
In the above example a for_each2 is used, which means that two state types are iterated. The operation is a scale_sum1
which simply calculates x1[i] = dt * x2[i]. odeint provides a set of predefined algebras:
for_each2
scale_sum1
x1[i] = dt * x2[i]
range_algebra
array_algebra
boost::array
fusion_algebra
boost::fusion::vector
std::tuple
vector_space_algebra
thrust_algebra
Many libraries for vector and matrix types provide expression templates for the elementary operations. Examples are Boost.Ublas, MTL4, and VexCL. Such libraries do not need an own algebra but can be used with the vector_space_algebra and the default_operations which simply calls the operations directly on the matrix or vector type. All you have to do in this case is to adapt odeint resizing mechanism. How this works for VexCL is described in this article. The adaption of Boost.Ublas and MTL4 is then very similar to the adaption of VexCL.
default_operations
VexCL introduces several vector types which live on OpenCL devices. The main vector type is vex::vector which is the classical analog to the std::vector. vex::vector can also be split over multiple devices. One of the major points of VexCL is that is supports expression templates. For example, it is possible to write code like
vex::vector
vex::vector< double > x() , y() , z();
// initialize x, y, z
z = 0.125 * ( x * x + 2.0 * x * y + y * y );
The second line in this example creates lazily an expression template which is evaluated when the assign operator is invoked. The advantage is surely that temporaries are avoided and you do not loose any performance.
Since VexCL already supports expression templates it can directly be used with the vector_space_algebra of odeint. There is no need to introduce an additional algebra or new operations. The example from the previous section can be written as
vex::vector< double > x , y;
vector_space_algebra algebra;
double dt = 0.1;
algebra.for_each2( x , y , default_operations::scale_sum1( dt );
In order to use vex::vector with odeint only the resizing of VexCL needs to be adapted for odeint. Resizing in odeint is necessary since many solvers need temporary state types. These state types need to be constructed and initialized which is done by the resizing mechanism of odeint.
The resizing mechanism of odeint consist of three class templates. These classes are is_resizeable<> which is a simply meta function telling odeint if the type is really resizable. The second class is same_size_impl<> which has a static method same_size taking two state_types as arguments and returning if both types have the same size. The third class is resize_impl<> which performs the actual resizing. These classes have a default implementation and can be specialized for any type.
is_resizeable<>
same_size_impl<>
same_size
resize_impl<>
For VexCL the specialization is:
template< typename T >
struct is_resizeable< vex::vector< T > > : boost::true_type { };
template< typename T >
struct resize_impl< vex::vector< T > , vex::vector< T > >
{
static void resize( vex::vector< T > &x1 , const vex::vector< T > &x2 )
{
x1.resize( x2.queue_list() , x2.size() );
}
};
template< typename T >
struct same_size_impl< vex::vector< T > , vex::vector< T > >
{
static bool same_size( const vex::vector< T > &x1 , const vex::vector< T > &x2 )
{
return x1.size() == x2.size();
}
};
That is all. Having the specializations one can use VexCL and odeint. Of course, these specializations are already defined in odeint. You only need to include:
#include <boost/numeric/odeint/external/vexcl/vexcl_resizing.hpp>
VexCL also has a multi-vector, which packs several instances of vex::vector and allows to synchronously operate on all of them. The resizing specializations for the multi-vector are very similar to vex::vector and are also included in the header above.
The power of GPUs is only used if one tries to solve large problems, such that many sub-problems can be solved in parallel. For ODEs one needs about 10000 coupled ODEs to gain performance from the GPU compared to the CPU. In this section two typical examples for large ODEs are introduced.
In the first example we will use the Lorenz system and study its dependence on one of the parameters. The Lorenz system is a system of three coupled ODEs which shows chaotic behavior for a large range of parameters. The ODE reads
dx / dt = -sigma * ( x - y )
dy / dt = R * x - y - x * z
dz / dt = - b * z + x * y
We will study the dependence on the parameter R. Therefore, we create a large set of these systems (each with a different parameter R),
pack them all into one system and solve them simultaneously on the GPU. The Lorenz system is a system of three coupled ordinary differential equations. If we want to solve N of these systems the overall state has 3*N entries. We can pack each component separately into one of VexCL's vectors. But multi-vector consisting of three sub-vectors fits this problem much better.
The typedefs are:
R
N
3*N
typedef vex::vector< double > vector_type;
typedef vex::multivector< double, 3 > state_type;
The vector_type here is needed to store the parameters R. The sub-vectors of the state_type can be accessed via:
vector_type
state_type
state_type X;
// initialize X
auto &x = X(0);
auto &y = X(1);
auto &z = X(2);
So, all x-components of the N Lorenz system are in X(0), all y-components are in X(1), and all z-components are in X(2). Now, we implement the system function. This function represents the ODE and is used from odeint to solve the ODE. The system needs to be a function object (a functor or a plain C-function) with three parameters. Is signature is void( const state_type&, state_type&, time_type ). The first parameter is an input parameter and represents the current state of the ODE, the second one is an output parameter and is used to store
the RHS of the ode. The third parameter is simply the time. As said above VexCL supports expression templates for numerical computation. By using expression templates the system function becomes very simple.
X(0)
X(1)
X(2)
void( const state_type&, state_type&, time_type ));
}
};
Note that the system function holds a vector for all parameters R. Each line in system functions computes the expression for the whole set of all N elements of the vector. This is in principle all. We can now instantiate one of odeints solvers and solve the ODE. A complete main program might look like this:
// setup the opencl context
vex::Context ctx( vex::Filter::Type(CL_DEVICE_TYPE_GPU) );
std::cout << ctx << std::endl;
// set up number of systems, time step and integration time
const size_t n = 1024 * 1024;
const double dt = 0.01;
const double t_max = 100.0;
// initialize R
double Rmin = 0.1 , Rmax = 50.0 , dR = ( Rmax - Rmin ) / double( n - 1 );
std::vector<double>;
// instantiate a stepper
runge_kutta4<
state_type , double , state_type , double ,
odeint::vector_space_algebra , odeint::default_operations
> stepper;
// solve the system
integrate_const( stepper , sys_func( R ) , X , 0.0 , t_max , dt );
As you can see, odeint's vector_space_algebra and default operation set are used here.
As a second example we choose a chain of coupled phase oscillators. Phase oscillators
are a very simplified version of usual oscillator where the state is described by a 2π periodic variable. If a single phase oscillator is uncoupled its phase φ is described by a linear growth dφ / dt = ω where ω is the phase velocity. Therefore, interesting behavior can only be observed if two or more oscillators are coupled. In fact, a system of coupled phase oscillators is a prominent example of an emergent system where the coupled system shows a more complex behavior than its constitutes.
2π
φ
dφ / dt = ω
ω
The concrete example we analyze here is:
dφ(i) / dt = ω(i) + sin( dφ(i+1) - dφ(i) ) + sin( dφ(i) - dφ(i-1) )
Note, that dφ(i) is a function of the time, the argument i denotes here the i.th phase in the chain. To implement such equations efficiently on the GPU Denis did a great job of introducing some kind of generalized stencils. The stencil for our problem is generated by
dφ(i)
i
extern const char oscillator_body[] = "return sin(X[-1] - X[0]) + sin(X[0] - X[1]);";
vex::StencilOperator< double, 3, 1, oscillator_body > S( queue_list() );
The first line simply generates an OpenCL string of the elementary operation done in each kernel. The second line instantiates the stencil operator. It can be applied to a vector x by imposing S(x). The complete system function of the chain of phase oscillators is then
S(x)
extern const char oscillator_body[] = "return sin(X[-1] - X[0]) + sin(X[0] - X[1]);";
struct sys_func
{
const state_type ω
vex::StencilOperator< double, 3, 1, oscillator_body > S;
sys_func( const state_type &_omega )
: omega( _omega ) , S( _omega.queue_list() )
{ }
void operator()( const state_type &x , state_type &dxdt , value_type t ) const
{
dxdt = omega + S( x );
}
};
In this section we compare the performance of VexCL against Thrust. Thrust is a high level library for CUDA which provides a STL like interface to vectors on the CUDA devices. Furthermore, it can easily be used to put the computations on one or more cores of your CPU by using OpenMP. The Lorenz example for Thrust is described in the tutorial of odeint. Thrust does not provide expression templates, but is has an advanced iterator system which lets you program the numerical expression in an easy manner. Nevertheless it is more complicated than VexCL.
The image below shows the performance of the Lorenz system example for several configurations of Thrust and VexCL. In detail it shows the performance of VexCL on one GPU, two GPUs, three GPUs, and on one CPU core. Furthermore, the performance for Thrust on the GPU (only single GPU computations are supported) and on one CPU are shown shown. It is clearly visible that Thrust outperforms VexCL on one GPU. But if more than one GPUs are used (and are installed on your computer) VexCL becomes faster. The same holds for the CPU version. Furthermore, one can clearly see that for small system sizes where the computation time is relatively small VexCL has a constant run-time. This is due to the fact that the OpenCL compiles the kernels at run-time for the GPU. (The right panel shows the performance of VexCL relative to Thrust on GPU. So if the curves are above 1 then VexCL is faster otherwise it is slower.)
The performance results for the phase oscillator chain are shown in the next figure. For the Thrust version of the chain the system function has been implemented with Thrust's iterator system. Interestingly, VexCL here outperforms Thrust. Of course, for small system sizes the constant overhead is present and here Thrust performs better. But for large systems VexCL becomes faster. This might be due to the fact that the iterators in Thrust have their price but it is not exactly clear why which version is faster.
We have shown how VexCL can be adapted to odeint and how it can be used to increase the performance when solving large ordinary differential equations. Large here means that the system size (number of coupled coupled ODEs) should be of the order 10000-100000 to see a reasonable performance gain compared to usual CPUs. For large systems this gain can be about 20 times.
The performance of VexCL has also been compared against Thrust. In one example a large ensemble of ODEs has been solved. It turns out that Thrust is about 10% faster in this case compared to VexCL. In the second example a system of coupled phase oscillators has been studied. Here VexCL is faster by a factor of 1.2. Nevertheless, the expression templates of VexCL are a big plus for this library. It lets the user solve complicated problems within minutes where the development with native CUDA or OpenCL code or even with Thrust requires much
|
http://www.codeproject.com/Articles/429183/Solving-ordinary-differential-equations-with-OpenC
|
CC-MAIN-2014-15
|
refinedweb
| 2,222
| 54.93
|
Design-Time Code Generation by using T4 Text Templates
Note
This article applies to Visual Studio 2015. If you're looking for Visual Studio 2017 documentation, use the version selector at the top left. We recommend upgrading to Visual Studio 2017. Download it here..
Note
A model is a data source that describes a particular aspect of an application. It can be any form, in any kind of file or database. It does not have to be in any particular form, such as a UML model or Domain-Specific Language model. Typical models are in the form of tables or XML files..
Creating a Design-Time T4 Text Template:
<#@ template hostspecific="false" language="C#" #> <#@ output extension=".txt" #>
If you added the template to a Visual Basic project, the language attribute will be "
VB".
Add some text at the end of the file. For example:
Hello, world!.
Note
If your project is a Visual Basic project, you must click Show All Files in order to see the output file..
Generating Variable Text
Text templates let you use program code to vary the content of the generated file.
To generate text by using program code
Change the content of the
.ttfile:
<#@ template hostspecific="false" language="C#" #> <#@ output extension=".txt" #> <#int top = 10; for (int i = 0; i<=top; i++) { #> The square of <#= i #> is <#= i*i #> <# } #>
<#@ template hostspecific="false" language="VB" #> <#@ output extension=".txt" #> <#Dim top As Integer = 10 For i As Integer = 0 To top #> The square of <#= i #> is <#= i*i #> <# Next #>
templatedirective should contain
language="VB".
"C#"is the default.
Debugging a Design-Time T4 Text Template.
Tip
debug="true" makes the generated code map more accurately to the text template, by inserting more line numbering directives into the generated code. If you leave it out, breakpoints might stop the run in the wrong state.
But you can leave the clause in the template directive even when you are not debugging. This causes only a very small drop in performance.
Generating Code or Resources for Your Solution:
<#@ template debug="false" hostspecific="false" language="C#" #> <#@ output extension=".cs" #> <# var properties = new string [] {"P1", "P2", "P3"}; #> // This is generated code: class MyGeneratedClass { <# // This code runs in the text template: foreach (string propertyName in properties) { #> // Generated code: private int <#= propertyName #> = 0; <# } #> }
<#@ template debug="false" hostspecific="false" language="VB" #> <#@ output extension=".cs" #> <# Dim properties = {"P1", "P2", "P3"} #> class MyGeneratedClass { <# For Each propertyName As String In properties #> private int <#= propertyName #> = 0; <# Next #> }
Save the file and inspect the generated file, which now contains the following code:
class MyGeneratedClass { private int P1 = 0; private int P2 = 0; private int P3 = 0; }.
Reading files or other sources
To access a model file or database, your template code can use assemblies such as System.XML. To gain access to these assemblies, you must insert directives such as these:
<#@ assembly name="System.Xml.dll" #> <#@ import namespace="System.Xml" #> <#@ import namespace="System.IO" #>:
<# var properties = File.ReadLines("C:\\propertyList.txt");#> ... <# foreach (string propertyName in properties) { #> ...
<# For Each propertyName As String In File.ReadLines("C:\\propertyList.txt") #>
Opening a file with a relative pathname
To load a file from a location relative to the text template, you can use
this.Host.ResolvePath(). To use this.Host, you must set
hostspecific="true" in the
template:
<#@ template debug="false" hostspecific="true" language="C#" #>
Then you can write, for example:
<# string fileName = this.Host.ResolvePath("filename.txt"); string [] properties = File.ReadLines(filename); #> ... <# foreach (string propertyName in properties { #> ...
<# Dim fileName = Me.Host.ResolvePath("propertyList.txt") Dim properties = File.ReadLines(filename) #> ... <# For Each propertyName As String In properties ... #> #>
Tip
A text template runs in its own app domain, and services are accessed by marshaling. In this circumstance, GetCOMService() is more reliable than GetService().
Regenerating the code automatically:
<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v11.0\TextTemplating\Microsoft.TextTemplating.targets" /> <PropertyGroup> <TransformOnBuild>true</TransformOnBuild> <!-- Other properties can be inserted here --> </PropertyGroup>
For more information, see Code Generation in a Build Process.
Error reporting
To place error and warning messages in the Visual Studio error window, you can use these methods:
Error("An error message"); Warning("A warning message");
Converting an existing file to a template:
<#@ template debug="false" hostspecific="false" language="C#" #> <#@ output extension=".cs" #>.
Guidelines for Code Generation
Please see Guidelines for Writing T4 Text Templates.
Next steps
See Also
Guidelines for Writing T4 Text Templates
|
https://docs.microsoft.com/en-us/visualstudio/modeling/design-time-code-generation-by-using-t4-text-templates?view=vs-2015
|
CC-MAIN-2018-47
|
refinedweb
| 720
| 50.02
|
fn:resolve-QName( qname as xs:string?, element as element() ) as xs:QName?
Returns.
Sometimes the requirement is to construct an
xs:QName
without using the default namespace. This can be achieved by writing:
if ( fn:contains($qname, ":") ) then ( fn:resolve-QName($qname, $element) ) else ( fn:QName("", $qname) )
If the requirement is to construct an
xs:QName using the
namespaces in the static context, then the
xs:QName
constructor should be used.
If $qname does not have the correct lexical form for
xs:QName
an error is raised [err:FOCA0002].
If $qname is the empty sequence, returns the empty sequence.
More specifically, the function searches the namespace bindings of $element for a binding whose name matches the prefix of $qname, or the zero-length string if it has no prefix, and constructs an expanded QName whose local name is taken from the supplied $qname, and whose namespace URI is taken from the string value of the namespace binding.
If the $qname has a prefix and if there is no namespace binding for $element that matches this prefix, then an error is raised [err:FONS0004]. discussed in Section 2.1 Terminology[DM].
Assume that the element bound to $element has a single namespace binding bound to the prefix "eg". fn:resolve-QName("hello", $element) => a QName with local name "hello" that is in no namespace. fn:resolve-QName("eg:myFunc", $element) => an xs:QName whose namespace URI is specified by the namespace binding corresponding to the prefix "eg" and whose local name is "myFunc".
Stack Overflow: Get the most useful answers to questions from the MarkLogic community, or ask your own question.
|
https://docs.marklogic.com/fn:resolve-QName
|
CC-MAIN-2022-27
|
refinedweb
| 271
| 52.39
|
The Module Import in JavaScript Has a Drawback
1. Named imports and autocomplete
Let's say you write a simple JavaScript module:
javascript
// stringUtils.jsexport function equalsIgnoreCase(string1, string2) {return string1.toLowerCase() === string2.toLowerCase();}
This is a module
stringUtils. The module has a named export
equalsIgnoreCase, which is a function that compares 2 strings ignoring the case.
Everything looks good so far.
Now, let's try to import
equalsIgnoreCase function from
stringUtils module inside of another JavaScript module
app:
javascript
// app.jsimport { equalsIgnoreCase } from './stringUtils';equalsIgnoreCase('Hello', 'hello'); // => true
Most likely you would write the code the following way:
First, you have to write the import names
import { }. At this step, the IDE cannot give any suggestions about the available names to import.
Then you continue writing
from './stringUtils'. Then move back to curly brackets and expand autocomplete to select the names to import.
Despite all the good things about ES2015 modules, the import module syntax makes difficult to use autocomplete.
2. Modules in Python
Now let's try to import named components in Python. Does it have the same problem?
Here's the same module
stringUtils and function
equalsIgnoreCase implemented in Python:
python
# stringUtils.pydef equalsIgnoreCase(string1, string2):return string1.lower() == string2.lower()
In Python, you don't have to explicitly indicate the functions to export.
Now, inside of another Python module
app, let's try to import the function
equalsIgnoreCase from
stringUtils:
python
# app.pyfrom stringUtils import equalsIgnoreCaseequalsIgnoreCase('Hello', 'hello') # => true
Most likely, you would write
app module the following way:
In Python, first, indicate the module you're importing from:
from stringUtils. Then you write what to import
import ....
If you'd like to know the functions available for import, the editor already knows the module name and gives the necessary suggestions. Way better!
3. The solution
The only solution I could find to enable autocomplete on named imports in JavaScript is to call IDEs for help.
For example, in Visual Studio Code, you could install the JavaScript (ES6) code snippets plugin.
Having the plugin enabled, by using the
imd snippet and hitting
tab key, the cursor first jumps into the position where you write the module path. Then, after pressing the
tab key, the cursor jumps back to the import position inside the curly brackets. Here's how it works:
4. Conclusion
In JavaScript, the import syntax forces you to indicate first the items (functions, classes, variables) you'd like to import, then the path to module. This approach is not autocomplete friendly.
In Python, on the opposite, you indicate first the module name, then the components you'd like to import:
from stringUtils import equalsIgnoreCase. This syntax enables easy autocomplete of the imported items.
With the use of IDEs possibilities, like the ES6 code snippet plugin, you could mitigate the problem of named import autocomplete in JavaScript. Still better than nothing.
Do you find difficult to use autocomplete with ES modules? If so, what.
|
https://dmitripavlutin.com/javascript-import-module-drawback/
|
CC-MAIN-2021-49
|
refinedweb
| 489
| 66.44
|
I…
If you ever feel the need to host a database on a server and do not have the resources to do so, you can setup the database locally on a laptop and expose the service to the outside world using ngrok. Please be aware that using ngrok has it’s own advantages and disadvantages and the connectivity isn’t as reliable as compared to AWS RDS. However, it’s faster to implement and cost effective for running POC’s and test apps for demo or test purposes.
Question: What is ngrok?
Answer: Ngrok exposes local servers behind NATs and firewalls to the public internet…
Over time as you create pull requests and move your changes from temporary branches over to the dev or master branch, a lot of branches can pile up on your local system and can be noisy when you are trying to list all the branches.
If you’re using GitHub, it conveniently gives you the option to delete the temporary branch after merging into dev or master. But, the local git repository still shows the remote and local branches even though they have been deleted from GitHub. When branches get deleted on origin, your local repository won’t take notice of that…
There are so many ways of hosting custom JAR files and importing them for your projects. You could use a Nexus server, store them in GitHub or even install them locally on all machines. But in a production environment, you may not have access to the build server to go and install custom JAR files. Adding them to your Nexus server in that case (if available) might seem like a good idea, but it comes with a drawback that every developer will have to setup a local Nexus server to keep the build process in sync with the production setup.
…
Here are instructions to install and run mcrypt on Debian 10 with PHP 7.3+
Check PHP Version
$ php -version
PHP 7.3.9-1~deb10u1 (cli) (built: Sep 18 2019 10:33:23) ( NTS )
Check if mcrypt is installed
$ php -m | grep mcrypt
Install pre-requisites
sudo apt-get install php-dev libmcrypt-dev php-pear
Install mcrypt PHP module
$ sudo pecl channel-update pecl.php.net
Updating channel "pecl.php.net"
Update of Channel "pecl.php.net" succeeded
$ sudo pecl install channel://pecl.php.net/mcrypt-1.0.2
...
...
Build process completed successfully
Installing '/usr/lib/php/20180731/mcrypt.so'
install ok: channel://pecl.php.net/mcrypt-1.0.2
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini
Add mcrypt.so…
Ever feel the need to sort a JSON by keys, OR sorting a dictionary by keys? Python doesn’t allow that.
Question: Is there an alternative?
Answer: Yes!
You cannot sort a dictionary by keys, but if the need is to print it out, you could covert it to a JSON and the resulting JSON output can be sorted by keys. Likewise, if you have JSON that you’d like to sort, you can first convert it to a dictionary and then convert it back to JSON and this time sort it by keys. And this is true for a multi-dimentional dictionary and JSON.
Converting dictionary to a sorted JSON
sorted_json = json.dumps(dict_data, sort_keys=True) # This JSON will be sorted recursively
Converting unsorted JSON to sorted JSON by keys
import jsondict_data = json.loads(unsorted_json)
sorted_json = json.dumps(dict_data, sort_keys=True) # This JSON will be sorted recursively
Using python/psycopg2 and wondering how life would be so much easier if you could get the query results to be a dictionary and you could get the value by using a keyword on the dictionary. psycopg2 by default returns results as a tuple so you have to use row[0], etc. to get the values. e.g. the code looks something like this
qSelect = "SELECT first_name, last_name, address FROM employee"cursor.execute(qSelect)results = cursor.fetchall()
for row in results:
print("First Name: {}".format(row[0]))
print("Last Name: {}".format(row[1]))
print("Address: {}".format(row reputation as a software provider.
Question: What are we trying to learn from this article?
Anyone ever told you to have several layers of security to protect your application? Damn right. As an application developer or a DB admin, how can you ensure that you’ve setup the right set of security principles for your database? This article will help you answer some of those questions and hopefully make you feel secure about your database and maybe help you have a sound sleep at night.
The general principle of segregating privileges to the database is that “If you shouldn’t be using it, you shouldn’t have access to it”. …
I am sure you’ve all been in a situation where you’d like to implement a counter to track website hits, database reads, API exceptions, etc. There are various ways this can be implemented with each one having their own pros and cons. I’ll briefly go over them and explain alongside, so just follow along.
This is the simplest and most efficient implementation considering you have a single threaded application. But in the modern world, this is a rarity so won’t be used often, but I’ll still mention it for the sake of it.
class SingleThreadCounter(object): def __init__(self): self.value = 0…
Mastering automation, improving efficiency and connecting systems.
|
https://varun-verma.medium.com/?source=post_internal_links---------1----------------------------
|
CC-MAIN-2021-21
|
refinedweb
| 910
| 63.59
|
I just came back to and
saw, that there have been no recent changes. I wonder, if this
is the current state or if there has been further development on
the topic.
If not I'd like to make a few suggestions
Describe memory offsets in multiples of the plattforms native
pointer size (i.e. sizeof(ptrsize_t)). Currently the ABI is
limited to 32 bit. (One might double the sizes implicitly for 64
bit plattforms).
Separate the ABI in Compile Level and Link Level.
The Compile Level operates on the alignment of data within memory
and the data transfer methods within a compilation object.
The Link Level however should be coupled to the output format
(COFF, ELF, $whatever). IMHO it makes sense so describe Link
Level ABI for different object formats.
E.g. the component system I've developed for my engine, called
ECS, similair to DDL, stores the properties of code objects in a
hierachical, EMBF like (EMBF a binary XML counterpart) structure
without elude to name mangling and other tricks. Since ECS
provides a sound set of the runtime code that would otherwise
call statical constructors (and module inits) it also conflicts
a bit with parts of any ABI that would force strict rules on
that topic. Since static constructor calling and module
initialization is part of the Link Level, logically put it
there. Link systems that differ from the usual ELF/PE/COFF will
not by inflicted that way.
Currently declaring a class $xxx implicitly instanciates a
Class$xxx, StaticClass$xxx and an instance that names
Static$xxx. I wonder if there could be a less namespace
polluting solution to that. Maybe somee new properties on the
modulespace?
I'm nearly done converting all the C++ source code of my 3D
engine to D. Where converting means: "puting nearly 20% of the
code to /dev/null". I just love D!!!
--
Wolfgang Draxinger
|
http://forum.dlang.org/thread/e9arn9$uir$1@digitaldaemon.com
|
CC-MAIN-2014-35
|
refinedweb
| 315
| 63.8
|
Afternoon, I'm working on a DOM-based application which I want to be compatible with as much of the installed base of Python DOM implementations as possible. I'm using DOM Level 2 Namespace-aware Core methods only, with an importer layer that fixes up known bugs in widely-deployed DOMs. I've checked minidom from Python 2.1 and 4DOM from PyXML 0.6.6 so far, and added workarounds for the following problems: - minidom: no native importNode support - minidom: insertBefore/appendChild/replaceChild with DocumentFragment Node fails to insert all new children due to destructive list iteration - minidom: attributes in no namespace get '' namespaceURI instead of None. Elements and attributes in no namespace get '' prefix instead of None. - 4DOM: elements and attributes in no namespace get '' namespaceURI and prefix instead of None. - 4DOM: localName of xmlns="..." declarations is '' instead of 'xmlns'. Are there any other known problems with common DOMs I ought to be looking out for? cheers, -- Andrew Clover mailto:and@doxdesk.com
|
https://mail.python.org/pipermail/xml-sig/2003-March/009315.html
|
CC-MAIN-2017-39
|
refinedweb
| 166
| 57.47
|
PWM sound output
PWM signal can change the brightness of LEDs. You must be quite familiar with it through some projects. What's more, it allows the buzzer to generate sounds.
This example shows how to use the
PWMOut to generate notes. It plays musical notes from 1 to 7 repeatedly.
What you need
- SwiftIO Feather (or SwiftIO board)
- Breadboard
- Buzzer
- Jumper wires
Circuit
- Plug the buzzer onto the breadboard.
- Connect any one leg to the pin GND and the other to the pin PWM5A.
Example code
You can find the example code at the bottom left corner of IDE: /
SimpleIO /
PWMSoundOutput.
// Produce different notes by changing the frequency of PWM signals.
// Import the library to enable the relevant classes and functions.
import SwiftIO
// Import the board library to use the Id of the specific board.
import MadBoard
// Initialize a PWM output pin the speaker connects.
let speaker = PWMOut(Id.PWM5A)
// Specify several frequencies to produce different sound.
let fre = [262, 294, 330, 349, 392, 440, 494]
// Play recurrently these notes.
while true {
for f in fre {
// Set the frequency and the duty cycle of output to produce each note.
speaker.set(frequency: f, dutycycle: 0.5)
// Play each note for one second.
sleep(ms: 1000)
}
}
Background
Buzzer
The PWM signal outputs high and low voltage alternatively. There is a diaphragm inside the buzz. A passive buzzer needs a PWM signal to vibrate the diaphragm. The frequency will influence the pitch. A higher frequency will produce a higher pitch.
Code analysis
let fre = [262, 294, 330, 349, 392, 440, 494]
This array stores the frequencies of seven notes from 1 to 7. The first frequency corresponds to middle C.
speaker.set(frequency: f, dutycycle: 0.5)
The frequency is an essential factor for sounds. The method
set() allows you to set both the frequency and duty cycle of the PWM signal.
sleep(ms: 1000)
sleep defines the duration of notes. Each note will last one second.
Reference
PWMOut - set the PWM signal.
MadBoard - find the corresponding pin id of your board.
|
https://docs.madmachine.io/tutorials/general/simpleio/pwm-sound-output
|
CC-MAIN-2022-21
|
refinedweb
| 341
| 69.48
|
#include "dmx.h"
#include "dmxstat.h"
#include "dmxlog.h"
#include "Xos.h"
Used to compute a running average of value.
Turn on XSync statistic gathering and printing. Print every interval seconds, with lines for the first displays. If interval is NULL, 1 will be used. If displays is NULL, 0 will be used (meaning a line for every display will be printed). Note that this function takes string arguments because it will usually be called from ddxProcessArgument in #dmxinit.c.
Allocate a DMXStatInfo structure.
Free the memory used by a DMXStatInfo structure.
Try to initialize the statistic gathering and printing routines. Initialization only takes place if dmxStatActivate has already been called. We don't need the same generation protection that we used in dmxSyncInit because our timer is always on a queue -- hence, server generation will always free it.
Note that a XSync() was just done on dmxScreen with the start and stop times (from gettimeofday()) and the number of pending-but-not-yet-processed XSync requests. This routine is called from #dmxDoSync in #dmxsync.c
Only for dmxstat.c and dmxsync.c
|
http://dmx.sourceforge.net/html/dmxstat_8c.html
|
CC-MAIN-2017-17
|
refinedweb
| 183
| 70.39
|
/*************************************************** Write a program that allows the user to enter a sequence of "moves" and prints out their position after the moves. Moves are: left - means a 90 deg counter clockwise turn (in place) right - means a 90 deg clockwise turn (in place) step - means step forward 1 unit stop - terminates the sequence of moves. The initial position is (0,0) facing North (up). So the sequence "left step step left step right stop" would leave you at (-2,-1). ***************************************************/ #include <iostream> #include <string> #include <cmath> using namespace std; int main() { // Initialize double PI; PI = 3.14159265; int x, y, angle; x = y = 0; angle = 90; string next; cout << "Enter moves: "; cin >> next; // Loop processing the "next" command at each iteration while(next != "stop") { if (next == "left") { angle = angle + 90; } else if (next == "right") { angle = angle + 270; // Two wrongs don't equal a right, but three lefts do! } else if (next == "step") { x = x + floor(cos(angle*PI/180) + 0.5); // See note below. y = y + floor(sin(angle*PI/180) + 0.5); } // Read next command cin >> next; } // Print final position cout << "Final position is " << '(' << x << ',' << y << ')' << endl; return 0; } /* NOTE: We can't just use sin(angle) and cos(angle). First of all the cmath functions expect angles to be given in radians. Second of all, sin and cos return doubles, which are decimal approximations of real numbers. So sin might return 0.9998 rather than 1. When that is implicitly cast to an int, everthing after the decimal point is truncated, so 0.9998 becomes 0 instead of 1. What we need to do is round to the nearest int. Unfortunately, cmath has floor and cieling but not "round to nearest". Turns out that that "floor(z + 0.5)" is the same as "round to nearest". Think about it! */
|
https://www.usna.edu/Users/cs/lmcdowel/courses/si204/S10/classes/class10_TE2v2_cpp.htm
|
CC-MAIN-2018-22
|
refinedweb
| 300
| 84.07
|
Program To Check Whether A Number Is A Perfect Number Or Not
In this blog, we will create a program in C# to check if an entered number is a perfect number or not.
Program To Check Whether A Number Is A Perfect Number Or Not
Introduction
Perfect numbers.
Program to check perfect number
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PerfectNumber { class Program { static void Main(string[] args) { int number, sum = 0; string divisors = ""; Console.WriteLine("---------------------------------------------------------------"); Console.WriteLine(" Perfect Number "); Console.WriteLine("----------------------------------------------------------------"); Console.Write("Enter Number To Check :: "); number = int.Parse(Console.ReadLine()); for (int i = 1; i < number; i++) { if (number % i == 0) { sum += i; divisors += i.ToString() + "+"; } } divisors = divisors.Remove(divisors.Length - 1, 1); Console.WriteLine("---------------------------------------------------------------"); Console.WriteLine(divisors + " = " + sum); if (sum == number) { Console.WriteLine("Hence , " + number + " Is A Perfect Number"); } else Console.WriteLine("Hence , " + number + " Is Not A Perfect Number"); Console.WriteLine("---------------------------------------------------------------"); Console.ReadKey(); } } }
Code Explanation
- First, we define three variables number type of integer, sum type of integer, and divisors type of string. We use numbers to get the input of a user, a sum to get the sum of the divisor, and divisors to add all divisors of the numbers in one string.
- Then we get input from the user and pass it to the number variable by converting it to an integer.
- Then we iterate a loop from 1 (one) to number – 1.
- In the loop, we module number by iterate variable I. If the remainder is 0 then add that number in sum and concat value of I in our variable divisors with plus (+) sign.
- After the loop, we remove the last one character from the divisors variable because the extra one + is also concat in the string. Here we just show this as all divisors sum is equal to sum for better user understanding.
- Next, we check if the sum is equal to the user’s input. If yes, then it shows a message that the entered number is a perfect number. Otherwise, the entered number is not a perfect number.
- Then, we use the Console.ReadKey() method to read any key from the console. By entering this line of code, the program will wait and not exit immediately. The program will wait for the user to enter any key before finally exiting. If you don't include this statement in the code, the program will exit as soon as it is run.
Output
I hope you find this blog helpful. If you get any help from this blog, please share it with your friends.
ADVERTISEMENT
ADVERTISEMENT
|
https://tutorialslink.com/Articles/Program-To-Check-Whether-A-Number-Is-A-Perfect-Number-Or-Not/2364
|
CC-MAIN-2021-43
|
refinedweb
| 436
| 67.45
|
Bugs item #3526361, was opened at 2012-05-13 11:38
Message generated for change (Tracker Item Submitted) made by
You can respond by visiting:
Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: None
Group: v3.0.0
Status: Open
Resolution: None
Priority: 5
Private: No
Submitted By: ()
Assigned to: Nobody/Anonymous (nobody)
Summary: GL.glGenLists not returning int on OSX 64 bit
Initial Comment:
I'm using py27-opengl 3.0.1_0 and py27-opengl-accelerate 3.0.1_0 on MacOS 10.7.3 64 bit via macports. I'm also using wxWidgets-devel 2.9.3_0+sdl if that's relevant.
I've installed the wxgui component of gnuradio and am getting the following error when I try and use an openGL widget:
Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/gnuradio/wxgui/plotter/plotter_base.py", line 187, in _on_paint
for fcn in self._draw_fcns: fcn[1]()
File "/opt/local/lib/python2.7/site-packages/gnuradio/wxgui/plotter/plotter_base.py", line 58, in draw
GL.glNewList(self._grid_compiled_list_id, GL.GL_COMPILE)
ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: wrong type
The code is at
Please make sure GL.glGenLists is returning what you expect it to return (namely an unsigned int). On some platforms I've seen PyOpenGL bindings not returning the generated value but rather expecting to assign it to the second parameter in a similar fashion than that of the C API.
Hope this helps!
Alejandro.-
Hi Alejandro,
self._grid_compiled_list_id = GL.glGenLists(1)
print self._grid_compiled_list_id
returns
'None'
----------------------------------------------------------------------
You can respond by visiting:
Hi,
Just wanted to say that I've got our visualization toolkit (visvis) running
in Python 3, based on the current Bazaar head of pyopengl. I've got all our
examples working on both Linux and Windows.
The only thing that doesn't feel right yet is that I have to pass the
shading code as a str and names for uniforms as bytes. But I understood
from Rob that this is on your todo list.
Thanks for your support so far. Regards,
Almar
On 27 April 2012 15:43, Rob Reilink <r.reilink@...> wrote:
> Hi Anthony,
>
> We (Science Applied) are using Py3 with bzr head. I am on Mac OS X, Almar
> Klein is on Win32. It seems that the result of this bug was that only
> functions that are provided by extensions (or something the like) were
> influenced.
>
> Almar is going to work on his visualization toolkit (visvis) to get that
> to work on Python3 (he just started and this bug was the first issue in
> PyOpenGL that he encountered). We do now have some of our test cases
> working, while others are not yet. The problem(s) may be either in visvis
> or in PyOpenGL, that is to be seen in the coming weeks (he's on holidays
> next week but he'll probably do some more testing/Py3 porting after next
> week)
>
> Anyway, for now, I'll create a fork and a pull request.
>
> Rob
>
>
> ---------------------------------------------
> Rob Reilink, M.Sc
> Science Applied
>
> phone: +31 6 187 26562
> ---------------------------------------------
>
>
>
>
> Op 27 apr 2012, om 15:04 heeft Mike C. Fletcher het volgende geschreven:
>
>
> BTW, is anyone actively using a Python3 version with bzr head? This bug
> seems like it would make the whole thing a non-starter (if no function
> will load, it doesn't seem anyone would get anywhere useful). If we're
> close, I'd prefer to get the major Python3 compatibility changes into at
> least one beta release of 3.0.2 before we roll out a final. I've got a
> TODO sitting in my inbox for allowing unicode in GLchar*, but AFAIK
> that's our only pending 3.x enhancement. If we're a long way from
> compatibility I may as well push a 3.0.2 beta and plan for 3.0.3 to have
> Python3 compatibility.
>
> Have fun,
> Mike
>
>
>
>
> ------------------------------------------------------------------------------
> Live Security Virtual Conference
> Exclusive live event will cover all the ways today's security and
> threat landscape has changed and how IT managers can respond. Discussions
> will include endpoint security, mobile security and the latest in malware
> threats.
> _______________________________________________
> PyOpenGL Homepage
>
> _______________________________________________
> PyOpenGL-Devel mailing list
> PyOpenGL-Devel@...
>
>
>
--
Almar Klein, PhD
Science Applied
phone: +31 6 19268652
|
http://sourceforge.net/p/pyopengl/mailman/pyopengl-devel/?viewmonth=201205
|
CC-MAIN-2014-10
|
refinedweb
| 726
| 65.93
|
In this series looking at features introduced by every version of Python 3, this is the first looking at Python 3.5. In it we examine one of the major new improvements in this release, new syntax for coroutines.
This is the 8th of the 15 articles that currently make up the “Python 2to3” series.
As I approach the halfway mark of going through all the currently released Python versions in this series of articles, I find myself reflecting briefly on those that I’ve done so far. I must confess it’s taking longer than I expected, probably because I’m going into way more detail than I originally intended. However, it’s been a useful exercise to drill in and add some code snippets — it’s quite easy to misunderstand a verbal explanation, but when you see that alongside some examples it gives you much more confidence in your understanding.
That said, I may try to fight my completionist tendencies and be a little more selective as we go. I’m also going to break things up into more parts, to make things a bit less of a slog!
Anyway, this time we’re up to Python 3.5, released 13 September 2015, bang on schedule 18 months after the release of 3.4. This will be the last release I’ll look at that’s no longer receiving security fixes at time of writing, so we’re getting increasingly close to versions that might still be being used in the real world at this point.
This release has a lot of big changes, the first of which is the subject of this entire article: coroutines.
Alright, I know I said I was talking about coroutines, and asyncio event loops aren’t just related to coroutines. They are intrinsically tied to how coroutines are executed, however, so I wanted to briefly talk about them first.
The event loop is the central scheduling construct in
asyncio. It provides multiple features, not all of which are required for coroutines but for completeness:
Since we’re talking about coroutines here, we won’t go into the I/O features of event loops, but they’re a pretty natural fit to use with coroutines.
The event loop doesn’t have a separate thread of execution controlling it, so it’s “paused” until you call into it to run it. Once you do so, it cycles around its own loop, executing callbacks and the like until it’s stopped. At this point control returns back to wherever you called the run function from.
There are two calls which run the loop:
run_forever()
stop()method is called. Note that most of the event loop classes are not thread-safe, so if you want to stop the loop from another thread you should probably use the
call_soon_threadsafe()method to execute it in the context of the event loop thread.
run_until_complete(future)
run_forever()except that it continues until the
Futurepassed as a parameter is done, then it exits.
The typical pattern is for the main thread to set up some initial callbacks or transports, add them to the event loop and then let it run. The code executed by these can schedule more callbacks within the loop as needed. For example, a callback can reschedule itself after another delay to create a repeating timer.
To schedule a call to be run ASAP in the loop, there’s a
call_soon() method, and to schedule calls for the future there are
call_later() and
call_at(), whose semantics you can probably work out from the names.
The other thing that’s worth knowing about event loops is that even though there can be multiple ones, there’s generally a default one for the current thread. Strictly speaking there’s a policy framework which can define context differently than per thread, but that’s getting a bit too far into the details for this overview. For now, suffice to say that you can call
asyncio.get_event_loop() to obtain the current event loop for the calling thread. If you’re writing a library which wants to use its own event loop in isolation from the rest of the code in an application for some reason, you’ll probably want to peruse the documentation further on this topic.
There are some more details to event loops, some of which are platform-specific, but those are the key points required to understand the implementation of coroutines. Here’s a simple bit of code to illustrate some of these calls.
All of this discussion so far has been in terms of callback functions, which are handy but not nearly as convenient as coroutines for many tasks. In the rest of this article we’ll see how coroutines work and interact with the event loop.
Release 3.5 added new syntax and library routines for declaring coroutines, defined in PEP 492, so I’m going to do a review of where things stand as of this release, which includes some features I glossed over in previous articles in expectation of this one. I did already look at this in a little detail in a previous article so you may like to look at that as well. It’s an important change, however, and it’s been 5 years since I wrote that so going over it again probably won’t be the worst idea — hopefully somewhere between that discussion and this one, most people should find enough to make things clear.
Do also bear in mind the point I raised in my first article on 3.4, however, that the coroutines situation evolved rapidly over the next few Python releases, so anything included in this article doesn’t necessarily still represent a best practice, upcoming articles may change some of these details.
Let’s start by defining a few terms. As of this release, a coroutine is a new type of object. Their relationship to regular functions is much the same as a generator’s relationship to functions: they look superficially quite similar, but the way you use them is quite different.
A coroutine function is defined with
async def name(...): syntax. Just as a generator function returns a generator object, a coroutine function returns a coroutine object when called.
Within a coroutine function the
await keyword can be used to suspend execution until a particular result is ready. As you might have guessed, there’s a new awaitable protocol which defines which objects can be awaited, and it mostly boils down to that object providing an
__await__() method1. This method should return an iterator, and so every
await is essentially waiting for some
yield down the call chain. So far, so Pythonic.
The part which may be a little less intuitive is that coroutines don’t even start until they’re awaited. This makes more sense if you consider them to be green threads — unlike real threads the operating system isn’t going to schedule them for you, so you need to context switch yourself. You do that by relinquishing control to them — i.e. awaiting them. Or if it’s easier you can think of them as generators, the semantics are quite similar.
Here’s brief snippet to illustrate it’s the order of
await not the order of definition which matters. Don’t worry too much about the stuff to actually execute it at the end, we’ll discuss that later on.
>>> import asyncio >>> >>> async def echo(arg): ... print(arg) ... >>> async def test(): ... first = echo("one") ... second = echo("two") ... await second ... await first ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(test()) two one >>> loop.close()
From this simple example, you can see that coroutines can wait for each other, which transfers execution into the one waited. You can see the similarities with generators here, where
await is very similar to the
yield from construct added in Python 3.3 for generator delegation. This similarity is not a coincidence as coroutines in Python have their origins as a “fork” of generators, and have slowly been evolving more independent syntax. When the awaited coroutine returns a value or raises an exception, control is returned to the awaiting coroutine as with generators yielding a value.
I also wanted to include a coroutines version of the earlier countdown code using callbacks, which you can find below:
You can see that it’s not really much shorter than the callbacks version, but I think the logic is more readable since it’s written as sequential loops. The extra complexity is mostly because
countdown() has to take care of cleanly cancelling any other tasks executing, but unlike the callbacks version this has have the advantage that the coroutines could catch
asyncio.CancelledError to implement some closing logic.
So far, there doesn’t seem to be a lot of flexibility here — this logic is essentially syncronous and could be achieved easily with standard functions. The flexibility starts to come as we realise that
await can’t just be used with other coroutines, it can also be used to wait for futures.
The
asyncio module provides a
Future class for use with corouties which is almost, but not quite, compatible with
concurrent.futures.Future. The main differences are:
wait()or
as_completed()provided by the
concurrent.futurespackage.
As usual, the
Future is just a standard interface for holding an eventual result, which allows the result to be queried (once ready) and allows callbacks to be registered to be called when the future is done. There are also methods
set_result(), to set the result value and mark the future as “done”, and
cancel(), to mark the future as “cancelled”. So, now we have a future that we can
await on within a coroutine.
>>> import asyncio >>> >>> fut = asyncio.Future() >>> fut.done() False >>> fut.cancelled() False >>> fut.result() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/andy/.pyenv/versions/3.5.10/lib/python3.5/asyncio/futures.py", line 288, in result raise InvalidStateError('Result is not ready.') asyncio.futures.InvalidStateError: Result is not ready. >>> fut.set_result("Message for you, sir!") >>> fut.done() True >>> fut.cancelled() False >>> fut.result() 'Message for you, sir!'
Here we can see an example of a coroutine awaiting on a bare
Future. We create an event loop, which is the
asyncio core scheduling object, and we use its
call_later() method to set the result of the
Future after a delay. If you’re trying to replicate this yourself, note that the time starts ticking the moment you execute
call_later(), as you can tell from the timestamps that I printed.
>>> import asyncio >>> import time >>> >>> async def pass_on_result(awaitable): ... return await awaitable ... >>> loop = asyncio.get_event_loop() >>> fut = loop.create_future() >>> print(time.time()); loop.call_later(20, fut.set_result, "my result") 1618217675.213969 <TimerHandle when=1187862.730957315 Future.set_result('my result')> >>> loop.run_until_complete(pass_on_result(fut)); print(time.time()) 'my result' 1618217695.219507
A few notes here. Firstly, the use of
create_future() on the loop is the preferred way to create futures, as this allows an event loop to provide an alternative implementation if appropriate. Secondly, the use of the
call_later() method of the event loop here to set a
Future result is very similar to the approach
asyncio.sleep() uses to delay for a specified interval. Thirdly, the reason why the
when parameter of the
TimerHandle is different to the time I’m printing is because I’m using
time.time() to get epoch time, whereas
asyncio.BaseEventLoop uses
time.monotonic() which has no relationship with actual time of day.
Since the only requirement here is that the parameter to
pass_on_result() is awaitable, then it doesn’t have to be a
Future. It can be another coroutine, as demonstrated by nesting the calls to the coroutine in the snippet below. The innermost call to
pass_on_result() is waiting on the
Future, but the other two are waiting on the nested coroutines.
>>> fut = loop.create_future() >>> loop.call_later(20, fut.set_result, "my other result") <TimerHandle when=1499600.826035453 Future.set_result('my other result')> >>> loop.run_until_complete(pass_on_result(pass_on_result(pass_on_result(fut)))) 'my other result'
We can also have multiple coroutines waiting on the same future, and they’ll all be woken up once it’s ready — although of course because these are coroutines rather than real threads they’ll actually get run sequentially. The example below uses
asyncio.gather() to run two coroutines on the same future. This function waits on multiple awaitables on parallel, and also automatically wraps bare coroutines in tasks — we’ll discuss tasks in a moment. The return is a list of all the results thus obtained.
>>> fut = loop.create_future() >>> loop.call_later(20, fut.set_result, "yet another result") <TimerHandle when=1499632.721701156 Future.set_result('yet another result')> >>> loop.run_until_complete(asyncio.gather(pass_on_result(fut), pass_on_result(fut))) ['yet another result', 'yet another result']
If you prefer a lower level of access, you can also register one or more callback functions directly with a
Future, which will be invoked when it becomes completed, either with a result, an error or a cancellation. One important detail, however, is that this callback is not invoked immediately that the result is set — with
asyncio.Future the callback is instead scheduled with the event loop.
The code below illustrates this — take a read through to see if you can figure out what’s going on, and I’ll add a few points of interest after it. This code uses the
run_until_complete() method on the event loop, which continually executes the loop until the specified awaitable is done3.
>>> def callback_factory(name): ... def callback(fut): ... try: ... print("Callback " + name + " result:", fut.result()) ... except Exception as exc: ... print("Callback " + name + " no result") ... return callback ... >>> async def delayed_cancel(fut): ... await asyncio.sleep(5) ... fut.cancel() ... print("Coroutine exiting") ... >>> fut1 = loop.create_future() >>> fut2 = loop.create_future() >>> fut1.add_done_callback(callback_factory("one")) >>> fut2.add_done_callback(callback_factory("two")) >>> fut1.set_result("finished fut1") >>> del fut1 >>> loop.run_until_complete(delayed_cancel(fut2)) Callback one result: finished fut1 Coroutine exiting Callback two no result
So the first point to note here is that the callback on
fut1 isn’t invoked as soon as the result is set, it’s invoked later. The second interesting point is that even though we
del fut1, the callback still remains queued and the result can still be recovered — this makes sense, because the queued callback must keep some sort of reference to
fut1 which prevents it from being destroyed until the callback is finished. This is worth remembering because if you have some callback invoked but for some reason you don’t enter the event loop, it’ll remain queued and may pop up unexpectedly later on in a completely unrelated piece of code that enters the loop.
The third note here is that the
fut2 callback is invoked when
fut2 is cancelled, but of course there’s no result to collect so calling
result() yields a
CancelledError exception, which we catch in the callback in this case. The fourth and final interesting point I’ll note here is that the
fut2 callback was invoked at all. Bear in mind the semantics of
run_until_complete() are that as soon as the specified awaitable is done, the event loop returns control to the calling code. Also bear in mind the callbacks are invoked by the event loop, and we can see that because
Coroutine exiting is printed after cancelling
fut2 but before the coroutine is invoked. So once
delayed_cancel() has completed,
run_until_complete() isn’t returning immediately, it’s continuing to invoke pending callbacks before finally returning control.
A final quick note on exceptions before we move on from
asyncio.Future. In real-world code you’ll most likely want to put some error handling into place in your coroutines. If you do this, bear in mind that cancelling a
Future is implemented using exceptions and you might well catch that by mistake, since in Python 3.5 the
CancelledError exception is still a subclass of
Exception2:
>>> async def catch_errors(awaitable): ... try: ... return await awaitable ... except Exception as exc: ... print("We caught " + repr(exc)) ... return None ... >>> fut = loop.create_future() >>> loop.call_later(20, fut.cancel) <TimerHandle when=1189566.356254259 Future.cancel()> >>> loop.run_until_complete(catch_errors(fut)) We caught CancelledError()
This sort of thing is why Pokémon exception handling4 is often discouraged, but personally I think it’s a useful pattern in certain circumstances where you don’t know upfront what the code you’re executing will be doing. It’s a matter of taste. If you do end up using broad exception specifications like this, however, you need to be aware of this issue to make sure you don’t catch things you don’t intend.
So now we’ve got a good understanding of the simple interface of
asyncio.Future, and also we’ve played with coroutines and seen their similarities with generators. The last piece of the puzzle is how these things are all scheduled by the event loop. This is also where we give a callback5 to my earlier promises6 to explain about wrapping coroutines in tasks.
You’ve probably noticed that a coroutine is really just a generator under the hood. The special behaviour that’s layered on top is the way that it’s scheduled as it becomes blocked and unblocked. This is the glue which transfers control between the coroutines which aren’t blocked on other awaitables, and this glue is provided by the task.
To understand this, let’s see what happens with a bare coroutine and no event loop. I’ll use the simple
pass_on_result() definition from earlier:
>>> async def pass_on_result(awaitable): ... return await awaitable ... >>> fut = asyncio.Future() >>> coro = pass_on_result(fut) >>> result = coro.send(None) >>> result._asyncio_future_blocking True >>> result is fut True
We execute the coroutine using the
send() method that was added to generators in Python 2.5. It’s important to note that native coroutines are a distinct concept, however, and don’t implement
__iter__() or
send() is the only way to resume execution within them.
When the coroutine blocks what comes back is the awaitable on which it’s blocked, in this case
fut. You’ll see also the special
_asyncio_future_blocking is set, but don’t worry too much about it — I think it’s mostly used to flag that this class meets the
Future interface, and also to detect some common pitfalls more gracefully. In the Python source code, all of the code paths where it has an unexpected value appear to lead to some exception being thrown.
At this point we have a native coroutine blocked on a future. Let’s give the future a value, and call
send(None) again:
>>> fut.set_result("my result") >>> try: ... coro.send(None) ... except StopIteration as exc: ... print("Got result", exc.value) ... Got result my result
At this point the coroutine is unblocked and completes, which yields
StopIteration just as a generator exiting would. One difference is that the coroutine has an actual return value, as opposed to generators which only
yield values. As it happens, the
value attribute of the
StopException instance is used to hold the return value.
So you can already see that working this by handle is pretty clunky and
asyncio.Task exists to wrap this up into a cleaner interface. What it does is intercept the values emitted by the coroutine and schedule appropriate handlers in an
asyncio event loop to handle them. In the case that the coroutine is blocked on a future, the task adds a callback to that future so that it can reschedule the coroutine when the future is done. In the case that the coroutine does a bare
yield, which is effectively yielding to other coroutines whilst remaining runnable, then it uses the
call_soon() method on the event loop to reschedule itself to be invoked agaim immediately once anything else currently pending has been processed.
I won’t go into every detail of its handling, as it has a lot of tricky logic to handle lots of edge cases, such as futures being cancelled or coroutines raising exceptions. One other point to note about
Task is that it’s a subclass of
Future, so a coroutine wrapped in a task can be treated like any other
Future instance.
OK, so we know how to use coroutines now, and the way that control reverts back to the event loop when we
await on things. That does leave a rather big question, however — what happens when we perform a blocking operation that doesn’t have support for coroutines? Since we’re cooperatively multitasking, this would prevent all other coroutines and callbacks from being invoked.
The simple answer to this is, of course, “so don’t do that, then”. However, Python’s use of special methods (i.e.
__xxx__()) can make it easy to do this without being aware of it. Fortunately Python 3.5 also includes some additional changes to support various specific cases where this might happen.
One fairly obvious such case is with context managers, which often do things like opening files or acquiring locks which can block. Fortunately this release introduces some new syntax to make context managers coroutine-friendly.
You may well already know this, but the context manager protocol involves calling an
__enter__() method at the start of the
with block and an
__exit__() method when the block is exited, either through normal flow or via an exception. We can’t mess around with these methods because it would be likely to break all sorts of existing code. But what we can do is add some new methods.
The two new methods are
__aenter__() and
__aexit__(), which are directly analagous to their non-asynchronous counterparts. There’s also a new syntax
async with ... which calls into these versions instead of the original pair. The fact that there are two new methods means that existing context managers can support both use-cases simultaneously, which avoids having to declare a whole set of parallel async versions of all the context managers that already exist (but they do need changes to add the new methods, of course).
These methods are expected to return an awaitable object to do the actual work. This allows the event loop to keep running until the context manager is ready, and again if the exit method also needs to block.
The new syntax can be considered equivalent to the code below.
# This new syntax: async with context_manager as ctx: ... # ... is essentially equivalent to this: ctx = await context_manager.__aenter__() try: ... except Exception as exc: if not await context_manager.__aexit__(type(exc), exc, exc.__traceback__): raise exc else: await context_manager.__aexit__(None, None, None)
Iterators are another obvious case where you can end up calling arbitrary code behind the scenes, so it’s not surprising that there’s also new syntax for them.
There’s a new syntax
async for ... which causes the new methods
__aiter__() and
__anext__() to used instead of the traditional
__iter__() and
__next__() respectively. The
__aiter__() method returns an async interator which supports an
__anext__() method, and this is expected to return an awaitable in the same way as in the context manager case. Instead of
StopIteration there’s also a new
StopAsyncIteration exception for termination.
Once again, there are some simple code equivalencies for
async for expressed below.
# This new syntax: async for item in async_iterable: # Body of loop goes here await my_function(item) # ... is essentially equivalent to this: iterator = async_iterable.__aiter__() while True: try: item = await iterator.__anext__() except StopAsyncIteration: break # Body of loop goes here await my_function(item)
One point that’s worth mentioning here is that with regular iterators, the
next() method is a convenient shorthand for caling the
__next__() method of the iterator. It’s hopefully clear from the explanation above that this won’t work with asynchronous iterators. Furthermore, there’s no equivalent
anext() method, you just have to call it yourself. Not a big deal, just an asymmetry to be aware of.
Also I should mention that implementing asynchronous iterators gets a bit easier in Python 3.6 due to the implementation of asynchronous generators — but you’re going to have to wait for a future article to talk about those.
Coroutines can be confusing at first to a lot of programmers. To those who’ve only ever written code that executes sequentially in a single thread, the notion of continually deferring execution back to some central loop is can seem odd, and to keep code readable it requires them to modularise code in ways that may not be natural at first. To those who’ve done a lot of multithreaded code, the lack of mutexes and other synchronisation primitives may seem unnecessarily dangerous, as they’ve been bitten by having to painfully debug those concurrency issues that you only ever seem to find under heavy load in production. Indeed, if you try to use multithreaded primitives into asynchronous code you’re more likely to introduce issues like deadlocks due to the coorperative nature of the multitasking.
However, once you become comfortable with asynchronous programming, I feel it can have a lot of advantages in encouraging well-structured modular code, and avoiding many of the risks inherent with true concurrency, as well as the overheads of OS-aware threads. Of course, it can also be layed on top of threads and/or processes for really optimum performance under significantly IO-bound activities.
There are definitely some pitfalls to keep in mind, which could take some getting used to. When you’re doing multithreaded coding, one of the main challenges is being aware of which libraries and functions are thread-safe (i.e. can be safely called from multiple threads concurrently). In a similar way, those using coroutines need to be aware if libraries they’re using are async-aware. For example, it’s not uncommon to perform I/O operations in the
__init__() method of a class, but that’s going to be a problem if someone uses that class in a coroutine. The best bet is to get into the habit of not doing any potentially blocking operations in
__init__() and instead make better use of context managers — this is going to be a pain to retrofit into some older code, however.
Hopefully this article has given you a good flavour of coroutines and how they work in Python. If you’re looking for a slower-paced and more detailed overview of
asyncio in general, check out the excellent import asyncio series of videos by Łukasz Langa from the EdgeDB team. It may start a little slowly for some, but I’d recommend at least checking out the fourth video which goes into the details of coroutines, including some great discussion of the generator heritage of coroutines in Python.
That’s it for this article, next time I’ll be going through another of the significant changes in Python 3.5, type hinting. Plus, if you like coroutines then do check back for when I’ve got the articles on Python 3.6-3.8 posted, as things have still got some way left to evolve on the coroutines front.
I say mostly because there are a few other cases where objects are awaitable without providing
__await__(). One example is a generator which has been decorated with
types.coroutine(). ↩
This is suboptimal for similar reasons why you don’t generally want to catch
StopIteration, and thankfully this was resolved in Python 3.8 by making
CancelledError a
BaseException subclass. ↩
As an aside, this is another case where a bare coroutine passed is automatically wrapped in a task, a topic of which I’ll frustratingly once again defer discussion. ↩
D’you see what I did there? ↩
D’you see what I did there? ↩
This is the 8th of the 15 articles that currently make up the “Python 2to3” series.
|
https://www.andy-pearce.com/blog/posts/2021/Apr/python-2to3-whats-new-in-35-part-1-coroutines/
|
CC-MAIN-2021-49
|
refinedweb
| 4,618
| 61.77
|
[download].
Whilst not completely oblivious to the problem you are seeking to address, I think there are (at least) two problems with what you are proposing:
And none of the existing layers would 'go away' in the process. Backward compatibility, not to mention vested interests, mean that all the existing layers will need to stay in place. No one is going to give up their 'meta.yml' file or equivalent.
In the end, you will have just added to the burden.
As an example of what I mean. this is a 'simple' .vcproj file. Don't just glance at the size of it, take a few moments to peruse the elements it contains, whilst bearing in mind the question -- what does this contribute to the actual building of the application?
In my assessment, about 80% to 90% of the content of that file is only there to support the metadata of the metafile format itself. Think about that a moment. Take this tiny snippet:
<xs:sequence>
<xs:element
<xs:complexType>
<xs:attribute name="Name" type="xs:string" use="require
+d" />
<!-- NOTE: all other attributes are properties of that
+particular tool object. -->
<!-- any unrecognized attribute will be ignored.
+-->
<xs:anyAttribute
</xs:complexType>
</xs:element>
</xs:sequence>
[download]
What does that actually mean? Anyone? What does it actually contribute to the build maintenance of the project? (My conclusion is: Nada!)
I recently downloaded a VC project that contains 11 source files. I don't use the MSVC IDE, and so I wanted to work out how to build them from the command line and delved into the 400+ line .vcproj file. I got completely lost. So then I tried to build it from the command line, and it came down to:
cl /MT *.c
[download]
That was all that was required. It built the entire thing right through to the executable, which then ran perfectly. Sure, I added a few extra options when I wrote a makefile, but still I ended up with a 10 line makefile.
What do those 400+ lines buy me?
This kind of thing always reminds me of watching a Michelin starred chef prepare a menu on TV. They stand there screaming orders at a dozen sous chefs, all running around performing gastronomic feats of valour. Eventually, a plate of food is delivered to the pass; the top man wipes away an imagined fingerprint and declares it fit for consumption, to a huge round of applause.
Meanwhile, my wife has cooked and served a fine meal for four, washing up as she went, whilst also watching and commenting on what the great man was doing: "Did you notice? He didn't taste a damn thing!"
When the process becomes more important than the product, seriously, it is time to re-evaluate your priorities.
The start of some sanity?
I've heard it said, and believe it to be true, that the accuracy of meta data decreases with the distance between the storage of the data and meta data.
For example if I edit a file, I type its name (or a part thereof, followed by the tab key) in the command line, and I am basically forced to notice a divergence between file name and the purpose of a file, should such a divergence occur. But if the purpose of a file was written down in a meta data file, I simply wouldn't notice unless I explicitly cared to remember updating the meta data.
That's why I find that storing meta data in storing so many different places (file names, comments and code in the file, plus some extra in Build.PL/Makefile.PL) isn't actually such a bad idea. It might be a bad idea for the author of a tool that needs the meta data, but for the author or maintainer of the distribution I believe it's the only viable way. After I all I want to program, not spend much time keeping my meta data in sync.
(I also believe that this is the deeper reason for the hatred that many windows users and developers feel towards the "registry", a huge central place for meta data that is in many ways too disconnected from the data it describes).
That said, I don't believe we have found the optimal sweep spot for meta data yet. Dist::Zilla and similar tools are an exploration in the opposite direction to what you propose: they try to derive meta data (for example dependencies) from the code as much as possible, allowing the author to focus even more on the code itself. I've never quite followed that path, though I'm not sure why. Maybe because it feels like giving up control. (Yes, dzil is flexible to let you decide which parameters you want to control yourself, and which it derives itself. But it requires learning about yet another complex system, and somehow I haven't yet felt the need to do so).
Given a single, consistent project metadata store, I begin a project by writing some of that metadata first.
I know this is just a use case, but it does sound pretty much like a top down approach. My projects usually work quite differently: They start as some throwaway .pl file, and if I happen to run it more often I copy it to ~/bin/, and if I expand it and think it might become beneficial to others, I start to extract most subroutines into a module and then CPANize it. That's also the reason why I don't care too much for Module::Starter and the like: they assume I start from scratch, but I don't. Adding the boilerplate usually seems like less work then starting with the boilerplate and adding my code to it.
I don't know what the summary of my somehow disconnected ramblings is; maybe it is that I find the idea intriguing, but that I don't think it will work for me. I have the feeling that it will violate the motto "don't repeat yourself"; the proposed meta data scheme seems to encourage repeating information that is already there in some way.
I agree absolutely that the accuracy of metadata decreases with distance from its subject. I'll go further: The usefulness of metadata decreases with distance from its subject. That's why I favor one file : one metafile. It's the least practical distance. I think of each metafile as the flip side of the subject file. You have a document, you edit the document; you want to make notes about the document, you flip it over and scribble there. I am opposed to the fat bloated trapdoor spider sucking goo from everywhere approach.
Synchronization is exactly my issue. moritz doesn't want to keep metadata in sync but that's exactly what we're doing manually when we copy from one place to another, with or without some format translation. My projects tend to fall apart as little pockets of metadata desynchonize. When I do release, then later I find getting back into an old project a staggering task. I simply can't remember all the informal relationships and unwritten rules.
Developers generally seem to dislike writing tests and documentation. Some will feel that writing yet more metadata only increases the burden of not-code. But my object is to streamline all of the not-code tasks as well as some of the coding by providing a means of interchange.
Multiple points of entry and exit mean that you are not required or expected to master yet another language and grand interface. Rather, the benefit comes incrementally. You continue to work as you always have. Perhaps you pull a feature branch from a contributor. You now have the opportunity to accept updates to your project's README, POD, and test suite. You can dismiss the offers or accept them and go straight to the updatated elements and re-tailor them. Of course if your contributor is using PMM then he may already have accepted these offers and delivered a complete, all files patch instead of a vague bug report. Which means less work for you.
If your projects don't have a single boilerplate start then you won't want that kind of tool. You may be more interested in a tool that tracks metadata as it accumulates and assists you later on when you want to throw on another Jenga block.
You may not want any of this. Picasso could paint with a toothbrush. I need more structure.
Does everyone really agree that it's "wise to use no hard tabs in code"? There are quite a few comments at the bottom of that page favouring tabs. See also Why tabs are clearly superior and Why I love having tabs in source code.
I use tabs. I'd compare tabs versus spaces to semantic HTML versus presentational HTML. By using tabs, you can view my source in a text editor with tab stops set to two spaces, four spaces, eight spaces or whatever, and it still looks sensible - I don't enforce my favourite indentation level on you.
Anyway, enough of that, that's not the main point of your post...
Project metadata: what I've been doing lately is to have a directory called meta inside the root directory of the project. This contains zero or more RDF files with project metadata - changelogs, credits, links to the bug tracker, repository, etc.
This can be all in one file, or split up arbitrarily - they are all combined into one in-memory model when they're processed. Currently I tend to use one file for a changelog, one for general project metadata, and a third one for keeping track of dependencies.
My Makefile.PL then assembles this into META.yml and Changes files, figures out the project's licence and creates a LICENSE file too. It does all that at the author side when making a distribution - thus the libraries for metadata management don't need to be installed at the end user's side.
The code for doing all this is on CPAN (of course):
Here's an example of a project that uses it: repo and distributed code on CPAN. Notice the size of Makefile.PL? 42 bytes. No metadata there - it's all in the meta directory.
update: here's another (bigger) project using the same metadata system.
# This file provides instructions for packaging.
@prefix : <> .
<
+>
:perl_version_from _:main ;
:version_from _:main ;
:readme_from _:main ;
:test_requires "Test::More 0.61", "File::Basename", "File::Spec",
+"Data::Dumper" ;
:requires "parent", "version 0.77".
_:main <
+ame> "lib/all/your/base/are/belong/to.pm" .
[download]
Except that Makefile.PL is an executable file, and if you want the data it contains, you need to run it. Run it and hope that it doesn't hose your system.
Module::Package (which I use) is just a wrapper for Module::Install - which itself is mostly a wrapper for ExtUtils::MakeMaker.
Perhaps one of the existing formats can be extended to cover the use case?
DOAP is a vocabulary for describing a software project using RDF.
No XML here.
I floated some vague Perl testing metadata ideas in Perl CPAN test metadata --
though it didn't generate sufficient interest
to provoke me into pursuing it further.
Defining "standard" names for metadata seems helpful yet
requires collaboration and cooperation from others.
It's annoying when different folks use different
names for essentially the same metadata.
You might have a go at proposing a standard naming
scheme and standard names for the project metadata
you find useful.
That's an interesting node.++
I like it
You should check out these : Config::Model, config-edit#-ui, CPAN::Meta::Spec, CPAN::Meta::History,
I think your idea fits in the /CPAN::Meta::/ namespace, but I also think it needs a Config::Model model
You should compare your ideas to the evolution of the cpan META spec :) I don't have enough knowledge of each to even start a comparison :)
I like the Config::Model idea because, if your app needs a config file, you simply create a model, and you get a config editor for free, both CLI and GUI, and a config file in any of ini/shell/perl/yaml....
And Dublin Core is an RDF vocabulary, which brings us back to 950556.
Thanks, deMize; that kind of concrete suggestion really helps. In fact Dublin Core may be the subject of this Meditation and I don't yet
|
http://www.perlmonks.org/index.pl?node_id=950529
|
CC-MAIN-2015-48
|
refinedweb
| 2,092
| 71.44
|
Python Effector - Step Effector Spline imitate
On 19/02/2013 at 13:39, xxxxxxxx wrote:
Hi,
Could any one help me with getting the spline data, from a user data on a python effector, to control the strength the effector has on the clones, similar to the spline in the Step Effector.
Im trying to make use of util.RangeMap to map the data back into the clones but can't seem to crack it. Any help would be great.
Cheers
On 20/02/2013 at 10:47, xxxxxxxx wrote:
there are some examples in python sdk examples which implement effector like behaviours.
you'll have to provide some code, so that we can actually help you. the basic approach
would be.
1. get the MoData
2. get the relevant matrix lists in the MoData
3. get matrix of you effector object
4. update/calculate the updated matrix for each particle with the effector matrix, your SplineData
and the the existing MoData matrix for the particle.
5. write the data back.
On 20/02/2013 at 15:46, xxxxxxxx wrote:
I have been through the python pluginin examples and have not found a spline gui implicated example? Maybe I missed something?
As a sarting poing I would just like to be able to control the effect on clones that the regular python effector has, this is the initial code:
import c4d from c4d.modules import mograph as mo #Welcome to the world of Python def main() : md = mo.GeGetMoData(op) if md==None: return 1.0 index = md.GetCurrentIndex() mode = md.GetBlendID() if mode==c4d.ID_MG_BASEEFFECTOR_POSITION: return c4d.Vector(0.5) else: return 1.0
I would just like a user data of a spline gui to effect the strength on the clones. Like the Step Effector does. Any help?
On 20/02/2013 at 16:17, xxxxxxxx wrote:
posting the python effector default code is not your own code. you also need to set
the python effector tu full control if you want to drive the particle matrices.
create a python effector, set it to full controll, add a vector userdata and a spline
userdata (in the exact order, the code expects the vector to be the first component)
and paste the code into the node. it is a rather simple example which uses the particle
index to aply an offset vector which is being throttled by the spline (which again is
being mapped along the indices).
import c4d from c4d.modules import mograph as mo from c4d import utils as u def main() : vec = op[c4d.ID_USERDATA,1] spldata = op[c4d.ID_USERDATA,2] md = mo.GeGetMoData(op) if md == None: return False cnt = md.GetCount() marr = md.GetArray(c4d.MODATA_MATRIX) fall = md.GetFalloffs() for i in reversed(xrange(0, cnt)) : splinf = u.RangeMap(value = i, mininput = 0, maxinput = cnt, minoutput = 0, maxoutput = 1.0, clampval = False, curve = spldata) marr[i].off = marr[i].off+fall[i] + (i * vec * splinf) # o md.SetArray(c4d.MODATA_MATRIX, marr, True) return True
On 21/02/2013 at 09:51, xxxxxxxx wrote:
Thank you for your help, much appreciated, it cleared up a few sticking points I had. I know you said that it was only a simple example but its having some unexpected functionality in that the spline.y data (0-1y) seems to effect the clones as normal, but not the spline.x points. So for example having a sin wave spline in the gui of 'spldata' wouldn't be reflected in the clones. I presume it has something to do with the way the clones are indexed and the data being passed back to them?
On 21/02/2013 at 10:20, xxxxxxxx wrote:
the matrix is driven by the index and the spline. to only have the spline influence your
offset vector remove the index as a factor. my example mapped both, the indices and
the spline, which will return a kind of non linear result.
marr _.off = marr _.off+fall _\+ (vec \* splinf)___
note that the input vector will be used in an absolute manner that way, not in a stepped
fashion, like the example above.
|
https://plugincafe.maxon.net/topic/6956/7832_python-effector--step-effector-spline-imitate
|
CC-MAIN-2020-40
|
refinedweb
| 691
| 67.04
|
7.6. Estimating a probability distribution nonparametrically with a kernel density previous recipe, we applied a parametric estimation method. We had a statistical model (the exponential distribution) describing our data, and we estimated a single parameter (the rate of the distribution). Nonparametric estimation deals with statistical models that do not belong to a known family of distributions. The parameter space is then infinite-dimensional instead of finite-dimensional (that is, we estimate functions rather than numbers).
Here, we use a kernel density estimation (KDE) to estimate the density of probability of a spatial distribution. We look at the geographical locations of tropical cyclones from 1848 to 2013, based on data provided by the NOAA, the US' National Oceanic and Atmospheric Administration.
Getting ready
You need cartopy, available at. You can install it with
conda install -c conda-forge cartopy.
How to do it...
1. Let's import the usual packages. The kernel density estimation with a Gaussian kernel is implemented in
scipy.stats:
import numpy as np import pandas as pd import scipy.stats as st import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import cartopy.crs as ccrs %matplotlib inline
2. Let's open the data with pandas:
# df = pd.read_csv('' 'cookbook-2nd-data/blob/master/' 'Allstorms.ibtracs_wmo.v03r05.csv?' 'raw=true')
3. The dataset contains information about most storms since 1848. A single storm may appear multiple times across several consecutive days.
df[df.columns[[0, 1, 3, 8, 9]]].head()
4. We use pandas'
groupby() function to obtain the average location of every storm:
dfs = df.groupby('Serial_Num') pos = dfs[['Latitude', 'Longitude']].mean() x = pos.Longitude.values y = pos.Latitude.values pos.head()
5. We display the storms on a map with cartopy. This toolkit allows us to easily project the geographical coordinates on the map.
# We use a simple equirectangular projection, # also called Plate Carree. geo = ccrs.Geodetic() crs = ccrs.PlateCarree() # We create the map plot. ax = plt.axes(projection=crs) # We display the world map picture. ax.stock_img() # We display the storm locations. ax.scatter(x, y, color='r', s=.5, alpha=.25, transform=geo)
6. Before performing the kernel density estimation, we transform the storms' positions from the geodetic coordinate system (longitude and latitude) into the map's coordinate system, called plate carrée.
h = crs.transform_points(geo, x, y)[:, :2].T h.shape
(2, 6940)
7. Now, we perform the kernel density estimation on our
(2, N) array.
kde = st.gaussian_kde(h)
8. The
gaussian_kde() routine returned a Python function. To see the results on a map, we need to evaluate this function on a 2D grid spanning the entire map. We create this grid with
meshgrid(), and we pass the
x and
y values to the
kde() function:
k = 100 # Coordinates of the four corners of the map. x0, x1, y0, y1 = ax.get_extent() # We create the grid. tx, ty = np.meshgrid(np.linspace(x0, x1, 2 * k), np.linspace(y0, y1, k)) # We reshape the grid for the kde() function. mesh = np.vstack((tx.ravel(), ty.ravel())) # We evaluate the kde() function on the grid. v = kde(mesh).reshape((k, 2 * k))
9. Before displaying the KDE heatmap on the map, we need to use a special colormap with a transparent channel. This will allow us to superimpose the heatmap on the stock image:
# []() cmap = plt.get_cmap('Reds') my_cmap = cmap(np.arange(cmap.N)) my_cmap[:, -1] = np.linspace(0, 1, cmap.N) my_cmap = ListedColormap(my_cmap)
10. Finally, we display the estimated density with
imshow():
ax = plt.axes(projection=crs) ax.stock_img() ax.imshow(v, origin='lower', extent=[x0, x1, y0, y1], interpolation='bilinear', cmap=my_cmap)
How it works...
The kernel density estimator of a set of n points \(\{x_i\}\) is given as:
Here, \(h>0\) is a scaling parameter (the bandwidth) and \(K(u)\) is the kernel, a symmetric function that integrates to 1. This estimator is to be compared with a classical histogram, where the kernel would be a top-hat function (a rectangle function taking its values in \(\{0,1\}\)), but the blocks would be located on a regular grid instead of the data points. For more information on kernel density estimator, refer to.
Multiple kernels can be chosen. Here, we chose a Gaussian kernel, so that the KDE is the superposition of Gaussian functions centered on all the data points. It is an estimation of the density.
The choice of the bandwidth is not trivial; there is a tradeoff between a too low value (small bias, high variance: overfitting) and a too high value (high bias, small variance: underfitting). We will return to this important concept of bias-variance tradeoff in the next chapter. For more information on the bias-variance tradeoff, refer to.
There are several methods to automatically choose a sensible bandwidth. SciPy uses a rule of thumb called Scott's Rule:
h = n**(-1. / (d + 4)). You will find more information at.
The following figure illustrates the KDE. The sample dataset contains four points in \([0,1]\) (black lines). The estimated density is a smooth curve, represented here with different bandwidth values.
There are other implementations of KDE in statsmodels and scikit-learn. You can find more information here:
See also
- Fitting a probability distribution to data with the maximum likelihood method
|
https://ipython-books.github.io/76-estimating-a-probability-distribution-nonparametrically-with-a-kernel-density-estimation/
|
CC-MAIN-2019-09
|
refinedweb
| 878
| 52.15
|
When
QLabel widgets. These widgets have the size Vertical Policy set to Preferred which automatically resizes the widgets down to fit the available space. The results are unreadable.
Problem of Too Many Widgets.png
Settings the Vertical Policy to Fixed keeps the widgets at their natural size, making them readable again.
Problem of Too Many Widgets With Fixed Heights
However, while we can still add as many labels as we like, eventually they start to fall off the bottom of the layout.
To solve this problem GUI applications can make use of scrolling regions to allow the user to move around within the bounds of the application window while keeping widgets at their usual size. By doing this an almost unlimited amount of data or widgets can be shown, navigated and viewed within a window — although care should be taken to make sure the result is still usable!
In this tutorial, we'll cover adding a scrolling region to your PyQt6 application using
QScrollArea.
Adding a QScrollArea in Qt Designer
First we'll look at how to add a
QScrollArea from Qt Designer.
Qt Creator — Select MainWindow for widget type
So we will choose the scroll area widget and add it to our layout as below.
First, create an empty
MainWindow in Qt Designer and save it as
mainwindow.ui
Add Scroll Area
Next choose to lay out the
QScrollArea vertically or horizontally, so that it scales with the window.
Lay Out The Scroll Area Vertically Or Horizontally
Voila, we now have a completed scroll area that we can populate with anything we need.
The Scroll Area Is Created
Inserting Widgets
We will now add labels to that scroll area. Lets take two labels and place it inside the
QScrollArea. We will then proceed to right click inside the scroll area and select Lay Out Vertically so our labels will be stacked vertically.
Add Labels to The Scroll Area And Set the Layout
We've set the background to blue so the illustration of this this works is clear. We can now add more labels to the
QScrollArea and see what happens. By default, the Vertical Policy of the label is set to Preferred which means that the label size is adjusted according to the constraints of widgets above and below.
Next, we'll add a bunch of widgets.
Adding More Labels to QScrollArea
Any widget can be added into a `QScrollArea` although some make more sense than others. For example, it's a great way to show multiple widgets containing data in a expansive dashboard, but less appropriate for control widgets — scrolling around to control an application can get frustrating.
Note that the scroll functionality has not been triggered, and no scrollbar has appeared on the right hand side. Instead the labels are still progressively getting smaller in height to accommodate the widgets.
However, if we set Vertical Policy to Fixed and set the minimumSize of height to 100px the labels will no longer be able to shrink vertically into the available space. As the layout overflows this will now trigger the
QScrollArea to display a scrollbar.
Setting Fixed Heights for Labels
With that, our scrollbar appears on the right hand side. What has happened is that the scroll area only appears when necessary. Without a fixed height constraint on the widget, Qt assumes the most logical way to handle the many widgets is to resize them. But by imposing size constraints on our widgets, the scroll bar appears to allow all widgets to keep their fixed sizes.
Another important thing to note is the properties of the scroll area. Instead of adjusting fixed heights, we can keep it in
Preferred , we can set the properties of the
verticalScrollBar to
ScrollBarAlwaysOn which will enable the scroll bar to appear sooner as below
ScrollArea Properties
Saving and running the code at the start of this tutorial gives us this scroll area app which is what we wanted.
App With Scroll Bar
Adding a QScrollArea from code
As with all widgets you can also add a
QScrollArea directly from code. Below we repeat the above example, with a flexible scroll area for a given number of widgets, using code.
from PyQt6.QtWidgets import (QWidget, QSlider, QLineEdit, QLabel, QPushButton, QScrollArea,QApplication, QHBoxLayout, QVBoxLayout, QMainWindow) from PyQt6.QtCore import Qt, QSize from PyQt6 import QtWidgets, uic import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.initUI()) self.widget.setLayout(self.vbox) ) self.setCentralWidget(self.scroll) self.setGeometry(600, 100, 1000, 900) self.setWindowTitle('Scroll Area Demonstration') self.show() return def main(): app = QtWidgets.QApplication(sys.argv) main = MainWindow() sys.exit(app.exec_()) if __name__ == '__main__': main()
If you run the above code you should see the output below, with a custom widget repeated multiple times down the window, and navigable using the scrollbar on the right.
Scroll Area App
Next, we'll step through the code to explain how this view is constructed.
First we create our layout hierarchy. At the top level we have our
QMainWindow which we can set the
QScrollArea onto using
.setCentralWidget. This places the
QScrollArea in the window, taking up the entire area.
To add content to the
QScrollArea we need to add a widget using
.setWidget, in this case we are adding a custom
QWidget onto which we have applied a
QVBoxLayout containing multiple sub-widgets.)
This gives us the following hierarchy in the window:
Finally we set up properties on the
QScrollArea, setting the vertical scrollbar Always On and the horizontal Always Off. We allow the widget to be resized, and then add the central placeholder widget to complete the layout.
)
Finally, we will add the
QScrollArea as the central widget for our
QMainWindow and set up the window dimensions, title and show the window.
self.setCentralWidget(self.scroll) self.setGeometry(600, 100, 1000, 900) self.setWindowTitle('Scroll Area Demonstration') self.show()
To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount with the code [[ couponCode ]] — Enjoy!
For [[ activeDiscount.description ]] I'm giving a [[ activeDiscount.discount ]]% discount with the code [[ couponCode ]] — Enjoy!
Conclusion.
In this tutorial we've learned how to add a scrollbar with an unlimited number of widgets, programmatically or using Qt Designer. Adding a
QScrollArea is a good way to include multiple widgets especially on apps that are data intensive and require objects to be displayed as lists.
Have a go at making your own apps with
QScrollArea and share with us what you have made!
For more information about using QScrollArea check out the PyQt6 documentation.
|
https://www.pythonguis.com/tutorials/pyqt6-qscrollarea/
|
CC-MAIN-2022-40
|
refinedweb
| 1,087
| 62.38
|
Introduction
Neural networks are one of the methods for creating artificial intelligence in computers. They are a way of solving problems that are too difficult or complicated to solve using traditional algorithms and programmatic methods. Some believe that neural networks are the future of computers and ultimately, humankind.
In this article, we'll describe how to implement a neural network in C# .NET and train the network using a genetic algorithm. Our networks will battle against each other for the survival of the fittest to solve the mathematical functions AND, OR, and XOR. While these functions may seem trivial, it provides an easy introduction to implementing the neural network with a genetic algorithm. Once the neural networks evolve to solve the easiest of mathematical functions, one could create much more powerful networks.
The Neural Network is a Brain
The neural network is modeled after, what we believe to be, the mechanics of the brain. By connecting neurons together, adding weights to the synapses, and connecting layers of neurons, the neural network simulates the processing behind the brain. Once a neural network is trained, the network itself holds the series of weights and can be considered the solution to a particular problem. By running the neural network with a series of inputs, an ouput is generated which provides the solution.
Supervised Training of a Neural Network is Boring
One of the more common methods for training a neural network is to use supervised training with backpropagation. This consists of creating a set of test cases for training and running the neural network on the training set. The neural network receives inputs from each piece in the training set and calculates the ouput. The difference between the output and desired output is calculated and the neurons weights are adjusted to minimize the difference, thus training the network. This process is repeated multiple times on each test case in the set until an acceptable error threshold is reached. Backpropagation is an acceptable method to train a neural network when you already have a set of test cases. However, if the problem you are trying to solve has too many possible cases or is too complicated to create specific test cases for, then you need an automatic approach to training the network.
Time For Battle with a Genetic Algorithm
According to evolution, the brain of a human being has evolved over millions of years. It took that long to get where we stand today. By implementing a similar algorithm to evolution, we can battle hundreds of neural networks against each other to solve a problem. The most fit of these networks can go on to create even more precise networks, until we have a satisfactory solution to the problem at hand.
The basics behind the genetic algorithm follow that of evolution. We start with a population of neural networks, assigned random weights. We determine a fitness test to run each network against. This allows us to determine how fit a neural network is to solve our problem. The most fit of the population move on to create offspring, with slightly different weights. This process can continue for as many iterations as desired.
Setting up the Neural Network
We'll be using a C# .NET neural network library called NeuronDotNet. For our genetic algorithm, we'll also be using a basic library, available here.
Download complete project source code.
To start our project, simply create a basic Visual Studio Console Application with C# .NET. You'll define your program body as follows:
using System;using System.Text;using NeuronDotNet.Core.Backpropagation;using NeuronDotNet.Core;using btl.generic;
namespace NeuralNetworkTest{ class Program { public static BackpropagationNetwork network;
static void Main(string[] args) { LinearLayer inputLayer = new LinearLayer(2); SigmoidLayer hiddenLayer = new SigmoidLayer(2); SigmoidLayer outputLayer = new SigmoidLayer(1);();
// AND TrainingSet trainingSet = new TrainingSet(2, 1); trainingSet.Add(new TrainingSample(new double[2] { 0, 0 }, new double[1] { 0 })); trainingSet.Add(new TrainingSample(new double[2] { 0, 1 }, new double[1] { 0 })); trainingSet.Add(new TrainingSample(new double[2] { 1, 0 }, new double[1] { 0 })); trainingSet.Add(new TrainingSample(new double[2] { 1, 1 }, new double[1] { 1 })); network.Learn(trainingSet, 5000);
double input1; string strInput1 = ""; while (strInput1 != "q") { Console.Write("Input 1: "); strInput1 = Console.ReadLine().ToString();
if (strInput1 != "q") { input1 = Convert.ToDouble(strInput1); if (input1 != 'q') { Console.Write("Input 2: "); double input2 = Convert.ToDouble(Console.ReadLine().ToString()); double[] output = network.Run(new double[2] { input1, input2 }); Console.WriteLine("Output: " + output[0]); } } } } }}
In the above code, we're using the Neural Network library to create our network. We're actually training the network using backpropagation for starters, but we'll change this to a genetic algorithm on the next step. Notice that we have a variable to represent our brain, called network. We then create 3 layers for our network. It's important to note that to solve the functions AND and OR we actually only need 2 layers (input and output). However, to solve the XOR function, we'll need an additional hidden layer. You can review the mathematics behind this for details, but we'll skip it here.
The C# neural network library then requires us to create connections between the layers. We do this by instantiating the BackpropagationConnector objects for each layer. Once linked, we call Initialize() to assign random values to the weights of the neurons.
We then proceed to create a training set for the function AND and train the network with backpropagation.
The AND function
The AND function is the same as multiplication and performs as follows, when given two binary digits:
AND
0 0 = 00 1 = 01 0 = 01 1 = 1
Our training set contains these four cases and the desired output. When we call the Learn() method on our neural network, the network learns how to arrive at the desired output when given each of the input values for AND. Once complete, our brain can perfectly perform the AND function.
Neural Network Output to AND
Input 1: 0Input 2: 0Output: 0.00598466150747038Input 1: 0Input 2: 1Output: 0.0350348930900449Input 1: 1Input 2: 0Output: 0.0357534100310869Input 1: 1Input 2: 1Output: 0.957545336188107
When running the program as shown above, we provide two binary digits as input and receive an output from the brain. The brain responds with a value from 0 to 1. The closer the value is to 1, the more of a "YES" the value can be considered. The closer the value is to 0, the more of a "NO" the value can be considered. In the above output, you can see how providing 0,0 resulted in the network printing 0.005, which when rounded, is 0. This is the correct answer to 0 AND 0. The same follows for the remaining cases. Most notably, when we provide 1, 1, the network responds with 0.957, which when rounded is 1. This is the correct answer to 1 AND 1.
Backpropagation is Interesting, But Lets Get to the Brain Wars
The backpropagation technique was shown above to let you see that once we create a genetic algorithm to match the brains against each other for survival of the fittest, we'll get the same, if not better, results from the winning neural network. It may seem mysterious how the genetic algorithm actually works, but the key is that the best will survive.
Adding the Code for the Genetic Algorithm
Modify the above code example by removing the training section of code and replacing it as follows:
GA ga = new GA(0.50, 0.01, 100, 2000, 12); ga.FitnessFunction = new GAFunction(fitnessFunction); ga.Elitism = true; ga.Go();
double[] weights; double fitness; ga.GetBest(out weights, out fitness); Console.WriteLine("Best brain had a fitness of " + fitness);
setNetworkWeights(network, weights);
if (strInput1 != "q") { input1 = Convert.ToDouble(strInput1); if (input1 != 'q') { Console.Write("Input 2: "); double input2 = Convert.ToDouble(Console.ReadLine().ToString()); double[] output = network.Run(new double[2] { input1, input2 }); Console.WriteLine("Output: " + output[0]); } } } }
We'll fill in the helper functions, including the fitnessFunction in a moment, but first a few notes on the above code. Notice that we've replaced the neural network training section with a genetic algorithm training method. We instantiate the genetic algorithm with a crossover of 50%, mutation rate of 1%, population size of 100, epoch length of 2,000 iterations, and the number of weights at 12. While the other numbers are variable, the last number is not. This one must match the exact number of weights used in your neural network. Since our network consists of 3 layers (input, hidden, and output) with 2 neurons at the input layer, 2 neurons in the hidden layer, and 1 neuron in the output layer, a fully connected neural network would require 6 connections (also called synapses). We must double this to include bias values. This gives us a total of 12 variable weights for the network. Our genetic algorithm will take care of assigning the weights. Evolution will take care of picking the best network. We just have to worry about the setup.
After our genetic algorithm finishes its evolution epochs, we pick the best result from the final population and assign its weights to a neural network. This gives us the best brain for the AND function. We then run the same test code to try the brain out.
You'll need the following helper functions to implement the genetic algorithm:
public static void setNetworkWeights(BackpropagationNetwork aNetwork, double[] weights) { // Setup the network's weights. int index = 0;
foreach (BackpropagationConnector connector in aNetwork.Connectors) { foreach (BackpropagationSynapse synapse in connector.Synapses) { synapse.Weight = weights[index++]; synapse.SourceNeuron.SetBias(weights[index++]); } } }
public static double fitnessFunction(double[] weights) { double fitness = 0;
// AND double output = network.Run(new double[2] { 0, 0 })[0]; // The closest the output is to zero, the more fit it is. fitness += 1 - output;
output = network.Run(new double[2] { 0, 1 })[0]; // The closest the output is to zero, the more fit it is. fitness += 1 - output;
output = network.Run(new double[2] { 1, 0 })[0]; // The closest the output is to zero, the more fit it is. fitness += 1 - output;
output = network.Run(new double[2] { 1, 1 })[0]; // The closest the output is to one, the more fit it is. fitness += output;
return fitness; }
The first function is simply a helper to populate the weights and bias of a neural network with a series of double values from an array (our genetic algorithms hold an array of double values). The most important function in the genetic algorithm is the Fitness Test.
The Fitness Test is the Hardest Part
The fitness test has always been the hardest part when creating a genetic algorithm. You have to determine a way to judge the fitness of a neural network, based upon its output. Even if a network fails to give the correct output, you have to provide an indication of how "correct" the network was, so that the genetic algorithm can sort the various networks in the population to know which are performing better. Even if all the neural networks in the current population perform horribly, certainly some perform better than others, even if they're all terrible! The hardest part is that we have to determine this automatically. Luckily for our example, we can easily create a fitness test for the AND function.
In the above function fitnessFunction(), we first populate a neural network with weights from the current genetic algorithm. We then run the network 4 times, against each input possibility. We want our output to closely match 1 when the input values are 1 and 1. For everything else, we want the network to output a zero. We can tell this to the fitness function by giving points based upon the output for how close it is to our desired value. For example, if the inputs are 0, 0, we want to see a zero as close as possible. The closer the output is to zero, the higher of a score this network will get. We calculate this by adding 1 - output. So if the output was 0.8 (very close to 1, which is very incorrect since 0 AND 0 = 0), we only give a score of 1 - 0.8, which is only 0.2. On the other hand, if the output is a 0.1, which is very correct, we give a score of 1 - 0.1, which 0.9. We continue this for the other test cases.
Whenever you create a fitness function for a genetic algorithm, remember that the most important part is to provide a fine gradient score. No matter how good or bad a network is, you should be able to give some numeric indication of how far off the network is from success.
With the fitness test in place, we can now run the network and see how it does.
Neural Network Output to AND with a Genetic Algorithm
Generation 0, Best Fitness: 3Generation 100, Best Fitness: 3.47803165619214Generation 200, Best Fitness: 3.99974219528311Generation 300, Best Fitness: 3.99999960179664Generation 400, Best Fitness: 3.99999981699116Generation 500, Best Fitness: 3.99999986294525Generation 600, Best Fitness: 3.99999990917201Generation 700, Best Fitness: 3.99999994729483Generation 800, Best Fitness: 3.9999999621852Generation 900, Best Fitness: 3.99999996309631Generation 1000, Best Fitness: 3.99999997541078Generation 1100, Best Fitness: 3.99999997739028Generation 1200, Best Fitness: 3.99999997740393Generation 1300, Best Fitness: 3.99999997740393Generation 1400, Best Fitness: 3.99999998185631Generation 1500, Best Fitness: 3.99999998214724Generation 1600, Best Fitness: 3.99999998217092Generation 1700, Best Fitness: 3.99999998217092Generation 1800, Best Fitness: 3.99999998410326Generation 1900, Best Fitness: 3.99999998410326Best brain had a fitness of 3.9999999842174Input 1: 0Input 2: 0Output: 0.05820069534838Input 1: 0Input 2: 1Output: 0.06753356769009Input 1: 1Input 2: 0Output: 0.02594788736069Input 1: 1Input 2: 1Output: 0.999999996869079
Notice in the output, our genetic algorithm advances in fitness as the populations evolve. After 2,000 epochs, our best brain had a fitness of 3.99. When we run the network, we get a very correct answer. All ouputs are 0 or less, except for 1 AND 1, which provides an output of 0.99, which when rounded is 1.
Implementing the OR Function
With our core code setup, we can easily implement the OR function by simply changing our fitnessFunction as follows:
// OR double output = network.Run(new double[2] { 0, 0 })[0]; // The closest the output is to zero, the more fit it is. fitness += 1 - output;
output = network.Run(new double[2] { 0, 1 })[0]; // The closest the output is to one, the more fit it is. fitness += output;
output = network.Run(new double[2] { 1, 0 })[0]; // The closest the output is to one, the more fit it is. fitness += output;
Neural Network Output to OR with a Genetic Algorithm
Generation 0, Best Fitness: 2.99999999999995Generation 100, Best Fitness: 3.99600659181652Generation 200, Best Fitness: 3.9991103135676Generation 300, Best Fitness: 3.99996421958631Generation 400, Best Fitness: 3.99999675609333Generation 500, Best Fitness: 3.99999943413239Generation 600, Best Fitness: 3.99999989442878Generation 700, Best Fitness: 3.9999999064053Generation 800, Best Fitness: 3.99999994092478Generation 900, Best Fitness: 3.99999994092478Generation 1000, Best Fitness: 3.99999994092478Generation 1100, Best Fitness: 3.9999999494151Generation 1200, Best Fitness: 3.99999995357012Generation 1300, Best Fitness: 3.99999995357012Generation 1400, Best Fitness: 3.99999995485334Generation 1500, Best Fitness: 3.99999995485334Generation 1600, Best Fitness: 3.99999996197061Generation 1700, Best Fitness: 3.9999999632428Generation 1800, Best Fitness: 3.9999999636009Generation 1900, Best Fitness: 3.9999999636009Best brain had a fitness of 3.99999996499874Input 1: 0Input 2: 0Output: 0.0001883188626Input 1: 0Input 2: 1Output: 0.999999983783592Input 1: 1Input 2: 0Output: 0.999999997192107Input 1: 1Input 2: 1Output: 0.999999997194924
Again, notice after 2,000 epochs, the best neural network can correctly solve the OR function. OR functions as follows:
OR
0 0 = 00 1 = 11 0 = 11 1 = 1
From our output, you can see that when we input 0, 0, the network outputs zero or less. When we provide 0, 1 we receive 0.99, which when rounded equals 1. The same follows for the remaining cases.
Implementing the XOR Function
The XOR function is a little more tricky with the brain. It's not as simple of a function as AND and OR, and actually requires the hidden layer in the neural network. Without that extra neuron, the brain simply can't perform a correct XOR function. Since our network already has a hidden layer with the required neuron, we can implement the XOR function by simply changing our fitnessFunction as follows:
// XOR double output = network.Run(new double[2] { 0, 0 })[0]; // The closest the output is to zero, the more fit it is. fitness += 1 - output;
output = network.Run(new double[2] { 1, 1 })[0]; // The closest the output is to zero, the more fit it is. fitness += 1 - output;
Neural Network Output to XOR with a Genetic Algorithm
Generation 0, Best Fitness: 2.39064761320888Generation 100, Best Fitness: 3.49697448976411Generation 200, Best Fitness: 3.49799189851772Generation 300, Best Fitness: 3.59338089950075Generation 400, Best Fitness: 3.60622027042199Generation 500, Best Fitness: 3.60624715441267Generation 600, Best Fitness: 3.60780488281301Generation 700, Best Fitness: 3.61234442064262Generation 800, Best Fitness: 3.61234442064262Generation 900, Best Fitness: 3.61237915839054Generation 1000, Best Fitness: 3.61237915839054Generation 1100, Best Fitness: 3.61243174970198Generation 1200, Best Fitness: 3.61257107003452Generation 1300, Best Fitness: 3.61268778306298Generation 1400, Best Fitness: 3.61268778306298Generation 1500, Best Fitness: 3.61268778306298Generation 1600, Best Fitness: 3.61268778306298Generation 1700, Best Fitness: 3.61268778306298Generation 1800, Best Fitness: 3.61268825395901Generation 1900, Best Fitness: 3.61268825395901Best brain had a fitness of 3.61268825395901Input 1: 0Input 2: 0Output: 0.00897356605564295Input 1: 0Input 2: 1Output: 0.881275105575929Input 1: 1Input 2: 0Output: 0.942749100068267Input 1: 1Input 2: 1Output: 0.202362385629545
Notice that the outputs to the XOR, while slightly less sure than the previous examples, still provide correct answers. XOR functions as follows
XOR
0 0 = 00 1 = 11 0 = 11 1 = 0
Our trained brain correctly solves this. When provided an input of 0, 1 the brain outputs 0.88. While this isn't as close as 0.99, it's still correct, as when rounded it equals 1. This brain could benefit from more evolution. We only performed 2,000 epochs and the XOR function is more complicated then the previous examples.
After running for 20,000 epochs, we obtain a best fitness of 3.84088, a noticable improvement, and the outputs are as follows:
Generation 19900, Best Fitness: 3.84087575095576Best brain had a fitness of 3.84088136209706Input 1: 0Input 2: 0Output: 0.044799648625185Input 1: 0Input 2: 1Output: 0.961866510073782Input 1: 1Input 2: 0Output: 0.992772678034412Input 1: 1Input 2: 1Output: 0.0689581773859488
Now you can see the brain is outputing a more exact answer of 0.96 when given 0, 1 and 0.99 when given 1, 0.
Conclusion
AND, OR, and XOR are great, but how about something cooler?
We've trained our neural network with a genetic algorithm in C# .NET to perform some basic mathmetical functions. We've seen how the fitness test is the key behind evolving the correct neural network. It was easy to train the AND, OR, and XOR by modifying the fitness function. In fact, to train our neural network to do anything at all, we simply need to modify the fitness function and our genetic algorithm handles the rest. The genetic algorithm will actually evolve anything you want, based on the fitness function. Of course, your neural network has to have enough neurons to support the logic, but you can adjust that as needed. Just keep in mind that the more complex your neural network, the longer you'll need to evolve the networks, and the more CPU power you'll need for processing.
Thinking about creating the next HAL, Data, or Terminator? You just need to devise the correct fitness function with a larger neural network. Of course, while the total capabilities of the neural network aren't fully realized yet, it's certainly possible to push the boundaries of science.
About the Author
This article was written by Kory Becker, founder and chief developer of Primary Objects, a software and web application development company. You can contact Primary Objects regarding your software development needs at
|
http://www.primaryobjects.com/CMS/Article105
|
CC-MAIN-2015-32
|
refinedweb
| 3,335
| 59.9
|
Almost half a million ArrayList<String> words too much?
I put together a ~400,000 word list for my password generating program. It has 3 modes which choose words from this list, and I fear that the program will lag or be slow to load. Do I need to add some extra efficiency lines of code to keep it snappy? Here is what I'm doing so far:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
publicclass WordData{
public List<String> wordList;
{
wordList =new ArrayList<String>();
wordList.add("cat");
wordList.add("dog");
wordList.add("bird");
//blah blah
}
}
I am coding all of the words into a separate class in the program to keep the list of words out of reach of people looking to add to their brute force lists. NetBeans has a macro recorder so I will let it run overnight while it puts each word within proper syntax. Am I overloading the wordList? It having to add each one of the words I specified would take a while, I think. Accessing it from a file makes no difference either. The current text file is about 4MB.
|
http://www.java-index.com/java-technologies-archive/519/new-to-java-5196830.shtm
|
crawl-001
|
refinedweb
| 192
| 75.71
|
Created on 2003-08-27 12:48 by jepler, last changed 2003-08-30 23:52 by rhettinger. This issue is now closed.
Hello.
Recently, Generator Comprehensions were mentioned again
on python-list.
I have written an implementation for the compiler
module. To try it
out, however, you must be able to rebuild Python from
source, because it
also requires a change to Grammar.
1. Edit Python-2.3/Grammar/Grammar and add an
alternative to the
"listmaker" production:
-listmaker: test ( list_for | (',' test)* [','] )
+listmaker: test ( list_for | (',' test)* [','] ) |
'yield' test list_for
1.5. Now [yield None for x in []] parses, but crashes
the written-in-C
compiler:
>>> [yield None for x in []]
SystemError: com_node: unexpected node type
2. Apply the patch below to Lib/compiler
3. Use compiler.compile to compile code with generator
comprehensions:
from compiler import compile
import dis
code = compile("""
def f():
gg = [yield (x,y) for x in range(10) for y
in range(10) if y > x]
print gg, type(gg), list(gg)
""", "<None>", "exec")
exec code
dis.dis(f.func_code.co_consts[1])
f()
4. It's possible to write code so that __import__ uses
compiler.compile
instead of the written-in-C compiler, but I don't have
this code handy.
Also, a test suite is needed, and presumably a
written-in-C implementation
as well. (option 2: make the compiler.compile interface
the standard
compiler, and let the builtin compiler support a Python
subset
sufficient to bootstrap the written-in-python compiler,
or arrange
to ship .pyc of the compiler package and completely get
rid of the
written-in-C compiler)
Logged In: YES
user_id=80475
Since the pep has been rejected, am closing the patch.
But will create a link to it from the PEP (note, the patch stays
on the record even after it is closed).
|
http://bugs.python.org/issue795947
|
crawl-003
|
refinedweb
| 304
| 55.64
|
Amazons since couple years without any problem and now that they are providing a platform with two Tesla M2050s to test my CUDA apps, I just want to say Thank You Amazon. already received the AMI. Therefore, you can skip the set up part. benefiting.
Utilizing GPUs to do general purpose scientific and engineering computing is named GPGPU. You can visit my previous blog posts where I’ve explained how to use NVIDIA CUDA capable GPUs to perform massively parallel computations. an account and are familiar with Amazon EC your account to finish the registration and to go through a phone verification..
My_KeyPair.
GPGPU_SecurityGroup.
In order to connect to the newly created instance:
Go to the CUDA Downloads website to see available downloads. At this time, we will download the 4.1 RC2 version from CUDA Toolkit 4.1 web site. Download and install the following items in the same order::
Now you are ready to compile and run a CUDA sample from the GPU Computing SDK. Please follow these steps: cannot:
#include <time.h>
computeGold(reference, h_A, h_B, uiHA, uiWA, uiWB); );
GPGPU is rising since the last couple years and now that Amazon provides a Windows GPU instance, it is much easier to jump onto the massively parallel software track as a Windows developer..
|
http://www.codeproject.com/script/Articles/View.aspx?aid=314776
|
CC-MAIN-2016-44
|
refinedweb
| 215
| 55.03
|
There.
I assume that you have already a good idea what Prometheus, Grafana and OpenShift are and that you have access to an OpenShift cluster which allows you to download docker images from the internet. The example has been tested with OpenShift 3.7 and might not work with older OpenShift versions.
The first step will be to deploy a simple demo application. It is a SpringBoot application that provides two RESTful services (“/hello-world” and “/metrics”) and already facilitates to be monitored with Prometheus. The demo application provides metrics for the request count of the “hello-world” service as well as Java hotspot metrics. More information how to provide metrics in Java application can be found here. My colleague Dr. Fabian Stäber gave a very good talk, how to provide metrics for a Java application without modifying the source code. An article of the talk can be found here.
The following code snip it shows how the Prometheus metrics are implemented in the Restful services:
@Component @Path("/") public class Metrics { private final Logger logger = LogManager.getLogger(Metrics.class); private final Counter promRequestsTotal = Counter.build() .name("requests_total") .help("Total number of requests.") .register(); { DefaultExports.initialize(); } @GET() @Path("/hello-world") @Produces(MediaType.TEXT_PLAIN) public String sayHello() { promRequestsTotal.inc(); return "hello, world"; } @GET() @Path("/metrics") @Produces(MediaType.TEXT_PLAIN) public StreamingOutput metrics() { logger.info("Starting service for metrics"); return output -> { try (Writer writer = new OutputStreamWriter(output)) { TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples()); } }; } }
The highlighted section of the source code marks initialization of the request counter; the java hotspot metrics. The Restful service “/metrics” returns the metrics of the demo application.
To deploy the demo application we first create a project in OpenShift called “demoapplication” and deploy the demo application in this project. We will do this in the OpenShift command line. To create project demoapplication execute:
oc new-project demoapplication
The deployment of the demo application is done with this command:
oc new-app -f -n demoapplication
If the demo application has been successfully deployed you should be able to open the demo application in a web browser (Hint: you can find the url in the route of the demo application ). You will see two links:
If you can see these links and they show similar results if you click on the links then you have successfully deployed the application.
The source code of the used demo application can be found here
We are going to deploy Prometheus with sidecar containers for OAuth (for the browser and “serviceaccounts”) and for alerts. The drawback with usage of OAuth at the time being is that service accounts (i.e. from Grafana) can’t be authenticated with a token unless the OAuth sidecar service account has the cluster role “system:auth-delegator” assigned to it. Unfortunately, the cluster role “system:auth-delegator” is by default not assigned to the roles like admin or view. Which means that you need to ask the OpenShift Cluster administrators whether they will assign the cluster role to the service account of Prometheus OAuth sidecar. If you are not able to get this role binding then we need to use a workaround. The workaround will bypass the OAuth sidecar for service accounts and will talk directly with Prometheus via the service endpoint. Hence Grafana can query data from Prometheus without authentication. Any other user, group or service account that knows the service endpoint can bypass the authentication as well. For most parts that shouldn’t be a problem, because the Grafana service account should only get read access to the project with Prometheus. Otherwise the deployment of Prometheus is straightforward. First we create a project called “prometheus” with the following command:
oc new-project prometheus
In the next step you either deploy Prometheus with the role “system:auth-delegator” for the service account with the following command:
oc new-app -f -p NAMESPACE=prometheus
or without the role by the command:
oc new-app -f -p NAMESPACE=prometheus
After this you should be able to login to Prometheus with your OpenShift account and see the following screen if you click on “Status->Targets”.
So far we only see that Prometheus is scraping pods and services in the project “prometheus”. No worries, we are going to change that in step 4.
The next step is to install Grafana. For this we first create a new project “grafana” with the command:
oc new-project grafana
Now we are going to deploy Grafana with the command:
oc new-app -f -p NAMESPACE=grafana
Next we need to grant the Grafana service account view access to the project “prometheus” with the following command, so that Grafana can display data from Prometheus:
oc policy add-role-to-user view system:serviceaccount:grafana:grafana-ocp -n prometheus
After this step you need to open Grafana in a browser. Here we need to create a data source for Prometheus. In order to do that, click on “Add data source”. You should see the following screen:
If you installed Prometheus without the role “system:auth-delegator” you need to provide a name for the datasource. We are going to use the name “Promtheus-OCP”. Set the URL to the endpoint IP address of the Prometheus service. This endpoint IP address can be determined with the following command:
oc describe service prometheus -n prometheus
You need to take the highlighted IP-Address:
If you press Add (later called Save & Test) the result should look like this:
### Setup Prometheus datasource with the role “system:auth-delegator”
If you installed Prometheus with the role “system:auth-delegator” you need to provide a name for the datasource. Set the URL to the URL of the prometheus website. You can look it up the with command:
oc get route prometheus -n prometheus
Further more you need to check the check box “Skip TLS Verification (Insecure)” and get the token for the service account grafana-ocp with this command:
oc sa get-token grafana-ocp
If you press save the result should look like this:
At the time being the deployed Prometheus will only search for in the project “prometheus”. We are going to change that so that the service and the pods of the demo application will be scrapped as well. For this we need to adapt the configuration of Prometheus that is stored in the config map prometheus in the file “prometheus.yaml” in the project “prometheus”. Edit the config map either in the browser or with the command line interface. Add the highlighted lines to the config map:
# A scrape configuration for running Prometheus on a Kubernetes cluster. # This uses separate scrape configs for cluster components (i.e. API server, node) # and services to allow each to use different authentication configs. # # Kubernetes labels will be added as Prometheus labels on metrics via the # `labelmap` relabeling action. # Scrape config for API servers. # # Kubernetes exposes API servers as endpoints to the default/kubernetes # service so this uses `endpoints` role and uses relabelling to only keep # the endpoints associated with the default/kubernetes service using the # default named port `https`. This works for single API server deployments as # well as HA API server deployments. scrape_configs: - job_name: 'kubernetes-pods' kubernetes_sd_configs: - role: pod namespaces: names: - prometheus - demoapplication__ - action: labelmap regex: __meta_kubernetes_pod_label_(.+) - source_labels: [__meta_kubernetes_namespace] action: replace target_label: kubernetes_namespace - source_labels: [__meta_kubernetes_pod_name] action: replace target_label: kubernetes_pod_name # Scrape config for service endpoints. # # The relabeling allows the actual service scrape endpoint to be configured # via the following annotations: # # * `prometheus.io/scrape`: Only scrape services that have a value of `true` # * `prometheus.io/scheme`: If the metrics endpoint is secured then you will need # to set this to `https` & most likely set the `tls_config` of the scrape config. # * `prometheus.io/path`: If the metrics path is not `/metrics` override this. # * `prometheus.io/port`: If the metrics are exposed on a different port to the # service then set this appropriately. - job_name: 'kubernetes-service-endpoints' tls_config: ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt insecure_skip_verify: true kubernetes_sd_configs: - role: endpoints namespaces: names: - prometheus - demoapplication relabel_configs: - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape] action: keep regex: true - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scheme] action: replace target_label: __scheme__ regex: (https?) - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_path] action: replace target_label: __metrics_path__ regex: (.+) - source_labels: [__address__, __meta_kubernetes_service_annotation_prometheus_io_port] action: replace target_label: __address__ regex: (.+)(?::\d+);(\d+) replacement: $1:$2 - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_username] action: replace target_label: __basic_auth_username__ regex: (.+) - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_password] action: replace target_label: __basic_auth_password__ regex: (.+) - action: labelmap regex: __meta_kubernetes_service_label_(.+) - source_labels: [__meta_kubernetes_namespace] action: replace target_label: kubernetes_namespace - source_labels: [__meta_kubernetes_service_name] action: replace target_label: kubernetes_name
A detailed description how applications in OpenShift/Kubernets can be discovered and then scrapped in Prometheus can be found here:
Kubernetes scrap configuration
The description of the “relabel_configs” can be found here: relabel_configs
Now that we have added the project “demoapplication” in two places in the config map, we need to grant the prometheus service account access to the project “demoapplication”. We do this with the command:
oc policy add-role-to-user view system:serviceaccount:prometheus:prometheus -n demoapplication
So we updated the Prometheus configuration. Now we need to reload the configuration in Prometheus so that it is able to find the pods and services in the added project. For our test setup we could just kill the Prometheus pod with the command:
oc delete pod prometheus-0 --grace-period=0 --force
For a production environment it is not a good idea just to kill Prometheus in order to reload the configuration, because you interrupt the monitoring. There is an alternative way, for this you need to submit an empty POST to Prometheus URL with the suffix “-/reload”. The problem here is that with our OpenShift you can’t just submit a POST directly to the Prometheus server, because of the OAuth authentication. Luckily we are able to execute the command within the prometheus pod itself with the following OpenShift CLI command
oc exec prometheus-0 -c prometheus -- curl -X POST
After executing this command and some time you should see on the “Status->Targets” the pods and the services of the demo application. In case you don’t see the services as “Up” you might need to hit refresh a couple of times in the browser.
It should look like this:
The scrap configuration used in this article requires annotations in the services and pods so that metrics can be scraped from them (opt-in). This is done with these three lines in scrap configuration for each job:
- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape] action: keep regex: true
If you want to scrap all pods respectivly services unless the specifed otherwise in the service or pod (out-out) you need to modify the configuration to this:
- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape] action: drop regex: false
For our example we use the opt-in configuration. In case your are wondering, the template of the “demoapplication” already contains the setting for scrapping the pods and the service. For the pod’s the configuration looks like this:
... template: metadata: annotations: openshift.io/generated-by: OpenShiftNewApp prometheus.io/path: /metrics prometheus.io/port: "8080" prometheus.io/scrape: "true" labels: app: ${APP_NAME} deploymentconfig: ${APP_NAME} spec: containers: - image: olafmeyer/${APP_NAME} imagePullPolicy: IfNotPresent name: ${APP_NAME} resources: {} ...
The configurations for the service look like this:
... - apiVersion: v1 kind: Service metadata: annotations: prometheus.io/scrape: "true" prometheus.io/scheme: http prometheus.io/port: "8080" # prometheus.io/path: /metrics labels: app: ${APP_NAME} name: ${APP_NAME} ...
With these configurations the pods and services are not only enabled for scrapping, furthermore the port, path and the scheme (http/https) for the metrics can be overwritten. In our case the used port of the demo application is 8080 instead of the default port 80.
The only part that is missing is to display the collected metrics of the demo application in Grafana. Like in every cooking show on TV, I have already prepared something. In our scenario you just need to import a dashboard to see some metrics. For this, you need first to download this (Grafana dashboard template)[] file. In order to use the template, select in the browser with the Grafana the Grafana-Logo (upper left)->Dashboards->Import.
In the next screen upload the Grafana dashboard template file. The following screen should look like this:
Here you define the name of the Grafana dashboard and the data source. Please select the data source that you have defined above for Prometheus. After this click the button “Import” and you should see something like this:
In order to get some metrics you call the service “hello-world” of the demo application a couple of times either in the browser or by executing the following command:
for i in {0..1000}; do curl -s.<your server name>/hello-world; done
Congratulation! You have now installed Prometheus and Grafana on your OpenShift cluster. Furthermore, you have installed a demo application and gathered metrics of it.
This article showed you how to deploy Prometheus and Grafana on an OpenShift Cluster without admin permissions. Also it described how to configure Prometheus to collect metrics of an application in a different project. Lastly it showed how to display these metrics in Grafana. This article is only the starting point on the monitoring of applications in OpenShift with Prometheus. The next steps could be to attach persistent volumes to Prometheus and Grafana to store the configuration and other data, extend the monitoring, add alerts, define an archiving of metrics, clustering of Prometheus and so.
The templates that are used to deploy Prometheus and Grafana are based on templates of these websites:
* OpenShift Origin Prometheus template
* Grafana on OpenShift by Eldad Marciano
|
https://labs.consol.de/de/development/2018/01/19/openshift_application_monitoring.html
|
CC-MAIN-2021-04
|
refinedweb
| 2,230
| 53.31
|
33123/machine-learning-and-python-code
So, I recently started with Machine Learning and coding in Python. I've been trying to figure out the partition method used in the Amazon fine food review data from kaggle and its code. What i also can't understand, is the purpose of the last 3 lines of code.
%matplotlib inline
import sqlite3
import pandas as pd
import numpy as np
import nltk
import string
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import confusion_matrix
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
from nltk.stem.porter import PorterStemmer
# using the SQLite Table to read data.
con = sqlite3.connect('./amazon-fine-food-reviews/database.sqlite')
#filtering only positive and negative reviews i.e.
# not taking into consideration those reviews with Score=3
filtered_data = pd.read_sql_query("""
FROM Reviews
WHERE Score != 3
""", con)
# Give reviews with Score>3 a positive rating, and reviews with a
score<3 a negative rating.
def partition(x):
if x < 3:
return 'negative'
return 'positive'
#changing reviews with score less than 3 to be positive vice-versa
actualScore = filtered_data['Score']
positiveNegative = actualScore.map(partition)
filtered_data['Score'] = positiveNegative
Any help would be greatly appreciated. Thanks.
Machine learning is the latest technology everyone ...READ MORE
Hello,
Both are a good programming language you ...READ MORE
The major difference is size includes NaN ...READ MORE
We can do data import using multiple ...READ MORE
No, the time to train the random ...READ MORE
suppose you have a string with a ...READ MORE
if you google it you can find. ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
You can use the markdown cell to do this. ...READ MORE
You seem to be having an empty ...READ MORE
OR
|
https://www.edureka.co/community/33123/machine-learning-and-python-code
|
CC-MAIN-2019-39
|
refinedweb
| 313
| 53.37
|
fredrikj.net / blog /
Additional results
August 26, 2016
The preprint Short addition sequences for theta functions (arXiv:1608.06810) by Andreas Enge, Bill Hart and myself is now available. We prove some nice new theorems about integer sequences of a very simple kind, namely successive values of quadratic polynomials such as the ordinary squares ($f(k) = k^2$). The purpose is actually to use the structure present in these sequences to speed up numerical evaluation of classical modular forms and functions such as the Dedekind eta function $\eta(\tau)$ and the j-invariant $j(\tau)$. The latest versions of Arb and CM implement the methods in the paper, resulting in a 4x speedup in practice over the classical method for evaluating these functions.
The eta function
Consider the series expansion of the eta function: $$\eta(\tau) = q^{1/24} \sum_{k=-\infty}^{\infty} (-1)^k q^{k(3k-1)/2} = q^{1/24} \left[ 1 - q - q^2 + q^5 + q^7 - q^{12} - q^{15} + \ldots \right]$$ The exponents $0, 1, 2, 5, 7, 12, 15, 22, 26, 35, 40, \ldots$ are the generalized pentagonal numbers, of Euler fame. Our goal is to compute the occurring powers of $q$ using as few complex multiplications as possible ($q = e^{2\pi i \tau}$ is a given complex number). Equivalently, we want to generate the occurring exponents using as few additions as possible: if $c = a + b$, then we get $q^c$ by computing $q^a \cdot q^b$. With different terminology, we want to find a short addition sequence that includes all the generalized pentagonal numbers as a subsequence. This is a variation of the well-known problem of finding a short addition chain to compute a single power $q^k$, but instead of considering a single exponent, we consider a sequence of exponents together.
The classical solution for the eta series is to introduce auxiliary sequences of finite differences: $$ 5 - 1 = 4, \quad 12 - 5 = 7, \quad 22 - 12 = 10, \ldots$$ $$ 7 - 2 = 5, \quad 15 - 7 = 8, \quad 26 - 15 = 11, \ldots$$ Since these sequences can be generated using one addition per term (they have a constant step size 3), we need two additions per term to construct the generalized pentagonal number sequence. In other words, we need $2N$ multiplications to compute the first $N$ terms of the eta function's $q$-series. However, inspection shows that some of the generalized pentagonal numbers can be written as the sum of two smaller generalized pentagonal numbers without relying on the auxiliary sequences. For example, $2 = 1 + 1, 7 = 2 + 5, 12 = 5 + 7, 22 = 7 + 15$. This doesn't work for all entries, but if it works for most entries, and if the remaining entries can be computed quickly enough, then asymptotically we should be able to get away with just $N + o(N)$ multiplications. We show that this, essentially, is the case:
Theorem: Assuming a standard conjecture about primes (Bateman-Horn), almost all generalized pentagonal numbers $c$ can be written as $c = a+b$ where $a,b$ are smaller generalized pentagonal numbers; the probability that no such representation exists is heuristically $O(1/\log c)$.
Theorem: Every generalized pentagonal number $c \ge 2$ can be written as $c = 2a+b$ where $a, b$ are smaller generalized pentagonal numbers.
In other words, we can compute each new term $q^c$ in the eta function's $q$-series as $q^c = (q^a)^2 \cdot q^b$, where $q^a$ and $q^b$ are previously computed terms. Moreover, if we use this only as a fallback and try $q^c = q^a \cdot q^b$ first, then (assuming Bateman-Horn) computing the first $N$ terms takes only $N + O(N / \log N)$ multiplications, compared to $2N$ with the classical method using finite differences.
You can easily check that solutions of $c=2a+b$ exist for the first few $c$. Here is some Python code and the output for $c < 1000$:
from itertools import takewhile def pentagonal(): a = 0; b = 1; c = 2; d = 4 while 1: yield a; a += c; c += 3 yield b; b += d; d += 3 # naive code; the search can easily be done much faster def solutions(c): return [(a,b) for a in takewhile(lambda a: a < c, pentagonal()) for b in takewhile(lambda b: b < c, pentagonal()) if 2*a + b == c] for c in takewhile(lambda c: c < 1000, pentagonal()): print c, solutions(c)
0 [] 1 [] 2 [(1, 0)] 5 [(2, 1)] 7 [(1, 5)] 12 [(5, 2)] 15 [(5, 5), (7, 1)] 22 [(5, 12)] 26 [(2, 22), (7, 12), (12, 2)] 35 [(15, 5)] 40 [(7, 26)] 51 [(22, 7)] 57 [(26, 5)] 70 [(15, 40), (22, 26), (35, 0)] 77 [(35, 7)] 92 [(26, 40), (35, 22), (40, 12)] 100 [(15, 70)] 117 [(51, 15)] 126 [(57, 12)] 145 [(70, 5)] 155 [(5, 145), (70, 15), (77, 1)] 176 [(77, 22)] 187 [(35, 117)] 210 [(70, 70), (92, 26)] 222 [(100, 22)] 247 [(51, 145)] 260 [(117, 26)] 287 [(126, 35)] 301 [(7, 287), (57, 187), (92, 117)] 330 [(35, 260), (77, 176), (145, 40)] 345 [(22, 301), (100, 145), (155, 35)] 376 [(77, 222), (100, 176), (187, 2)] 392 [(176, 40)] 425 [(40, 345), (187, 51), (210, 5)] 442 [(210, 22)] 477 [(26, 425), (145, 187), (210, 57)] 495 [(35, 425), (222, 51), (247, 1)] 532 [(70, 392), (155, 222), (260, 12)] 551 [(247, 57)] 590 [(260, 70)] 610 [(117, 376)] 651 [(287, 77)] 672 [(70, 532), (301, 70), (330, 12)] 715 [(145, 425)] 737 [(330, 77)] 782 [(345, 92)] 805 [(77, 651), (155, 495), (330, 145)] 852 [(35, 782), (376, 100), (425, 2)] 876 [(12, 852), (392, 92), (425, 26)] 925 [(187, 551)] 950 [(287, 376), (345, 260), (425, 100)]
It's a bit surprising that this always works. Many $c$ have just a single solution; there is no asymptotic trend to suggest that the first few cases are anything but coincidences. Meanwhile, some $c$ do have many solutions, so there is no obvious bijection at work either. We discovered the result empirically: while tracing some code that tried several different term combinations for constructing addition sequences, we noticed that the $2a+b$ branch alone worked for the first several thousand $c$. Proving the conjecture then took a bit of work (the proof uses mostly basic algebraic number theory, but it's not trivial).
The same for theta
We also prove similar results relevant for the computation of Jacobi theta functions. Here we are mainly interested in the so-called theta constants which are given by the three series $$\sum_{k=1}^{\infty} q^{k^2}, \quad \sum_{k=1}^{\infty} (-1)^k q^{k^2}, \quad \sum_{k=1}^{\infty} (-1)^k q^{k(k+1)}.$$ These theta series are not the most general possible, but they are sufficient for computation of $\operatorname{SL}_2(\mathbb{Z})$ modular forms and functions, and for special values of elliptic functions. The exponents $k^2 = 1,4,9,\ldots$ are of course the squares, and we call $k(k+1) = 2,6,12,\ldots$ the trigonal numbers (these are twice the more well-known triangular numbers).
Just like with the pentagonal numbers, the classical algorithm to evaluate any one of the theta series uses the differences between successive exponents. This requires $2N$ multiplications for $N$ terms. We prove (again subject to Bateman-Horn) that $N + O(N / \log N)$ multiplications suffice. Our counterparts of the "$2a+b$" theorem for pentagonal numbers are the following:
Theorem: Every trigonal number $c \ge 6$ is the sum of at most three smaller ones.
Theorem: Every almost-square $c \ge 24$ is the sum of at most three smaller almost-squares (an almost-square is an integer $c = k^2 - 1$).
In practice, the three theta series are usually needed together, so it's useful to consider the quarter-squares $1, 2, 4, 6, 9, 12, 16, \ldots$ formed by interleaving squares and trigonal numbers. We show the following:
Theorem: Every quarter-square $c > 1$ is the sum of a smaller one and twice a smaller one.
We can do a little better yet if we interleave the exponents $k(k+1)$ with $(2k+1)^2-1$ and $(2k)^2$, where we have split the squares into the odd and even terms and peeled off one factor $q$ from the powers of $q$ with an odd exponent so that all exponents are even. The interleaved sequence $2, 4, 6, 8, 12, 16, 20, 24, 30, 36, \ldots$ can be written in closed form as $2 \lfloor k^2 / 8 \rfloor$. We show the following:
Theorem: Every element $c \ge 4$ in the sequence $2 \lfloor k^2 / 8 \rfloor$ is the sum of two smaller ones.
The last theorem shows that we can compute all three theta series to $N$ terms each using $2N$ multiplications altogether, in contrast to the $4N$ multiplications required with the classical finite difference method. Note that this complexity result does not depend on any conjectures.
Baby steps
There is one more trick before we get to the end of the paper. We clearly need at least $N$ multiplications to compute $N$ distinct powers of $q$, but we might get away with fewer multiplications to compute a sum of powers if we can avoid computing every single power explicitly.
The idea of the baby-step giant-step algorithm for polynomial evaluation, also called rectangular splitting, is to write $$ \begin{align*} \sum_{k=0}^T c_k q^k & = [c_0 + c_1 q + \ldots + c_{m-1} q^{m-1}] \\ & + [c_m + c_{m+1} q + \ldots + c_{2m-1} q^{m-1}] q^m \\ & + [c_{2m} + c_{2m+1} q + \ldots + c_{3m-1} q^{m-1}] q^{2m} \\ & \vdots \\ \end{align*} $$ for some tuning parameter $m$. The coefficients $c_k$ are assumed to be cheap to multiply with, in our case $c_k \in \{-1,0,+1\}$. We need about $m + T / m$ complex multiplications with this scheme: $m$ to precompute the powers $q^2, q^3, \ldots q^{m-1}$ which allows evaluating all the polynomials inside brackets quickly, and $T / m$ complex multiplications to evaluate the outer polynomial in $q^m$. In the dense case, that is when most $c_k \ne 0$, it is optimal to take $m \approx T^{1/2}$, giving $2 T^{1/2}$ total complex multiplications. The truncated eta and theta series are very sparse, however: we have only $N \sim T^{1/2}$ nonzero $c_k$ for $k \le T$, and it turns out that this choice of $m$ gives no improvement over the classical approach of computing all powers explicitly.
In the sparse case, we can do better by choosing $m$ in such a way that only a subset of $q^2, q^3, \ldots, q^{m-1}$ appear with a nonzero coefficient in the inner polynomials. This means that we want to find parameters $m$ such that the squares, trigonal numbers or generalized pentagonal numbers respectively take few distinct values modulo $m$. For example, if $s(m)$ is the number of distinct square residues modulo $m$, we need about $s(m) + N^2 / m$ complex multiplications to evaluate $\sum_{k=1}^N q^{k^2}$ rather than $m + N^2 / m$. It now makes sense to look for $m$ such that $s(m) / m$ is small. The list of optimal $m$ values for the sequence of squares is OEIS A085635, also listed in Table 4 in the paper. For example, $s(3600) = 176$, so if we pick $m = 3600$, only $176 / 3600 \approx 5\%$ of the powers $q^2, q^3, \ldots, q^{m-1}$ need to be computed.
In the paper, we determine how to choose $m$ nearly optimally for an arbitrary quadratic exponent sequence $F(k) = Ak^2 + Bk + C \in \mathbb{Q}[k]$, giving squares, trigonal numbers and pentagonal numbers as a special case, and we show that $\sum_{k=1}^N q^{F(k)}$ can be computed using only $O(N / \log N)$ multiplications by this approach. Actually, the asymptotic complexity is slightly better than this: it is $N^{1 - c / \log \log N}$ for a certain constant $c > 0$, and this is better than $O(N / \log^r N)$ for any $r > 0$.
The conclusion
To summarize, we have gone from $2N$ (the classical method) to $N + o(N)$ (short addition sequences) to $O(N / \log N)$ (baby-step giant-step) multiplications for summing the first $N$ terms in the $q$-series of the Dedekind eta function or the Jacobi theta function constants.Asymptotically, arithmetic-geometric mean (AGM) iteration is better than evaluation of the $q$-series, as it only costs $O(\log N)$ multiplications. However, the AGM method has a large implied big-O constant, so the $q$-series are usually faster in practice, particularly when optimized.
The end of the paper presents some benchmark results. Here is a copy of the final table, which shows the time in seconds to compute one value of the Dedekind eta function to varying levels of precision:
Both CM-0.3 and Arb use the new baby-step giant-step algorithm, and have nearly identical timings. The old CM-0.2.1 uses a short addition sequence to evaluate the $q$-series using approximately one multiplication per term. Pari/GP uses the classical method. In practice, about a factor two is saved both when going from Pari/GP to CM-0.2.1. and from CM-0.2.1 to CM-0.3.
An implementation of the AGM method is also timed for comparison. Note that the crossover for the AGM method is less than $10^4$ with the unoptimized $q$-series evaluation in Pari/GP but close to $10^7$ bits with the optimized $q$-series evaluation in the latest CM and Arb.
In other settings, baby-step giant-step techniques can easily save a factor 100. The reason why the improvement is not so dramatic here is that the $q$-series are so sparse that it takes very little work to evaluate them even with naive methods. There just isn't much work left to remove by being clever! Nonetheless, in applications where we need tens of thousands of function values, saving a small factor can make a difference.
This paper generated a few interesting "new" integer sequences. We should probably submit them to OEIS...
|
http://fredrikj.net/blog/2016/08/additional-results/
|
CC-MAIN-2017-13
|
refinedweb
| 2,393
| 51.01
|
Category:Wren-gmp
This is an example of a library. You may see a list of other libraries used on Rosetta Code at Category:Solutions by Library.
Wren-gmp is a module which brings the speed and power of the GNU Multiple Precision Arithmetic Library ('GMP') to the Wren programming language. It consists of three classes: Mpz, Mpq and Mpf which operate on arbitrary precision signed integers, rational numbers and floating-point numbers respectively.
Some methods in the Mpf class require the GNU MPFR library ('MPFR') to work as they not supported by GMP itself.
It is the twenty-ninth Wren source code (in the talk page) to a text file called gmp.wren and place this in the same directory as the importing script so the Wren-gmp Comparable class can even be imported via Wren-gmp itself.
Currently, Wren-cli does not support plug-ins though this or similar functionality is likely to be added in a future version (it's already present in DOME). Consequently, scripts using the Wren-gmp module must be run under the control of a special executable whose source code (wren-gmp.c) is also included (in the talk page). This executable translates Wren method calls to calls to the corresponding GMP/MPFR functions and can be built with a command line such as the following using GCC under Linux:
$ gcc -O3 wren-gmp.c -o wren-gmp -lmpfr -lgmp -lwren -lm
If you then want to run a script called myscript.wren you would type at the command-line:
$ ./wren-gmp myscript.wren
myscript.wren should include a line such as the following to import the classes you want to use in that particular script:
import "./gmp" for Mpz, Mpq, Mpf
The same executable can be used to run any other Wren-gmp scripts unless they require additional functionality not available in Wren itself in which case the C code will need to be suitably modified and recompiled.
GMP is dual licensed under GNU LGPL v3 and GNU GPL v2, and MPFR is licensed under the former. Full details can be found on their websites' home pages linked to above.
Pages in category "Wren-gmp"
The following 20 pages are in this category, out of 20 total.
|
http://rosettacode.org/wiki/Category:Wren-gmp
|
CC-MAIN-2022-27
|
refinedweb
| 375
| 68.7
|
I tend to think that pie charts should be avoided in 99% of the cases that they are used in. Unless your goal is to mislead (which is sometimes the case!), or you have a strict use case for them, you can normally find a better way to communicate your point.
That being said, just because we won’t do something, doesn’t mean we don’t need to know how it is done. As such, this article is going to take us through a simple example of creating a pie chart in Matplotlib.
As ever, let’s get our modules and data ready to go.
import pandas as pd import matplotlib.pyplot as plt %matplotlib inline
Our pie chart is going to display the share of Premier League wins, as shown in our data below:
leagueWins = {'Team':['Manchester United','Blackburn Rovers','Arsenal', 'Chelsea','Manchester City','Leicester City'], 'Championships':[13,1,3,4,2,1]} df = pd.DataFrame(leagueWins, columns=['Team','Championships']) df
So we want the pie chart to plot the numbers in our Championships column. ‘plt.pie()’ will do exactly that:
plt.pie(df['Championships']) #This next line just makes the plot look a little cleaner in this notebook plt.tight_layout()
So we have a pie chart! It doesn’t tell us a great deal without labels, except that there is a big blue lump that takes up over half of the pie.
As with all of its other plot types, Matplotlib gives good customisation options. Let’s use some of these to add a title, labels and colours in our arguments:
#Create a list of the colours used for the teams, in order. teamColours=['#f40206','#0560b5','#ce0000','#1125ff','#28cdff','#091ebc'] plt.pie(df['Championships'], #Data labels are the team names in the dataFrame labels = df['Team'], #Assign our colours list colors = teamColours, #Give a tidier angle to ur first data angle startangle = 90 ) #Add a title plt.title("Premier League Titles") plt.tight_layout()
Summary
I strongly recommend not using pie charts, we just struggle to process circular space in comparison to bar charts or even a table – especially when the numbers are relatively simple.
However, just in case it is ever needed, we have seen in this article how easy it is to create a pie chart in Matplotlib with the ‘.pie()’ command. It is also clear that we need to make use of Matplotlib’s customisation features to tidy things up, add a bit of relevant colour and titles. Passing these as arguments into the earlier command makes this easy.
Next up, read up on some different (better!) visualisation types!
|
https://fcpython.com/tag/pie-chart
|
CC-MAIN-2018-51
|
refinedweb
| 434
| 70.23
|
We.
We have just published an article on how to use the
Navigator and
Tabbar React components. Please take a look here after reading this article.
Onsen UI 1.x was built on top of Angular. The Angular dependency made it hard for us to develop React components for Onsen UI 1.x since Angular and React don’t play well together, not to mention that the developer would be forced to load two libraries just to be able to use the components. With Onsen UI 2.0 this is not an issue anymore since the core library has been reimplemented in pure JavaScript as Web Components.
The demos in this article are available here. In case you missed it we released automatic styling in the latest beta. The demos use the latest development version so they will be automatically styled based on the platform. To see it in action you can open DevTools in Chrome and change to an Android device. If you reload the page the components will automatically switch to Material Design.
Kitchen-sink example
The following example shows the React extension for Onsen UI in action. It showcases some of the components as well as the automatic styling. Please try changing the platform on the first screen to see how it renders on both iOS and Android.
The code for the example is available on my GitHub page.
React
React is a JavaScript library that is used to create reusable components. It is reactive in the sense that the components will update when the data changes. These updates are done in a smart way so that React only renders the elements it needs to. Unlike Angular it is not a full-fledged frontend framework but instead only provides APIs to create components. This gives the developer a lot of freedom in choosing the rest of the technologies used in an app.
Since React is easy to use with other technologies there is a large ecosystem of libraries and tools. You can get routing using the React router library and state management with Redux.
Creating a component with React is very simple. When using ES6 every component can be defined as a class. In the following example I create a simple component that keeps tracks of how many times the user has clicked a button.
The full code is available on my GitHub page.
import React from 'react'; import ReactDOM from 'react-dom'; class MyComponent extends React.Component { constructor(props) { super(props); this.state = { clicks: 0 }; } handleClick() { this.setState({ clicks: this.state.clicks + 1 }); } render() { return ( <div> <p> <button onClick={this.handleClick.bind(this)}>Click me!</button> </p> <p> You have clicked {this.state.clicks} times! </p> </div> ); } } ReactDOM.render(<MyComponent />, document.getElementById('app'));
The code is pretty self-explanatory. When the component is first created the
constructor method is run to set the initial state. We set the click counter to 0 in the constructor. The component is rendered using the
render method which will be run every time the state is updated using the
setState method.
The code
<button onClick={this.handleClick.bind(this)}>Click me!</button>
will cause the
handleClick method to be called every time the button is clicked. Inside
handleClick the state is updated by increasing the click counter which will trigger the
render method to run again.
See the component in action below:
To learn more about React, please refer to the documentation.
Not just a wrapper
The React extension for Onsen UI 2.0 is not just a simple wrapper. The Web Components in Onsen UI 2.0 are created using the Custom Elements API. We use this API to create new HTML tags and give them functionality. The behavior of the elements is controlled by setting the HTML attributes and calling methods attached to the elements.
Of course we could create React components that just wrap these elements and expose these methods. However, we don’t believe this is a good idea since a lot of the methods don’t fit into the philosophy of React. We want to make the APIs that the extension provides to make as much sense as possible for React developers.
We would love to know what you think about these components. You can try them out and play with them by cloning this repository. If you think the interface is lacking or if you find some bugs, please let us know in our forum or in the comments below.
This is a list of some of the components that have already been implemented:
DialogModal dialogs
PopoverA popover element
FabThe Floating action button from Material Design
InputInput elements such as text inputs, checkboxes and radio buttons
NavigatorStack based navigation
PullHookA “pull to refresh” component
SwitchDraggable toggle switch
TabbarTab based navigation
- And many more…
Using the extension
Using the Onsen UI components in React is very simple. The
react-onsenui library is released on NPM and it exports all the components so they can be used easily in browserify or webpack or even loaded directly in the browser.
The currently released version of the core Onsen UI library does not support these bindings yet so in order to try them out, please install the experimental version by putting the following in the
devDepencies of your
package.json:
"onsenui": "git://github.com/OnsenUI/OnsenUI-dist.git#2.0.0-react.4"
We will release a new version on NPM soon that is compatible with the React extension.
To use the components all you need to do is load the library and use them in your JSX.
import React from 'react'; import Ons from 'react-onsenui'; import onsen from 'onsenui'; class MyPage extends React.Component { handleClick() { onsen.notification.alert('You clicked the button!'); } render() { return ( <Ons.Page> <Ons.Toolbar> <div className="center">Title</div> </Ons.Toolbar> <Ons.Button onClick={this.handleClick}>Click me!</Ons.Button> </Ons.Page> ); } }
These components are still in alpha stage, so don’t be alarmed if something breaks. If you find any issues or have any ideas on how to improve them, please open an issue on GitHub.
Conclusion
We hope you are as excited as we are about the React extension. We would like to get your feedback on the interface. Please share your thoughts in the comments or on the forum.
In a few days we will release an article on how to use the navigation components in React. We have changed the APIs for the
Navigator and
Tabbar components to make more sense for React developers. If you are an Angular 2 developer we are happy to say that we are developing components for Angular 2 as well. We will preview them as well in the coming weeks. Stay tuned!
If you like Onsen UI please leave us a star on our GitHub page.
|
https://onsen.io/blog/react-onsen-ui-preview/
|
CC-MAIN-2018-47
|
refinedweb
| 1,134
| 65.73
|
I couldn’t find anything related to this and the closest post was this:
From the wiki: SDL_GetWindowSurface - SDL Wiki
You may not combine this with 3D or the rendering API on this window.
But it seems to work with X11 and also with a software renderer on wayland,
kmsdrm and X11.
Tested on the git version. Using sway for wayland and X11 (XWayland), dwm for
X11 and linux 5.18.10 for kmsdrm. And if it matters I’m using intel integrated
graphics.
$ sdl2-config --version 2.23.1
Here’s a simple example that causes this problem.
#include <assert.h> #include "SDL.h" int main(void) { int err = SDL_Init(SDL_INIT_VIDEO); assert(err >= 0); SDL_Window *w = SDL_CreateWindow("bug?", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0); assert(w != NULL); SDL_Renderer *r = SDL_CreateRenderer(w, -1, 0 /* | SDL_RENDERER_SOFTWARE */ ); assert(r != NULL); SDL_Surface *s = SDL_GetWindowSurface(w); if (s == NULL) { SDL_Log("%s\n", SDL_GetError()); } SDL_DestroyRenderer(r); SDL_DestroyWindow(w); SDL_Quit(); return 0; }
On wayland and kmsdrm it outputs:
INFO: No hardware accelerated renderers available
and on X11 it works without errors.
When SDL_RENDERER_SOFTWARE is uncommented it seems to work fine.
|
https://discourse.libsdl.org/t/sdl-getwindowsurface-works-with-renderer-on-x11/37782
|
CC-MAIN-2022-33
|
refinedweb
| 183
| 51.34
|
OpenGL Discussion and Help Forums
>
OpenGL Developers Forum
>
OpenGL under Windows
> Error of "GL_HISTOGRAM was not declared"
PDA
View Full Version :
Error of "GL_HISTOGRAM was not declared"
JCheng
05-03-2010, 03:22 AM
My program came with error of "GL_HISTOGRAM was not declared", but I did include <gl.h> at its header. Is it correct? Tks.
Stephen A
05-03-2010, 04:20 AM
You need to include <glext.h>, too. The latest version is always available here:
JCheng
05-03-2010, 08:49 AM
Hi, Stephen A,
Thanks. But, after I added, the same error still existed. Any other recommended? Tks.
For your reference, below is the headers that I used:
================================================== =============
#include "gl/math3d.cpp"
#include "gl/glut.h"
#include "gl/torus.c"
#include "gl/vectormath.c"
#include "gl/glext.h"
#include "gl/gltools.cpp"
#include <stdio.h>
#include <stdlib.
================================================== =============
Powered by vBulletin® Version 4.2.3 Copyright © 2018 vBulletin Solutions, Inc. All rights reserved.
|
https://www.opengl.org/discussion_boards/archive/index.php/t-170871.html?s=850dd9b2a9a5466583fc0bc0b3a637b0
|
CC-MAIN-2018-05
|
refinedweb
| 157
| 72.53
|
Windows 8: Go mobile with Windows 8
Many of the improvements made to Windows 8 are designed to streamline and help you manage mobile connectivity.
Billy Anders
People want the same level of mobility on their PCs as they get on their smartphones. It’s unlikely that they just want to connect to the Internet. They want to surf, socialize and explore. They want their PCs connected and ready to use whenever and wherever they are.
The fundamentals of wireless connectivity in the reengineered Windows 8 go beyond incremental improvements. This is a good example of technology that requires new hardware to work in concert with new software to realize its full potential. For true mobility, Wi-Fi alone won’t be enough. Therefore, there’s fully developed and integrated Mobile Broadband (MB) within Windows 8. That connectivity exists right alongside Wi-Fi.
Windows 7 had MB, but there were often a number of hurdles to overcome before connecting. You needed the requisite MB hardware (such as an MB dongle or embedded module and SIM) and data plan. You also needed to locate and install third-party device drivers—and in some cases software—before getting your first connection.
If your device drivers and mobile software weren’t available locally, you usually had to find another connection type (most likely Wi-Fi) to the Internet to find them. This was a sizable hurdle to connecting with MB, right when you most needed that connection.
To eliminate the guesswork in locating and installing device drivers for MB, the Windows 8 design team worked with mobile operator and MB hardware partners across the industry. The team designed a hardware specification that device makers can incorporate into their device hardware. Windows 8 has an in-box MB-class driver that works with all devices and eliminates the need for additional device driver software. Just plug in the device and connect. The driver stays up-to-date via Windows Update, ensuring a reliable MB experience.
The USB Implementers Forum (USB-IF) recently approved the Mobile Broadband Interface Model (MBIM) specification as a standard. Major device makers have already begun adopting this standard into their device designs, including some devices designed for other OSes.
Mobile management
MB devices typically come with radio and connection management software. Device manufacturers, PC manufacturers and mobile operators all develop, distribute and support these applications for connecting to their networks, turning radios on and off, configuring connection settings, and getting contact information for help and support.
Prior to Windows 8, you needed these applications to provide functionality not native to Windows. This additional software often conflicted with the Windows Connection Manager, showing different networks, network status and a separate interface. Windows 8 eliminates this confusion by providing simple, intuitive and fully integrated radio and connection management.
New Windows 8 network settings let you turn individual radios on and off (Wi-Fi, MB or Bluetooth), as well as disable all radios at once with the new “airplane mode.” Windows 8 also gives you native radio management to eliminate conflicts and confusion. It provides a consistent experience for controlling your radios without installing additional software. This is new for PCs, although it has obviously long been available on today’s mobile phones.
The new wireless network settings in Windows 8 let you see and connect to all available MB and Wi-Fi networks from one convenient interface. This interface is consistent, so you don’t have to worry about to which network you want to connect. Windows 8 does this by starting with the correct default behaviors. Then it gets smarter by learning your network preferences over time.
One of those default behaviors is to prioritize Wi-Fi networks over broadband whenever one of your preferred Wi-Fi networks is available. Wi-Fi networks are typically faster with lower latency and higher data caps (if they aren’t free). When you connect to a Wi-Fi network, you automatically disconnect from your MB network. When appropriate, Windows 8 also powers down the MB device, which increases battery life. If there’s no preferred Wi-Fi network available, you’re automatically reconnected to your preferred MB network.
To ensure you connect to the correct network when there are multiple networks available, Windows 8 maintains an ordered list of your preferred networks based on your explicit connect and disconnect actions, as well as the network type. For example, if you manually disconnect from a network, Windows 8 will no longer automatically connect to that network. If you decide to disconnect from one network and connect to another, Windows 8 will move the new network higher in your preferred networks list. Windows 8 automatically learns your preferences in order to manage this list for you.
When you resume from standby, Windows 8 can reconnect you to your preferred Wi-Fi networks faster by optimizing operations in the networking stack. It will provide your network list, connection information and hints to your Wi-Fi adapter. So, when your PC resumes from standby, your Wi-Fi adapter already has all the information it needs to connect to your preferred Wi-Fi networks.
This means you can reconnect your PC to a Wi-Fi network from standby in about a second. You’ll often reconnect before your display is even ready. You don’t have to do anything special for this. Windows 8 just learns which networks you prefer and manages everything for you. This was a major part of the architectural work the Windows 8 team did in the networking stack and with its hardware partners.
Connecting to mobile broadband
Even with its broad availability, Wi-Fi by itself doesn’t enable the ubiquitous Internet access that users increasingly want. True mobility requires MB, which provides connectivity over cellular networks (the same networks as your smartphone). However, just including MB in Windows 8 wasn’t enough. Connecting to MB had to be simpler, more intuitive and more like Wi-Fi.
MB is fully integrated into Windows 8. When you’re ready to connect to an MB network, simply insert your MB device or SIM card into your Windows 8 PC, and Windows 8 takes care of the setup.
If you have a carrier-unlocked MB device that supports carrier switching (which may be the case for most MB users outside the United States), Windows 8 has native support that lets you select and connect to any supported carrier from within the Windows interface.
You no longer have to install any drivers, or a radio and connection manager. Windows 8 also automatically identifies which mobile operator is associated with your device (or SIM card). It will then brand it in the Windows Connection Manager with the mobile operator’s logo, configure the PC for connecting to the mobile operator’s network and download the operator’s MB app (if it has one) from the Windows Store.
If you purchased and activated a data plan along with your SIM or MB device, all you need to do is connect to the network. Then Windows 8 gets out of the way and lets you do what you want to do.
If you don’t already have a data plan and would like to purchase one, simply click the “Connect” button for the mobile operator you want. Windows 8 automatically directs you to that operator’s MB app or Web site, where you can select a data plan (for example, a time-based, limit-based or subscription-based plan).
The new AT&T MB app walks you through purchasing a data plan. After you’ve purchased your plan, your mobile operator provisions your PC over the air for its network, including information about your data plan details and Wi-Fi hotspots.
Behind the scenes, Windows 8 identifies the MB subscriber information and looks up the mobile operator in the new Access Point Name (APN) database. Then it pre-provisions the system to connect to the operator’s network. Meanwhile, your core connection experience stays the same.
The operator’s MB app is then made available via the “View my account” link, or from the app’s tile on the Start screen. There, you can check and see how much data you’ve used, pay your bill, manage your account and get customer support.
Avoid ‘bill shock’
Many of you have read headlines about people receiving huge bills from their mobile operators. The industry has termed this “bill shock.” The problem has received enough attention that certain agencies have begun taking regulatory steps to ask mobile operators to alert their customers when their data usage reaches a certain threshold.
Mobile operators all have different ways of responding when subscribers exceed their data usage allotment. An operator may block your Internet access, throttle (slow down) your data speed, or simply begin charging you per kilobyte or megabyte. If you’re unaware that you’re beyond your data usage limit, you’ll likely continue using your data plan and rack up additional charges. This can result in bill shock.
Prior to Windows 8, the Windows OS maintained consistent behavior on all types of networks relative to bandwidth usage. Windows 8 takes the network cost into consideration. MB networks most likely have restrictive data caps with higher overage costs than Wi-Fi. Windows 8 will adjust networking behavior with these metered networks accordingly.
Windows 8 automatically disconnects from MB and connects you to your preferred Wi-Fi networks whenever they’re available. This reduces your data usage on MB when possible. Because a number of people use public Wi-Fi, Windows 8 includes support for popular Wi-Fi hotspot authentication types, including Wireless Internet Service Provider roaming (WISPr), Extensible Authentication Protocol (EAP)-SIM/AKA/AKA Prime (SIM-based authentication) and EAP-TTLS (popular on university campuses).
Windows 8 manages your authentication your home or office.
On a PC with both MB and Wi-Fi, Windows 8 will move you from MB to the less-costly Wi-Fi network automatically whenever it’s available. This again reduces your MB usage and your potential for bill shock.
Another way Windows 8 optimizes your bandwidth usage is by changing the Windows Update download behavior. With automatic updating, Windows Update will defer the background download of all updates until you connect to a non-metered network, such as your home broadband connection.
In that case, Windows Update will download the update regardless of the network type. You can always override the deferred download by launching Windows Update and manually initiating the update download at a more convenient time. Again, you are in full control of your device.
Most fixed-line broadband plans also have data caps and overage fees. Those data caps are typically much higher than MB. Therefore, Windows 8 wouldn’t change the behavior for these connections. You’re always in control and can always mark any wireless network as metered or unmetered by selecting “reduce data usage” in the right-click (or tap and hold) menu for that network.
Windows applications need to behave well on metered networks, so there’s a new set of developer APIs within the ConnectionCost class of the Windows.Networking.Connectivity namespace. If you’re an application developer, you should leverage these APIs and adapt the behavior of your app. You could allow a low-definition versus high-definition video stream, or a header-only versus full-sync of e-mail, depending on the network type. This adaptive behavior is critical, as it results in actual cost savings.
Even with Windows and other applications behaving smartly on the network, you might still want to know how much data you’ve consumed. Windows 8 provides local data usage counters within the network settings. These counters provide real-time local data usage estimates for Wi-Fi and MB network connections.
The local counters keep track of the amount of data used on each individual network type so you don’t have to. You can reset the counter whenever you want. This can be useful if you want to monitor your usage month-to-month or even within a session. Although you should think of the local data counters as a quick way to determine your usage, they’re not a substitute for what mobile operators will report. This amount may vary slightly, and should be available in the operator’s app.
Another way Windows 8 helps you manage your MB data usage is by letting mobile operators alert you as you approach your bandwidth cap. Some countries have already begun to mandate that operators send messages to subscribers as they approach their bandwidth cap, or once they begin roaming to a different network. The mobile operator may send you a Short Message Service (SMS) or Unstructured Supplementary Service Data (USSD) alert as you approach your bandwidth cap The MB operator’s app notifies you and updates its Start screen tile.
The Windows 8 Task Manager provides more granular information if you want to know how much data a particular app has consumed on the network. You can see the approximate active and historical data consumption of any process over metered and non-metered networks. With this information, you can take control by identifying which apps are consuming the most bandwidth and taking action if needed.
Windows 8 is designed with mobility in mind. The experience with getting and staying connected across MB and Wi-Fi networks has been greatly simplified.
.jpg)
Billy Anders is group manager for Wireless and Mobility in Windows engineering. He has program management responsibility for Wi-Fi, Mobile Broadband/Cellular, Proximity, HTTP, and core wireless connectivity technologies, scenarios and devices for Windows. He lives in the Puget Sound area with his wife, sons Billy and Jacob, where he enjoys fitness, outdoor photography, traveling and food.
Related Content
|
https://technet.microsoft.com/en-us/library/dn237242.aspx
|
CC-MAIN-2017-22
|
refinedweb
| 2,298
| 53.21
|
subprocess execute shell - Calling. See the documentation.
stream = os.popen("some_command with args")will do the same thing as
os.systemexcept. See the documentation.
The
Popenclass of the
subprocessmodule. This is intended as a replacement for
os.popenbut.
The
callfunction from the
subprocessmodule. This is basically just like the
Popenclass and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:
return_code = subprocess.call("echo Hello World", shell=True)
See the documentation.
If you're on Python 3.5 or later, you can use the new
subprocess.runfunction, which is a lot like the above but even more flexible and returns a
CompletedProcessobject when the command finishes executing.
The os module also has all of the fork/exec/spawn functions that you'd have in a C program, "my mama didnt love me && rm -rf /".
How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script? Process Creation
/* UPD 2015.10.27 @eryksun in a comment below notes, that the semantically correct flag is CREATE_NEW_CONSOLE (0x00000010) */'])
I always use
fabric for this things like:
from fabric.operations import local result = local('ls', capture=True) print "Content:/n%s" % (result, )
But this seem to be a good tool:
sh (Python subprocess interface).
Look an example:
from sh import vgdisplay print vgdisplay() print vgdisplay('-v') print vgdisplay(v=True).
The edit was based on J.F. Sebastian's comment.()
Update:
subprocess.run is the recommended approach as of Python 3.5 if your code does not need to maintain compatibility with earlier Python versions. It's more consistent and offers similar ease-of-use as Envoy. (Piping isn't as straightforward though. See this question for how.)
Here's some examples from the docs.
Run a process:
>>> subprocess.run(["ls", "-l"]) # doesn't capture output CompletedProcess(args=['ls', '-l'], returncode=0)
Raise on failed run:
>>> subprocess.run("exit 1", shell=True, check=True) Traceback (most recent call last): ... subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Capture output:
>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE) CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0, stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')
Original answer:
I recommend trying Envoy. It's a wrapper for subprocess, which in turn aims to replace the older modules and functions. Envoy is subprocess for humans.
Example usage from the readme:
>>> r = envoy.run('git config',>> r.std_err ''
Pipe stuff around too:
>>> r = envoy.run('uptime | pbcopy') >>> r.command 'pbcopy' >>> r.status_code 0 >>> r.history [<Response 'uptime'>]
...or for a very simple command:
import os os.system('cat testfile')
>>>
It can be this simple:
import os cmd = "your command" os.system(cmd)
subprocess.check_call is convenient if you don't want to test return values. It throws an exception on any error.
os.system does not allow you to store results, so if you want to store results in some list or something
subprocess.call works.
Shameless plug, I wrote a library for this :P
It's basically a wrapper for popen and shlex for now. It also supports piping commands so you can chain commands easier in Python. So you can do things like:
ex('echo hello shell.py') | "awk '{print $2}'"
I quite like shell_command for its simplicity. It's built on top of the subprocess module.
Here's an example from the docs:
>>> from shell_command import shell_call >>> shell_call("ls *.py") setup.py shell_command.py test_shell_command.py 0 >>> shell_call("ls -l *.py") -rw-r--r-- 1 ncoghlan ncoghlan 391 2011-12-11 12:07 setup.py -rw-r--r-- 1 ncoghlan ncoghlan 7855 2011-12-11 16:16 shell_command.py -rwxr-xr-x 1 ncoghlan ncoghlan 8463 2011-12-11 16:17 test_shell_command.py 0
Under Linux, in case you would like to call an external command that will execute independently (will keep running after the python script terminates), you can use a simple queue as task spooler or the at command
An example with task spooler:
import os os.system('ts <your-command>')
Notes about task spooler (
ts):
You could set the number of concurrent processes to be run ("slots") with:
ts -S <number-of-slots>
Installing
tsdoesn't requires admin privileges. You can download and compile it from source with a simple
make, add it to your path and you're done.
|
http://code.i-harness.com/en/q/15c8c
|
CC-MAIN-2019-09
|
refinedweb
| 748
| 60.61
|
C++ coutPritesh
Cout : Display Output to User Using Screen(Monitor)
In C++ Insertion operator is used to display value to the user. The value may be some message in the form of string or variable.
Syntax : Display Value to User
cout << variable;
Explanation : Insertion Operator
- Include <iostream.h> header file to use cin.
#include<iostream.h>//traditional C++ OR #include<iostream>// ANSI Standard using namespace std;
- cout is used for displaying data on the screen.
- The operator << called as insertion operator or put to operator.
- The Insertion operator can be overloaded.
- Insertion operator is similar to the printf() operation in C.
- cout is the object of ostream class.
- Data flow direction is from variable to output device.
- We can still use printf() for displaying an output..
- Multiple outputs can be displayed using cout.
Live Example : Displaying Output on Screen
#include<iostream.h> using namespace std; int main() { int number1; int number2; cout<<"Enter First Number: "; /* Display the message to tell the user to do appropriate action */ cin>>number1; cout<<"Enter Second Number: "; /* Display the message to tell the user to do appropriate action */ cin>>number1; cin>>number2; cout<<"Addition : "; cout<<number1+number2; //Display Result return 0; }
Output :
Enter First Number: 8 Enter Second Number: 8 Addition : 16
Different ways of using cout in c++
Way 1. Simple Use of cout and Insertion Operator:
int tempNumber=6; cout << tempNumber;
- In above example, tempNumber is declared as integer variable. And value 6 is assigned to it.
- when control comes over cout , Program will display the output to screen.
- Likewise we can display integer, character or string.
Way 2 : Cascading Multiple Variables in Cout
int a=10; int b=20; cout << a << b;
is similar to –
int a=10; int b=20; cout << a; cout << b;
Way 3 : cout to display string
cout << string ; //for displaying string output or cout << "Display String" ;
- The extraction operator is also used for getting string.
- When blank space is detected, extraction operator stops reading input.
- cin allow us to enter only one word.
- For reading entire line, we use getline() function.
Way 4 : Use of expression in cout
int num1; int num2; cin >> num1; cin >> num2; cout<< "Addition is : " << num1+num2 ;
- Expression can be evaluated inside cout statement.
- In above example, we are accepting 2 values from user.
- The addition of two numbers is displayed on the screen
- For that we use the expression for adding two numbers in the output statement directly.
Way 5 : Display Output on new line
- We can use ‘n‘ or ‘endl‘ to print the output on new line.
cout << "Hello,n"; cout << "My name is nPooja..."; or cout << "Hello," <<endl; cout << "My name is" <<endl; cout << "Pooja..." <<endl;
Output :
Hello, My name is Pooja...
*External Link : More on cout | cout Statement | Sample Example
|
http://www.c4learn.com/cplusplus/cpp-cout/
|
CC-MAIN-2019-39
|
refinedweb
| 461
| 56.66
|
intermediate
Store is a data structure that holds a state and a function for extracting a representation of it.
If we think in a component oriented fashion when building user interfaces, this datatype is the most basic unit.
This structure is also a
Comonad because it represents a lazy unfolding of all possible states of our user interface.
import arrow.data.* val store = Store(0) { "The current value is: $it" } store.extract() // The current value is: 0
If we want to change the initial state of the store we have a
move method:
val newStore = store.move(store.state + 1) newStore.extract() // The current value is: 1
We also have two methods from
Comonad:
extract for rendering the current state.
coflatMap for replacing the representation type in each future state.
import arrow.core.* val tupleStore = store.coflatMap { it: Store<Int, String> -> Tuple2("State", it.state) } tupleStore.extract() // Tuple2(a=State, b=0)
And as a
Comonad is also a
Functor we have
map which allows us to transform the state representation:
val upperCaseStore = store.map { it: String -> it.toUpperCase() } upperCaseStore.extract() // THE CURRENT VALUE IS: 0
|
https://arrow-kt.io/docs/arrow/data/store/
|
CC-MAIN-2018-51
|
refinedweb
| 186
| 58.48
|
On Sat, Jul 26, 2014 at 10:04 PM, Eric W. Biederman<ebiederm@xmission.com> wrote:> David Drysdale <drysdale@google.com> writes:>>> The last couple of versions of FreeBSD (9.x/10.x) have included the>> Capsicum security framework [1], which allows security-aware>> applications to sandbox themselves in a very fine-grained way. For>> example, OpenSSH now (>= 6.5) approach.>>>> I'm attaching a corresponding draft patchset for reference, but>> hopefully this cover email can cover the significant features to save>> everyone having to look through the code details. (It does mean this is>> a long email though -- apologies for that.)>>>>>>doesn't prevent fchmod(2).Also, because they're associated with the struct file there is no wayto pass a file descriptor with only a subset of rights across a UNIXsocket (how do I send a read-only FD corresponding to myO_RDWR file?).>key things that makes them analogous to object-capabilities andsuitable as the substratum for Capsicum. But the coarseness of theexisting rights, and the lack of coherent policing of those rights,means that an (opt-in) extension like Capsicum is useful.> In fact internal to linux with FMODE_READ and friends we already have> restrictions on which methods are allowed on linux file descriptors.> So this whole entire abstraction layer you are adding seems just plain> broken.>>it for Capsicum a while ago: I don't think a firm conclusion was reached. As I understand it,there's also a theoretical argument that revocation can be constructedon top of the capability system, by handing out capabilities to proxyobjects that can then change their behaviour so they no longer passoperations through.>> 2) Capsicum Capabilities Data Structure>> --------------------------------------->>>> Internally, the rights associated with a Capsicum capability FD are>> stored in a special struct file wrapper. For a normal file, the rights>> check inside fget() falls through, but for a capability wrapper the>> rights in the wrapper are checked and (if capable) the underlying>> wrapped.]>> I have already mentioned that this is an insane choice of semantics> right? Adding an extra layer on top of a data structure that is a> perfectly good restrictor of rights.>> If you can't add the restriction on struct file itself I would argue> that the semantics of capsicum are fundamentally broken.>> I can not imagine why in the world you would want and extra layer of> indirection, complication, and maintenance.See above.>>access means it's much easier for an application to adapt to Capsicum.A simple example is something like unzip/tar -xf, where locking it downoutput directory -- which it could do anyway.Similarly, migrating an application that writes temporary files out tosome tempdir is much more straightforward if openat(dfd,...) is stillallowed.>> c) In capability mode it should still be possible for a process to send>> signals to itself with kill(2)/tgkill(2).>> Again is it worth it?>> I would think you would want capability mode to default to the minium> set of system calls you could get away with (to keep kernel code> auditing to a minium) and only add things if the performance gain of> using the syscall exceeds the pain.The set of syscalls allowed in capability mode is based more on theprinciple of restricting access to global namespaces, to prevent (inparticular) the confused deputy problem. Allowing kill(self) is a pragmaticcompromise to make it easier to migrate existing applications to useCapsicum.> If you look at a kernel like sel4 it succeeds in with an object> capability model with many fewer system calls than you are proposing> to export. Roughly just read, write and close.>> Consider the fact if you really want a kernel layer you can completely> trust and rely on someone needs to write a formal proof of that layer.> Short of that someone certainly needs to audit the kernel code very> closely so simplicity of semantics and simplicity of implementation are> very important.seL4 may have a much simpler (and more formally-correct) model, butthe aim of Capsicum is to get some of the benefits of that well-analysedmodel without the need for a (massive) migration effort -- and in a waythat allows co-existence of migrated and unmigrated code.>>f>> functionality gives the tools needed to implement capability mode.>>>>>>.>> EricI think that's a lot harder for application writers to do -- they would needto have CAP_SYS_ADMIN to set up the namespace & mounts beforedropping privileges. And the net result would again be much lessfine-grained (e.g. for the unzip example above, the specific capabilityrights prevent reading of any files that already exist in the outputdirectory).
|
https://lkml.org/lkml/2014/7/28/408
|
CC-MAIN-2017-51
|
refinedweb
| 760
| 52.49
|
02 March 2012 11:11 [Source: ICIS news]
(adds analyst comments, background)
By Nurluqman Suratman
?xml:namespace>
SINGAPORE
“We just did a pre-feasibility study with a partner. We will do a year-long feasibility study and decide whether to go ahead [with the cracker project],” the spokesperson said, without elaborating.
This project would constitute an upstream expansion for IVL, after its acquisition of US-based ethylene oxide/ethylene glycol maker
The $795m (€596m) acquisition of Clear Lake, Texas-based
Old World is the largest single EO/EG production facility in the
The facility also produces 204,000 tonnes/year of purified EO and 358,000 tonnes of monoethyelene glycol (MEG).
IVL’s pipeline of projects in which it plans to invest $4-5bn over the next years, could include the US shale gas-based cracker, said Naphat Chantaraserekul, a Bangkok-based analyst at brokerage DBS Vickers Securities.
“[IVL’s] Management believes that they can capitalise on cheap shale gas and establish upstream to downstream value chain for polyester,” Chantaraserekul said.
IVL plans to commence work on the cracker in 2015 and complete the project in 2017, he added.
The Thai firm has plans to raise its combined global production capacity for purified terephthalic acid (PTA), polyethylene terephthalate (PET) and fibres to at least 10m tonnes/year by 2014, from about 5.5m tonnes/year currently.
Taking into account the company’s recent acquisitions and expansions, IVL’s overall production capacity, excluding capacity in associated firms, will rise by 23% to 6.5m tonnes in 2012, Chantaraserekul said.
In
The company is looking at further expansions.
|
http://www.icis.com/Articles/2012/03/02/9537611/thailands-ivl-mulls-building-us-shale-gas-based-cracker.html
|
CC-MAIN-2013-20
|
refinedweb
| 266
| 50.87
|
Suppose, we have a list and the power of a list is defined by the sum of (index + 1) * value_at_index over all indices. Alternatively, we can represent it like this −
$$\displaystyle\sum\limits_{i=0}^{n-1} (i+1)\times list[i]$$
Now, we have a list nums that has N positive integers. We can select any singular value in the list, and move (not swap) it to any position, it can be shifted to the beginning of the list, or to the end. We can also choose to not move any position at all. We have to find the maximum possible final power of the list. The result has to be modded by 10^9 + 7.
So, if the input is like nums = [4, 2, 1], then the output will be 16.
To solve this, we will follow these steps −
P := [0]
base := 0
for each i, x in index i and item x in A, 1, do
insert P[-1] + x at the end of P
base := base + i * x
Define a function eval_at() . This will take j, x
return -j * x + P[j]
Define a function intersection() . This will take j1, j2
return(P[j2] - P[j1]) /(j2 - j1)
hull := [-1]
indexes := [0]
for j in range 1 to size of P, do
while hull and intersection(indexes[-1], j) <= hull[-1], do
delete last element from hull
delete last element from indexes
insert intersection(indexes[-1], j) at the end of hull
insert j at the end of indexes
ans := base
for each i, x in index i and item x in A, do
j := the portion where x can be inserted in hull, maintaining the sorted order
j := maximum of j - 1, 0
ans := maximum of ans, base + eval_at(i, x) - eval_at(indexes[j], x)
return ans mod (10^9 + 7)
Let us see the following implementation to get better understanding −
import bisect class Solution: def solve(self, A): P = [0] base = 0 for i, x in enumerate(A, 1): P.append(P[-1] + x) base += i * x def eval_at(j, x): return -j * x + P[j] def intersection(j1, j2): return (P[j2] - P[j1]) / (j2 - j1) hull = [-1] indexes = [0] for j in range(1, len(P)): while hull and intersection(indexes[-1], j) <= hull[-1]: hull.pop() indexes.pop() hull.append(intersection(indexes[-1], j)) indexes.append(j) ans = base for i, x in enumerate(A): j = bisect.bisect(hull, x) j = max(j - 1, 0) ans = max(ans, base + eval_at(i, x) - eval_at(indexes[j], x)) return ans % (10 ** 9 + 7) ob = Solution() print (ob.solve([4, 2, 1]))
[4, 2, 1]
16
|
https://www.tutorialspoint.com/program-to-find-out-the-maximum-final-power-of-a-list-in-python
|
CC-MAIN-2021-49
|
refinedweb
| 442
| 62.31
|
Asked by:
Reading SharePoint List from Console Application
Question
I'm writing a console application that needs to access a SharePoint list on a remote server. It needs to read the "table" from the list (do not need to write/modify, just read the data), and then process the data into a report (filtering it by date, modified by, and some custom columns for categorization). What would be the best way to do this?
I currently have it working by exporting the list as an Access database which is linked. Then, my program connects to this accdb and gets the information. The only problem is that some columns do not come through correctly. I have some columns with Choice and Lookup types (checkmarks for categorization, a list of names to choose from, etc), however these do not come through. When I view the list online through SharePoint, the values are displayed correctly. In my console application though, all single-line text or multi-line text fields come through perfectly (including formatting for rich text and HTML fields), however the Choice and Lookup fields do not come through properly (the data in those fields shows up as "Caiv></div>ExternalClass134...").
How can I either fix the current access method, or is there a better way to connect to a SharePoint site and read a list without modifying it?
Many thanks in advance!
Tuesday, October 26, 2010 8:55 PM
- Moved by Figo Fei Monday, November 1, 2010 3:15 AM (From:Visual C# General)
- Moved by Peter Jausovec Monday, November 8, 2010 11:30 PM (From:Sharepoint Development with Visual Studio)
All replies
Hi George,
The first design question to consider is where you console application will be run? If the console application will be run from a SharePoint Server then you could use the SharePoint Object Model. If you plan to run the console application from computer without SharePoint then you should use Web Services.
The next question is what version of SharePoint are you using? If you are using MOSS 2007 then your choices are basically the object model or web services. If you are using SharePoint 2010 then you can the Object Model, Web Services (ASX, WCF, Rest), or the client-side API.
Eitherway, you want to treat the SharePoint list as a database table. Meaning it is just a repository storing your data.
Here is a great example of reading values from a task list:>"); }
Reference: - Contains Console Application Examples.
Dennis Bottjer | Follow Me: @dbottjer | Blog: Dennis Bottjer.comWednesday, October 27, 2010 1:24 AM
Hello Dennis, thank you very much for your reply.
The console application will not be running on the SharePoint server (I do not have access to that server, exception for SharePoint via my web browser). I'd like the application to be able to run from any machine (except for the SharePoint server). The SharePoint server is running 12.0.0.6504 (2007). My development machines are running Windows 7 and Windows Server 2008 R2 (Using Visual Studio 2010 with a .NET 4 project).Wednesday, October 27, 2010 8:33 PM
Hi George,
Since you are using MOSS 2007 you have fewer options than are available with SharePoint 2010 but your task is still quite achievable. SharePoint exposes web services for use within client applications such as the console application you are developing. I would suggest reference the list service: http://<server-url>/_vti_bin/lists.asmx
References:, November 1, 2010 3:24 AM
Thanks Dennis, that article is great and is (partially) working for me.
It successfully pulls some information from all lists available in my SharePoint site. However, I only need it to access one specific list, and then give me all of the data from that list. Unfortunately, the way the code works now, it gives me the name of the list and the description, however it won't list the description of each line item in a given list (although it does list the name of the line item). The Description field in my list is where some vital data I am trying to extract is stored, and I have many other columns/fields that I need to pull from. I'm not sure how to make it pull more column data out.
How can I add more columns/fields to retrieve data from, including custom fields I've created? Also, how can I limit this code to only a single, specific list, rather than pulling everything?
Thanks again for your help. It's my first time working with SharePoint via ASP.NET, so I'm really appreciate of any help I can get.Wednesday, December 8, 2010 5:20 PM
A more common call to get list items from a specific list is GetListItems. There's a code sample in the article that builds up a <Query> you also have a <ViewFields> element which is where you define the columns you want to return (please note this will need to use the internal name of the columns).
My SharePoint Blog -, December 8, 2010 6:42 PM
|
https://social.msdn.microsoft.com/Forums/en-US/87b6c6eb-9561-472b-b9ed-5417c0a724e8/reading-sharepoint-list-from-console-application?forum=sharepointdevelopmentprevious
|
CC-MAIN-2022-05
|
refinedweb
| 848
| 69.72
|
How many times you want the loop to iterate. That is the statements within the code block of a for loop will execute a series of statements as long as a specific condition remains true.
Every for loops defines initializer, condition, and iterator sections.
Syntax:
The for loop initialize the value before the first step. Then checking the condition against the current value of variable and execute the loop statement and then perform the step taken for each execution of loop body.
The initializer declares and initializes a local loop variable, i, that maintains a count of the iterations of the loop. The loop will execute four times because we set the condition i is less than or equal to count.
for (int i = 1; i < = count; i++)
initialization : int i = 1 Initialize the variable i as 1, that is when the loop starts the
value of i is set as 1
condition : i < = count Set the condition i < =count , that is the loop will execute up to
when the value of i < = 4 (four times)
step : i++
Set the step for each execution of loop block as i++ ( i = i +1)
The output of the code as follows :
Current value of i is - 2
Current value of i is - 3
Current value of i is - 4
C# Sample For loop program full source code
Infinite Loop
All of the expressions of the for loop statements are optional. A loop becomes infinite loop if a condition never becomes false. You can make an endless loop by leaving the conditional expression empty. The following statement is used to write an infinite loop.
Here the loop will execute infinite times because there is no initialization , condition and steps.
break and continue
We can control for loop iteration with the break and continue statements. break terminates iteration and continue skips to the next iteration cycle. The following program shows a simple example to illustrate break and continue statement.
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { for (int i = 1; i < = 5; i++) { if (i == 2) continue; if (i == 3) break; MessageBox.Show("execute " + i + " times !!"); } } } }
|
http://csharp.net-informations.com/statements/csharp-for-loop.htm
|
CC-MAIN-2015-11
|
refinedweb
| 368
| 59.43
|
Okay, I was given this problem, its another of those file I/O streams and I was wondering how I can change this code to be more "efficient" and change a lot of things. I'm having trouble on what I should change and what I should keep. Please help me out on this one. Thank you! Oh, this code does work by the way. Please nothing too fancy! I would just like to change a lot of things to make it better.
Write a program that reads in a set of positive integers, representing test scores for a class, and outputs how many times a particular number appears in the list. You may assume that the data set has, at most, 100 numbers and that -999 marks the end of the input data. The numbers must be output in increasing order. For example, for the data: 55 80 78 92 95 55 78 53 92 65 78 95 85 92 85 95 95 the output is: Test Score Count 53 1 55 2 65 1 78 3 80 1 85 2 92 3 95 4 input2.txt has this numbers: 55 80 78 92 95 55 78 53 92 65 78 95 85 92 85 95 95 #include <iostream>//include statement(s) #include <iomanip> #include <fstream> using namespace std;//using namespace statement(s) const int MAX_SIZE = 999;//constant variable declaration(s) void getScoresAndSize(int arry[], int& arrySize);//void function header(s) void displayScoreArray(int arry[], int arrySize); void orderArray(int arry[], int arry2[], int arrySize); void outputData(int arry[], int arrySize); int main() { int scoreArray[MAX_SIZE];//variable declaration(s) int newScoreArray[MAX_SIZE]; int ArraySize; getScoresAndSize(scoreArray, ArraySize);//void function call(s) displayScoreArray(scoreArray, ArraySize); orderArray(scoreArray, newScoreArray, ArraySize); cout << "After reordering the array, "; displayScoreArray(newScoreArray, ArraySize); outputData(newScoreArray, ArraySize); cout << "Program is exiting..." << endl; system ("PAUSE");//Black box to appear and stay return 0;//return statement(s) } void getScoresAndSize(int arry[], int& arrySize) { ifstream scorFil; scorFil.open("input2.txt"); if (scorFil.fail())//if score file fails, program outputs "cannot open file" { cout << "The input2.txt file was not opened by the program. Ending program..." << endl; exit(1); } else if (!scorFil.fail())//if score file opens, program outputs "file was opened successfully" cout << "The input2.txt file was succesfully opened by the program." << endl; int score; arrySize = 1; for(int i = 0; !scorFil.eof(); i++ && arrySize++)//for loop for the readable file, collect the scores { //the array size is incremented as well scorFil >> score; arry[i] = score; } cout << "The scores from the file were succesfully transferred into an array."<<endl; cout << "The array contains " << arrySize << " scores." << endl << endl; scorFil.close(); return; } void displayScoreArray(int arry[], int arrySize) { cout << "The Scores are: " << endl; for (int i = 0; i <= (arrySize - 1); i++)//for loop to print out each score { cout << arry[i] << " ";//spaces between each score if ((i + 1) % 21 == 0) cout << endl; } cout << endl; cout << endl; return; } void orderArray(int arry[], int arry2[], int arrySize) { int index = 0;//new array for index for (int score = 0; score <= 100; score++)//for loop to check the scores from 0 to 100 { for (int i = 0; i <= (arrySize - 1); i++) { if(arry[i] == score) { arry2[index] = score; index++;//index increments } } } } void outputData(int arry[], int arrySize) { int oldNum = arry[0]; int count = 1; cout << "Score" << setw(11) << "Count" << endl;//output header for(int i = 1; i <= arrySize; i++) { if(arry[i] == oldNum) { count++;//counter increments } else { cout << " " << oldNum << setw(11) << count << endl; count = 1; } oldNum = arry[i]; } cout << endl; }
Thanks for the help!
|
https://www.daniweb.com/programming/software-development/threads/480984/write-a-program-that-reads-in-a-set-of-positive-integers-representing-test
|
CC-MAIN-2018-34
|
refinedweb
| 589
| 56.89
|
In today’s Programming Praxis exercise, we have to write a program to generate form letters. Let’s get started, shall we?
First, some imports:
import Control.Applicative ((*>), (<*>), (<$>)) import Text.CSV import Text.Parsec
The format for the message template is simple enough to do with a plain recursive algorithm, as I did initially, but in the end I decided to go with Parsec since it’s slightly cleaner.
fillWith :: String -> [String] -> String fillWith text vars = either show concat $ parse form "" text where form = many $ escape <|> count 1 anyChar escape = char '$' *> (string "$" <|> ((vars !!) . read <$> option "0" (many1 digit)))
Once we have the function to fill in the message template with a record, doing this for multiple records is pretty simple.
formLetters :: FilePath -> FilePath -> IO [String] formLetters schema vars = either (return . show) . map . fillWith <$> readFile schema <*> parseCSVFromFile vars
A quick test to see if everything is working properly:
main :: IO () main = mapM_ putStrLn =<< formLetters "schema.txt" "data.txt"
Yep. Now make sure never to use this code because nobody wants to see more form letters
Tags: bonsai, code, form, Haskell, kata, letters, praxis, programming
|
http://bonsaicode.wordpress.com/2010/11/30/programming-praxis-form-letters/
|
CC-MAIN-2013-48
|
refinedweb
| 183
| 63.8
|
.
- The Creating Web Sites section contains articles related the basics of Web page construction.
- Content Design and Presentation deals with issues involving layout, positioning, and CSS.
- The Data Storage and Cookies section includes persistence and other data management concepts.
- Integrating Sites and Services provides information related to Accelerators, AJAX, Open Search and others related topics.
- Quick Reference Guides collects summary articles designed to help you find specific facts quickly.
- Security Considerations outline the concepts and ideas to help protect Web sites from malicious behavior.
- The Testing Web Sites section covers the Internet Explorer Developer Tools, the Microsoft Application Compatibility Toolkit for deploying Internet Explorer, the Mark of the Web, and other information useful for troubleshooting rendering issues and markup problems.
PingBack from
I don’t like it since there is no easy way to download parts of the MSDN Library. Also, navigating tables of contents is hard since there is no next and previous link at the top or bottom of each topic and not a keyboard shortcut for these common tasks of changing to the next and previous topic. You have to hunt your place in the table of contents continuously. I cannot even suggest changes or even update things that are wrong and usually sending feedback through the edit box at the top changes nothing, since I have sent feedback many times and errors are still there after years. Finally MSDN is so so boring to read. It is not like the rest of the web that offers tutorial-like guides. Go to Firefox’s extentions page. Tutorials, ready code to use, easy 5 pages overview, any student for example can follow. MSDN has all specifics even minor details. But if I want to write a simple something, MSDN has a long reading curve as it were. I have to read staff that I don’t care about. Where is the tutorial-like nature of things. At my university, nobody likes it.
Well at least it has been updated. Although I will probably only ever use it to find out why IE is behaving differently to every other browser on the market.
Is it really necessary to waste so much space at the top for the search bar, languages etc, signing in etc. Changing language does very little as all the developer information is in English anyway.
It seems microsoft just wants to constantly get me to sign in, search the web using their search etc. If I want hotmail I will go to that page.
Why not just have a nice clear website for developers.
Nice article. Learned about two things I didn’t know IE could do (saveSnapshot, The Internet Explorer cache is case-sensitive).
You might consider providing the low-bandwidth version in a link. I find it’s faster and less visually distracting.
@Mike
The low bandwidth version is less annoying in that respect. I will warn you that once you visit a URL with (loband), all the other MSDN urls you visit will be in lo-band mode. You can opt back out with the "Switch off low bandwidth view" link in the top right corner.
I’d just like to see documentation of the IE8 command line options.
Nowhere to be found…
All that matters is that where IE deviates from the specs, it IS CLEARLY DOCUMENTED!!
e.g. If viewing the Element.setAttribute(name, value) method… it better damn well explain that until version 8 of IE (running in Standards mode) that this implementation was HORRIBLY, HORRIBLY BROKEN!
Joel
Hi
A major problem that I seemed to be overlooked in terms of windows and the performance are antivirus software. Antivirus software can slow down the PC and web experince very much.
There is huge difference between antivirus programs and their impact on performance on Windows.
See, for example in the free AVG antivirus and Eset antivirus 4.
The free AVG antivirus, and others extremely slow down PC and Web browsing on older PC and are Netbook. While Eset antivirus 4 has almost no influence in practical use.
Microsoft has plans whith a free antivirus called Morro a continuation of OneCare.
Therefore Microsoft should do a lot more work in marketing and telling people how much influence the antivirus on performance on PCs and webbrowsing.
I really hope that Morro from microsoft become just as fast as Eset antivirus 4, whith small footprint as posible.
A major problem that seemed to be overlooked in terms of windows and the performance, are antivirus software. Antivirus software can slow down the PC and web experince.
There is a huge difference between antivirus programs and their impact on performance on Windows and webbrowsing.
See, for example the free AVG antivirus and Eset antivirus 4.
The free AVG antivirus, and others antivirus slow down PC and Web browsing on older PC and are Netbook extremely. While Eset antivirus 4 has almost no influence in perfomance in practical use.
Microsoft has plans whith a free antivirus called Morro a continuation of OneCare.
Therefore Microsoft should do a lot more work in marketing and telling pc users how much influence the antivirus has on performance on PCs and webbrowsing.
I really hope that Morro from Microsoft become just as fast as Eset antivirus 4, whith just as small footprint.
@Lance Leonard [MSFT]
Every single webpage of documentation at MSDN
- has many validation markup errors, even webpages claiming, boasting that IE 8 is now CSS 2.1 compliant, complies better with web standards, etc.
- has many code examples which make use of invalid elements or attributes which would fail markup validation and/or CSS validation
- would have more validation markup errors if the doctype declaration was declaring a strict DTD
- have code examples which are clearly and utterly outdated, which promote bad or not-recommendable coding practices in all sorts of ways (regarding accessibility, validity, usability, compliance, forward-compatibility, cross-browser, code maintainability, etc). In many cases, this was done years ago, was part of the browsers war era and it was deliberate from Microsoft (document.all, code to access form elements, id-ed elements, etc) MSDN webpages are the promoting backward-compatibility, breaking the web, living in the past.
- have code examples which rely on proprietary attributes and methods: ie document.all, id-ed elements in global namespace, etc.
E.g.: 4 significant coding errors in 2 instructions taken from one MSDN webpage:
{
For example, the assignments below are the same—they both set the font size to 72 pixels.
document.all.MyElement.style.fontSize = "72";
document.all.MyElement.style.fontSize = 72;
taken from
en-us/library/ms533036(VS.85).aspx
}
- have very rarely links to outside documentation about HTML, CSS, javascript, DOM, etc.
- have a DHTML drop-down list for changing the language and country. So it works with javascript support enabled and will rely and use user system resources, just to change language. How often within a month would a normal, average person need to change language and country? (Lance Leonard, how many languages do you speak, understand, read and write?) Besides, if the content is not translated ("We were unable to locate this content in"), why do you need to provide such feature? MSDN should just provide a select which could work without javascript support.
MSDN webpages now do the same with about *_anything_* (ie providing feedback) without any kind of analysis of a benefits vs drawbacks analysis or usability study. Those DHTML drop-down, popups interfere (hog CPU, require RAM, fast video card, etc) more than they actually help the users, at least users with modest user system resources. This annoying DHTML effect has been expanded to other Microsoft webpages: IE beta feedback for instance. Lots of people have been complaining about it during a whole year and it’s still there.
Same thing with annoying me everywhere and all the time about downloading and installing Silverlight. How often do I have to tell your MSDN/Microsoft webpages that I do not want to download Silverlight??
- have no useful, relevant, helpful info on compatibility (browser version) otherwise such info is highly suspect or plain wrong or misleading. You see, we know and you know very well that each and all of your CSS properties had bugs, many bugs before IE 8 was released. Ordinary web developers who may visit MSDN reference just do not know how bad your support was.
- promote and over-use inline style, "Get IE 7" promotion buttons, utterly misunderstand some elements (label), lack good interactive examples, etc.
To me, MSDN documentation webpages is like a desert in the middle of an island, where all kinds of things are happening, almost disconnected from reality, at least today’s reality, where there is no communication with the outside world.
Gérard Talbot
@Lance Leonard [MSFT]
Every single webpage of documentation at MSDN
- that cover or explain the label element mis-explain it or misunderstand it: there is an implicit form of label and there is an explicit form of associating a label to its form control. There is no such thing as intrinsic controls, at least in HTML 4.01 specification. So why introduce a concept that is not defined anywhere? Why not use the concept which is already well defined and explained in HTML 4.01 specification, and this, since 1999?
- that uses a form element in fact misuses the form element. Whenever a form element is defined, there must be an action attribute specification. A form element is there to submit data to a server, otherwise your code misuses form elements .. and that happens very often in MSDN webpages, examples, code snippets.
- that uses a button element in fact miscodes the button element. The default type of the button element is submit. So, creating a command button, a push button to execute a script of some sort without explicitly specifying the attribute type="button" is a markup compliance mistake. And MSDN webpages do this everywhere. Even the Windows Internet Explorer Testing Center ( ietestcenter/frame_holder.htm )
does this and we’ve explained that this was a markup compliance error.
- uses a too small font size for a large majority of people in my opinion.
Top 10 Reasons Why Big Type Is Good Business
Top Ten Web Design Mistakes of 2005: 1. Legibility Problems
"For this year’s list of worst design mistakes, (…) I asked readers of my newsletter to nominate the usability problems they found the most irritating. (…) About two-thirds of the voters complained about small font sizes or frozen font sizes;"
. "
fm.no-ip.com/auth/bigdefaults.html
The fact that font size is widespread accessibility issue on MSDN does not surprise me; F. Miata lists Microsoft in his Hall of shame webpage. None of the accessibility advocates on font-size (Felix Miata, Lighthouse, accessify.com, Chris Beal) is echoed in any way/shape/manner in any of the MSDN webpages. MSDN contributes to and promotes unconsciously, unintentionally the inaccessible web we have today.
Gérard Talbot
Gerard makes many, many good points. As the "central" source for info for developers looking to see what IE supports it should be VERY accurate, standards compliant, and be VERY forthcoming with IE’s lack of standards compliance in the past. Do not make developers hunt for the details about where and how and under what conditions IE breaks the rules or does not support things.
It will save web developers a lot of headache if IE8 can fix the bugs IE7 has in rendering websites. Developers are forced to make a fix in their CSS files specifically for IE7. Microsoft needs to follow the standard format that other popular Gecko-based browsers use.
I am not a developer. I am a browser and e-mail user. IE-8 takes much longer to load; I don’t need that.
@Quality Directory – The version of Trident used in IE8 standards mode appears to be more CSS 2.1 compliant than Gecko 1.9.
MSDN has always been bloated and slow IMO. I only visit it to trouble-shoot WIE’s esoteric problems or find alternatives to its lack of support for major parts of the W3C DOM. In particular, that tree menu is ugly, has scrollbars, and it’s really slow to respond on my computer. When I search MSDN, I never use that thing; instead, I perform a new Google search for everything I want from MSDN.
Looking at the page in low-bandwidth mode, MSDN is clean, but the design and readability is awful… You could do better than that after taking an entry-level design class.
As for your table of contents, it still looks incoherent. It would probably be better to start from scratch and organize that; all I see is a huge expanse of text and nothing sticks out. You also need to free up some more screen space; the header and menu areas take up a third of the screen real-estate, if not more (I have my font sizes forced to 18px in Firefox for readability) for stuff that’s either useless or could be reorganized so that it takes up less space.
The more HTML and CSS compliant IE becomes, the better. I’m interested to see the browser grow and get back the lost followers.
You might have updated the menu, but the content is from some dark and distant past…
"Handling form submissions requires knowledge of a programming language such as Perl, C++, or server-side scripting and Active Server Pages (ASP)."
LOL
Why not delete all of the docs that you have and start again? Preferably without the awful MSDN shell.
Not exactly on topic, but: are the IE app compat images going to be updated? They apparently expire on the 30th of April.
Well lets just say its al little improvement, Gr Lenen
As Richard pointed out above. The "Internet Explorer Application Compatibility VPC Images" all expired today. So far there is no sign of new images.
I have to test my web-app in ie6, 7, and 8. Please please please upload new images. My income suffers when people sign up for my app and leave right away because they are using IE8 and there are unresolved oddities with that browser that cause parts of my web-app to vanish.
I need to be able to test and fix my JS/CSS for IE8. For that I need an IE8 image (and ie7 and ie6). Thank-you.
@Oliver: The latest VPC images are always located here: //go.microsoft.com/fwlink?LinkID=70868
The content team assures me that the new images are currently publishing.
And what about developer documentation?
On
Note This interface is available as of Microsoft Internet Explorer 5 and is subject to change.
And we have KB articles like this
WebApp.exe Enables User to Move WebBrowser Ctrl
Move a WebBrowser Control? Nowhere near what the article is for.
And why the IE team broke their own compiler? Or Visual C++ wizards are broken because they use the web browser control to begin with? Is there any other web browser control feature need to op-out to maintain a behavior consistent with IE7?
|
https://blogs.msdn.microsoft.com/ie/2009/04/23/recent-changes-to-ie-content-on-msdn/
|
CC-MAIN-2016-07
|
refinedweb
| 2,524
| 63.59
|
4904/locating-child-nodes-in-selenium-webdriver
I am using Selenium WebDriver to automate my web application. I am able to find tags using By.xpath.
But I find lots of child nodes within the main node.
Example:
<div id="id_1">
<div>
<span />
<input />
</div>
</div>
I tried the following:
WebElement div1 = driver.findElement( By.xpath( "//div[@id='id_1']" ) )
But I want to find the input, then I tried the following:
driver.findElement(By.xpath( "//div[@id='id_1']//input" ) )
Now I only have div1 and not having its XPath. I want to do the following:
WebElement findInput = driver.findElement(div1, By.xpath("//input"));
But I can see that no such method exists. How to solve this issue?
In this situation you can try doing the following:
WebElement input = div1.findElement(By.xpath(".//input"));
Hey Yash, if you want to locate ...READ MORE
I'm currently working on Selenium with Python. ...READ MORE
using OpenQA.Selenium.Interactions;
Actions builder = new Actions(driver); ...
|
https://www.edureka.co/community/4904/locating-child-nodes-in-selenium-webdriver
|
CC-MAIN-2020-16
|
refinedweb
| 161
| 53.47
|
Hello,
I am writing a script in python to perform a segmentation. I noticed, though, that I cannot use some packages because when I extract the shape of my images using img.shape, the number of channels is not at the end as expected but it is in second position.
As an example: I have an image composed of 250 pixels in xy, 50 slices and 2 channels.
from tifffile import imread img = imread("image.tif") print(img.shape)
I would expect to get as an outcome (50, 255, 255, 2).
Instead, I get (50, 2, 255, 255)
Does somebody know why the channel value is not returned as the last value?
I need to correct this because I use a python package whose functions may extract the last value as the number of channels and use this info later for computations. Does somebody know how I can fix this?
Thank you!
Cheers,
Lucrezia
|
https://forum.image.sc/t/image-shape-gives-number-of-channels-at-the-wrong-position/48726
|
CC-MAIN-2021-10
|
refinedweb
| 154
| 71.55
|
Oh, hmm. Actually, when I run:
from mojo.UI import * print(getTestInstalledFonts())
...I get an empty list. This gets populated with test installed fonts once I make them.
Perhaps the opening error message could just be made more clear? Or maybe it's not needed at all, if Robofont automatically de-installs test fonts on crashing?
what RoboFont does related to test install:
each test install font path is added to a list in the prefs, on quit RF loops over this list and deinstalls all fonts.
When RF crashes, it cannot deinstall those fonts. So the next launch detects those test installed fonts, a popup will appear and RF tries to deinstall them.
RoboFont tries to inform users as much as possible on issues happening in the background. Silent fixes are not the best solutions for many cases...
|
https://forum.robofont.com/topic/269/crash-with-testinstalled-font/
|
CC-MAIN-2019-22
|
refinedweb
| 139
| 75.91
|
Important: Please read the Qt Code of Conduct -
why when i want copy (with memcpy)struct array to char array , character array is null??
- stackprogramer last edited by kshegunov
why when i want copy (with memcpy)struct array to char array , character array is null??
#include <iostream> #include <string.h> using namespace std; int main() { struct group{ int num=1; int age=2;}; struct group a[17]; int m = sizeof(a); char b[200]; memcpy(&b[0],&a,sizeof(a)); cout << "Hello World" <<n<< " "<<m<<endl<<"b='"<<b[2]<<"'--"<<endl; return 0; }
you can see that output is null, why we can not copy struc array to char array??
thank in advance
sh-4.2$ main Hello World 136 b=''--
[Moved to C++ Gurus ~kshegunov]
- mrjj Lifetime Qt Champion last edited by
What are u trying to do ?
The list (group) is structs and you try to copy a struct to one char ?
That can never really work. It won't fit.
The struct is 2 ints and how would that fit into one char `?
Can you explain what you want b (array) to be ?
- stackprogramer last edited by
@mrjj thanks
i want to copy struct to char array not one char ....
i want to use this for send on udp socket. new array char is send for other ip with this binary form,
i don't want to use Qbytearray, i should only use char array, i am strict on this method.
to add to @mrjj you got a couple of issues to observe.
- byte order
- size of int
- byte alignment
In your case you are running into the byte order issue, I guess. This is dependent on processor you are using. The size problem depends on the OS and compiler. Also there is the byte alignment which changes the size of your structure. When you are using a 64 bit compiler you might problems with the size of b.
- jsulm Lifetime Qt Champion last edited by
@stackprogramer Instead of hacking around with low level stuff you should take a look at
@stackprogramer
You well understand what memcpy does?
memcpy(str2, str1, 10);
The above line copies the first 10 characters of str1 to str2.
|
https://forum.qt.io/topic/80200/why-when-i-want-copy-with-memcpy-struct-array-to-char-array-character-array-is-null
|
CC-MAIN-2021-43
|
refinedweb
| 366
| 81.02
|
RationalWiki:Saloon bar/Archive39
Contents
- 1 New study gives insight into the power of minority extremists
- 2 Lexicon
- 3 Curling up in a ball and crying for the future of humanity
- 4 Not cool
- 5 Books
- 6 Humorous BON wandalism
- 7 Has this come up yet?
- 8 Griffin on Question Time
- 9 WND poll fun
- 10 Logic dictates that all WIGOs should be consolidated into a singular portal
- 11 Death penalty or not?
- 12 Vodka is for drinking, not for...
- 13 Selling water
- 14 Teh flood gates are Breaking. ORLY?
- 15 Bryan college
- 16 Oh boy, this is a good one.
- 17 Scienceblogs is down
- 18 RandomSelection
- 19 Monty Python on Jimmy Fallon
- 20 Time travel
- 21 Snoring is deadly
- 22 Anyone seen this nutball shit?
- 23 Too many YouTube transclusions?
- 24 Body piercing
- 25 Who's good with Spanish?
- 26 Faux News Comments
- 27 I want one of those
- 28 Last minute holloween costume ideas
- 29 Naked Man Arrested in his own home
- 30 Can I be a Sysop?
- 31 Quote
- 32 Daily Telegraph
- 33 one month down
- 34 Copyright backwards?
- 35 Sic transit gloria GeoCities
- 36 And now for something completely different
- 37 Oh dear
- 38 I've been looking at this for two days now
- 39 Need Help on Article of the Weak
- 40 My PC is more liberal than me
- 41 The mostly harmless criteria for sysops
- 42 Vandal
- 43 Constructive Mouse Wiggling
- 44 Taking a break
- 45 Google needs to be dissappeared next.
- 46 Random WIGO poll idea:
- 47 Jinx's blog
- 48 Conspiracy Theory Rock!
- 49 Browsers flamewar below this line
- 50 Ares
- 51 Old Catholic Church
- 52 New editors
- 53 BBC Encapsulates RW
- 54 Flower
- 55 Trials
- 56 Music
- 57 Deal or No Deal Australia psychic challenge
- 58 MJ
- 59 Anyone else heard this?
- 60 Creationists are really bad at strategy
- 61 Quick Q
- 62 Ethics
- 63 The blackleg graduate student?
New study gives insight into the power of minority extremists[edit]
"Moderately conservative people who belong to the Republican Party, for example, may believe that people with extremely conservative views represent their party, because those are the opinions they hear most often. However, that may not be true." Interesting article about a study conducted by smoking-hot Kimberly Rios Morrison of Ohio State University. 17:31, 22 October 2009 (UTC)
- "People with relatively extreme opinions may be more willing to publicly share their views than those with more moderate views." Uh, when did this reporter start channelling Captain Obvious? ListenerXTalkerX 17:34, 22 October 2009 (UTC)
- Doesn't seem that obvious to me - I would expect the more extreme to keep their traps shut, in general. Of course, the last 30 years of US politics has encouraged the most extreme on the right, at least, to trumpet their views far and wide. ħuman 20:23, 22 October 2009 (UTC)
- It seems to come down to people being more comfortable sharing their views if they believe that there is a significant number of people sharing those views. Presumably that would also apply to people with moderate views, although extremists are a bit easier to notice. --Ask me about your mother 20:32, 22 October 2009 (UTC)
Lexicon[edit]
Reading All the President's Men again, and I got to thinking - what a good thing it took place at the Watergate. We'd look a bit silly referring to scandals as "Iran-Park Hyatt" or "Travel-Holiday Inn". --PsygremlinPraat! 17:47, 22 October 2009 (UTC)
- The "gate" meme is quite handy to tack onto scandals (It's not just the internet, MC). I was watching some of those New World Order conspiracy videos on YouTube recently and evidently the Watergate Hotel is owned by the Catholic Church or perhaps the Illuminati. Lily Inspirate me. 17:59, 22 October 2009 (UTC)
Curling up in a ball and crying for the future of humanity[edit]
co2isgreen.net YorickIs Joe Biden Eva Braun? 18:34, 22 October 2009 (UTC)
- Don't give up hope yet. It might be a Poe. Tetronian you're clueless 21:18, 22 October 2009 (UTC)
- No, it ain't a Poe. Notice all the earnest stuff urging readers to write to Senate about it. See also this blog/report in the Guardian. Unsurprisingly the "CO2 is Green" group is founded & funded by carbon fuel industry fatcats, & it's applying for tax exempt status. We should probably have an article on it at RW if we don't already. ŴêâŝêîôîďMethinks it is a Weasel 22:19, 22 October 2009 (UTC)
- In that case, I weep for our future as well. Tetronian you're clueless 22:31, 22 October 2009 (UTC)
- At first I thought it was a Poe because it read like something I would make up with my friends. Then I realized that they were actually advertising on the television and billboards where I live. I can only hope there are not enough gullible people to believe this, but living in Montana I know that is a pipe dream. YorickSounds sexy on the telephone 04:00, 23 October 2009 (UTC)
- It's amazing that people still can't get their heads around very simple facts. YES, CO2 is "the food of the planet, dontchaknow" and I'm yet to come across any biologist that says it isn't very important. But pizza is also a nice food for a human; and if you stuff your face with enough pizza you die. Same principle; more of something good isn't necessarily better. Really, is this actually that difficult to grasp? theist 11:47, 23 October 2009 (UTC)
Not cool[edit]
After a botched firmware upgrade, my router was sitting there flashing at me. Don't ask me how I stuffed it up, I don't really know what I could have done wrong, these Netgears are usually pretty good with upgrades. Anyway, I did the factory-reset thing which got it to work again for some reason; whatever the stuffup was, it can't have been too bad because I don't have a paperweight instead of a router.
The downside of my router working again was that in the face of "oh em gee, I'm gonna have to shell out $100 for another one", I forgot to secure my wifi after the reset. Wonderful, I'm only about ten days into my cycle and I've already had all my bandwidth leeched. Now I get to spend the rest of the cycle on a 64k shaped connection. Lovely. -RedbackG'day 20:25, 22 October 2009 (UTC)
- Meh, I guess you'll have to put up with pr0n that doesn't move until the end of the month. Can't you just go and beat up all your neighbors who nicked your bandwidth? CrundyTalk nerdy to me 11:54, 23 October 2009 (UTC)
Books[edit]
Has anyone read Snake Oil 101? I came across it on Amazon and wondered if it was any good. Lily Inspirate me. 20:31, 22 October 2009 (UTC)
- Seems an odd topic for an author who writes mostly about art. Aboriginal Noise What the ... 21:17, 22 October 2009 (UTC)
Humorous BON wandalism[edit]
Are they trying to send us a secret message? ħuman 23:31, 22 October 2009 (UTC)
- Is that the random junk appearing from a range of IP addresses? Been wondering if it's even worth vandal binning them, since I assume they're hitting proxies or using Tor, so probably not worth playing whack-a-mole with them? --Ask me about your mother 23:34, 22 October 2009 (UTC)
-
- I figured those were some kind of bot, since they were inserting random nonsensical messages that looked like they had been cut and pasted from various websites. Tetronian you're clueless 23:52, 22 October 2009 (UTC)
- On second thought, maybe not. Tetronian you're clueless 00:37, 23 October 2009 (UTC)
Has this come up yet?[edit]
I am having trouble tracing this story to get down to whats going on. tmtoulouse 07:00, 23 October 2009 (UTC)
- Just sounds like the anti-vaccination crowd jumping on anything they can get their hands on. theist 11:39, 23 October 2009 (UTC)
- Also, speaking of vaccines. Someone forwarded this to me. Wondering what people think about it. The Cochrane Review that it cites can be found here - I find it noteworthy that, despite mentioning it and extensively citing the author as proof that vaccines are a "cult-like" scam, they didn't link to it even though they have linked to a few other things (although these are glorified adverts for someone's book). theist 13:08, 23 October 2009 (UTC)
Griffin on Question Time[edit]
Discussion here by the looks of it... SJ Debaser 11:56, 23 October 2009 (UTC)
WND poll fun[edit]
From here. Ok, so the charge is to "[s]ound off on Sunstein's call to abolish government sanctioning of marriage". What I would consider the "libertarian" option ("Marriage is a personal commitment - government has nothing to do with it") is sitting at 4%. The backwards-ass, anti-libertarian, fear mongering option ("A strong institution of marriage and family is an antidote to nanny-state government - no wonder Sunstein wants it marginalized" - i.e., stop the government nanny-state with government nannying) is the clear winner. I absolutely love these people. — Sincerely, Neveruse513 / Talk / Block 12:57, 23 October 2009 (UTC)
- Hmmm... attacking WND with a vote bot would be sooooo worth it. Immoral and wrong, but certainly worth it. theist 13:03, 23 October 2009 (UTC)
- It's crossed my mind. You could probably get a mention on the front page out of it too. — Sincerely, Neveruse513 / Talk / Block 13:09, 23 October 2009 (UTC)
- Actually, on second thoughts, the last thing we need is adding fuel to the persecution complex fire... Still, one might just be worth it. theist 13:17, 23 October 2009 (UTC)
- I don't know if their persecution complex could get worse. "Soundoff: What do you think of internet terrorists' attempts to silence conservative free speech?" Can you imagine the options? — Sincerely, Neveruse513 / Talk / Block 13:22, 23 October 2009 (UTC)
Logic dictates that all WIGOs should be consolidated into a singular portal[edit]
- This discussion was moved to RationalWiki:Proposed WIGO merger. - π 11:10, 24 October 2009 (UTC)
Death penalty or not?[edit]
Posted this on Aces page but thought it could be of greater interest. Its 17 pages but well worth a read. Rad McCool 09:31, 22 October 2009 (UTC)
- All civilised countries have stopped using the death penalty. Bob Soles 09:57, 22 October 2009 (UTC)
- <reads article> Whelp, fuck. --YossieSpring in Fialta 16:40, 23 October 2009 (UTC)
Vodka is for drinking, not for...[edit]
10 things vodka is good for besides drinking--Thanatos 02:29, 23 October 2009 (UTC)
- Whatever you're linking to isn't there anymore. ŴêâŝêîôîďMethinks it is a Weasel 18:50, 23 October 2009 (UTC)
Selling water[edit]
Round the Horne on BBC7 (Repeat from 1967! repeated @ 12:00 & 19:00 today) had a skit on the ridiculous idea of selling water on TV ads. If they could see it now! I am eating & honeychat 08:20, 23 October 2009 (UTC)
- Oh bona! Mr Horne, bona. I listened to RTH with my parents when I was too young to really appreciate the late, great Kenneth Williams. Bob Soles 11:26, 23 October 2009 (UTC)
- Ditto. That and the wonderful Jest (or was it just?) a Minute. PsygremlinSermā! 11:30, 24 October 2009 (UTC)
- Just A Minute is still going on (and on, and on...). ГенгисRationalWiki GOLD member 11:40, 24 October 2009 (UTC)
Teh flood gates are Breaking. ORLY?[edit]
Star Dentist ORLY TAITZ Pulls a Andy.
You can see that the Google search shows 4,390,000 articles about omnipotent current speaker of the House Nancy Pelosi and 4,550,000 articles about Eligibility attorney Orly Taitz. They can’t hold the line, the flood gates are broken, the truth about Obama’s illegitimacy to presidency is pouring into main street, the public is rising against this puppet of the Wall street, against the Kenyan usurper, the minutemen are rising.
Boy, If CAPS LOCK DAY ever need a mascot...
- Why does she refer to herself as Orly Taitz Esquire? I was brought up that Esquire was the male form of Miss. Bob Soles 14:02, 23 October 2009 (UTC)
- It's what some very pretentious lawyers call themselves. Andy does it, too. — Sincerely, Neveruse513 / Talk / Block 14:04, 23 October 2009 (UTC)
- I believe it's a US thing as I've never seen it in the UK and the only people who seem to use it are lawyers when writing to their clients (in my experience). Originally I thought Any was just being pretentious when he put Esq. after his name but looking it up on Google it appears to be general practice for US legalites. I followed up on that as one of the things that my father taught me was not to use pretentious titles. One of his pet hates was people who insist on being called "Mister" or introduce themselves as "Mister Smith" as if mister was something special. Consequently I always give my full name when people ask rather than saying "Mr. Khant". ГенгисRationalWiki GOLD member (Mr.) 18:23, 23 October 2009 (UTC)
- I think it's just considered pretentious and vulgar to use that sort of thing unnecessarily in the UK. Hence why we were all "Andrew Schlafly Esq.' WTF?" And of course, people only use them when they know they're meaningless, hence why very few Profs or Docs use their titles unless they come from diploma mills and just want to sound fancier than they are. theist 19:53, 23 October 2009 (UTC)
Bryan college[edit]
Just glancing at this place ('cause that's where this guy went) and I'm reminded of:
- "I'm not applying there."
- "Why not?"
- "I looked at the prospectus & there's not a black face to be seen."
- "Hadn't realised you were so principled!"
- "Oh, it's not principles; but I wouldn't go to a place that can't afford Photoshop."
Was it someone on here who said it or have I read it elsewhere on t'web? I am eating & honeychat 18:30, 23 October 2009 (UTC)
- In their revolving header gallery (3 of 8) there is a fairly attractive lady of colour. Tokenism? ГенгисRationalWiki GOLD member 18:43, 23 October 2009 (UTC)
- I must have a blind spot: I'm still not sure she's not white. (could almost be a young me!) I am eating & honeychat 18:47, 23 October 2009 (UTC)
- She ain't white. But she's real fine. 18:49, 23 October 2009 (UTC)
- I guess they could have found someone with darker skin-tone. ГенгисRationalWiki GOLD member 19:10, 23 October 2009 (UTC)
- I suspect any place with a bullshit major such as "origins studies" might have diversity issues. Sterile alpaca
Oh boy, this is a good one.[edit]
For the Star Wars fans among us... ĴαʊΆʃÇä₰ Reticulating splines 04:20, 24 October 2009 (UTC) [1]
- Forgive me if I don't roll on the floor in fits of laughter, I guess it must be an age thing. (From someone who saw Star Wars on its first release at the Odeon, Leicester Square.) ГенгисRationalWiki GOLD member 07:00, 24 October 2009 (UTC)
Scienceblogs is down[edit]
Anybody know what's happening? Corry 14:55, 24 October 2009 (UTC)
- Aren't they upgrading because of problems with the commenting? - π 14:56, 24 October 2009 (UTC)
RandomSelection[edit]
I've modified Extension:RandomSelection (the <choose> thing) so that it doesn't disable the cache. This means that random stuff will remain the same until you purge the cache of a page. Your signatures will still work as expected (see this), but they won't change when you refresh the page (unless someone else has edited or purged the page). For cases when you want a refresh to produce a new random option, you can use the uncached parameter (e.g. the casino). -- Nx / talk 18:43, 24 October 2009 (UTC)
Monty Python on Jimmy Fallon[edit]
I just realized no one mentioned this and I thought some might enjoy - 4 of MPFC (Jones, Gilliam, Cleese, and Idle) on Late Night With Jimmy Fallon from 10/14/09. [2] If parts 2-4 don't come up in the related videos box, I think just changing the "part-1" in the url will keep things moving. ħuman 23:22, 24 October 2009 (UTC) Nope: [3] [4] [5] are 2,3, and 4. Two more links in a moment... ħuman 23:33, 24 October 2009 (UTC)
- I'll have a looksee at this tomorrow. How come Michael Palin wasn't on? It's so sad Chapman died cuz - apart from the fact he was still very young - he was probably my favourite if I had to pick one. SJ Debaser 23:37, 24 October 2009 (UTC)
- EC) Recently read Graham's biog. Happy & sad all in one. I am eating & honeychat 23:37, 24 October 2009 (UTC)
- @ Super: apparently Palin & Cleese aint the best of mates. I am eating & honeychat 23:38, 24 October 2009 (UTC)
- Ah, that's a shame. I just looked at the first video briefly and JEEE-ZUZ, Eric Idle looks nothing like in the shows (although the first one was broadcast forty years ago). SJ Debaser 23:41, 24 October 2009 (UTC)
- Palin was travelling, pity that. Wheel of Carpet Samples part one [6] part two [7]
in a bit. There's also some Bright Side of Life [8] bit to come. These are pigs, they load slowly, but I couldn't find better BW versions at utoob. ħuman 23:55, 24 October 2009 (UTC)
- There was a documentary (called Monty Python, the Lawyer's Cut) shown on IFC all week about MP, so 1 hour a night I was in heaven (figuratively). They'd follow up each episode of the doc with either Holy Grail, Life of Brian or Live from the Hollywood Bowl. Good stuff. Aboriginal Noise What the ... 01:08, 25 October 2009 (UTC)
Time travel[edit]
It's one AM; in an hour it'll be one AM. That is all. I am eating & honeychat 00:00, 25 October 2009 (UTC)
Snoring is deadly[edit]
So I was reading Fox news (I often do to get a dose of "OMG OBAMA MARXIST COMMUNISIM!") and came upon this. If Fox were really really a news website would they have side banners for this kinda crap? AceMcWicked 01:37, 25 October 2009 (UTC)
- The snoring thing? Are you saying they had an ad up for it? As much as I hate to defend them, online news sources do have to pay for themselves somehow.--Mustex 13:24, 25 October 2009 (UTC)
- Keep in mind Ace, we used to have ads for all sorts of madness before Trent stopped using them. Cubic educated Hoover! 13:46, 25 October 2009 (UTC)
- Sneezing is also deadly. Totnesmartin 14:25, 25 October 2009 (UTC)
Anyone seen this nutball shit?[edit]
I know Ann "Horse-Face" Coulter is a loon but this takes the cake...AceMcWicked 21:50, 23 October 2009 (UTC)
- John Wilkes Booth was hardly a liberal. Timothy McVeigh belong to a far-right Christian Identity movement. - π 22:15, 23 October 2009 (UTC)
- Who was the guy who shouted her down and said "YOU are a hate crime"? I want to shake his hand and tell him that next time around he has my blessing to break her already deformed nose. If you want something deliberately inflammatory while simultaneously outright wrong, you can't go much further that that bitch. theist 11:05, 24 October 2009 (UTC)
- I know I'm in the minority on this, but I think its still somewhat open to interpretation whether or not Timothy McVeigh was a racist. Sure, he read and sold The Turner Diaries, but that book was a mixture of extreme racism and extreme anti-gun control, and there's no question he was against gun control. Also, according to his wikipedia page last time I checked they interviewed his family and former roommate who said he was pretty much indifferent to racial matters. Granted, he certainly wasn't marching for Civil Rights, but I'd be willing to buy that he was so anti-government that he just ignored everything else (still, that hardly makes him a "liberal").--Mustex 01:00, 26 October 2009 (UTC)
Too many YouTube transclusions?[edit]
I don't know what others think about this, but personally I think that YouTube transclusion thing is getting used waaayy too much here at the Saloon bar.
I can see its advantage in a few RW articles where a video is really relevant, but in the bar it's just seems like an attention-hogging waste of space. In a lot of cases the threads that start with a video don't provoke much of a discussion anyway (just look further up this page) but they take up more space on the page than a lot of other sections. Can't we go back to just posting links to YouTube?
Alternatively, just put one video up at the top of the page, as a kind of bar-room TV, and change the tape periodically evey few days. That way if people want to comment on it, they can start a discussion below, but if they don't, it would be easy to ignore, like the jukebox.
Any thoughts? ŴêâŝêîôîďMethinks it is a Weasel 10:12, 24 October 2009 (UTC)
- One YouTube transclusion is one too many. I am eating & honeychat 10:17, 24 October 2009 (UTC)
- I will never open this page on my phone or laptop. When I asked Trent to install this extension it was more to look at clogo and rebuttals on YouTube a la Banana fallacy. A link that says "check out this video here" is just as effective and doesn't cost us nearly as much CPU time and bandwidth. - π 10:25, 24 October 2009 (UTC)
- That was the original intention, but like any novelty feature, it'll get overused. Linking to YouTube is much better anyway as with the embedded things you can't use YouTube's features like ratings, comments or the "see also" bits. If some one wants to exercise AUTHORITA and cut them down, that's fine by me. theist 11:01, 24 October 2009 (UTC)
- I think you have a good point, links are the way to go. Javasca₧ sysop and 'crat! (does it matter?) 14:31, 24 October 2009 (UTC)
- I have exercised authoritae -- Nx / talk 14:59, 24 October 2009 (UTC)
- Ye gods, you'd think we were living in an age of 800bps modems, not an age where everyone wanders round with a 1.5Mbps+ broadband connection in their pockets. What exactly is the problem with putting a video on this page? I don't get it. The flash is always cached, so if you don't click play it doesn't take any time to load. --JeevesMkII The gentleman's gentleman at the other site 16:59, 24 October 2009 (UTC)
-
- I've never reached 500 kbs. I dream of a decent broadsband connection. I'm downloading a 863 MB file now - it's varying between 3 & 11 hours estimated. I am eating & honeychat 17:05, 24 October 2009 (UTC)
UTC)
- Of course when I was a lad we had it tough, my first modem was 1200/300 baud. (Does anyone even use that term any more?) ГенгисRationalWiki GOLD member 19:10, 25 October 2009 (UTC)
Let me see if I understand. Between me going to bed at maybe 130 this morning and staggering back from brunch someone managed to discern consensus of the mob and disable embedded YouTube videos. WHAT THE FUCK. Issues like this don't get raised and resolved within 12 hours. This is an issue that could much more effectively been dealt with by discussing a policy change rather than enforcing a small number of users' will by fiat and without anything even remotely approaching adequate consideration by the community at large. I agree that embedding videos should be done sparingly on high traffic pages for any number of reasons including those mentioned. But what I do on my userpage or post on my pals' talkpages is none of your fucking business. Don't like embedded videos or my taste in electro and hip hop? Ok then make a point of avoiding my userspace and Ace, Human, Rad, etc's talkpages. This situation was handled really poorly. 17:36, 24 October 2009 (UTC)
- It was on the saloon bar -- Nx / talk 17:49, 24 October 2009 (UTC)
Body piercing[edit]
While I am too old to really appreciate the aesthetics of pierced tongues/nipples/labia/foreskins/clitorises surely these vegetarians are just going way over the top. ГенгисRationalWiki GOLD member 19:26, 25 October 2009 (UTC)
P.S. Apologies for another Telegraph posting.
- It's not natural to eat animals, but it is to shove assault rifles through your cheeks? SJ Debaser 19:29, 25 October 2009 (UTC)
- I liked the dude with the coils of wire. ħuman 19:39, 25 October 2009 (UTC)
- I'd almost call Photoshop on the whole thing, but I've read enough issues of Bizarre to know that this shit really does happen. theist 20:10, 25 October 2009 (UTC)
- My word. If that's what the vegetarians get up to, I wonder what the vegans do?--BobNot Jim 21:39, 25 October 2009 (UTC)
- I've seen some pretty bizarre piercings before, but these are way more over-the-top than any I've seen in person. I'm pretty sure they aren't photoshopped, but....wow. Aboriginal Noise What the ... 01:02, 26 October 2009 (UTC)
Who's good with Spanish?[edit]
Hey, I'm a big fan of the Spanish version of Dracula (in 1931 it was cheaper to shoot 4 versions in different languages than to dub Lugosi's version, only the Spanish and English versions survive, and I think the Spanish version was better in every way), but I was wondering whether or not the Count speaks Spanish with an Eastern European accent. Based on these clips could anyone tell me? --Mustex 00:50, 26 October 2009 (UTC)
- It doesn't seem too out of line with the Spanish I usually hear, except when he says "Dracula". Aboriginal Noise What the ... 01:00, 26 October 2009 (UTC)
- I don't know if you are familiar with european Spanish as spoken in Spain but it sounds OK to me. It is perhaps a little over-articulated but I'd guess that that is in keeping with the times and the nature of the film. It would have been interesting to hear a few more of the other actors speaking in Spanish to see if they spoke in South American versions of Spanish.--BobNot Jim 07:50, 26 October 2009 (UTC)
Faux News Comments[edit]
I often read comments on Fox News stories in order to get angry/depressed/giddy with laughter. This one I found really takes the cake however..."Odumbo has nothing to offer so he resorts to this kind of smear. What else did you expect from an empty suit with a record of voting 'present'? Odumbo blows dead goats.". WTF? AceMcWicked 03:01, 26 October 2009 (UTC)
I want one of those[edit]
Also from the Torygraph - Dyson's latest invention, the bladeless fan. ГенгисRationalWiki GOLD member 19:28, 23 October 2009 (UTC)
- Fuck that asshole and his crazy-awesome inventions I can't afford. — Sincerely, Neveruse513 / Talk / Block 19:33, 23 October 2009 (UTC)
- Funny time of year to launch a fan. Aylesburymartin 19:36, 23 October 2009 (UTC)
- I saw that a while ago. Hasn't it got a fan in the base to give the airflow a start? "The Air Multiplier works by sucking in one unit of air at the base, and pushing it out at speed through a thin gap in the fan's ring." I don't think it's what it sort of claims to be. (bernouli(?) effect springs to mind)I am eating & honeychat 19:41, 23 October 2009 (UTC)
- Indeed, it seems like it changes the place where the fan actually is. It's not like it's some other mechanism such as a screw. Like the AirBlade, that wasn't really anything new, it was just a normal bloody hand dryer with the power cranked up to 11. theist 19:49, 23 October 2009 (UTC)
- He's really hung up about all this buffeting from a normal fan. I hope I don't start to notice it. — Sincerely, Neveruse513 / Talk / Block 19:51, 23 October 2009 (UTC)
- My (many) fans often buffet me, sometimes I can't walk down the street unbuffeted - bloody paparazzi. I am eating & honeychat 19:55, 23 October 2009 (UTC)
- If I can't have your autograph then you could at least throw me some crumbs. ГенгисRationalWiki GOLD member 19:07, 25 October 2009 (UTC)
Last minute holloween costume ideas[edit]
I need some. Preferably in the next 8 minutes. Thanks. — Sincerely, Neveruse513 / Talk / Block 21:24, 23 October 2009 (UTC)
- Last year my 11th hour Halloween costume, believe it or not, was Alger Hiss. I just dressed as 50's as possible (suit, thin tie, fedora, cigarette) and wrote CONFIDENTIAL on a manila folder with random papers in it. Some people actually figured out who I was.
- I was really hammered before going to this halloween party a few years back, cant remember what I on but I remember hunting around my bedroom (which was a fucking nightmare of mess) and ended up grabbing some of the filthy porno I had lying around and tying it to my chest with a network cable. My costume - Internet Porn. Thought it was pretty clever for guy who was barely functioning. AceMcWicked 21:33, 23 October 2009 (UTC)
- Is a sheet with a couple of eye-holes too obvious? Lily Inspirate me. 22:16, 23 October 2009 (UTC)
- Hey, you don't want to show up at the party in the same outfit as Ed Poor. 23:42, 23 October 2009 (UTC)
- I'd go with the lost camper. Some dirty jeans, a dirty coat, a hat and a flashlight, maybe a little fake blood and your all set--Thanatos 22:58, 23 October 2009 (UTC)
- Hype how you will be a ninja, or a pirate or a hacker or some shit, then come dressed as a Catholic cardinal. When people start going WTF?, scream at them "NOBODY EXPECTS THE SPANISH INQUISITION!!!111!1!1!". Lulz should insue if British people are nearby --The Emperor Kneel before Zod! 03:04, 24 October 2009 (UTC)
A sheet with three holes - one at the crotch. You're an Orthodox Jewish rapist ghost.--Tom Moorefiat justitia 03:39, 24 October 2009 (UTC)
- Last year I shaved my head, added some fake blood to my forehead, and became GG Allin. This year I'm trying Captain Lou Albano. Couple of rubber bands, a Hawaiian shirt, and a graying wig. Aboriginal Noise What the ... 14:49, 25 October 2009 (UTC)
Naked Man Arrested in his own home[edit]
I know that I've made it pretty clear I think theamazingatheist is a jerk (I'm not alone, anon's targetted him too), but this is one of his good videos, and it makes a good point about how ridiculous this is: --Mustex 01:08, 25 October 2009 (UTC)
- Nudity is generally overrated. It's the covering up that exacerbates and emphasises the effect of nakedness. On a nudist beach where everyone is naked then nobody gives a damn. In fact the sight of most people naked is distinctly nonsexual. All that Adam & Eve with their fig-leaves crap only serves to draw attention to nakedness when it's the most natural thing in the world. Humans are born naked, and every other creature on this planet is naked for their entire lives, yet somehow our societies have inculcated the belief that this is a "bad thing". Bollocks! - from someone who occasionally also wanders around the house au naturel. ГенгисRationalWiki GOLD member 19:55, 25 October 2009 (UTC)
- Interesting actually. When did nudity start becoming unacceptable? Is there even anywhere in the Bible which condemns it? I've never read it. SJ Debaser 20:01, 25 October 2009 (UTC)
- This is another one on the subject. Probably the funniest thing Argumental has done yet. theist 20:16, 25 October 2009 (UTC)
- SuperJosh asks: When did nudity start becoming unacceptable? Is there even anywhere in the Bible which condemns it? Nudity probably became unacceptable when people started to get cold after leaving Africa. In some nice warm countries nudity only became unacceptable when European missionaries told them it was sinful. According to the hallucinations of some bronze age shepherds Adam and Eve became ashamed of their nakedness after being convinced to eat an apple by a talking snake.--BobNot Jim 21:34, 25 October 2009 (UTC)
- I generally don't like being naked in my own home, partially because I don't like being reminded of my love handles, and partially because I have a somewhat irrational fear of anything sharp/rough coming into accidental contact with my genitals.--Mustex 00:54, 26 October 2009 (UTC)
- I loathe nudists with a deep passion. Genitals flopping everywhere. MarcusCicero 10:42, 26 October 2009 (UTC)
Can I be a Sysop?[edit]
Any of you cunts want to make me a sysop? MarcusCicero 10:21, 26 October 2009 (UTC)
- Given your penchant for deleting stuff when you're angry, perhaps not. I did it once but I think I got away with it Totnesmartin 10:29, 26 October 2009 (UTC)
- When have I deleted stuff when angry? MarcusCicero 10:40, 26 October 2009 (UTC)
- Having a potty mouth shouldn't stop you being a sysop - but it does. Bob Soles 10:42, 26 October 2009 (UTC)
- My potty mouth is tongue in cheek. Cunt. MarcusCicero 10:43, 26 October 2009 (UTC)
- Umm... no. --Edgerunner76Your views are intriguing to me and I wish to subscribe to your newsletter 12:00, 26 October 2009 (UTC)
- You can't. But your brother could if he wanted. RaoulDuke 12:50, 26 October 2009 (UTC):Get a fucking life MarcusCicero 13:01, 26 October 2009 (UTC)
- Honestly, I don't see the harm in letting MC be a sysop. Then we could block him to vent our frustration. ...and now you're all going to think I'm a sock of his... Tetronian you're clueless 12:53, 26 October 2009 (UTC)
- I think it'd violate the "mostly harmless" rule. But then again, there's nothing a sysop can actually do to irrevocably bork the wiki. theist 12:55, 26 October 2009 (UTC)
- Apart from deep burning stuff. CrundyTalk nerdy to me 12:58, 26 October 2009 (UTC)
- Why would I 'deep burn' stuff? Thats just hysteria. MarcusCicero 13:01, 26 October 2009 (UTC)
- All deletions are observable and reversible by sysops, there's no such thing as "deep burn". The only trouble that can happen is when you delete pages with lots of revisions as that causes a slight issue and you need one of Nx's special restore scripts. theist 13:14, 26 October 2009 (UTC)
- Can these scripts reverse a situation where someone deletes a page and replaces it with a new page, thereby wiping the change history? CrundyTalk nerdy to me 13:32, 26 October 2009 (UTC)
- That's not how page deletion works. Cubic educated Hoover! 13:43, 26 October 2009 (UTC)
- Crundy goes off to try it CrundyTalk nerdy to me 14:15, 26 October 2009 (UTC)
- Ah, OK, you do get a "View or restore 3 deleted edits?" after restoring the page, so the data isn't lost. Fair do's CrundyTalk nerdy to me 14:20, 26 October 2009 (UTC)
- I'm convinced that I did something by accident once involving page moves, renaming and deleting (in some order) which could only be recovered by Trent going back to the database - and even then a little bit was lost. But I can't remember the details.--BobNot Jim 14:37, 26 October 2009 (UTC)
- I'm throwing in my hat to have Bob desysopped, considering these questionable practices leading to deep burns, topped off with selective memory about the details to prevent it. I sense danger. — Sincerely, Neveruse513 / Talk / Block 14:43, 26 October 2009 (UTC)
Why would you want to be a sysop? It's boring. I've been a sysop for s while, perhaps a year, and I've only had cause to use my powers once and that time there were a horde of other sysops on hand to quell the vandal. Me!Sheesh!Mine! 13:28, 26 October 2009 (UTC)
Make him a sysop. — Sincerely, Neveruse513 / Talk / Block 13:33, 26 October 2009 (UTC)
- Yeah, give him another chance, and if he goes on a rampage then block him forever. CrundyTalk nerdy to me 14:20, 26 October 2009 (UTC)
- I've given MC the change. I've never had a problem with MC to be honest so he has my trust, as well as, from what I can see, the trust of a few others. So long as he stays on the meds and doesn't dick about, I'm more than happy to add him to the sysop list. theist 14:50, 26 October 2009 (UTC)
- "The Change"? When do the hot flushes start then?
Make that man a sysop like everyone else. Lots of knicker-twisting here, with the usual histrionics from the usual quarters. Its just a fucking webshite. Let him play too. If he fucks the place up, promote him back to user. What's so complicated about that? DogPMarmite Patrol 23:19, 26 October 2009 (UTC)
- Currently, he is. If we had just made him on and left it at that... Broccoli 23:21, 26 October 2009 (UTC)
- I
conquerconcur with DogP. Let him have his powers as long as he doesn't abuse them. Fucking hell, didn't we even demote RobS at one point? DickTurpis 23:54, 26 October 2009 (UTC)
- I'm sorry, but are all you people fucking insane? For one thing, it always used to be the case that we'd never demote someone who asked to be demoted. That's an almost sure sign they're up to no good. Secondly, don't you fuckers remember what happened last time it was decided MC was mostly harmless? As if it isn't bad enough we have to put up with this little wankstain wandering around abusing people and fucking up articles, now you want to make him a sysop? For your next trick, will you be swallowing some live grenades? --JeevesMkII The gentleman's gentleman at the other site 06:24, 27 October 2009 (UTC)
- Lol. I love Jeeves. RW wouldn't be the contradiction in terms it is without him. And I must also give thanks to my fellow Irishman DogP. I go out of my way not to rile him (Out of some twisted kind of national loyalty) and it looks like he shares my vision of this place. Lookit, Jeeves is pathetic, let him whinge all he wants. There are two kinds of people on this place - liberals and autocrats. Ace, Jeeves, Susan, Thedictator, TOP, and Edgerunner are the autocrats. Ardmonikov, DogP, Genghis, Bob, Human and Broccoli the liberals. I'll write a book about it all some day. P.S- I still look at Jeeves mark one every so often. That parting shot is simply the most innane in the history of the internet. 'leaving and never coming back' is such an old trick but highly effective in notching up the drama levels. pity he came back though. 134.226.1.234 13:25, 27 October 2009 (UTC)
- Seriously MC fuck off. Everyone you have listed has contributed more to this place in one afternoon than you have with all your bullshit and whining. I don't care what you get, you are too big of an ignoramus to actual be able to do anything destructive with it any way. With all your bluster you have done nothing more than annoy a few people and that is all you are capable of. As far as I can tell you are still having a cry that Susan said religion is bullshit and you got your little feelings hurt. Well boo fucking hoo. You can dish it out but when someone insults something you believe in you act like a petulant child. - π 13:35, 27 October 2009 (UTC)
- Something I believe in? Do you really think I'm a conservative Christian? I wouldn't expect a bigot to understand the difference between finding bigotry horrible because its bigotry, and finding bigotry horrible because its personally offensive. 134.226.1.234 13:45, 27 October 2009 (UTC)
Quote[edit]
Heh, I'm liking this from David Thorne's twitter feed:
"Creationists and Intelligent Design advocates are the same thing. Like a clown and a clown carrying an umbrella."
Can we add it to the ID page somewhere? CrundyTalk nerdy to me 14:32, 26 October 2009 (UTC)
- I've added it to the ID article as it wasn't totally overrun by quotes anyway (I like quotes, but one or two of our articles do it too much). I think it works well. Like "ID is creationism in a cheap suit" which I think is Dawkins but it may have its origins elsewhere. theist 14:39, 26 October 2009 (UTC)
Daily Telegraph[edit]
For those who do not read the non-CP WIGOs there is a new one in WIGO:Blogs which is pretty much culled from our series on Internet Laws. We get a few linkbacks for some of them (but not all, even for those which are RW specific). ГенгисRationalWiki GOLD member 19:07, 23 October 2009 (UTC)
- 4 links in one article ain't bad. If any Telegraph readers come here though they'll probably have adverse reactions. I am eating & honeychat 19:22, 23 October 2009 (UTC)
- Good point... Tell 'em Telegraph "CRICKET!!!" theist 19:33, 23 October 2009 (UTC)
- Who the hell was Rob Pommer? Cubic educated Hoover! 19:40, 23 October 2009 (UTC)
- Cracker? theist 19:47, 23 October 2009 (UTC)
- @toast:If any Telegraph readers come here though they'll probably have adverse reactions - but at least they'll know how to make tea properly. Totnesmartin 20:03, 23 October 2009 (UTC)
- Can we have a wikipedia article now? AceMcWicked 21:12, 23 October 2009 (UTC)
- I dare someone with some street cred on WP to suggest that. Cubic educated Hoover! 21:29, 23 October 2009 (UTC)
- I was thinking the same thing, but remember the guys who were mostly against it (and Poe's Law) were pretty much all over it and had Trent banned for a week or something. I'm liking the comments, that one from "Steve Foley" is either taking it all too seriously (in which case I pity them) or trying to take the piss out of people who take it seriously (and failed, thus I still pity them). Still, some of the other proposals are pretty good. theist 11:46, 24 October 2009 (UTC)
- I love the fact Ken is now internationally famous. - π 12:18, 24 October 2009 (UTC)
- I let him know on his aSoK talk page. ГенгисRationalWiki GOLD member 12:36, 24 October 2009 (UTC)
- Aha, he responded. ГенгисRationalWiki GOLD member 11:05, 25 October 2009 (UTC)
- We need to get an article on Skitt’s Law. - π 13:01, 24 October 2009 (UTC)
- To be fair, I think WP's notability guidelines suggest that a site has to be the subject of an article. Still, an article like this clearly shows we're on the right track. Dreaded Walrus t c 08:24, 25 October 2009 (UTC)
- It probably isn't notable enough. Though, I notice that I really can't find any proper references to this "poetry" one that the guy who shoved it out of the WP article put in. It's certainly not commonly used. A few people in recent months have been like "oh, it's Poe's law about Edgar Allen Poe" but I'm convinced this is because for the last few months WP has topped RW on the Google search, and of course, WP has refused to acknowledge "our" Poe's Law (well, strictly, one of the admins on a power trip and a vendetta against Trent refused to let it in, I'm also partly convinced its the same guy who wandalised the article with the "stupid atheist blogs" comment). theist 08:38, 25 October 2009 (UTC)
<(UD) I guess most people haven't bothered to revisit this article but I notice that now there are two posts from PJR and one from TK. The PJR ones look genuine but is the TK one a parodist? ГенгисRationalWiki GOLD member 19:04, 25 October 2009 (UTC)
- Damnit, I wanted to add my own but the comments system seems to be broken now. Crundy's law: The aggressiveness and unreasonableness of an internet poster is inversely proportional to their grammar and spelling skills. CrundyTalk nerdy to me 12:34, 27 October 2009 (UTC)
- The list has made it to Pharyngula now too. –SuspectedReplicantretire me 14:06, 27 October 2009 (UTC)
- If PZ coins his own law we'll have to have it immediately! You know, posterity and all that. theist 14:12, 27 October 2009 (UTC)
- Lol: "Cole's Law: Thinly sliced cabbage." CrundyTalk nerdy to me 21:38, 27 October 2009 (UTC)
one month down[edit]
I moved into my university accommodation four weeks ago today. Fortunately, we all seem to get along and have avoided killing one another so far. As for the following 7 months, only time will tell... SJ Debaser 19:00, 24 October 2009 (UTC)
- I've already started making plans for extreme revenge pranks. Broccoli 19:03, 24 October 2009 (UTC)
- Halloween next weekend. That'll be fun. The one girl in our house (technically there are two, but the other one never hangs out with the us) is one of those scaredy-girls, so freaking her out should be easy but highly entertaining. She'll probably try and strangle me in my sleep however. SJ Debaser 19:14, 24 October 2009 (UTC)
- Yeah, my friend had a kinky girlfriend who used to do that to him as well. CrundyTalk nerdy to me 21:01, 25 October 2009 (UTC)
Ok, I have a question concerning copyright laws that occurred to me when I was considering the name "Alucard" ("Dracula" spelled backwards). Ok, for those of you unfamiliar with the name, it originated in the movie "Son of Dracula" in the 1940s, starring Lon Chaney Jr. as Count Dracula, who used the name as a pseudonymn (if you're curious, the movie itself was somewhat confusing about whether he was merely A Count Dracula, and the son of the original Universal Dracula, or THE Count Dracula in a different continuity. He was simply called "Count Dracula" in the film, and the title seems to either be a holdover from earlier drafts of the script, or the result of some scenes being cut. Production was so rushed during this era either is believable). In the last three decades "Alucard" has shown up in several works as either a traveling name Dracula uses (The Batman vs Dracula and arguably Hellsing), or the name of Dracula's son (Castlevania).
Now, here's my question: The novel Dracula is in the public domain, the movie Son of Dracula is not. Is the name Alucard in the public domain, or do these works have to pay royalties?
I could honestly see it going either way. On the one hand, the movie was the first time the name Alucard was used, but at the same time how could it be copyright infringement if in a Dracula-based work Dracula merely said "I can't use my real name...I'll just reverse it!" and his name reversed just happened to be the same as the name Universal used? Furthermore what if, for some inexplicable reason, someone decided to publish the book Dracula with all the text backwards so people could read it in the mirror (not saying it would be logical, just arguing legality here)? "Alucard" would be printed in the book over and over again because its "Dracula" backwards?
I could maybe see the argument that if a character named "Alucard" was Dracula's son (as in Castlevania) it would be copyright infringement, but then what if the son uses it as a pseudonymn, or its a cousin or nephew?--Mustex 00:21, 26 October 2009 (UTC)
- I'd say it's no big deal. In Helsing, the main character is a vampire named Alucard, but is really Dracula. A name is hard to copyright. Two of my past usernames were those of anime characters (Tabris and Nate River). Characters can be copyrighted, but I do not believe names can be.--Thanatos 01:13, 26 October 2009 (UTC)
- Well, yeah, but I don't think your user names are a very good example, since you weren't deriving a profit from them.--Mustex 01:37, 26 October 2009 (UTC)
- True, but you mentioned both Castlevania and Helsing. They both use the name Alucard, and they make profits. Alucard is a name tied to Dracula, will always be associated with Dracula, but not exclusive to that one movie. Someone might have used the name Alucard before that.--Thanatos 03:18, 26 October 2009 (UTC)
- Yes, but I was guessing that they might just pay royalties.--76.18.115.64 14:08, 26 October 2009 (UTC)
- And having been on a Star Trek forum (*shudder*) where everyone is fighting over who gets the username Captain Kirk, I can tell you that usernames really can't break copyright very easily. And of course, just mentioning or using something doesn't necessarily violate copyright - for instance, Space Marine is copyrighted by Games Workshop, but it doesn't stop people using the term many many times. They just can't create their own thing and use that name to describe it and then sell it. And I don't think the name Alucard would qualify for copyright, anyway. theist 12:13, 26 October 2009 (UTC)
- You can Register a Trade Mark, but that only protects it where there's likely to be confusion: Swan kettles & Swan Matches come to mind. Wasn't there a Mr (or Mrs) MacDonald in Scotland who was sued by (guess who) for calling his caff Macdonald's. Of course there's "To boldly go" which is copyright I understand. I am eating & honeychat 12:35, 26 October 2009 (UTC)
- I don't think it is. At least I can't find a mention of it being so. theist 13:33, 26 October 2009 (UTC)
- I think claiming copyright on a single character name would be tough. (Trademarks are a different matter of course as they uniquely identify a product.) Secondly "Alucard" was simply another name for the character "Dracula" - not a new character anyway. Could I claim copyright on "Nazrat" if I wrote a new Tarzan story? I doubt it.--BobNot Jim 13:59, 26 October 2009 (UTC)
- Fictional characters and other items are an intellectual property and their creator can control use of such in perpetuity. [Warning:the following contains Dr Who geekdom] Terry Nation, for instance, got rich (one the very few tv writers to do so) because he kept hold of his rights to the Daleks. sometimes a show can't reuse a character because the creator charges too much for the right to use it. the was a big stink about the two blokes who created Superman as well, wasn't there?. So in a nutshell, there is copyright on characters. Totnesmartin 14:54, 26 October 2009 (UTC)
- Siegel and Shuster, the creators of Superman sold the character to National Periodical Publications (now DC Comics) for what, in retrospect, seems to be a pittance -- the grand sum of one hundred dollars. Remember, though, that was the Depression, and they were teenagers (or early twenties), so, while its nothing compared to what the character became worth, they thought it was a pretty good deal at the time. Flash forward about fifty years to the debut of the first Christopher Reeve Superman movie. Both Siegel and Shuster were getting old, in poor health, and flat broke. One was, in fact, legally blind. They did lots of media interviews that basically boiled down to, "we created this character, we'vo got no money, and there's a major motion picture that's about to make truckloads of money." DC was essentially shamed to putting them on a stipend -- about $20K/year at time (not huge, but not bad for the late Seventies). Its my understanding that DC increased the amount over the years, and they were able to, at least, enjoy retirement. Flash forward again, to the present. Both Siegel and Shuster are gone now, but one of their estates is fighting a legal battle over the rights to some of the other characters he created, most especially Superboy. Results are still pending in that case. Marvel Comics is in a similar battle with the creator of Captain America. MDB 13:14, 28 October 2009 (UTC)
Sic transit gloria GeoCities[edit]
Today GeoCities is officially closed. Just sayin. [9] Corry 23:55, 26 October 2009 (UTC)
- My totally embarrassing (and nearly a decade old) web pages are still there. Me!Sheesh!Mine! 15:14, 27 October 2009 (UTC)
- Don't worry -- if you want to create garish web pages with whatever you think looks cool at the moment and make someone who works in web design want to gouge his eyes out, there's always myspace. MDB 15:21, 27 October 2009 (UTC)
And now for something completely different[edit]
Anyone read Unseen Academicals yet? I've just ordered it on Amazon. I am eating & honeychat 23:59, 26 October 2009 (UTC)
- I don't feel it's one of his best; it's a bit like Making Money, as if he's trying too hard. On the other hand Nation is possibly the best thing he's ever done. Bob Soles 01:18, 27 October 2009 (UTC)
- I just never got into Nation. The writing style he uses in it annoys me. theist 14:17, 27 October 2009 (UTC)
- Whenever Pratchett fans get together and discuss which are the best/worse books there is always strong disagreement. My dad and I have pretty similar tastes but he thinks that Monstrous Regiment is one of the best, I cant get on with it. I really rate Jingo, he finds the portrayal of Vetnari all wrong. The only place where we all agree is that Eric is a disaster - cue cries of 'No, no, it's my favourite' Bob Soles 14:37, 27 October 2009 (UTC)
- I've not read UA yet - it's on my
ChristmasSaturnalia wishlist. My favourite is still Small Gods, but I like almost all of his books. The only one I really don't like is The Last Continent. It spends the whole time pointing and giggling "see how clever I was working in yet another Aussie reference?" at you. –SuspectedReplicantretire me 14:52, 27 October 2009 (UTC)
- I'm a few books behind (reading Monstrous Regiment at present, with mixed feelings) but really prefer his earlier books, which seemed a lot more spontaneous & original. I find most of his later ones too formulaic, & he seems to labour a few weak jokes too hard sometimes. But I really like pretty much all of his Vimes / city watch books. ŴêâŝêîôîďMethinks it is a Weasel 21:48, 27 October 2009 (UTC)
Oh dear[edit]
From the Daily Telegraph (amazingly): see rule 6 Silvermute 14:54, 27 October 2009 (UTC)
- In fact, did one of you lot write this piece? RW is all over it (and Ken)! Silvermute 14:58, 27 October 2009 (UTC)
- See the top of the page. 15:02, 27 October 2009 (UTC)I am eating & honeychat
- D'oh. Never post when over-excited at something you've just found is the message here, I suppose. Silvermute 15:06, 27 October 2009 (UTC)
I've been looking at this for two days now[edit]
and I can't stop. Is there something wrong with me? Or is this totally fucking hilarious? — Sincerely, Neveruse513 / Talk / Block 15:06, 27 October 2009 (UTC)
- Ah, look at his little hat! SJ Debaser 15:09, 27 October 2009 (UTC)
- I'm not sure there is anything wrong with you but I think all these "funny" cat pictures are stupid and I have two (soon to be three) cats. So, if liking things that some random internet person thinks are stupid is "wrong" than, yeah, there is something wrong with you. Me!Sheesh!Mine! 15:17, 27 October 2009 (UTC)
- Agree Sheesh. Cats are capable of really stupid things without human intervention. My #1 cat jumped off my office type chair t'other day: the chair spun & the cat just moved vertically ⇓ instead of up to the desk. The followthrough: "I meant to do that" attitude was really amusing & not repeatable.
- There's definitely something hypnotic about it. theist 15:20, 27 October 2009 (UTC)
- In many areas of life, I'm a reasonably sophisticated guy. I like good wine and fine food, appreciate literature and music, and can discourse on philosophy and metaphysics with my similarly erudite friends... but give me a picture of a cat with a silly caption and I'll giggle like an idiot. –SuspectedReplicantretire me 15:21, 27 October 2009 (UTC)
But is he taking it off or flipping it?? — Sincerely, Neveruse513 / Talk / Block 17:06, 27 October 2009 (UTC)
Need Help on Article of the Weak[edit]
Ok, I want to submit one, but the link seems to literally have spaces in it, so I'm not sure how to link. Anyone interested in helping me figure out how to link, do the following: Google "Vampire Research Society" (yes this group is serious), click on their website, and then follow the link labeled "Can Such Creatures Really Be."--Mustex 21:14, 27 October 2009 (UTC)
- Replace the spaces with "%20". Cubic educated Hoover! 21:35, 27 October 2009 (UTC)
- Is this the page you meant? Cubic educated Hoover! 21:40, 27 October 2009 (UTC)
- K, I'm going to test it here: --Mustex 21:41, 27 October 2009 (UTC)
- It has autoplayed music, that alone qualifies it for AOTW. theist 21:56, 27 October 2009 (UTC)
- Does this mean my Userpage is now an article of the Weak? That would be interesting... --The Emperor Kneel before Zod! 22:16, 27 October 2009 (UTC)
My PC is more liberal than me[edit]
I use Firefox as my preferred web browser and every time I follow a link to a FoxNews article, Firefox up and quits.--Thanatos 02:46, 28 October 2009 (UTC)
The mostly harmless criteria for sysops[edit]
There is a reason we have this criteria for sysops. Someone with technical knowledge and a malicious streak can actually do considerable harm to each other and the wiki with sysops powers. I am not going to go into details about how that might be done so as to not give any ideas. I am not weighing in on the discussion about Marcus one way or another. He has failed to capture my interest, and even if he does have malicious intent I think he lacks the technical knowledge to do anything more then annoying. However, the meme that everything a sysops can do can be easily undone by any other sysops with no lasting effect is not actually true. Hence, why there should be some level of a judgment call made when sysopsing users. tmtoulouse 22:33, 26 October 2009 (UTC)
- I agree, but I'm not the one who makes any kind of decisions round here. CrundyTalk nerdy to me 22:58, 26 October 2009 (UTC)
- Ok then. We can remove the most dangerous rights (editinterface, edituserjscss, bigdelete) from sysops. That would leave us pretty safe, no? -- Nx / talk 23:03, 26 October 2009 (UTC)
- Can we remove ActLikeAFuckingPrick as well? I think MC would probably abuse that one. CrundyTalk nerdy to me 23:47, 26 October 2009 (UTC)
- Sorry, I don't have root password to MC's brain -- Nx / talk 23:51, 26 October 2009 (UTC)
- (ECx2)Then I stand corrected and apologise for spreading said meme, I assumed (based on what we have written in the pages about being a sysop) that it just included patrolling edits, blocking and vandal binning users and locking/moving/deleting pages. If it is the case that sysops can do some serious damage, I think we need to start restricting sysop powers a lot more - and by extension, 'crat powers even further. There are users getting sysop powers within a minuscule number of edits these days, before they've even shown they have a proper interest in the wiki. Whereas about a year ago you almost had some time to get some edits in before getting it. While I absolutely trust Trent and Nx's opinions on how dangerous sysop powers can be if misused, if there really is a problem, then the solution needs to be applied universally, not just as an excuse to stop someone who has got under the skin of a few posters from getting it. theist 23:51, 26 October 2009 (UTC)
- I concur, it has been something I have been mulling around for a while. We are relatively safe because it would take someone with above average technical skills (and not just wiki skills but computers and programming in general) to really cause havoc and we haven't exactly drawn the ire of malicious computer programmers sneaking sysops rights on our site. However, the largest security issues can probably be cleaned up a bit and should be. I will discuss it with Nx, any changes shouldn't really effect anyone that I am aware of. tmtoulouse 23:56, 26 October 2009 (UTC)
- I agree (not that that means anything), and even if it did affect us I don't think most of us sysops would mind. I, for one, will not miss any of the powers you mention. Tetronian you're clueless 00:00, 27 October 2009 (UTC)
- I assume these changes would be quite "under the hood" as it were, so wouldn't affect our policy of sysopship. However, I have thought of one issue; namely revision-delete. We use this to hide personal info that has been incorrectly uploaded here. So all it takes if someone wants to get some personal details that they suspect are held on RationalWiki is to come here, make 5-6 posts on WIGO:CP saying "look at those morons, lOL!!!" and they'll get sysoped and be able to track it down (another negatively side effect of doing it within a few edits is that well meaning editors have been insulted and left because certain 'crats take the "demotion" joke a bit too far and start telling people to get out of their sight etc. etc.). I know we haven't had any personal info that is particularly useful up here yet but some things have leaked out and as Conservapedia gets more attention, the more likely it'll come under the eyes of the real arseholes out there who will likely try to hi-jack RW for their own purposes - and if Schlafly thinks he's being persecuted by vandals now, he has no idea what can and will happen if he continues to draw attention to himself and piss people off.
- As you said a few months ago, we're passing through Dunbar's Number so things may get rocky and we might want to consider restructuring how we give out user rights, or at least put some more official guidelines on the sysopship demotion. theist 10:59, 27 October 2009 (UTC)
I defer to Trent and Nx for anything technical. I do stand by my other things I have written about sysop rights here. I think making it easy is the best defense against any malicious intent. When it becomes a chess-like game worth winning on something like CP, you are inviting trouble. When it is like musical chairs with one extra chair, there is no prize. Sysop rights is all about the means and not so much the ends for someone intending malice. --Edgerunner76Your views are intriguing to me and I wish to subscribe to your newsletter 10:55, 27 October 2009 (UTC)
- I can assure you all that I don't have the first clue about how I would do any of the scary things you mention. To be fair I am not a vandal, I have never vandalised, and its only the most autocratic and mean spirited of members here who accuse me of being a troll. I don't really care about getting the powers, I asked for a laugh and deliberately provocatively just to see if it would happen. I honestly didn't think it would create a furore, though perhaps I should have known better considering the emotional and hysterical tendencies of the likes of thedictator (Geek with no life/possibly a virgin) and Jeeves (Unrepentant bigot and deviant) 134.226.1.234 13:30, 27 October 2009 (UTC)
- Although I totally disprove of name-dropping people and calling them arseholes like that, MC has a point. He is not a vandal and has made no malicious actions towards the wiki as a project or whole - a provocative little turd, yes, but that's mostly the fault of people who let themselves get provoked by it. theist 14:15, 27 October 2009 (UTC)
- I just have a minor correction. This is not a furor. Furors would include much more profanity, some all caps posts, perhaps some lulcatz pics
and a liberal application of that take a breather template.This is about as melodramatic as some collection of us deciding what to have for lunch. Me!Sheesh!Mine! 14:21, 27 October 2009 (UTC)
Neutering sysops[edit]
I took away several rights from sysops:
- Editing the MediaWiki namespace (editinterface). Unfortunately there's no way to distinguish between pages that only allow wikicode and those that allow arbitrary html.
- Editing other users' css/js files. (editusercssjs)
- Deleting pages with more than 2000 revisions. (bigdelete) I don't see why we'd ever want to delete a page that has that much revisions anyway.
Bureaucrats can do all of the above. They also get a big red warning when deleting a page with more than 2000 revisions. The irrational numbers usergroup which I created specifically for Pi has editinterface and bigdelete, so don't go around giving it to random people. Promotions to cratship should take into account these changes. I don't think we need to introduce a third usergroup, either between sysops and crats, or above crats, but I'm open to suggestions. -- Nx / talk 07:58, 28 October 2009 (UTC)
- I think there's a decent compromise there, it removes crap that sysops could use to bork the wiki but would never use for legit reasons anyway - ergo we can still do the "sysops for all" thing. 'Cratships I think need to be seriously considered in the future. We need to give it to the guys who would want to and need to use the stuff that comes with it - I don't think the "been here a while" cuts it entirely. Plus, if we cut down on crats, there's less chance of people being sysop'd on sight and get abuse from the demotion joke before they've even realised what it actually means. I definitely don't think we need any more groups; there's a few technically minded individuals with access to the server and that certainly doesn't want expanded or given out "just because you've been here even longer". theist 11:31, 28 October 2009 (UTC)
- I've only just turned up and I demand all the above-mentioned rights NOW NOW NOW Real first name and last initial 13:47, 28 October 2009 (UTC)
- I propose that people who ask for sysops status should be disqualified for the position. Just a suggestion :P AndroidWe are all machines 15:07, 28 October 2009 (UTC)
- I propose that people who propose that people who ask to be sysops shouldn't be sysops shouldn't be sysops. Real first name and last initial 17:18, 28 October 2009 (UTC)
Vandal[edit]
Why are people at MIT wandalising us?
C:\>IPCity.exe 18.251.5.130
Country: US
Region: MA
City: Cambridge
Latitude: 42.364601
Longitude: -71.102798
Metro code: 506
Area code: 617
ISP: "Massachusetts Institute of Technology"
Organisation: "Massachusetts Institute of Technology"
Map:
I would have thought that the students therein would have more of a brain? CrundyTalk nerdy to me 23:45, 26 October 2009 (UTC)
- You can never tell what those subversive liberals will do to us, can you, TK. --The Emperor Kneel before Zod! 23:49, 26 October 2009 (UTC)
- Yeah... let's not do this kind of thing. Corry 23:53, 26 October 2009 (UTC)
- Yes, using a simple IP lookup on vandals is creepy. If they want to remain anonymous then all they have to do is create a sock with no email address logged. And criticism is fine, as long as it's in the right place. Why not talk on the mainpage talk page, or here, or the CP talk page? CrundyTalk nerdy to me 23:57, 26 October 2009 (UTC)
- I don't know why you needed look up. - π 00:39, 27 October 2009 (UTC)
- Because it was interesting to see if someone spamming the crap out of the site was a CP editor. And look, MG is now talking to us instead of writing stupid messages on the nominations page. CrundyTalk nerdy to me 00:42, 27 October 2009 (UTC)
- What I mean IP with the first number lower that 64 are class A networks, blocks of the internet so large you could read it off this comic. - π 00:45, 27 October 2009 (UTC)
- Umm, am I having a stroke or was that word salad? CrundyTalk nerdy to me 01:00, 27 October 2009 (UTC)
- Lets try again. The internet is a finite sized thing. They (Al Gore probably) gave a quarter of it to the people that either, designed, built, or paid for it. You can tell their bits because their addresses which look like ###.###.###.### where # is a number, all have before the first dot a number strictly less than 64. - π 01:06, 27 October 2009 (UTC)
- So, weirdos have the IP address <64.0.0.0 Mask 255.0.0.0? CrundyTalk nerdy to me 01:11, 27 October 2009 (UTC)
- IPs less than <64.0.0.0 tend to be government or companies with defence links, Haliberton for example. If you see anything starting with a 48, that is Obama. - π 01:16, 27 October 2009 (UTC)
- I just had a mental image of Obama using his super-sekrit government Blackberry to troll the shit out of CP and other right-wing blogs after a bad day. Corry 01:27, 27 October 2009 (UTC)
- That is such a pleasant idea of the President vandalising CP because he is bored. Actually seeing as he has 16,777,216 IPs at his discretion he would be hard to block. He could have a special red laptop brought into to the oval office with a clean IP for his new sock. Reminds me of the time Ken blocked Oxford muttering something about Dawkins. - π 01:49, 27 October 2009 (UTC)
- I can image the exchange:
Obama-Rahm! Get me Andy Schlafly on the line! He's disabled account creation again!
Rahm Emanuel- He's spped dial 2 on the red telephone, right between Putin and Brown.
Obama- Thanks. Mr Schlafly? This is the President. What? No, I'm not a Muslim! Yes, I'm black. No, I do not have secret prayer session over basketball. Look, I know you're sore over the law review election, but that was decades ago! Can you just reenable account creation? Who? Jpatt? No! TK? Fine! *hangs up* Rahm! Get me Guantanamo Bay on the line! I need to speak to Prisoner #1827 ASAP!
Lulz. --The Emperor Kneel before Zod! 02:10, 27 October 2009 (UTC)
Yeah, criticizing the CP Awards on the CP Awards page is totally inappropriate. Call the FBI. And just because we can use IP tracers doesn't make it less creepy. RaoulDuke 00:01, 27 October 2009 (UTC)
- Its not creepy, its public information; people have a choice whether to register and hide behind an anoymous name to publicly broadcast their name. Running checkuser just on suspicion is creepy. The first is like someone taking off their clothes in a public place, the second is like peeking through the curtains into someone's bedroom. ГенгисRationalWiki GOLD member 07:00, 27 October 2009 (UTC)
- Nothing creepy happened. People get led around a little too easily sometimes. 1. BON pops on as a BON contending he is the real MarkGall on the (likely fake) RW MarkGall's page. 2. BON posts a criticism of the CP Awards, as a BON. BON openly does these things as a BON because BON wanted any interested CP checkuser to see his IP address (and abuse his authority by checkusing an offsite IP address). 3. An editor posts BON's IP whois trace. That's what you get when you post as a BON. Big deal. 16:15, 28 October 2009 (UTC)
Constructive Mouse Wiggling[edit]
This makes you feel good and you're helping reach a target too. –SuspectedReplicantretire me 15:32, 27 October 2009 (UTC)
- Hee! like it! I am eating & honeychat 15:38, 27 October 2009 (UTC)
- I haven't had that much fun slapping someone across the face since my first relationship. theist 15:42, 27 October 2009 (UTC)
- I slapped him to the beat of "Guns of Brixton" by the Clash. SJ Debaser 15:44, 27 October 2009 (UTC)
- I'm up to 400 now over about three sessions. I was thinking that this plays into their persecution complex a little, but really, its totally tame compared to the shit that was made against Blair and Bush (back in the day). theist 16:08, 27 October 2009 (UTC)
- 500! Cubic educated Hoover! 20:09, 27 October 2009 (UTC)
- ONE THOUSAAAAAND! --The Emperor Kneel before Zod! 21:28, 27 October 2009 (UTC)
OOPS:I am eating & honeychat 12:38, 29 October 2009 (UTC)
- Current Private Eye cover is a "Free Cut-Out-'n'-Keep Halloween Novelty: A Nick Griffin Horror Mask. I am eating & honeychat 12:43, 29 October 2009 (UTC)
- Indeed. And a particularly scary picture of him it is too (although it's tricky to find a non-scary picture of him). Shame about the website though. –SuspectedReplicantretire me 12:48, 29 October 2009 (UTC)
Taking a break[edit]
I've got some "personal" "stuff" going on and it's affecting my wikimanners (ask ListenerX), so I'm de-bookmarking RW and WP until I get my shit together again. I don't know when that'll be. I love this place but I'm not right for it at the moment. Totnesmartin 19:08, 27 October 2009 (UTC)
- Dude, come back quick and I hope everything works out for ya. You'll be missed. AceMcWicked 19:58, 27 October 2009 (UTC)
- I wish you a safe return to the wiki. — Sincerely, Neveruse513 / Talk / Block 19:59, 27 October 2009 (UTC)
- Sorry to hear real life is intruding Martin but I know what you mean. Hope you get everything sorted soon and come back the dollhouse. ГенгисRationalWiki GOLD member 20:26, 27 October 2009 (UTC)
- Best of luck mate, make sure you don't come back until you're ready. SJ Debaser 21:07, 27 October 2009 (UTC)
- Take care. See you soon. ŴêâŝêîôîďMethinks it is a Weasel 21:23, 27 October 2009 (UTC)
- Yeah, take a break and give it a rest. It'll do you good. theist 21:33, 27 October 2009 (UTC)
- Bye, come back as soon as you can. I should take a wikibreak too, but my previous experience shows I don't end up taking the break. - π 21:37, 27 October 2009 (UTC)
- Best to you Mr.Totnes. Be well. DogPMarmite Patrol 05:37, 28 October 2009 (UTC)
- Have a good break - but please don't be away too long. –SuspectedReplicantretire me 05:52, 28 October 2009 (UTC)
Google needs to be dissappeared next.[edit]
Now I am sure this is a government plot to feed me corrupted data and get me fired. --The Emperor Kneel before Zod! 22:28, 27 October 2009 (UTC)
- The answer is just 10-10. What's so hard about that? --The Emperor Kneel before Zod! 22:32, 27 October 2009 (UTC)
- Definitely a rounding error at some stage due to using too many digits. It starts screwing up at 100 - 99.999999, and gets raptured at 100 - 99.9999999999999. ħuman 23:36, 27 October 2009 (UTC)
Random WIGO poll idea:[edit]
Besides the up/down arrows, would it be possible to add "good"/"bad" buttons so we can indicate if we think it's good news or bad news? --Gulik 17:38, 28 October 2009 (UTC)
- I think it'd have the homogeneity of a Fox News poll. — Sincerely, Neveruse513 / Talk / Block 17:45, 28 October 2009 (UTC)
- I concur, we tend to be a pretty non varied group around here. SirChuckBCall the FBI 18:04, 28 October 2009 (UTC)
- Agree. It's like changing the polling criteria mid-vote. Who knows whether people are voting on the underlying item or the craft of the WIGO. 18:14, 28 October 2009 (UTC)
- Good/bad is pretty arbitrary, and I am against the idea. ĴάΛäšςǍ₰ edits from 119.83.19.238 18:32, 28 October 2009 (UTC)
- I am against anything that hasn't been spewed from my own revolting orifices. Just another chapter in the long running saga of Ace vs. "Society", what ever the fuck that is. AceMcWicked 21:03, 28 October 2009 (UTC)
- Lonesome Roads McWicked ;) — Sincerely, Neveruse513 / Talk / Block 21:04, 28 October 2009 (UTC)
- Someone has to do it, I picked up the gauntlet.. Ace "Lonesome Roads" McWicked 21:09, 28 October 2009 (UTC)
- So let me get this straight: because of your lifelong struggle with the rest of the human population, we can't put good/bad buttons on WIGOs? Tetronian you're clueless 21:12, 28 October 2009 (UTC)
- Quite and you are getting off lightly, I gave hell to the clerk at the Video Store the other week. Worthless fucker, who is he to tell me I have fines? AceMcWicked 21:16, 28 October 2009 (UTC)
- The one-dimensional arrows have caused me to consider carefully where I click more than once. Am I voting that this is a good thing or a bad thing? An interesting or dull thing? An inspired or a moronic thing? Or any other x/!x thing. Personally, I vote on a "Will I come back here?" basis. An interesting/funny/insane link or links gets a vote if it's likely to be interesting/funny/insane when I come back six months from now. Of course, opinions change so this isn't a perfect method, but it works well enough to serve. –SuspectedReplicantretire me 22:19, 28 October 2009 (UTC)
- Wow that's a complicated system. I just ask myself: Did I laugh? Did I facepalm or groan in horror? Is the WIGO written in a humorous way? If so, it gets a green arrow. If not, yellow or red. Tetronian you're clueless 22:29, 28 October 2009 (UTC)
- Me too. If the way the WIGO was written, or what it linked to, "amused" me, I vote up. If not, maybe down. Or forgot what I was doing and stopped caring. And if it was really fucking lame, I bitch on the talk page after voting it down. ħuman 03:41, 29 October 2009 (UTC)
- In a lot of cases (WIGOworld especially) it's what they call on Flickr "Interestingness" that leads me to the . With WIGOCP almost anything they say or do is amusing also but here "Uniquity" comes up too - the constant repetition of some types of WIGO grows boring. I am eating & honeychat 09:50, 29 October 2009 (UTC)
- To me, the "way it's written" is a non-entity. If it's crap, it can be re-written as WIGOs are Wiki-property. I always take it for "interestingness" and "relevance" - although with this criteria I usually prefer to not vote than to vote down. Toast has a good point about "Uniquity" that I think is very appropriate to WIGO:CP; "TK blocked someone" - booooorrrrring. "Andy wants to debate Richard Dawkins live" - oooh, this will be fun. theist 09:55, 29 October 2009 (UTC)
Jinx's blog[edit]
I was looking at PZ Myers' dungeon, and I noticed a link to an anti-PZ blog run by our old friend, "penis-bone Jinx". It's the usual idiocy, trying to make Christianity look good and athism/science/everyone else look bad and having the opposite effect via sheer stupidity, but I love this entry. Yes Jinx, I fully understand why you prefer the latter. Idiots are always attracted to flattery more than honesty. It's the way of the world. --Kels 21:48, 28 October 2009 (UTC)
- Errrr I got a gotse. Nice one Jinx. Incidently I tried to comment on his blog a little back, nothing profane, and he did not approve my comment. AceMcWicked 21:52, 28 October 2009 (UTC)
- Fixed. - π 21:54, 28 October 2009 (UTC)
- Looks like he's not accepting any comments at all these days. And goatse? Seriously? Sorry about that, I didn't check the link. Not surprising, he's unusually attracted to the idea of anal sex, perhaps Daniel1212 and Ken should have a few...words...with him. --Kels 21:57, 28 October 2009 (UTC)
- Yeah it were on his shockandblog website. I made a reasonable and nonhostile comment - nada. AceMcWicked 21:58, 28 October 2009 (UTC)
- I got blocked from Shock and Blog for laughing at his threat to report me to my ISP. Two months later and they still seem very uninterested. - π 22:00, 28 October 2009 (UTC)
- They are just waiting for Jinx to say the word Π, then they'll drop the sword of Damacles which he has hovered over you for so long. AceMcWicked 22:03, 28 October 2009 (UTC)
- I hope that one of his beloved kids visits RW, stumbles across a link to daddy's blog, and then comes face to face with Mr Goatse's strained sphincter. Would be fun for them to see what daddy gets up to at the office. And yep, the boy is mad. He could just as well be reading Superman comics, preferring to believe that his city is kept safe by the man of steel. --Ask me about your mother 22:04, 28 October 2009 (UTC)
Conspiracy Theory Rock![edit]
I can't believe this aired on television... Stuart Sewer 22:57, 27 October 2009 (UTC)
- That's an awesome cartoon! ħuman 23:38, 27 October 2009 (UTC)
- I love how Lorne Micheals claimed that is was never aired again only because it didn't get a lot of laughs and didn't fit the flow of the show..... Gotta love a coverup. SirChuckBCall the FBI 23:47, 27 October 2009 (UTC)
- Why didn't he just use the "laugh, dammit" sign they use for all the unfunny crap they do show? ħuman 23:53, 27 October 2009 (UTC)
- I wish I could comment on this, but they discuss my employer.Punky Your mental puke relief 23:54, 27 October 2009 (UTC)
Browsers flamewar below this line[edit]
Some topic several months ago piqued my interest. What browsers does everybody use around here? --The Emperor Kneel before Zod! 02:53, 28 October 2009 (UTC)
- We could just ask Trent or Nx for the numbers of each? - π 02:56, 28 October 2009 (UTC)
- Boring. I much prefer the chance to vote. --The Emperor Kneel before Zod! 02:57, 28 October 2009 (UTC)
- Well you could have saved this for next weeks pointless poll. - π 03:20, 28 October 2009 (UTC)
- Eh, let the newcomers play with our toys. They're Shiny. ħuman 06:13, 28 October 2009 (UTC)
- You can only vote once? I use Safari at home, plus I occasionally use Firefox for the few pages that don't play nice with Safari. Plus, I use Safari on my phone. At work, I use Internet Explorer, mostly, plus Chrome when I'm at the home office and not on customer site.
- Even if you asked preferred browser, it would depend on the OS: Safari for the Mac, Chrome for Windows. MDB 12:56, 28 October 2009 (UTC)
- Paf, all you poor "firefox" users should know by now that Internet Explorer is the superior internet browser. *runs for the hills* ĴαʊΆʃÇä₰ bruragh braaargh grah mragh bruragh! 13:11, 28 October 2009 (UTC)
- I use Firefox on my pc, & Opera on my cellphone. I am eating & honeychat 13:45, 28 October 2009 (UTC)
- I probably use Firefox most, but I look down at my Quick Launch toolbar to see Chrome, IE, FF, Opera and Safari icons all looking back at me. I make a point of using all the major browsers thedo wikis attract FF users?se days so I don't become too much of a fanboi for any given one. –SuspectedReplicantretire me 14:21, 28 October 2009 (UTC)
The "boring" server log info. tmtoulouse 15:39, 28 October 2009 (UTC)
- Extrapolating wildly - active Ratwikians are big on Firefox - see the vote above - but our casual visitors reflect the wider use of IE. Bob Soles 15:42, 28 October 2009 (UTC)
- Probably because the people who just visit the site because of a link will reflect the wider internet community. The ones who stay to edit will be the sort of nerd who wants to stay and edit a wiki, and face it, nerds use firefox. theist 16:39, 28 October 2009 (UTC)
- Looking at my teflpedia stats. I get about 2000 unique visitors a month and a vanishing small number of them edit. (Most of them left over from the RW summer vacation. Thanks people.) The strange thing is that slightly over 50% of them use firefox. I can't believe that so many English teachers are techo-nerds though. Or do wikis attract FF users?--BobNot Jim 19:59, 28 October 2009 (UTC)
- Any sort of Wiki-editing requires at least a small technical skill-set to enable the formatting of one's posts and contributions. This probably leaves three-quarters of all computer users high and dry. ListenerXTalkerX 20:05, 28 October 2009 (UTC)
- I also think that by this point people just instinctively know that when they use IE their computers break. I had to remove it from my mom's windows machine and give FF the IE icon because she simply didn't understand there was such a thing as another browser. She called the IE logo "the internet." But it doesn't take much to get past that, which is where I would think alot of FF users are starting from. 20:53, 28 October 2009 (UTC)
People still use Netscape? Yikes! Sterile alpaca 20:46, 29 October 2009 (UTC)
I use Chrome and Firefox at the same time so I can access 2 of my Youtube or email accounts or whatever at the same time, though most of the surfing I do happens on Chrome, but on ad-heavy sites I use FF. I have Opera as a backup, Safari and SeaMonkey in reserve, and IE as the last resort. I would add Lynx (a text only browser) to the line up, but I can't get it to work. Not a problem though. AndroidWe are all machines 20:58, 29 October 2009 (UTC)
Ares[edit]
Did anyone watch the Ares 1-X go up? Seems pretty successful so far. Shame it will probably all get canned in favour of blowing the cash on bombing dirty foreigners. theist 15:44, 28 October 2009 (UTC)
- There are some legitimate arguments for canceling the Constellation project. The US is trillions of dollars in debt, and NASA wastes an obscene amount of money each year. Tetronian you're clueless 21:10, 28 October 2009 (UTC)
- Bullshit. NASA's proposed FY2010 budget is $18.7 billion, or about 0.52% of the overall FY2010 federal budget. I'll grant that NASA doesn't always use its budget to the best extent that it could, but by no means does it 'waste obscene amounts of money'. There are many other much larger waste of money in the budget. Of course, Constellation is still probably not the best plan, but that doesn't excuse your point.--146.57.80.12 21:40, 28 October 2009 (UTC)
- I think sending people into space is silly. To the moon, that was cool. But the future of exploration is robotics. The Mars Rover things were far cooler than anything the Apollo project ever did. Keeping people alive over long trips through space is silly. Robots can go to Mars, and even beyond, and come back with samples, or send data on samples, far cheaper than sending protoplasm and water and stuff, and getting it back. Bonus? No icky deaths of schoolteachers. ħuman 03:44, 29 October 2009 (UTC)
- And of course, the US military budget is $512 million a year, which IIRC doesn't include Iraq and Afghanistan, so, NASA aren't really wasting billions and billions are they? And the benefits of space exploration are more than just financial, I reckon that in the persuit of going into space, we can develop technology at just as much of a pace that we do when beating each other with sticks and trying to find a better stick. theist 10:29, 29 October 2009 (UTC)
- I'm very much in favor of manned space exploration/colonization. Off-site backups, baby. --Gulik 00:30, 30 October 2009 (UTC)
- Yeah, I suppose we waste a lot money more on other things. But just the thought of launching rockets and stuff into space while people right here are starving seems awful. And yeah, backups are nice, but I'd like to see a perfected biosphere first. Tetronian you're clueless 00:34, 30 October 2009 (UTC)
- There's a zillion other useless things that money's spent on that could be stopped before Ares. <>Cigarette manufacture/sales comes to mind.</> We've got to keep science and technology advancing or stagnate - that's what being #1 primate's all about. I am eating & honeychat 01:00, 30 October 2009 (UTC)
- Ok, I concede defeat. There are many, many things that can be cut before NASA. Tetronian you're clueless 01:03, 30 October 2009 (UTC)
Old Catholic Church[edit]
Ok, now that the page on Sean Manchester mentions the Old Catholic Church, do you think we should do a page on them? I was thinking of making it a Fun page, something like this: "The Old Catholic Church is a splinter group from the main Catholic Church. They broke away because they don't believe the Pope is infallible...on the other hand, THEY CHOSE A VAMPIRE HUNTER AS BISHOP OF ENGLAND! They are more liberal than the regular Catholic Church, and allow female priests...on the ohter hand, THEY CHOSE A VAMPIRE HUNTER AS BISHOP OF ENGLAND! etc."--Mustex 15:54, 28 October 2009 (UTC)
- How many vampires has he bagged so far? --Gulik 17:36, 28 October 2009 (UTC)
- Depends on who you ask. He and David Farrant both claim to have bagged the Highgate Vampire single-handed (essentially accusing each other of fraud).--Mustex 21:28, 28 October 2009 (UTC)
- Why is appointing a vampire hunter stupider/weirder than appointing an exorcist or a faith healer? This is Christianity remember, they like that sort of stuff. Real first name and last initial 09:42, 29 October 2009 (UTC)
- Well, part of it isn't just that he believes in vampires, its also that his belief in vampires seems based on 1940s movies rather than folklore. If you want more than that, I'd say vampires are more testable than God or ghosts or angels or anything like that, if only because vampires are supposed to have a physical body that we could actually see, capture, and run tests on. But yet, no one has ever found such an animated corpse.--Mustex 14:14, 29 October 2009 (UTC)
New editors[edit]
This is an excellent reason for encouraging new editors. Many of us take existing articles for granted. Just sayin' I am eating & honeychat 13:34, 29 October 2009 (UTC)
- All new editors are trouble makers, we should disable account creation at random to discourage them. - π 13:36, 29 October 2009 (UTC)
- Or, we should disabled editing and account creation at night time to stop them. CrundyTalk nerdy to me 13:39, 29 October 2009 (UTC)
- Or just block anyone who joined later than (plucks date out of thin air) February 2008? I am eating & honeychat 13:47, 29 October 2009 (UTC)
- Hey, you would block me then. Actually you should have blocked me, my first edits were shit and was an annoying little bugger. - π 13:51, 29 October 2009 (UTC)
- I think we definitely need to be ready and able to alter and dump massive amounts of crap that are essentially left over from when RW was all about Conservapedia. theist 18:12, 29 October 2009 (UTC)
Revolution[edit]
- To follow up on Armondikov's point, I honestly think that a complete change from the ground up is what RW needs. In other words, the sites ethos should be re-stated and the about section rewritten. This website has lofty principles (About holding authoritarianism to account, for example) yet never even comes close to touching this. But yet again this point will be ignored, lambasted as 'trolling' and will probably result in Ace accusing me of not complying with the wims of the majoritarian tyranny of the mob. Ah well. MarcusCicero 20:00, 29 October 2009 (UTC)
- I'm not sure "revolution" is the right way to go at all. And the mission statement works fine, we just have a high proportion of editors who are more interested in some things than others. If RW's membership expanded, was maintained and wasn't distracted by Conservapedia, things would improve dramatically. There's no need for a "revolution" or to try and force it in any way. theist 20:46, 29 October 2009 (UTC)
- Well, you know... we all want to change your head... ħuman 21:20, 29 October 2009 (UTC)
- I'm with ArmondikoV on this one. The beauty of RW is that Trent left it up to us to make decisions on policy and direction. There is no reason to force people into making RW into something only you want it to be. Tetronian you're clueless 21:29, 29 October 2009 (UTC)
- <Please to all enjoy les sanglots longs of the world's smallest violin playing just for MC.> --Robledo 21:32, 29 October 2009 (UTC)
- You know what MC? I think there is too much CP. I think we are falling short of our mission. Do you know what I do about it? I EDIT THE FUCKING ARTICLES!! I CREATE NEW FUCKING ARTICLES ON THINGS WE NEED!! I TRY TO ENCOURAGE (NOT ABUSE) OTHERS TO DO SO!! People would listen to you more about reforming RationalWiki if it looked like you were trying to improve it yourself, rather than causing problems. - π 22:31, 29 October 2009 (UTC)
- <extreme sarcasm> Perhaps if MC came up with a writing plan for us.... </extreme sarcasm> Tetronian you're clueless 22:35, 29 October 2009 (UTC)
- I have always felt Schlafly has a point, that the editors doing the most complaining are doing the least editing. However their are two crucial difference. 1) if you make lots of edits and you disagree with Schlafly he will call them unsubstantial and 2) you are cautious about editing a CP article as you can be blocked for adding cited facts if they don't gel with Andy's world view. As neither of those are an issue here, dive straight in. - π 22:42, 29 October 2009 (UTC)
- Agreed with the differences. That's why I'd never even dream of berating someone for only commenting on WIGO:CP and nothing else (as much as such activity may irk me personally, people getting prominence with less than 1 in 10 edits in the mainspace pulls at my elitism gene). But actions really do speak louder than words and that's not just rhetoric, it's actually true. If you want to change RW, you can either A) ask someone to help who you know has a similar style and set of goals to you B) Suggest new articles on the to do page or C) Go ahead and unilaterally do it yourself (throw caution to the wind and damn the typos!) There's plenty of options and one of the best things about our (lack of) structure is that all these are possible and we're, as an entity, remarkably flexible and open. I think many of the criticisms are valid and do hold true, but a big song and dance that does nothing but point them out definitely won't cure it. theist 00:44, 30 October 2009 (UTC)
- How can anyone possibly move forward when the tyranny of the majority demands illogicity and hysterical anti theist bigotry? MarcusCicero 09:34, 30 October 2009 (UTC)
- So it's everyone else's fault that you don't write much? Why can't you just take the saloon bar off your watchlist and get on with adding to the articles? Real first name and last initial 09:48, 30 October 2009 (UTC)
-
- My my Pie you really are a bitter old charletan. Of course I don't know what I'm doing, I barely know how to use a computer. What is your issue and why on earth do you get so riled up? You remind me of Jeeves. MarcusCicero 13:20, 30 October 2009 (UTC)
- There is no such thing as free speech, we are paying for this you know? - π 13:23, 30 October 2009 (UTC)
- Just link to the video. There is general agreement the embedding is overused.--Tom Moorefiat justitia 13:25, 30 October 2009 (UTC)
BBC Encapsulates RW[edit]
This exchange just took place on The Restaurant - a new series from Auntie Beeb:
- Voiceover: ...their mission, to encapsulate the true taste of Nigeria. And that needs some goat
- A: Do you have any goat meat?
- Butcher: No.
- B: Next best thing. Do you have any tripe?
If you can't get goat, use tripe. I never heard a better definition of RW :) I'm including the link to dictionary.com in case the slang meaning of "tripe" doesn't translate... –SuspectedReplicantretire me 20:17, 29 October 2009 (UTC)
- Kind of makes me want to edit the stub template: "This article doesn't have much goat, but it has the second best thing; tripe!" theist 20:28, 29 October 2009 (UTC)
- I like it! Probably a bit too obscure for general useage, alas. –SuspectedReplicantretire me 21:05, 29 October 2009 (UTC)
- No matter, it will be an inside joke for a year or two and then it will be template-worthy. Tetronian you're clueless 21:39, 29 October 2009 (UTC)
- Might work very well as the default "reason" on the delete template? (Lacks goat, has tripe?) Or is that a bit too nasty? ħuman 22:31, 29 October 2009 (UTC)
- Depends, but I don't think anyone really takes delete "reasons" seriously. I think MC could use it for ammo - and indeed that's what I was thinking of - because where RW fails its "goat" it puts out "tripe" and the metaphors get mixed and the infinitives get split and no one, not even the classics students, know what the hell anyone is talking about. theist 00:35, 30 October 2009 (UTC)
- For those who can use the iPlayer and missed it... Here it is. Skip to about 7:20. –SuspectedReplicantretire me 05:20, 30 October 2009 (UTC)
Flower[edit]
Well, despite being persistently pecked at by the chooks, infested with red spider mite, being shocked at a severe temperature change, and then getting red spider mite again, my Brugmansia somehow managed to flower this year. Poor thing. It's into the garage for overwintering in a couple of weeks. CrundyTalk nerdy to me 20:29, 29 October 2009 (UTC)
- Ah, house plant abuse. I wish I could say I haven't been there, but I have. Sterile alpaca 20:44, 29 October 2009 (UTC)
- Oh no, I love the plant. Unfortunately the red spider mite was the start of a series of problems. I had to put it outside to kill the spider mite, which shocked it due to the lower temperature, and then the chickens were left to munch at it, and then frost risk came so I brought it back indoors, and the spider mite came out of hibernation. Little shits. I love that damn plant. CrundyTalk nerdy to me 20:53, 29 October 2009 (UTC)
- Nice... amazing it had enough energy to pop those out! ħuman 20:57, 29 October 2009 (UTC)
- The smell is quite intense at 5pm-ish as well (in a nice way). CrundyTalk nerdy to me 20:59, 29 October 2009 (UTC)
- My only house plant is called "Miranda". I've no idea what she is but she was here when I moved in and was almost dead through neglect. She certainly looks a lot healthier these days. In case you're wondering, I called her Miranda when she was still nearly dead. I thought "To Be Admired" (it's a Gerund of Obligation in Latin - cf Amanda; to be loved) would inspire her to recover. Yes. I need a girlfriend. I admit it. –SuspectedReplicantretire me 21:30, 29 October 2009 (UTC)
- It's nice that you managed to revive it like that though. I did the same with an African Violet that was as dry as a <insert your own joke here> CrundyTalk nerdy to me 21:32, 29 October 2009 (UTC)
- My Brugmansia is bigger than your Brugmansia. 22:41, 29 October 2009 (UTC)
- Oh god, it's like being back at boarding school. Get the ruler out. CrundyTalk nerdy to me 22:45, 29 October 2009 (UTC)
- I had a a nasty experience on the juices of this plant. Jeeeeeeeeeesus. You're not planning to eat/drink this plant are you Crundy? AceMcWicked 22:53, 29 October 2009 (UTC)
- You ate brugmansia? Wow, not a good idea. Do tell, did you end up lying in a pool of your own piss crying with pupils the size of the moon? CrundyTalk nerdy to me 08:58, 30 October 2009 (UTC)
- Very bad idea, 3 days of bad. AceMcWicked 11:04, 30 October 2009 (UTC)
- 3 days? That's worse than bromo-dragonfly. CrundyTalk nerdy to me 11:36, 30 October 2009 (UTC)
Datura ekspert[edit]
I have six really big daturas (forty quart pots) and over-winter them in my basement. Some actually like a chilly climate for blooming. Try this: (if you can get them to flower over winter), take six or so blooms and place them the the bedroom afore turning in for the night...wonderful dreams. Do not eat the blooms or the leaves. That Would Be Bad. You won't remember it and someone might end up teh ded. Don't try to feed them during the winter, though some ex-laundry water might be a nice treat for them. 00:11, 30 October 2009 (UTC) CЯacke®
Speaking of house plants, can anyone tell me how to keep my horseradish alive for 10 days without water? Broccoli 23:29, 29 October 2009 (UTC)
- I assume you'll be away? Provide it a magic reservoir that allows "just enough" water to percolate into the pot. Set up a pan of some sort. Fill a gallon or so jug with water and support it upside down a few mm from the bottom of the pan. Place plant in pan so just a little water wicks up into its pot. Voila! ħuman 23:59, 29 October 2009 (UTC)
- I think horseradish will survive so long as the rhizome is kept alive...oh and what "human" said. CЯacke®
- I will never go near one of these bad plants again. Bad Bad Bad. AceMcWicked 00:14, 30 October 2009 (UTC)
- Put a bucket full of water in the center of your kitchen floor. Surround it with your plants. Cut lengths of yarn or twine sufficient to dip one end in the bucket and bury the other in several inches of soil. Use a clothes pin or binder clip to keep the yarn in place. Go on vacation. Capillary action will keep your plants alive. 00:25, 30 October 2009 (UTC)
-
- Thanks! I don't have a pan big enough to put the plant in, but I do have string, a jug and a jar of plum chutney, so I've set up Nutty's method. Broccoli 00:52, 30 October 2009 (UTC)
- Try it out for a few days before you go and tell me how it works. I've never done it :) That was me talking mad-science. 00:59, 30 October 2009 (UTC)
- I leave in less than 24 hours. I'll see if it worked when I get back. Broccoli 01:05, 30 October 2009 (UTC)
- EC) Horseradish? No bother: I always found that it was harder to kill than to keep. It's propagated by root cuttings anyhow so if it dries out just dig it up, chop the root & re-pot as many as you want. Ten years ago I had an infestation of the stuff (don't get me wrong, I love the sauce) even repeated mowing didn't kill it. Eventually I sold the house & left the problem to the buyer! I am eating & honeychat 01:12, 30 October 2009 (UTC)
- You keep horseradish as a houseplant? Actual horseradish and not wasabi? CrundyTalk nerdy to me 08:56, 30 October 2009 (UTC)
Trials[edit]
Hrmph. The wife had to bring her files home for court today (they don't give you much of a life with her job) and one of them is for a couple who have been beating the shit out of their baby (ala Baby P style) and she had to look at the photo evidence. This included photos of a small baby with a massive black eye, and both eyeballs were completely red from burst blood vessels. The second was the case of a chav who was driving (UI) at about 80mph and smashed into the back of a vicar who was stationary at some temporary traffic lights. the vicar's car was crushed almost half way and he was pronnounced dead at the scene. The chav was fine. Therefore one can conclude that either:
1) God really doesn't exist, or
2) God is an asshole.
I hope she gets them sent down. CrundyTalk nerdy to me 21:30, 29 October 2009 (UTC)
- Wow. I don't envy her line of work. I hope they get sent down too. Tetronian you're clueless 21:37, 29 October 2009 (UTC)
- This beating up babies shit seems to be getting more common. I don't have children myself and intend to keep it that way, but having been around various examples of combined genes, I can understand why people could occasionally get frustrated with them. Various friends and family members have admitted to me that the idea of giving their offspring a slap has crossed their minds more than once.
- Okay, I think we can all understand that. Cases like Baby P(eter) and this one, though, really make you wonder about the people involved. I like to think that if I ever did hit a baby (I didn't enjoy typing that) out of frustration, that I'd be shocked into a realisation of what I'd done and do whatever was necessary to give it care. Whether or not I'd turn myself in, I don't know but that's a separate matter. The really upsetting thing about most modern cases is that the violence was prolonged and premeditated. The precise details of the Baby P case haven't come out (or rather, I haven't gone looking) but it appears that his parents stubbed out ciggies on his skin and used other long-term forms of abuse. That's not spur-of-the-moment. That's fucking sick.
- [calms down a bit] The point I'm trying to make is this: is it another case of things like this being discovered more frequently and, ipso facto, being reported more frequently... or is this shit really happening more these days? I hope it's the former. –SuspectedReplicantretire me 21:50, 29 October 2009 (UTC) Sorry for the rant. Struck a nerve.
- Don't apologize. If we get used to this sort of thing happening and just ignore it because it is familiar, we move farther and farther away from preventing it. Tetronian you're clueless 22:33, 29 October 2009 (UTC)
- Just be careful when saying things like "This beating up babies shit seems to be getting more common". Remember the spotlight fallacy, selective reporting and cherry picking - we have (half decent) treatments of all three fallacies and eventualities. I still remember reading about stories where they've uncovered Egyptian hieroglyphics that say "ooh, kids these days" and mor realistically, I remember my mother saying how she walked back home after a night out in the 70s with her keys in her knuckles in case she was attacked and lets not think about how brutal street life was hundreds of years ago. The short story is; these might not really becoming more common, only the reporting and sensationalising of them. That said, I'm not defending any of it, I'm just saying have some perspective where it seems to be "worse than ever". The dichotomy of God being non-existent or a total cunt, however, I cannot disagree with at all - you'd have to have some very rose tinted glasses to disagree with that. theist 01:54, 30 October 2009 (UTC)
- Yes... I know. That's why I said "seems" and then asked the question at the end. I'm not saying violence against children never used to happen (Moors murders f'rinstance) but I don't recall hearing about this kind of torture on babies before. Is it purely reporting or is society getting more sick? –SuspectedReplicantretire me 05:13, 30 October 2009 (UTC)
- Oh, silly me. These were commitals, not trials. The chav case (death by dangerous driving) is indictable only, so she just has to point out the charge and it gets sent to the crown court. She's trying to get the child abuse case sent to the crown as well, because the mags can only dish out a maximum sentence of 6 months, which is a bit short for beating up a baby over a prolonged period of time (the baby also has broken ribs and a broken ulna by the way). CrundyTalk nerdy to me 09:04, 30 October 2009 (UTC)
Music[edit]
Most of you probably won't like it, but I think this is pretty effing awesome. Tetronian you're clueless 00:25, 30 October 2009 (UTC)
Deal or No Deal Australia psychic challenge[edit]
It's no substitute for Randi's $1 million challenge, but it's still fun to watch. Here's the youtube link. Enjoy the meal!Gooniepunk2010 Oi! Oi! Oi! 06:53, 30 October 2009 (UTC)
- Maybe we could add it to the red link Deal or No Deal article. - π 06:55, 30 October 2009 (UTC)
- This video of Australian Deal or No Deal is much funnier. - π 11:09, 30 October 2009 (UTC)
MJ[edit]
My housemate is a bastard. Last night he called me into his room and showed me a video of some guy walking around the late Michael Jackson's Neverland ranch - I hadn't heard this before, but supposedly there was a ghost of MJ caught on camera. Anyway, my friend showed me the video, except this was an altered version. There was an ominous horror music kinda thing going on in the background, then as the shadow passed in the distance which was supposedly the ghost, I dead corpse comes up on the screen, and as it tells you to turn the speakers up loud it screams at you. I predicted this about 10 seconds before it happened, having seen these things beforehand, but I still felt like punching my housemate. SJ Debaser 15:31, 27 October 2009 (UTC)
- I got burnt by that very video, and felt like an ass because of it. Shoulda seen it coming. Aboriginal Noise What the ... 15:52, 27 October 2009 (UTC)
- I had a house mate once who was kicked out of the Army for reasons that were never made clear to me - I think he was on disability for whatever it was wrong with him and he'd spend his days down at the airport video taping planes landing and taking off. I came home from work one day and he insisted on showing me his video of the day - "Here's a plane taking off. Here is one landing. Wait, heres come another!" I told him I thought it was great and wandered off but he got mad and shouted up the stairs after me "Well! I guess if you have seen one plane take off and land you have seen them all then!" Well, yes, you fucking nitwit. AceMcWicked 20:03, 27 October 2009 (UTC)
Anyone else heard this?[edit]
That putting onions in your socks cures colds and the flu? My grandma used to tell me that her family did this all the time--Thanatos 02:35, 29 October 2009 (UTC)
- Ever heard of "add new section"? ħuman 02:37, 29 October 2009 (UTC) (Just got pissed over an unnecessary EC)
- I did press the button--Thanatos 04:06, 29 October 2009 (UTC)
- The top one or the bottom one? - π 04:07, 29 October 2009 (UTC)
- Putting aside a rather nasty attack from Human (everything ok mate? Here, have a Screwdriver, on me). I had never heard of this before it showed up on Snopes' Hot 25 They say it is false (duh) SirChuckBCall the FBI 06:21, 29 October 2009 (UTC)
-
- Those old cures all seemed to depend on various combinations of onions, vinegar and brown paper. I am unaware of the curative properties of brown paper. Is it healthier than white paper? A modern update seems to be that eating curry cures a cold. The germs aren't supposed to like the heat. Real first name and last initial 09:49, 29 October 2009 (UTC)
My late cousin believed that if you had a wart, you should rub a dish towel on it, then toss the dish towel onto the roof of your home. His mother was not amused that he tossed one of her dish towels onto the roof... MDB 11:31, 29 October 2009 (UTC)
- In such a case you need to claim that it's your religious belief and people must repect it. theist 11:41, 29 October 2009 (UTC)
- You would be a bigot not to accept people throwing your linen on to the roof. - π 12:37, 29 October 2009 (UTC)
- What a waste of a dish towel. You're supposed to put some peas in a bag (same number of peas as warts), leave the bag on a path, and whoever picks it up gets your warts. Real first name and last initial 12:47, 29 October 2009 (UTC)
- No,no. You prick a hole in an ivy leaf or is it you wrap small stones in an ivy leaf; anyway, one for each wart and then bury the leaf in the garden. When the leaf is completely rotted away your wart will have gone. (BTW ivy leaves take a long time to rot.) ГенгисRationalWiki GOLD member 13:04, 29 October 2009 (UTC)
- Half a raw potato rubbed on t'wart & then buried. Also many uses for cow pats. I am eating & honeychat 13:07, 29 October 2009 (UTC)
- in passing: is there any truth in the "fact" that if you rub garlic on the sole of your foot, your breath will smell of garlic? I am eating & honeychat 13:09, 29 October 2009 (UTC)
I for one am nearly certain this would work. And what better place to store your onions anyway? I do have one minor aesthetic concern in that I would be worried that the onions would make my rather slim and elegant ankles look a bit lumpy, perhaps even veering in to cankle territory. I almost took a picture of one my ankles as proof of their natural beauty but my office mates would have laughed at me if I tried to hitch my leg in position of the camera on my mac book. You'll just have to take my word for it. Me!Sheesh!Mine! 13:19, 29 October 2009 (UTC)
- The curry curing a cold thing is actually because of two properties of capsaicin: (1) It is an irritant analgesic used for neuropathic pain. In small doses as a topical cream it acts as a painkiller, therefore a curry will help your sore throat. (2) Has a decongestant action because of the burning sensation in the mouth, which clears your nose. So it does make your cold feel better, but certainly doesn't help it persay. CrundyTalk nerdy to me 13:30, 29 October 2009 (UTC)
- Ah, here you go, from the BNF: "Rubefacients act by counter-irritation. Pain, whether superficial or deep-seated, is relieved by any method which itself produces irritation of the skin. Counter-irritation is comforting in painful lesions of the muscles, tendons, and joints, and in non-articular rheumatism. Rubefacients probably all act through the same essential mechanism and differ mainly in intensity and duration of action." CrundyTalk nerdy to me 13:31, 29 October 2009 (UTC)
- I have to put a stop to this right now, it's been going on here for far too long. The phrase is per se (Latin for "by itself") and not persay. </rant>. ГенгисRationalWiki GOLD member 16:19, 29 October 2009 (UTC)
- Fucking hell, I can hardly speak English, let alone Latin. CrundyTalk nerdy to me 16:32, 29 October 2009 (UTC)
Irregardless, it is a mute point. Me!Sheesh!Mine! 16:54, 29 October 2009 (UTC)
- The Welsh still have the best cold cure in my book. 1) Go to bed. 2) Hang a hat on your bedpost. 3) Drink whiskey (or fermented sheep's milk) until you see two hats 4) In the morning you will feel better (or have such a hang over, you won't care about your cold). --PsygremlinSermā! 18:58, 29 October 2009 (UTC)
Wait a moment! If the curry thing is true, why can't we have curry on the NHS? Real first name and last initial 21:05, 29 October 2009 (UTC)
- Funnily enough, you can have whiskey on the NHS. If you are admitted with methanol poisoning then they'll give you whiskey because the ethanol competes with methanol for alcohol dehydrogenase, and the methanol is excreted directly without being metabolised. That's the odd thing about methylated spirit: the antidote is mixed with the poison. CrundyTalk nerdy to me 12:17, 30 October 2009 (UTC)
Creationists are really bad at strategy[edit]
Hey, just decided to run the word "altruism" into fstdt, and was surprised that only 4 examples of crazy fundies using the word came up, and none of them were on the topic of evolution. I'm very surprised they haven't tried to use altruism as an example of "irreducible complexity" yet. I mean so many of their arguments revolve around presenting concepts that sound right in a few sentences, but require long explanations to counter. Just say "If we evolved by natural selection, why do we act altruistically, since helping others isn't in the interest of our reproductive fitness?" To an uneducated layperson, that makes sense. Then an actual scientist tries to explain kin selection, group selection, mutual reciprocity, altruistic punishment, and (probably most importantly for humans) indirect reciprocity, and the lay people are completely lost, and its easy for them to tune it all out.--Mustex 06:22, 30 October 2009 (UTC)
- I have heard that argument several times before actually. It is not that unusual. - π 06:44, 30 October 2009 (UTC)
- It's usually used as an argument against atheism rather than evolution. CrundyTalk nerdy to me 10:10, 30 October 2009 (UTC)
-
- I've always heard it used against evolution. Dawkins has quite a lot on the subject in (I think) The Selfish Gene. –SuspectedReplicantretire me 10:26, 30 October 2009 (UTC)
- Do they specifically refer to it is irreducibly complex, though? I've heard the "so how do you explain altruism", but never seen it crossed with IC. theist 13:42, 30 October 2009 (UTC)
- I've never seen it described as irreducibly complex. It's usually just "Any instinct for altruism is against an organism's interests so it would die out so evolution is wrong" sort of nonsense. –SuspectedReplicantretire me 14:02, 30 October 2009 (UTC)
If they do use it then why wasn't it on fstdt?--Mustex 20:11, 30 October 2009 (UTC)
Quick Q[edit]
Any Russki speakers in the house? Используйте для пароля одновременно латинские буквы и цифры Fox 11:12, 30 October 2009 (UTC)
- nvm, I think it wanted me to use both letters and numbers. Fox 11:14, 30 October 2009 (UTC)
- That's correct. Wondering what site you are registering to. Not a Russian speaker myself, I'm sure Bohdan/Henry could help you, if he still exists. Editor at CPmały książe 12:22, 30 October 2009 (UTC)
- I like... "Russian" music ;) Filling in a few gaps in my extensive library =) Fox 12:39, 30 October 2009 (UTC)
- Always been a very big fan of bit torrent, but with the latest mutterings ("3 strikes and you're disconnected!") about P2P, I'm forcing myself to look to the Russian model of "wth? stick it all on RapidShare". Finding some rather pleasant rarities, too. Had to fork out £6 to get a 30 day RapidShare sub though: the queue time was just getting too long what with all those tight-arsed, skinflint "free" users clogging teh tubes. Fox 20:38, 30 October 2009 (UTC)
- Get yourself a sensible ISP. I did actually get a nastygram a couple of months ago for my torrenting activities, which my ISP forwarded to me for purposes of pointing and laughing. It demanded my internet be cut off immediately for the crime of downloading a movie. My ISP has the policy that they won't take any action without a legitimate court order, which makes you more or less bombproof since there's no way in hell the movie studios are going to take you to small claims court for this. It'd cost more than they could ever recover. --JeevesMkII The gentleman's gentleman at the other site 22:54, 30 October 2009 (UTC)
- That's funny, didn't the RIAA do just that? ħuman 00:20, 31 October 2009 (UTC)
- I believe they did have a policy of instigating legal proceedings against college students and parents of juveniles who d/l p2p. Using the reasoning that these were the least likely to be able to afford to get legal defense. Meantime, in the UK. (More bollox from the totalitarian
Neu ArbeitNew Labour government.) Fox 00:30, 31 October 2009 (UTC)
Ethics[edit]
A thought occurred to me today. From what I've seen, the Design Institute is willing to payroll anyone with any education in any field of science, relevant or not. It seems to me that if, after I finished my Masters in Anthropology I decided to approach them pretending to be interested in a job, I'm sure they'd be very eager to talk to me (assuming they ever hired someone like me I'm sure they would simply report my field as "Anthropology" and conveniently "forget" that I'm cultural, not physical. They'd probably kill for a physical anthropologist on their side). It seems that I could then arrange to have them "find out" that I'm gay (I'm not really), and wait to see how quickly they find an excuse to not accept me. If I did this, it seems to me that I could produce another smoking gun, proving that they're goals are religious and not scientific (if they were interested in science, what objection would they have to employging a gay man if he honestly believed in and was prepared to argue for design?). My question, though, is: would this be ethical? It would clearly involve two counts of dishonestly (posing as a creationist, and posing as a homosexual). Just wanted some feedback.--Mustex 23:38, 30 October 2009 (UTC)
- Seems to me, you think too much. Fox 23:42, 30 October 2009 (UTC)
- Sounds like a trick for a journalist. Doesn't sound too non-ethical, either, not compared to purposefully writing rubbish for them for the money. Broccoli 00:08, 31 October 2009 (UTC)
- I don't see how anything positive could come from this endeavour. You've already said that they'll "find an excuse" not to accept you, so how are you going to prove that it was because of sexual orientation, let alone because of religion? Unless you could prove that to the government, then the incident wouldn't change anybody's opinion about the Design Institute, since their heartland supporters are probably equally homophobic. Meanwhile you'd have ruined your career & possibly your life for no real reason. ŴêâŝêîôîďMethinks it is a Weasel 00:15, 31 October 2009 (UTC)
- There's absolutely zero chance they would fire you for being gay. And ask yourself just how hard you're prepared to work for them in the meantime doing something you think is wrong and terrible. If you didn't work demonstrably hard, they could fire you for that justifiably, and if you worked very hard, you'd be helping them more than you could ever hurt them.--Tom Moorefiat justitia 01:19, 31 October 2009 (UTC)
- Think of the money you could make writing joke articles for them! Broccoli 01:21, 31 October 2009 (UTC)
- Tom, you apparently missed the point. The issue is NOT to work for them and get fired, its to see how interested they are in recruiting me, and how quickly they become disinterested when they came to think I was gay. In short: I would never actually be hired.--Mustex 01:33, 31 October 2009 (UTC)
- Ah, in that case they just won't hire you. They don't have to explain themselves as to why; academia is a rough gig, as you should know after hacking through grad school, and they can easily give a dozen reasons why they don't need another Anthro MA or PhD.--Tom Moorefiat justitia 01:35, 31 October 2009 (UTC)
The blackleg graduate student?[edit]
Okay, serious moral-practical crisis brewing here. The quick summary, as a TA I am automatically placed in a union upon entering my graduate program. My union is getting ready to call a strike, and I have to make some decisions and am looking for intelligent feedback.
Some background that complicates the issue[edit]
Graduate students at McMaster who are in the sciences and engineering departments are well supported. In addition to your TA pay we receive scholarships, bursary, and departmental funding to make sure we can survive our experience. We don't make much, but I can pay my tuition, my rent, eat, and with your help support RW. That is about it.
However, the humanity departments don't have this funding. The only source of support for these students is the TAship. That means that small changes in tuition increases or changes in TA funding have a disproportionate effect on the two populations at the university. The union is run by people out of the humanities, for various reasons. They are more likely to be engaged in the "system", show up to meetings and they have a larger vested interest in the outcome. The political sci department is in charge of bargaining and overseeing a strike as a poly sci major interested in public work is like publishing in nature.
I am perfectly happy with the proposed contract by the univesrity, but that's because of my additional support. A strike is likely at this point.
Reasons not to strike[edit]
- I am TAing for my supervisor for my research, who is the one person most responsible for my success and good standing in this program. Pissing her off is not a good idea.
- I don't think the union leadership represents me or my interest (see above), and have vested interest in seeing a strike regardless of the contracts proposed.
- I barely make enough to survive, as an international student my tuition and fees are greatly increased compared to baseline, the strike pay would net me less money per month, I may not be able to afford such things as rent, or god forbid internet access.
- I am not in a career job, I am here for 2 more years and out. This isn't clearly analogous to unions that represent employees that will have a lifetime at their job.
- My strike pay will come at a significant cost of time and energy working picket lines, more time than I truely have to lose.
- I think a lot of TAs might chose to scab, weaking the strike and making my "stand" meaningless.
- Canadian strikers are fucking wimps. York University near by went on a strike that shut the university down, the government finally stepped in and said "go back to work." They wound up capitulating and getting a worse contract than if they had not gone on strike. The thought of telling the government to shove it never occurred to them. If these people aren't willing to fight once its on the line what is the point?
- I feel sorry for the undergraduates who will be shafted on their education...but only so much.
Reasons to strike[edit]
- I was raised on Union folk lore in a family that has always supported the struggle for better working conditions, scabbing is antithesis to my up bringing and my own political outlook.
- There is significant social and political risk to striking with my fellow TAs who do go on strike.
- The union can seek sanctions against scabs, or force you out of the union all together.
- Even if none of this happens, if it works beautifully and the university capitulates, I get a benefit from others hardship with no personal sacrifice.
So what the hell should I do? Union can call a strike as early as Friday at midnight. Fearless Leader 00:20, 29 October 2009 (UTC)
Discussion[edit]
- I would strike, but I am always that way inclined. - π 00:26, 29 October 2009 (UTC)
- I've always been pro-union, even though I am a manager in a union shop and they all hate me, so I'd be inclined to stick with my union brothers/sisters. If you scab, there is a possibility of retribution from your fellow TAs who chose to strike, it would be difficult to convey your aforementioned issues to them. I assume there were meetings involved leading to the possibility of strike? That would have been a great way to air out the laundry, if you will. I'm not sure how the system works for universities, but I know there are laws in place for elementary/high school teachers who go on strike in that they can only be out for a set amount of time before they have to return to class (my alma mater is currently on the verge of strike themselves). Does this rule apply to universities, and if so, does it apply to TAs? Aboriginal Noise What the ... 02:08, 29 October 2009 (UTC)
- Hmmmm. As a lifelong member of IBEW (I guess, once you're in, you're never out?), which, ironically or amusingly is the union any employees I ever have would join (so I'd have to strike with them?), I think if you're in a union, and they call a strike, you strike. But then there are all the points in the "against" section. The politics... how much time would you lose working on your papers and your experiments, while hanging out in the cold weather waving a sign saying "McMaster Unfair!!11eleventy!"? Can you secretly work while wasting some hours each day blocking access to your workspace? Anyway, I say "strike". Although sometimes union movements create stupid situations, if the brothers and sisters don't link arms, there is nothing at all. ħuman 02:17, 29 October 2009 (UTC)
PS, isn't this also a great opportunity to experiment with drinking yourself to death? ħuman 02:18, 29 October 2009 (UTC)
- I want to chime in before Listener goes all arrrREDREDREDRED!!! Don't strike!!! only REDREDREDREDS strike. It's a tough call. as "red" as I am, it's hard--even as a grad student myself--to get behind the idea of a strike for many of the reasons you list here. Tops for me is that this is a limited contract (five years v. your two) and not a lifetime vocation. I like the idea of exploring alternative strategies (not inputting grades might be one example) that might gum up the works/be a pain in the ass but wouldn't do as much to muck up the u-grads' semesters, or your bottom line. And the big problem is, as you point out, that diffferent faculties have very different cultures re: the role and treatment of TAs/grad students, which makes it hard to co-ordinate plane and outlooks (my department only lets people in with five years of guaranteed funding in the form of TA'ing, free money and tuition waivers. Anthro, for example, does not, and people often have to fend for themselves. Hard to co-ordinate given the real disparities.) Anyway, as weird as it is for me to say this, on this one, I think you have to follow your heart...RaoulDuke 02:58, 29 October 2009 (UTC)
- Actually, IIRC, ListenerX doesn't dislike unions, just union corruption. - π 03:22, 29 October 2009 (UTC)
- (EC) RaoulDuke, I have no problem with workers going on strike if they are dissatisfied with their working conditions. The only things I have problems with in that area are (1) unions being given legal privileges so that workers cannot be made directly accountable for unreasonable demands (as they would be in the case of a worker-owned company); (2) the fact that most union rallies I have attended have drawn out perhaps ten actual workers and also most left-wing cranks within ten miles. (Also union corruption, but that is a fairly apolitical dislike.)
- Tmtoulouse, based on the conditions you have outlined above, if I were you I would cross the picket line with barely a glance left or right, but if you cannot do that with a clear conscience then most certainly you should not do it. ListenerXTalkerX 03:25, 29 October 2009 (UTC)
- A very well-put response from LX. ħuman 03:34, 29 October 2009 (UTC)
- That is going to ruin Raoul's day, I bet he was looking forward to that argument. - π 03:38, 29 October 2009 (UTC)
- Your given reasons to strike: Reason 1. While this may be important to you psychologically it obviously should be checked against whether striking is useful or in your best interest. Reasons 2 and 3 look like pressures outside of the question of whether the strike is "right" / "wrong" or "good" / "bad". One could argue that there is a level of intimidation involved which it would be best to ignore. A cynic could regard reason 4 as an argument either way.
- In contrast, your "reasons not to strike" strike me as generally persuasive.--BobNot Jim 07:34, 29 October 2009 (UTC)
- The real problem is surely: "as a TA I am automatically placed in a union upon entering my graduate program." As a one time union member and partner to a similar, I always retained the ability to vote with my feet and leave the union if I found they were growing too irrational. I never did (I always worked for smallish companies where we saw the owners almost daily) but I had the option. I am eating & honeychat 10:06, 29 October 2009 (UTC)
- (EC)I recall a massive stike action by some groups of lecturers a few years ago in the UK where they basically stopped marking. Students went fucking apeship over it - remember, if you do it, these are the guys who will be affected, strikers choose to strike and take the stuff that comes with such action, the students you teach are more than collateral damage. What are the conditions of the strike? Ceasing all teaching or just certain aspects like formal or assessed marking? Are you still going to be there for any undergrads who knock on your door after hours saying "dude, what the hell does this mean?". Of course, I'm biased towards this point because I actually do like teaching and still young enough to know what it's like to be a confused and bewildered student. You do seem to have more points against the strike action, though and your reasons for don't seem like you have your heart in it and you've decided already. theist 10:10, 29 October 2009 (UTC)
- Morally a very difficult decision. On the one hand, you feel strongly about unions and the laudable goals they pursue. Scabbing would be a blow to the effectiveness of the union itself, though you've said Canadian student unions are hosers, and would subject you to the ire and derision of your comrades. On the other, this particular union was thrust upon you and does not completely represent your interests. Let me ask you this: what kinds of deals do those few grad students who are not members of the union get? Is you PI the one responsible for renewing your gig? Would quitting the union get you what you've got now without getting you in trouble with those rabble rousers? 14:37, 29 October 2009 (UTC)
If you believe in the union movement, then you've only got one (probably very difficult) question to consider: do the humanities TAs have a legitimate case for strike action? If they do, then you should walk out alongside them. If they don't, then break the strike with a clear conscience. --Robledo 18:48, 29 October 2009 (UTC)
Update[edit]
Thanks to everyone for the discussion it has helped focus my thoughts somewhat. After having met with many of my fellow TAs I think we have a path of action. The biggest questions is the legitimacy of the right of the union leadership to call a strike. They have a "strike mandate" vote that was advertised as a "bargaining tool" and "not a vote to strike." This strike mandate vote got about 200 out of the 3000 TAs. This is clearly not a legitimate mandate to strike. What we have decided is to band together in the event that negotiations fail and to tell the union that we do not think they have a true mandate and that they need to call a general meeting and ask for a strike vote. If at that meeting the membership of the union votes to strike, I, as well as many other luke warm supporters will go ahead and support the strike full heartedly knowing its the true wish of the majority of members. If the strike vote fails, or if they refuse to call such a vote then I think its safe to say that the union is out for itself and not representing our interest and at that point strikebreaking starts to look like a better possibility. tmtoulouse 19:56, 30 October 2009 (UTC)
- Always worrying when unions don't hold proper strike ballots =/ Usually means they know beforehand they won't get the approval of the membership. I'm a supporter of trade unionism, btw, but also of democracy and fair representation within the union. Look what happened to the NUM when Scargill decided not to hold a national ballot ... Fox 20:14, 30 October 2009 (UTC)
I gotta say this much, while the issues of strike, money and standing outside in the snow all winter suck, starting a grass roots political movement is damn fun. I had forgotten how great it is. After leaving NM I sort of dropped politics to the side. So even this little taste is a much needed salv. There is an amazing ground swell of support from the TAs as well. I think the vast majority have felt the same as me, that we are being strong armed by a union that doesn't have our interest at heart. The game starts in earnest tomorrow. However, a strike has been officially called.
So just a note, and I may bring this up again later more prominently, if I wind up having to strike through December, or longer, I am going to need help keeping RW up. Hopefully it won't happen. 21:14, 31 October 2009 (UTC)
|
https://rationalwiki.org/wiki/RationalWiki:Saloon_bar/Archive39
|
CC-MAIN-2022-21
|
refinedweb
| 23,945
| 70.63
|
01 December 2010 18:03 [Source: ICIS news]
LONDON (ICIS)--The Styrolution joint venture (JV) between BASF and INEOS will just hand more power to an already-small pool of producers, European acrylonitrile-butadiene styrene (ABS) consumers said on Wednesday.
Buyers complained that there were only four main ABS manufacturers in western Europe as it was, with INEOS and BASF the largest, and if the plan were to go through their combined capacities would be close to 60% of the domestic market.
The 50:50 JV would combine not just ABS, but global business activity in styrene monomers, polystyrene and other styrene-based copolymers. However, its establishment was still subject to approval by the appropriate antitrust authorities. The two companies hope to implement the venture in late 2011.
However, ABS players were not so sure this would happen. One customer said: “I’ll be surprised if the competition authorities don’t have something to say about this.”
BASF has two ABS plants in Europe, a 200,000 tonne/year unit in Antwerp, Belgium, and an 80,000 tonne/year site in Ludwigshafen, Germany, according to the ICIS Plants and Projects Database.
INEOS runs a 130,000 tonne/year plant in ?xml:namespace>
Their main competition in the region would be Styron’s 200,000 tonne/year site at
BASF says that with worldwide ABS capacity reaching 6m tonnes, consumers had little to worry about should the JV be approved.
“ABS is a global market and there is enough production worldwide to ensure there is enough competition,” BASF spokesman Michael Grabicki said.
However, European players said that competitive imports from
These factors had already contributed to ABS compounding grade prices rising from €1,450-1,480/tonne ($1,883-1,922/tonne) to €1,790-1,840/tonne since January, according to ICIS.
“I buy from both [BASF and INEOS] and can see no good coming from this at all… It’ll be good for the producers because it means higher prices and more control over the market for them,” one buyer said.
Other suppliers were more measured in their views, and while they also expressed apprehension about the JV, there were also questions over the business direction Styrolution would take with regards to ABS.
INEOS tended to concentrate more on coloured, performance and specialty grades, targeted more towards the high end of the market, while BASF focused more on the extrusion and commodity sectors, players said.
“It will be interesting to see what happens, as they run two different product lines. We will have to see how they integrate and what strategy they take,” a seller said.
For now, observers were waiting on the verdict of competition regulators before speculating too much on the consequences of Styrolution.
($1 = €0.77)
For more on ABS visit ICIS chemical intelligence
For more on BASF
|
http://www.icis.com/Articles/2010/12/01/9415816/styrolution-implications-concern-europe-abs-players.html
|
CC-MAIN-2014-42
|
refinedweb
| 472
| 56.39
|
94578/without-filling-required-required-fields-printed-console
Hello,
For your query you can refer this one:
Hope it helps you!!
This worked for me. Check this out
import ...READ MORE
Have you tried this one? ...READ MORE
Hi Esha, you can get the number ...READ MORE
Hey Joel, you can use following lines ...READ MORE
The better way to handle this element ...READ MORE
enable trusted connection in internet explorer by ...READ MORE
TestNG and JUnit are test frameworks .
it ...READ MORE
To Allow or Block the notification, access using Selenium and you have to ...READ MORE
Hello,
You want to use a non-breaking space ...READ MORE
Hello @ naresh,
With the actions object you should ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in.
|
https://www.edureka.co/community/94578/without-filling-required-required-fields-printed-console
|
CC-MAIN-2021-31
|
refinedweb
| 143
| 69.58
|
Implementation status: to be implemented
Synopsis
#include <stdio.h>
#include <wchar.h>
wint_t btowc(int c);
Description
The function transforms a single byte to a wide character.
Arguments
c - a character to be transformed.
The behavior of this function is affected by the
LC_CTYPE category of the current locale.
Return value
The wide-character representation of that character c.
WEOF - if c is equal
EOF or if (unsigned char) c does not constitute a valid (one-byte) character in the initial shift state.
btowc() does not return
WEOF if c has a value in the range
0 to
255 inclusive.
Errors
No errors are defined.
|
https://phoenix-rtos.com/documentation/libphoenix/posix/btowc
|
CC-MAIN-2020-34
|
refinedweb
| 105
| 60.21
|
@Fil thanks for pointing out the Mozilla's App Manfiest!
@Ken I think prudent that Apache Cordova listen to BlackBerry's experience
with the widget spec. We're both using it in similar ways and Apache
Cordova will likely hit the same areas for customization. Ken, can you
elaborate on how BB10 will be deviating even further? Is there a link out
there?
Regardless of what we choose, we don't want to invent our own app manifest
"standard" and so it's worth reviewing the two that are out there. Below
are the spec links.
W3C Configuration Document (config.xml):
BlackBerry WebWorks config.xml:
Mozilla App Manifest:
Michael
On Tue, May 29, 2012 at 11:13 AM, Ken Wallis <kwallis@rim.com> wrote:
> Laurent and I were just chatting about this. Certainly feel that we
> should have a common shared format for application metadata. Default
> option would be to look at the W3C widget spec which we all are or already
> have done in RIM's case. ;)
>
> That said, you know that we have gone past the spec already, and with BB10
> we will have to go even farther down the custom namespace route. We (RIM)
> may need to actively diverge on some concepts that might have Widget
> equivalents but just don't map properly (Not sure yet, but starting to get
> a feeling...) I would suspect that Cordova will need custom elements as
> well.
>
> Do we ask the question then, is this still the right choice, use widget
> spec as a basis and expand where needed? Use it as inspiration, but not be
> beholden to it? Something completely custom, or aligned with other
> initiatives like Mozilla?
>
> Lots of questions... ;)
> --
>
> Ken Wallis
>
> Product Manager – BlackBerry WebWorks
>
> Research In Motion
>
> (905) 629-4746 x14369
>
> ________________________________________
> From: Filip Maj [fil@adobe.com]
> Sent: Tuesday, May 29, 2012 2:02 PM
> To: callback-dev@incubator.apache.org
> Subject: Re: Cordova and config.xml
>
> Just want to point out too that mozilla has/is working on their equivalent
> of config.xml
>
>
>
>
> JSON! :r
>
> On 5/29/12 10:57 AM, "Shazron" <shazron@gmail.com> wrote:
>
> >I concur - we had this discussion sometime ago but with respect to the
> >whitelist, and eventually decided to support access tags in config.xml to
> >consolidate all the platforms. We didn't have a plan then on when to
> >include this feature. Not seeing it in the Roadmap though pre-2.0 or even
> >for 2.0:
> >
> >On Tue, May 29, 2012 at 9:49 AM, Michael Brooks
> ><michael@michaelbrooks.ca>wrote:
> >
> >> From my understanding, yes.
> >>
> >> PhoneGap Build currently uses it (not as extensively as BB) to describe
> >>the
> >> app's metadata and configuration (access, permissions, etc).
> >>
> >> My understanding is that as we build out the CLI for Apache Cordova,
> >>then
> >> config.xml support will be added.
> >>
> >> Michael
> >>
> >> On Mon, May 28, 2012 at 1:12 PM, Gord Tanner <gtanner@gmail.com> wrote:
> >>
> >> > Hey,
> >> >
> >> > I am wondering if cordova is going to continue aligning to the W3C
> >> > config.xml?
> >> >
> >> > Unless I am mistaken it looks like BlackBerry and PlayBook are the
> >>only
> >> > platforms that are currently using it. Is there plans to use
> >>config.xml
> >> > more cross.
>
|
http://mail-archives.apache.org/mod_mbox/incubator-callback-dev/201205.mbox/%3CCAP7NMPqRFMMbKnBCiRpVq+ZkK4AkiZHURqH__8qWeT6jFbekzg@mail.gmail.com%3E
|
CC-MAIN-2017-13
|
refinedweb
| 529
| 76.11
|
05 November 2012 11:12 [Source: ICIS news]
SINGAPORE (ICIS)--China National Offshore Corp (CNOOC) is expected to spend about $5.0bn (€3.9bn) on Queensland Curtis LNG (QCLNG), in which the company has acquired an equity interest, ratings firm Moody’s Investor Service said on Monday.
The amount will cover the acquisition cost of a partial stake in the Australian liquefied natural gas (LNG) project, as well as capital expenditure, said Moody’s vice president and senior analyst Simon Wong in a statement.
CNOOC has bought a stake in the QCLNG project for $1.93bn from BG Group. Moody’s said the acquisition is “credit negative” for CNOOC but has no immediate impact on its “Aa3” rating and stable outlook.
"The deal indicates a very aggressive level of risk appetite on the part of CNOOC, as it was announced just four months after CNOOC Ltd – CNOOC's 64%-owned subsidiary – proposed the acquisition of Nexen Inc for $15.1bn, said Wong.
"If both deals proceed as proposed, CNOOC's consolidated financial profile will materially weaken,” the analyst said.
Moody’s, however, is maintaining its “Aa3” rating on CNOOC Group, which enjoys a high level of support from the Chinese government given the group’s “strategic importance to ?xml:namespace>
"We consider that the increase in CNOOC's stake in the QCLNG project and the long-term LNG supply agreement with BG Group will further strengthen CNOOC's dominant position as China's largest importer for LNG," said Kai Hu, Moody's local market analyst for CNOOC.
CNOOC owns most LNG-receiving ports in operation and under construction in
"The QCLNG deal is also in line
|
http://www.icis.com/Articles/2012/11/05/9610679/cnooc-likely-to-spend-5bn-on-queensland-curtis-lng.html
|
CC-MAIN-2015-11
|
refinedweb
| 276
| 58.32
|
So, I run meteor test --driver-package practicalmeteor:mocha and it takes maybe a minute to a minute and a half to run a test. It there an obvious gotcha here that I’m missing?
Meteor test very long build times
Today i tried wallaby js.
It’s expensive but i was immediatly hooked and had to bought it, what a time saver !
Yea, that’s a little pricey, but worth it if it eliminates the headaches that come with Meteor testing. Which platform are you using it on?
Can you share any pointers setting up Wallaby with Meteor?
I’m really keen to try it, but I’m not sure how to setup the wallaby config.
I’m using a config file by Arunoda/Mantra, slightly modified :
module.exports = function (wallaby) { // There is a weird error with the mui and mantra. // See: // Using require here seems to be the error. // Renaming it into `load` just fixed the issue. var load = require; return { files: [ { pattern: 'client/**/tests/*.js', ignore: true }, { pattern: 'server/**/tests/*.js', ignore: true }, 'client/imports/modules/**/components/*.js', 'client/imports/modules/**/actions/*.js', 'client/imports/modules/**/containers/*.js', 'client/imports/modules/**/libs/*.js', 'client/imports/**/*.jsx' ], tests: [ 'client/**/tests/*.js' ], compilers: { '**/*.js*': wallaby.compilers.babel({ babel: load('babel-core'), presets: ['es2015', 'react', 'stage-2'] }) }, env: { type: 'node' }, testFramework: 'mocha', setup: function() { global.React = require('react'); } }; };
Awesome!
I had to learn about those babel presets and how to install them. Also, it seems I had to install babel-core.
I’m testing this with the 1.3 version of the Meteor-React Todo app tutorial. I modified your config a bit more, just to load different files
return { return { files: [ 'imports/**.js' ], tests: [ '**/*.tests.js' ], ...
Now that wallaby appears to be running, I’m getting my first error, it’s not finding modules:
Error: Cannot find module 'meteor/meteor' at imports/api/tasks.tests.js:1:0
That line in imports/api/tasks.tests.js is:
import { Meteor } from 'meteor/meteor';
Not sure how to get wallaby to load that module.
Running wallaby.js now with IntelliJ Idea. Wow, this is unbelievable. Everyone should try this…
@tomRedox and @mhurwi, that error is because you cannot just import the Meteor framework that way. But it is possible to stub out Meteor parts, which is a good testing strategy anyway. Don’t test parts that are not your to test.
See more about this in a post I’ve written here yesterday.
In the opening post I explain how to use
proxyquire with
sinon to stub out the Meteor framework, and in followup comment I explain how to use
testdouble to do the very same thing.
@smeijerm thanks for the response, I saw your post, it looks really useful.
I completely agree re mocking (and potentially DI too), but actually in my case the module I couldn’t load was
meteor/practicalmeteor:chai that I needed in order to set up the assertions in the unit test! The actual SUT was a vanilla JS class. Looking at your code I see your using Chai straight from npm which is a much better approach.
That does beg a question though, for external modules like Lodash, moment, accounting and the like I probably wouldn’t bother stubbing those out, I’m happy to accept them as well tested black boxes (i.e. they aren’t things I feel the need to test). If I use the npm versions that should be fine, but for Meteor packages it looks like I’d need to stub them which is a nuisance.
The trick is indeed to use npm packages whenever possible.
If you really want to use the meteor lodash package (although I cannot come up with a reason why), you should be able to replace the meteor lodash package by an npm lodash module while running the tests.
Be sure to use
npm install --save-dev lodash in that case to prevent a double presence in your production code.
And be sure to npm install the same version as your meteor package. Because you won’t be testing the same functionality otherwise.
Meteor 1.3 testing - with "meteor/meteor:x" package imports
Whilst it works with WebStorm I’m wondering if it will work with Meteor as it’s not listed at all:
Should have googled more. I’ve found this recent addition so it seems with the config it works:
|
https://forums.meteor.com/t/meteor-test-very-long-build-times/20599/10
|
CC-MAIN-2019-04
|
refinedweb
| 738
| 65.73
|
PetClinic is a sample application demonstrating the usage of Spring Python.
It uses CherryPy as the web server object.
A detailed design document (NOTE: find latest version, and click on raw) is part of the source code. You can read it from here or by clicking on a hyperlink while running the application.
Assuming you just checked out a copy of the source code, here are the steps to run PetClinic.
bash$ cd /path/you/checked/out/springpython bash$ cd samples/petclinic bash$ python configure.py
At this point, you will be prompted for MySQL's root password. This is NOT your system's root password. This assumes you have a MySQL server running. After that, it will have setup database petclinic.
bash$ cd cherrypy bash$ python petclinic.py
This assumes you have CherryPy 3 installed. It probably won't work if you are still using CherryPy 2. NOTE: If you are using Python 2.5.2+, you must install CherryPy 3.1.2+. The older version of CherryPy (3.1.0) only works pre-2.5.2.
Finally, after launching it, you should see a nice URL at the bottom:. Well, go ahead! Things should look good now!
Snapshot of PetClinic application
Spring Wiki is a wiki engine based that uses mediawiki's markup language. It utilizes the same stylesheets to have a very wikipedia-like feel to it.
TODO: Add persistence. Currently, Spring Wiki only stores content in current memory. Shutting it down will cause all changes to be lost.
This article will show how to write an IRC bot to manage a channel for your open source project, like the one I have managing #springpython, the IRC chat channel for Spring Python.
I read an article, Building a community around your open source project, that talked about setting up an IRC channel for your project. This is a route to support existing users, and allow them to work with each other.
I became very interested in writing some IRC bot, and I since my project is based on Python, well, you can probably guess what language I wanted to write it in.
To build a bot, it pays to have use an already written library. I discovered python-irclib.
For Ubuntu users:
% sudo apt-get install python-irclib
This bot also sports a web page using CherryPy. You also need to install that as well.
Well, of course I started reading. The documentation from the project's web site was minimal. Thankfully, I found some introductory articles that work with python-irclib.
Using this, I managed to get something primitive running. It took me a while to catch on that posting private messages on a channel name instead of a user is the way to publicly post to a channel. I guess it helped to trip through the IRC RFC manual, before catching on to this.
At this stage, you may wish to get familiar with regular expressions in Python. You will certainly need this in order to make intelligent looking patterns. Anything more sophisticated would probably require PLY.
What I really like is that fact that I built this application in approximately 24 hours, counting the time to learn how to use python-irclib. I already knew how to build a Spring Python/CherryPy web application. The history pages on this article should demonstrate how long it took.
NOTE: This whole script is contained in one file, and marked up as:
""" Copyright 2006-2008 SpringS. """
So far, this handy little bot is able to monitor the channel, log all communications, persistently fetch/store things, and grant me operator status when I return to the channel. My next task is to turn it into a web app using Spring Python. That should let me have a web page to go along with the channel!
class DictionaryBot(ircbot.SingleServerIRCBot): def __init__(self, server_list, channel, ops, logfile, nickname, realname): ircbot.SingleServerIRCBot.__init__(self, server_list, nickname, realname) self.datastore = "%s.data" % self._nickname self.channel = channel self.definition = {} try: f = open(self.datastore, "r") self.definition = cPickle.load(f) f.close() except IOError: pass self.whatIsR = re.compile(",?\s*[Ww][Hh][Aa][Tt]\s*[Ii][Ss]\s+([\w ]+)[?]?") self.definitionR = re.compile(",?\s*([\w ]+)\s+[Ii][Ss]\s+(.+)") self.ops = ops self.logfile = logfile def on_welcome(self, connection, event): """This event is generated after you connect to an irc server, and should be your signal to join your target channel.""" connection.join(self.channel) def on_join(self, connection, event): """This catches everyone who joins. In this case, my bot has a list of whom to grant op status to when they enter.""" self._log_event(event) source = event.source().split("!")[0] if source in self.ops: connection.mode(self.channel, "+o %s" % source) def on_mode(self, connection, event): """No real action here, except to log locally every mode action that happens on my channel.""" self._log_event(event) def on_pubmsg(self, connection, event): """This is the real meat. This event is generated everytime a message is posted to the channel.""" self._log_event(event) # Capture who posted the messsage, and what the message was. source = event.source().split("!")[0] arguments = event.arguments()[0] # Some messages are meant to signal this bot to do something. if arguments.lower().startswith("!%s" % self._nickname): # "What is xyz" command match = self.whatIsR.search(arguments[len(self._nickname)+1:]) if match: self._lookup_definition(connection, match.groups()[0]) return # "xyz is blah blah" command match = self.definitionR.search(arguments[len(self._nickname)+1:]) if match: self._set_definition(connection, match.groups()[0], match.groups()[1]) return # There are also some shortcut commands, so you don't always have to address the bot. if arguments.startswith("!"): match = re.compile("!([\w ]+)").search(arguments) if match: self._lookup_definition(connection, match.groups()[0]) return def getDefinitions(self): """This is to support a parallel web app fetching data from the bot.""" return self.definition def _log_event(self, event): """Log an event to a flat file. This can support archiving to a web site for past activity.""" f = open(self.logfile, "a") f.write("%s::%s::%s::%s\n" % (event.eventtype(), event.source(), event.target(), event.arguments())) f.close() def _lookup_definition(self, connection, keyword): """Function to fetch a definition from the bot's dictionary.""" if keyword.lower() in self.definition: connection.privmsg(self.channel, "%s is %s" % self.definition[keyword.lower()]) else: connection.privmsg(self.channel, "I have no idea what %s means. You can tell me by sending '!%s, %s is <your definition>'" % (keyword, self._nickname, keyword)) def _set_definition(self, connection, keyword, definition): """Function to store a definition in cache and to disk in the bot's dictionary.""" self.definition[keyword.lower()] = (keyword, definition) connection.privmsg(self.channel, "Got it! %s is %s" % self.definition[keyword.lower()]) f = open(self.datastore, "w") cPickle.dump(self.definition, f) f.close()
I have trimmed out the instantiation of this bot class, because that part isn't relevant. You can go and immediately reuse this bot to manage any channel you have.
Well, after getting an IRC bot working that quickly, I want a nice interface to see what it is up to. For that, I will use Spring Python and build a Spring-based web app.
def header(): """Standard header used for all pages""" return """ <!-- Coily :: An IRC bot used to manage the #springpython irc channel (powered by CherryPy/Spring Python) --> <html> <head> <title>Coily :: An IRC bot used to manage the #springpython irc channel (powered by CherryPy/Spring Python)</title> <style type="text/css"> td { padding:3px; } div#top {position:absolute; top: 0px; left: 0px; background-color: #E4EFF3; height: 50px; width:100%; padding:0px; border: none;margin: 0;} div#image {position:absolute; top: 50px; right: 0%; background-image: url(images/spring_python_white.png); background-repeat: no-repeat; background-position: right; height: 100px; width:300px } </style> </head> <body> <div id="top"> </div> <div id="image"> </div> <br clear="all"> <p> </p> """ def footer(): """Standard footer used for all pages.""" return """ <hr> <table style="width:100%"><tr> <td><A href="/">Home</A></td> <td style="text-align:right;color:silver">Coily :: a <a href="">Spring Python</a> IRC bot (powered by <A HREF="">CherryPy</A>)</td> </tr></table> </body> """ def markup(text): """Convert any references into real web links.""" httpR = re.compile(r"(http://[\w.:/?-]*\w)") alteredText = httpR.sub(r'<A HREF="\1">\1</A>', text) return alteredText class CoilyView: """Presentation layer of the web application.""" def __init__(self, bot = None): """Inject a controller object in order to fetch live data.""" self.bot = bot @cherrypy.expose def index(self): """CherryPy will call this method for the root URI ("/") and send its return value to the client.""" return header() + """ <H2>Welcome</H2> <P> Hi, I'm Coily! I'm a bot used to manage the IRC channel <a href="irc://irc.ubuntu.com/#springpython">#springpython</a>. <P> If you visit the channel, you may find I have a lot of information to offer while you are there. If I seem to be missing some useful definitions, then you can help grow my knowledge. <small> <TABLE border="1"> <TH>Command</TH> <TH>Description</TH> <TR> <TD>!coily, what is <i>xyz</i>?</TD> <TD>This is how you ask me for a definition of something.</TD> </TR> <TR> <TD>!<i>xyz</i></TD> <TD>This is a shortcut way to ask the same question.</TD> </TR> <TR> <TD>!coily, <i>xyz</i> is <i>some definition for xyz</i></TD> <TD>This is how you feed me a definition.</TD> </TR> </TABLE> </small> <P> To save you from having to query me for every current definition I have, there is a link on this web site that lists all my current definitions. NOTE: These definitions can be set by other users. <P> <A href="listDefinitions">List current definitions</A> <P> """ + footer() @cherrypy.expose def listDefinitions(self): results = header() results += """ <small> <TABLE border="1"> <TH>Keyword</TH> <TH>Definition</TH> """ for key, value in self.bot.getDefinitions().items(): results += markup(""" <TR> <TD>%s</TD> <TD>%s</TD> </TR> """ % (value[0], value[1])) results += "</TABLE></small>" results += footer() return results
Well, so far, I have two useful classes. However, they need to get launched inside a script. This means objects need to be instantiated. To do this, I have decided to make this a Spring app and use inversion of control.
So, I defined two contexts, one for the IRC bot and another for the web application.
class CoilyIRCServer(PythonConfig): """This container represents the context of the IRC bot. It needs to export information, so the web app can get it.""" def __init__(self): super(CoilyIRCServer, self).__init__() @Object def remoteBot(self): return DictionaryBot([("irc.ubuntu.com", 6667)], "#springpython", ops=["Goldfisch"], nickname="coily", realname="Coily the Spring Python assistant", logfile="springpython.log") @Object def bot(self): exporter = PyroServiceExporter() exporter.service_name = "bot" exporter.service = self.remoteBot() return exporter
class CoilyWebClient(PythonConfig): """ This container represents the context of the web application used to interact with the bot and present a nice frontend to the user community about the channel and the bot.\ """ def __init__(self): super(CoilyWebClient, self).__init__() @Object def root(self): return CoilyView(self.bot()) @Object def bot(self): proxy = PyroProxyFactory() proxy.service_url = "PYROLOC://localhost:7766/bot" return proxy
I fit all this into one executable. However, I quickly discovered that both CherryPy web apps and irclib bots like to run in the main thread. This means I need to launch two python shells, one running the web app, the other running the ircbot, and I need the web app to be able to talk to the irc bot. This is a piece of cake with Spring Python. All I need to utilize is a remoting technology.
if __name__ == "__main__": # Parse some launching options. parser = OptionParser(usage="usage: %prog [-h|--help] [options]") parser.add_option("-w", "--web", action="store_true", dest="web", default=False, help="Run the web server object.") parser.add_option("-i", "--irc", action="store_true", dest="irc", default=False, help="Run the IRC-bot object.") parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False, help="Turn up logging level to DEBUG.") (options, args) = parser.parse_args() if options.web and options.irc: print "You cannot run both the web server and the IRC-bot at the same time." sys.exit(2) if not options.web and not options.irc: print "You must specify one of the objects to run." sys.exit(2) if options.debug: logger = logging.getLogger("springpython") loggingLevel = logging.DEBUG logger.setLevel(loggingLevel) ch = logging.StreamHandler() ch.setLevel(loggingLevel) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") ch.setFormatter(formatter) logger.addHandler(ch) if options.web: # This runs the web application context of the application. It allows a nice web-enabled view into # the channel and the bot that supports it. applicationContext = ApplicationContext(CoilyWebClient()) # Configure cherrypy programmatically. conf = {"/": {"tools.staticdir.root": os.getcwd()}, "/images": {"tools.staticdir.on": True, "tools.staticdir.dir": "images"}, "/html": {"tools.staticdir.on": True, "tools.staticdir.dir": "html"}, "/styles": {"tools.staticdir.on": True, "tools.staticdir.dir": "css"} } cherrypy.config.update({'server.socket_port': 9001}) cherrypy.tree.mount(applicationContext.get_object(name = "root"), '/', config=conf) cherrypy.engine.start() cherrypy.engine.block() if options.irc: # This runs the IRC bot that connects to a channel and then responds to various events. applicationContext = ApplicationContext(CoilyIRCServer()) coily = applicationContext.get_object("bot") coily.service.start()
Now that you have a CherryPy web app running, how about making it visible to the internet?
If you already have an Apache web server running, and are using a Debian/Ubuntu installation, you just need to create a file in /etc/apache2/sites-available like coily.conf with the following lines:
RedirectMatch ^/coily$ /coily/ ProxyPass /coily/ ProxyPassReverse /coily/ <LocationMatch /coily/.*> Order allow,deny Allow from all </LocationMatch>
Now need to softlink this into /etc/apache2/sites-enabled.
% cd /etc/apache2/sites-enabled % sudo ln -s /etc/apache2/sites-available/coily.conf 001-coily
This requires that enable mod_proxy.
% sudo a2enmod proxy proxy_http
Finally, restart apache.
% sudo /etc/init.d/apache2 --force-reload
It should be visible on the site now.
|
https://docs.spring.io/spring-python/1.1.x/reference/html/samples.html
|
CC-MAIN-2017-39
|
refinedweb
| 2,332
| 52.46
|
Test::Assert - Assertion methods for those who like JUnit.
# Use as imported methods # package My::Test; use Test::Assert ':all'; assert_true(1, "pass"); assert_true(0, "fail"); use Test::More; assert_test(sub { require_ok($module) }); # Use for debugging purposes # Assertions are compiled only if Test::Assert was used # from the main package. # package My::Package; use Test::Assert ':assert'; my $state = do_something(); assert_true($state >= 1 && $state <=2) if ASSERT; if ($state == 1) { # 1st state do_foo(); } elsif ($state == 2) { # 2nd and last state do_bar(); } my $a = get_a(); my $b = get_b(); assert_num_not_equals(0, $b) if ASSERT; my $c = $a / $b; # Clean the namespace no Test::Assert; # From command line $ perl -MTest::Assert script.pl # sets Test::Assert::ASSERT to 1
This class provides a set of assertion methods useful for writing tests. The API is based on JUnit4 and Test::Unit::Lite and the methods die on failure.
These assertion methods might be not useful for common Test::Builder-based (Test::Simple, Test::More, etc.) test units.
The assertion methods can be used in class which is derived from
Test::Assert or used as standard Perl functions after importing them into user's namespace.
Test::Assert can also wrap standard Test::Simple, Test::More or other Test::Builder-based tests.
The assertions can be also used for run-time checking.
Thrown whether an assertion failed.
By default, the class does not export its symbols.
Enables debug mode if it is used in
main package.
package main; use Test::Assert; # Test::Assert::ASSERT is set to TRUE $ perl -MTest::Assert script.pl # ditto
Imports some methods.
Imports all
assert_* methods,
fail method and
ASSERT constant.
Imports all
assert_* methods and
ASSERT constant.
Disables debug mode if it is used in
main package.
This constant is set to true value if
Test::Assert module is used from
main package. It allows to enable debug mode globally from command line. The debug mode is disabled by default.
package My::Test; use Test::Assert ':assert'; assert_true( 0 ) if ASSERT; # fails only if debug mode is enabled $ perl -MTest::Assert script.pl # enable debug mode
Immediate fail the test. The Exception::Assertion object will have set message and reason attribute based on arguments.
Checks if boolean expression returns true value.
Checks if boolean expression returns false value.
Checks if value is defined or not defined.
Checks if value1 and value2 are equals or not equals. If value1 and value2 look like numbers then they are compared with '==' operator, otherwise the string 'eq' operator is used.
Force numeric comparation.
Force string comparation.
Checks if value matches pattern regexp.
Checks if reference value1 is a deep copy of reference value2 or not. The references can be deep structure. If they are different, the message will display the place where they start differing.
Checks if value is a class or not.
assert_isa( 'My::Class', $obj );
Runs the code and checks if it raises the expected exception.
If raised exception is an Exception::Base object, the assertion passes if the exception
matches expected argument (via
Exception::Base->matches method).
If raised exception is not an Exception::Base object, several conditions are checked. If expected argument is a string or array reference, the assertion passes if the raised exception is a given class. If the argument is a regexp, the string representation of exception is matched against regexp.
use Test::Assert 'assert_raises'; assert_raises( 'foo', sub { die 'foo' } ); assert_raises( ['Exception::Base'], sub { Exception::Base->throw } );
Wraps Test::Builder based test function and throws Exception::Assertion if the test is failed. The plan test have to be disabled manually. The Test::More module imports the
fail method by default which conflicts with
Test::Assert
fail method.
use Test::Assert ':all'; use Test::More ignore => [ '!fail' ]; Test::Builder->new->no_plan; Test::Builder->new->no_ending(1); assert_test( sub { cmp_ok($got, '==', $expected, $test_name) } );
Exception::Assertion, Test::Unit::Lite.
If you find the bug or want to implement new features, please report it at
Piotr Roszatycki <dexter@cpan.org>
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See
|
http://search.cpan.org/~dexter/Test-Assert-0.0504/lib/Test/Assert.pm
|
CC-MAIN-2015-32
|
refinedweb
| 680
| 58.38
|
This module is an AnyEvent user, you need to make sure that you use and run a supported event loop. Loading this module will install the necessary magic to seamlessly integrate IO::AIO into AnyEvent, i.e. you no longer need to concern yourself with c...MLEHMANN/AnyEvent-AIO-1.1 - 21 Jul 2009 03:34:51 GMT - Search in distribution
This is the IO::AIO-based backend of AnyEvent::IO (via AnyEvent::AIO). All I/O operations it implements are done asynchronously....MLEHMANN/AnyEvent-7.12 5 (4 reviews) - 27 Jan 2016 18:15:38 GMT - Search in distribution
- AnyEvent - the DBI of event loop programming
- AnyEvent::IO - the DBI of asynchronous I/O implementations
- AnyEvent::Util - various utility functions.
- 1 more result from AnyEvent » is an AnyEvent user, you need to make sure that you use and run a supported event loop. This module implements a thin wrapper around IO::AIO. All of the functions that expect a callback are being wrapped by this module. The API is exactly...MLEHMANN/Coro-6.511 3 (7 reviews) - 26 Jun 2016 21:46:51 GMT - Search in distribution
- Coro - the only real threads in perl
- Coro::BDB - truly asynchronous bdb access
- Coro::Intro ...MUIR/IO-Event-0.813 - 18 Sep 2013 03:46:26.3 - 12 May 2016 16:54:52 GMT - Search in distribution
This task contains all distributions under the POE namespace....APOCAL/Task-POE-All-1.102 - 09 Nov 2014 11:07:41
This is the request object as generated by AnyEvent::HTTPD and given in the request callbacks....ELMEX/AnyEvent-HTTPD-0.93 5 (1 review) - 04 Aug 2011 08:42:18 GMT - Search in distribution
|
https://metacpan.org/search?q=AnyEvent-AIO
|
CC-MAIN-2016-36
|
refinedweb
| 280
| 64.81
|
Word embeddings or word vectors represent each word numerically so that the vector matches how that word is used or what it means. Vector encodings are learned by considering the context in which the words appear.
Words that appear in similar contexts will have similar vectors. For example, the vectors for “leopard”, “lion” and “tiger” will be close to each other, while they will be far from “planet” and “castle”.
Also, Read – Machine Learning Project on Rainfall Prediction Model.
Word Embeddings in Action
Even cooler, the relationships between words can be examined with math operations. Subtracting the vectors for “male” and “female” will return another vector. If you add that to the vector for “king”, the result is close to the vector for “queen”.
These vectors can be used as features for machine learning models. Word embeddings will generally improve the performance of your models above encoding a bag of words. spaCy provides incorporations learned from a template called Word2Vec. You can access it by loading a large language model like en_core_web_lg. Then they will be available on the tokens of the vector attribute.
Code language: PHP (php)Code language: PHP (php)
import numpy as np import spacy # Need to load the large model to get the vectors nlp = spacy.load('en_core_web_lg')
These are vectors of 300 dimensions, with a vector for each word. However, we only have document-level tags and our templates will not be able to use word-level embeds. So you need a vector representation for the whole document.
Code language: PHP (php)Code language: PHP (php)
# Disabling other pipes because we don't need them and it'll speed up this part a bit text = "These vectors can be used as features for machine learning models." with nlp.disable_pipes(): vectors = np.array([token.vector for token in nlp(text)]) vectors.shape
(12, 300)
There are many ways to combine all the word embeddings into a single document vector that we can use for training the model. A simple and surprisingly efficient approach is to simply average the vectors for each word in the document. Then you can use these document vectors for modelling.
spaCy calculates the average document vector you can get with doc.vector. Here is an example of loading spam data and converting it to document vectors. The dataset I am using here can be downloaded from here.
Code language: PHP (php)Code language: PHP (php)
import pandas as pd # Loading the spam data # ham is the label for non-spam messages spam = pd.read_csv('spam.csv') with nlp.disable_pipes(): doc_vectors = np.array([nlp(text).vector for text in spam.text]) doc_vectors.shape
(5572, 300)
Classification Models for Word Embeddings
With document vectors, you can train scikit-learn models, xgboost models, or any other standard approach to modelling.
Code language: JavaScript (javascript)Code language: JavaScript (javascript)
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(doc_vectors, spam.label, test_size=0.1, random_state=1)
Here is an example using Support Vector Machines (SVM). Scikit-learn provides an SVM LinearSVC classifier. It works the same as other scikit-learn models.
Code language: PHP (php)Code language: PHP (php)
from sklearn.svm import LinearSVC # Set dual=False to speed up training, and it's not needed svc = LinearSVC(random_state=1, dual=False, max_iter=10000) svc.fit(X_train, y_train) print(f"Accuracy: {svc.score(X_test, y_test) * 100:.3f}%", )
Accuracy: 97.312%
Document Similarity
Documents with similar content usually have similar vectors. So you can find similar documents by measuring the similarity between vectors. A common metric for this is cosine similarity which measures the angle between two vectors, a and b.
Code language: JavaScript (javascript)Code language: JavaScript (javascript)
def cosine_similarity(a, b): return a.dot(b)/np.sqrt(a.dot(a) * b.dot(b)) a = nlp("REPLY NOW FOR FREE TEA").vector b = nlp("According to legend, Emperor Shen Nung discovered tea when leaves from a wild tree blew into his pot of boiling water.").vector cosine_similarity(a, b)
0.7030031
Also, Read – Linear Search Algorithm with Python.
I hope you liked this article on Word Embeddings in Machine Learning. Feel free to ask your valuable questions in the comments section below. You can also follow me on Medium to learn every topic of Machine Learning.
|
https://thecleverprogrammer.com/2020/09/11/word-embeddings-in-machine-learning/
|
CC-MAIN-2021-43
|
refinedweb
| 711
| 58.99
|
#include <gromacs/analysisdata/dataframe.h>
Value type wrapper for non-mutable access to a data frame.
Default copy constructor and assignment operator are used and work as intended. Typically new objects of this type are only constructed internally by the library and in classes that are derived from AbstractAnalysisData.
Methods in this class do not throw, but may contain asserts for incorrect usage.
Note that it is not possible to change the contents of an initialized object, except by assigning a new object to replace it completely.
Constructs a frame reference from given values.
Constructs a frame reference from given values.
Constructs a frame reference to a subset of columns.
Creates a frame reference that contains
columnCount columns starting from
firstColumn from
frame, or a subset if all requested columns are not present in
frame.
Mainly intended for internal use.
Returns error in the x coordinate for the frame (if applicable).
All data do not provide error estimates. Typically returns zero in those cases.
Should not be called for invalid frames.
Convenience method for accessing error for a column value in simple data.
Currently, this method returns zero if the source data does not specify errors.
Returns zero-based index of the frame.
The return value is >= 0 for valid frames. Should not be called for invalid frames.
Returns whether the object refers to a valid frame.
If returns false, return values of other methods are not specified.
Returns point set reference for a given point set.
Should not be called for invalid frames.
Returns the number of point sets for this frame.
Returns zero for an invalid frame.
Convenience method for accessing present status for a column in simple data.
If present(i) returns false, it is depends on the source data whether y(i) and/or dy(i) are defined.
Returns the x coordinate for the frame.
Should not be called for invalid frames.
Convenience method for accessing a column value in simple data.
|
https://manual.gromacs.org/current/doxygen/html-lib/classgmx_1_1AnalysisDataFrameRef.xhtml
|
CC-MAIN-2021-17
|
refinedweb
| 326
| 60.72
|
In the context of .NET applications, settings are data that are not the main input or output of a program, but are nonetheless necessary for the program to function. Like business data, settings can change. An example of a setting is a folder path or a Web Service URI. Settings are often stored in application configuration files (app.config or web.config) to allow an administrator to easily change their values without refactoring and recompiling. This solution mostly works well for a single application. However, on occasions, the need arises to reuse settings across multiple applications. How to accomplish this with minimal code is the subject of this article.
In an earlier article, I demonstrated how settings stored in a machine.config file can be exposed to multiple applications via strongly typed properties of a settings wrapper class. While simple and effective, this approach has two limitations:
To overcome these limitations, we need a new game plan.
Our approach will involve creating a custom settings provider that will read, and if needed, write to our custom data store. The data store can be an XML file, a relational database, or just about anything else. For the demo, I chose what's likely to be the most common approach - store the settings in a database. So, first we will create a database table and seed it with some data. Then, we will use Visual Studio to quickly generate a class with properties to match our settings. To allow the settings class to communicate with the data store, we will then create a new provider and instruct the settings class to use it. In this demo, the provider class will use LINQ to SQL to perform database reads and updates, but you could as well use any data access technology: Entity Framework, raw ADO.NET, a third party ORM, or whatever else suits your purpose. To emphasize the point, this approach hinges not on specific data access technology or a specific backend choice, but rather on wiring the settings class to use a custom settings provider, which we will do in steps 5-7.
As mentioned above, my data store will be a database table. In designing the schema for storing settings, we are faced with several decisions. Do we store all data in a single column as varchar, or do we store data in different fields or even different tables depending on type? I like several things about the schema that I've chosen for this demo. Take a look at the Settings table below:
varchar
For simplicity, I am storing the name value pairs in one table. If you are bent on normalization, you may just as easily split them into separate tables. The interesting part here is the data type of the Value field. As you see, I am using sql_variant. I chose sql_variant because, unlike varchar, it preserves information about the underlying type (bit, int, date, etc.) without the need to create a field or table for every data type you might end up using. This is one of the niceties of SQL Server. If you like it, use it. Otherwise, or if you are using an RDBMS that does doesn't have the sql_variant data type, choose an alternative that works.
sql_variant
I've also added a Description field and an Enabled field to turn a setting on or off as needed.
After you have your table, populate it with some settings. Here are mine:
If you already have a library that serves as a core reference for other projects in your solution, you can use it and skip this step. If not, add a new Class Library project to your solution. In my sample, this project is named NetRudder, which also serves as the root namespace for other projects.
Add the following assembly references to the library created in the previous step:
If your solution already contains a Data Access Layer, you can use it instead. For the demo, I simply added a new LINQ to SQL data context to my NetRudder project. I then created a Setting class mapped to the Settings table that we created earlier. With LINQ to SQL, this is as easy as dragging out the table from Server Explorer to the designer surface. The new class looks like this:
Setting
Notice an interesting detail: the type of the Value property is Object - this is the default LINQ to SQL mapping for sql_variant, and it works just fine for our purposes.
Value
Object
To take advantage of the .NET Application Settings architecture, we need to create a class that inherits from ApplicationSettingsBase. If you followed my previous post, you already have a settings class. If not, you can use Visual Studio Settings Designer to quickly create one:
ApplicationSettingsBase
NetrudderSettings
At this point, Visual Studio has generated a wrapper class for us with properties named identically to our settings.
Let's recap for a moment. We now have the following pieces in place:
What's missing is a class that will mediate between the Data Access Layer and the settings class. So, let's create it.
In the Settings Designer, click "View Code". As you can see, NetrudderSettings is a partial class. If you want to add properties manually instead of using the Settings Designer, you could do so here. This is particularly useful if you need your properties to be writeable (see note below). For now, we just need to decorate our class with the following attribute:
<SettingsProvider(GetType(LinqSettingsProvider))> _
Partial Public NotInheritable Class NetrudderSettings
What we just did by adding the attribute is instruct the settings class to use a custom provider that we are going to write. Without this attribute, NetrudderSettings would use LocalFileSettingsProvider, which is the default provider class that knows how to "talk to".NET configuration files (machine.config, app.config, web.config) but not to databases or anything else.
LocalFileSettingsProvider
We have not yet created a LinqSettingsProvider class, so you will see a squiggly underline under the class name. Putting the cursor over the name to bring up the error correction menu, choose to have Visual Studio create the class for you. (If you don't get this option because you are using VS Express, just create the class manually.)
LinqSettingsProvider
By default, when you use the Settings Designer to add settings, the properties that Visual Studio creates to expose these settings are marked ReadOnly. If some of your settings need to be writable, you will have to create these properties manually. No big deal. Using the Settings Designer, remove any settings that you want to be writeable. Open the partial class that you've modified in this step, and add the properties that you want to be writeable following the pattern below:
ReadOnly
<Global.System.Configuration.ApplicationScopedSettingAttribute()> _
Public Property Year() As Integer
Get
Return CType(Me("Year"), Integer)
End Get
Set(ByVal value As Integer)
Me("Year") = value
End Set
End Property
The settings provider is the only part of our solution that actually communicates directly with the Data Access Layer. It's up to us to instruct it on how to do it. First, make sure that your provider class inherits from SettingsProvider. At this point, you should be looking at a stub that looks similar to this:
SettingsProvider
Public Class LinqSettingsProvider
Inherits SettingsProvider
Public Overrides Property ApplicationName() As String
Get
End Get
Set(ByVal value As String)
End Set
End Property
Public Overrides Function GetPropertyValues(ByVal context As _
System.Configuration.SettingsContext, ByVal collection _
As System.Configuration.SettingsPropertyCollection) _
As System.Configuration.SettingsPropertyValueCollection
End Function
Public Overrides Sub SetPropertyValues(ByVal context As _
System.Configuration.SettingsContext, ByVal collection _
As System.Configuration.SettingsPropertyValueCollection)
End Sub
End Class
Add the following line to the Initialize method:
Initialize
MyBase.Initialize(Me.ApplicationName, col)
Add the following code in the Getter of ApplicationName property (leave the Setter empty):
ApplicationName
ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
Add code to the GetPropertyValues method that reads values from the data store and into a SettingsPropertyValueCollection. To conserve space, I won't paste the code here, but you can see it all in the included demo. Of course, if you didn't use LINQ to SQL, the part of the code that interacts with the Data Access Layer will look somewhat different.
GetPropertyValues
SettingsPropertyValueCollection
Add code to the SetPropertyValues method that takes the updated settings and persists them to the database (see the attached project).
SetPropertyValues
We are almost done. This last step creates a nice shortcut to a synchronized instance of our settings class, making it easier to work with. Paste the following code into a new module, substituting your root namespace for Netrudder:
Netrudder
<Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Public Module PublicSettingsProperty
Public ReadOnly Property Settings() As Netrudder.My.MySettings
Get
Return Netrudder.My.MySettings.Default
End Get
End Property
End Module
Compile the project. Done!
To test the settings, I created a new console project and referenced the NetRudder assembly. You can do the same basic test with a different application type. The following code reads my settings from the database and outputs them to the console. It also updates the Year property, which I made writeable earlier. Notice that to persist the update to the data store, you need to call the Save method of the settings class, which it inherits from ApplicationSettingsBase.
Year
Save
With Netrudder.Settings
Console.WriteLine("Copyright {0} {1}", .Year, .Copyright)
Console.WriteLine("Lat/Lng: {0},{1}", .Lattitude, .Longitude)
.Year = 2009
'Persist the settings change
.Save()
End With
Just because you have a custom settings provider doesn't mean you can't also store some settings in a .config file as before. Remember how in step 6 we instructed our settings class to use our custom settings provider? Well, you can override this behavior for individual properties. So, if you have a setting whose value may be unique to each application, you can set the provider for that property to LocalFileSettingsProvider and store the value in app.config/web.config. Check out the SettingsProvider link to MSDN below to read more about mixing and matching providers.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
General News Suggestion Question Bug Answer Joke Rant Admin
Man throws away trove of Bitcoin worth $7.5 million
|
http://www.codeproject.com/Articles/136152/Create-a-Custom-Settings-Provider-to-Share-Setting?fid=1600764&df=90&mpp=10&noise=1&prof=True&sort=Position&view=None&spc=Relaxed
|
CC-MAIN-2013-48
|
refinedweb
| 1,725
| 55.24
|
What is the most efficient algorithm for counting the number of factors of an integer?
What is the most efficient algorithm for counting the number of factors of an integer?
It think that the 'policy' of every forum is that you post your code,thus your attempt of achieving what you are asking,and based on that improve the code!
This is my small effort...It works but it will not fit into my program
Code:int count_factors(int n) { int i,f=1; if(n==1) return 1; else { for(i=2;i<=(n/2);i++) { if(n%i == 0) f++; } return (f+1); } }
I am sure there are some better approach of finding upto square_root(n) and some recursive approach. Any ideas for that?? Just some discussion....I am not asking to write the code for me...
Oh,ok
Well the first thing it comes to mind is that if you want to use sqrt then you have to load the library of math,which makes your program a bit slower.Well the first thing it comes to mind is that if you want to use sqrt then you have to load the library of math,which makes your program a bit slower.
Ok I see....using sqrt is not a much good choice then, but still using sqrt will save the time for other some useless looping,actually it will just balance the loading of libraries I guess....Whether using recursive approach is faster than the for loop??...Well I found some resources on wikipedia Integer factorization - Wikipedia, the free encyclopedia
But I am not much good in maths or the algorithm subject...some topics are going above the head
When having a problem we may solve it with a recursive algorithm or with an iterative one.When these two algorithms have the same complexity(=the actions done by them are of equal cost),then the iterative one is been selected.Why?Because recursion has the system to handle the stack with functions call etc. which is very expensive.
What the link says is that this problem is a heuristic.Also mind that it also says that non-efficient algorithms are found for these problem(when numbers are big.).
So you might want to take a look at this Fermat's factorization method - Wikipedia, the free encyclopedia
Ya right,recursion has to handle the stacks so extra consumption of resources....."An algorithm that efficiently factors an arbitrary integer would render RSA-based public-key cryptography insecure."---Haha, its already declared there does not still exist an efficient algorithm for that...It seems to find more I have to go more detail into the world of number theories and algorithms...
Especially Numerical Analysis and Algorithms and Complexity will give you a boost at these kind of things
This public domain library is stated as being the fastest code for finding factors, in the article you linked to:
Msieve | Free Security & Utilities software downloads at SourceForge.net
I'm not clear what you mean by your trial by division code "not fitting into your program"? It seems like a very small function, although it's also one of the slowest ways to find the factors.
A few notes on your trial by division code:
Calculate the max value outside the for loop, so that value is calculated only one time. max=n/2+1 allows the slightly faster test of <, instead of <=.Calculate the max value outside the for loop, so that value is calculated only one time. max=n/2+1 allows the slightly faster test of <, instead of <=.Code:int count_factors(int n) { int i,f=1,max; if(n==1) return 1; else { max=n/2+1; for(i=2;i<max;i++) { if(n%i == 0) f++; } return (f+1); } }
If you can stop the inner loop at the square root of n, instead of n/2, by including math.h, then by all means, include math.h!
Again, make the calculation for max=sqrt(n)+1, just before the start of the for loop, so the calculation will only be made one time.
For VERY large prime numbers, you will be stuffed, of course. There is no known algorithm that will find all the factors of such numbers (and their related semi-primes), in a reasonable amount of time.
The main question is: What do your really want to calculate?
The code you've posted counts all divisors of a number, e.g. for 12 the result is 6 because 12 is divisible without a remainder by 1, 2, 3, 4, 6, 12
The rest of the posts talk about integer factorization which "is the decomposition of a composite number into smaller non-trivial divisors, which when multiplied together equal the original integer." (from the wikipedia article)
So for 12 the factors are 2x2x3 and counting all factors will result in 3.
So what do you want to do?
Bye, Andreas
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
Thanks Adak....for the suggestion of your calculating one time, I did not notice that....I mean by saying not fitting into my program means that I am trying to solve a question and it gives certain time constraint, and finding the factor is a crucial part in solving the problem...so the trial division definitely doesn't fit here, thats what i meant. Well it seems now that the factor finding approach for the solution to the problem is not going to give much help....its consuming a lot time...
Last edited by rakeshkool27; 08-24-2012 at 09:23 PM.
|
http://cboard.cprogramming.com/c-programming/150328-efficient-algorithm-counting-number-factors.html
|
CC-MAIN-2016-40
|
refinedweb
| 1,009
| 69.72
|
When two pure tones are nearly in tune, you hear beats. The perceived pitch is the average of the two pitches, and you hear it fluctuate as many times per second as the difference in frequencies. For example, an A 438 and an A 442 together sound like an A 440 that beats four times per second. (Listen)
As the difference in pitches increases, the combined tone sounds rough and unpleasant. Here are sound files combining two pitches that differ by 16 Hz and 30 Hz.
16 Hz:
30 Hz:
The sound becomes more pleasant as the tones differ more in pitch. Here’s an example of pitches differing by 100 Hz. Now instead of hearing one rough tone, we hear two distinct tones in harmony. The two notes are at frequencies 440-50 Hz and 440+50 Hz, approximately the G and B above middle C.
100 Hz:
If we separate the tones even further, we hear one tone again. Here we separate the tones by 300 Hz. Now instead of hearing harmony, we hear only the lower tone, 440+150 Hz. The upper tone, 440+150 Hz, changes the quality of the lower tone but is barely perceived directly.
300 Hz:
We can make the previous example sound a little better by making the separation a little smaller, 293 Hz. Why? Because now the two tones are an octave apart rather than a little more than an octave. Now we hear the D above middle C.
293 Hz:
Update: Here’s a continuous version of the above examples. The separation of the two pitches at time t is 10t Hz.
Continuous:
Here’s Python code that produced the .wav files. (I’m using Python 3.5.1. There was a comment on an earlier post from someone having trouble using similar code from Python 2.7.)
from scipy.io.wavfile import write from numpy import arange, pi, sin, int16, iinfo N = 48000 # sampling rate per second x = arange(3*N) # 3 seconds of audio def beats(t, f1, f2): return sin(2*pi*f1*t) + sin(2*pi*f2*t) def to_integer(signal): # Take samples in [-1, 1] and scale to 16-bit integers m = iinfo(int16).max M = max(abs(signal)) return int16(signal*m/M) def write_beat_file(center_freq, delta): f1 = center_freq - 0.5*delta f2 = center_freq + 0.5*delta file_name = "beats_{}Hz_diff.wav".format(delta) write(file_name, N, to_integer(beats(x/N, f1, f2))) write_beat_file(440, 4) write_beat_file(440, 16) write_beat_file(440, 30) write_beat_file(440, 100) write_beat_file(440, 293)
In my next post on roughness I get a little more quantitative, giving a power law for roughness of an amplitude modulated signal.
Related: Psychoacoustics consulting
4 thoughts on “Acoustic roughness”
Are the files for 293hz vs 300hz swapped? I can hear two tones in with the 300hz file, but only one in the 293hz file.
Anon: The files are not swapped. There is a hint of the higher tone in the 300 Hz file, but not in the 293 Hz file, at least as I hear it.
I suggest you try and make the same thing with a triangle wave. I suppose the harmonic content of the interference would be rather interesting!
The script works in Python 2.7 if “from __future__ import division” is included at the top. The issue is with the “x/N” in write_beat_file, since both x and N are ints. Maybe also the “m/M” in to_integer, but M is probably a float.
|
https://www.johndcook.com/blog/2016/03/30/acoustic-roughness/
|
CC-MAIN-2017-43
|
refinedweb
| 582
| 73.47
|
genGDRTests.pl - Creates GDR test files from test sql scripts. This version creates no test conditions for anything other than the main test file. All files, other than the main test files are fixed, are the same for each generated test. Test is run tw2ce to generate tests only for stable values. (Dates are still a problem.)
1.3.0
genGDRTests.pl -i <infile> -o <outfile> -c <odbc connection> -r <resultSets> -n <namespace> [options]
Specify input file
Specify output file
Specify ODBC connection for Test script
Output version type
Specify privileged ODBC connection for Setup/Teardown scripts
Pre-test file
Post-test file
Common initialisation code file
Common cleanup code file
Resultsets (numeric list) for which to generate test conditions
Specify namespace for test class
[Don't] generate scalar value test conditions
[Don't] generate SQL types declaration
Ded MedVed.
Hopefully none.
Copyright (c) 2012, Ded MedVed. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see)
|
http://search.cpan.org/~dedmedved/VSGDR-UnitTest-TestSet/genGDRTests.pl
|
CC-MAIN-2014-10
|
refinedweb
| 172
| 55.03
|
- ×
A React framework for building text editors.
Filed under user interfaceShow All
Before getting started, please be aware that we recently changed the API of Entity storage in Draft. The latest version,
v0.10.0, supports both the old and new API. Following that up will be
v0.11.0which will remove the old API. If you are interested in helping out, or tracking the progress, please follow issue 839.
Getting Started
Currently Draft.js is distributed via npm. It depends on React and React DOM which must also be installed.
npm install --save draft-js react react-dom or yarn add draft-js react react-dom
Using Draft.js
import React from 'react'; import ReactDOM from 'react-dom'; import {Editor, EditorState} from 'draft-js'; class MyEditor extends React.Component {') );
Note that the editor itself is only as tall as its contents. In order to give users a visual cue, we recommend setting a border and a minimum height via the
.DraftEditor-rootCSS.
Browser Support
[1] May need a shim or a polyfill for some syntax used in Draft.js (docs).
[2] IME inputs have known issues in these browsers, especially Korean (docs).
[3] There are known issues with mobile browsers, especially on Android (docs).
Resources and Ecosystem
Check out this curated list of articles and open-sourced projects/utilities: Awesome Draft-JS.
Discussion and Support
Join our Slack team!
Contribute
We actively welcome pull requests. Learn how to contribute.
License
Draft.js is MIT licensed.
Examples provided in this repository and in the documentation are separately licensed.
|
https://www.javascripting.com/view/draft-js
|
CC-MAIN-2019-13
|
refinedweb
| 258
| 60.92
|
Over a year ago, when I first tried the OLPC/Sugar software, I was fascinated by the activities in TamTam applications. Had any of them been available in my time, I may even have liked attending, go to:.
Getting started
You will need to install the following packages: csound and csound-python.
Csound requires an XML-like configuration file with three sections. Create a minimal file, tutorial.csd:
<CsoundSynthesizer> <CsOptions> </CsOptions> <CsInstruments> </CsInstruments> <CsScore> </CsScore> </CsoundSynthesizer>
You will be satisfied with the default options. The instruments section is where we define the ‘orchestra’, which comprises all the instruments that will be used to create our musical masterpiece. These are the same as the contents of
myfile.orc in the beginner’s articles in.
The score section will contain a list of instructions for the instruments in the orchestra. These are the same as the contents of
myfile.sco, mentioned in the articles mentioned earlier.
Create the same simple instrument as in the beginners’ introduction:
<CsInstruments> </CsInstruments>
The first four lines have header information, which controls the output format. The remaining lines are the definition of the instrument, which is a simple oscillator operating at a frequency of 440Hz and a volume of 10000, about a third of the maximum. (Volume is represented as a 16-bit integer.) The third parameter to the oscil command/opcode identifies the waveform table to be used in the score given below. The oscillator is given a variable name
aout. The same sound is passed to both the channels.
Now, add the score:
<CsScore> f 1 0 16384 10 1 ; table #, start time, the size, generator, parameter i 1 0 1 ; instrument #, start time, duration </CsScore>
f is the waveform table, which is available at the start of performance with 16,384 samples. The generator value 10 with parameter 1 corresponds to a sine wave in Csound.
The
i line is an instrument event with the instrument number, the start time and the duration in seconds as the parameters.
You can run the following script, get a wave file and play it:
$ csound -Wo tutorial.wav tutorial.cs $ aplay tutorial.wav
Controlling Csound using Python(‘tutorial.csd’) # Set the Csound command for off-line rendering. csound.setCommand(‘csound :
instr 1 ‘i’, ‘k’ or ‘a’. A variable starting with the letter ‘i’ is initialised to a value when the instrument is started, and does not usually change. The letter ‘a’ indicates an audio rate variable and the letter ‘k’ indicates a control rate variable.
There are also some special ‘p’ variables or parameters that send values from the score to the orchestra—p1, p2 and p3 are the instrument’s number, start time and their duration. The variables p4, p5, p6, etc, are flexible. They are used here for amplitude, frequency and the waveform table.
Now, add a call to
add_score to the
tutorial.py as follows:
csound.setCommand(‘csound -Wo tutorial.wav temp.orc temp.sco’) add_score(csound) # Export the .orc and .sco file for performance
Now, code an
add_score method:
def add_score(csound): sarega = [130.8, 146.8, 164.8, 174.6, 195.0, 220.0, 246.9, 261.6] for time in range(8): csound.addNote(1, time, 1, 8000 , sarega[time], 1)
Your instrument will play the notes. Let us improve the instrument and put an envelope in each event. Modify the instrument definition in
tutorial.csd as follows: envelope using the opcode
linseg, which represents the starting amplitude followed by pairs of time intervals and the amplitude at the end of the interval.
The control variable
kamp starts with 0, rises to 1 in .2 seconds, then drops to .8 in the next .2 seconds, retaining that value until .2 seconds before the end. In the last .2 seconds, the value drops from .8 to 0. As you can imagine, an instrument can be programmed to generate pretty complex sounds for each event. You can get an idea of the programming possibilities by playing two frequencies close to each other. Replace the
add_score method in the
tutorial.py with:
def add_score(csound): sarega = [130.8, 146.8, 164.8, 174.6, 195.0, 220.0, 246.9, 261.6] for time in range(8): that uses a converter opcode to convert a number into a frequency. The whole number represents the octave, and the decimal part the semitone. So, at the instruments section in
tutorial.csd, add the following:
instr 2 iamp = p4 ifqc = cpspch(p5) itabl1 = p6 kamp linseg 0, .2, 1, .2, .8, p3-.5, .8, .2, 0 asigl oscil iamp, ifqc*.999, itabl1 asigr oscil iamp, ifqc*1.001, itabl1 outs asigl*kamp, asigr*kamp endin
Notice that the definition has a different oscillator definition for the right and left channels. In the score section, include a second waveform table:
f2 0 16384 10 1 .5 .3333
This table is also a sine wave but includes the first and second harmonics with amplitudes that are a half and a third of the primary wave.
Now, modify the
add_score method in
tutorial.py to use both instruments:
def add_score(csound): sarega = [130.8, 146.8, 164.8, 174.6, 195.0, 220.0, 246.9, 261.6] pitch = [8.00, 8.02, 8.04, 8.05, 8.07, 8.08, 8.11, 9.00] for time in range(8): csound.addNote(1, time, 1, 8000 , sarega[time], 1) csound.addNote(2, time, 2, 8000, pitch[time], 1)
The second instrument plays the same tones but at an octave higher. It also uses the second waveform table. You can explore various programming possibilities—like varying amplitudes, varying durations and varying the relative start time of instruments.
As you would have noticed, there is no constraint on the size of the orchestra you can single-handedly create. You can find some simple drum instruments at. So go ahead, try them and, may be, create a synthetic tabla!
Next month, we will explore playing around Soundfonts and Csound to create sounds.
Connect With Us
|
http://opensourceforu.com/2009/05/creating-rhythmic-noise/
|
CC-MAIN-2016-36
|
refinedweb
| 1,002
| 67.55
|
Having to interpret strings and extract information always has been necessary and is mostly related to writing complex looking code and logic.
Many things can be handled with tokenizers, however with these, there is not much room for different variants of a string or separators that vary from case to case.
Regular expressions allow more complex processing, but it is a pain create the them, debug them and understand them a few months later.
This acticle shows the usage of a small class providing a "natural" way of dealing with complex extraction patterns using a very tiny class.
Note: The article and sources are updated to handle the problems of the first version.
The best way to demonstrate the need is to provide two simple examples:
We need to process strings from a log file like the following:
------------------snip------------------
Process: Tsk Mgr.EXE - Start Date: 2008-20-01 Duration: 00:01:54 - Description: Task Manager
Process: EXPLORER.EXE - Start Date: 2008-20-01 Duration: 00:01:54 - Description: Explorer
End-of-day
Process: Tsk Mgr.EXE - Start Date: 2008-21-01 Duration: 00:00:12 - Description: Task Manager
...
------------------snap------------------
The area of interest are the parts in italics: the process name, the start date and the duration. We need to extract them.
The log file lines looks similar, there first problem is that
there are lines we don't need, like "End-of-day" or the empty line.
The second problem
we encounter is that we cannot really deal with standard tokenizers, as
we have no separation character. Space cannot be used, as the process
name of "Tsk Mgr.exe" contains a space itself, which would shift all
the following tokenized parts.
The colon (:) *could* be used, however, we would have to remove the " - Start Date" from the process name and we would like to get the "Duration" part as one.
If we would explain a human how to extract the values, we would tell him to
take the part after "Process:" until the dash "-" before "Start Date:",
then the part after "Start Date:" until "Duration:", the part after
"Duration:" until the dash before "Description:".
Written in a "masked" way, the string processing format looks like:
Process: #### - Start Date: #### Duration: #### - Description: Task Manager
What
we need to parse in our application are the "####" parts. And what
would be more natural than to be able to enter exactly this mask
pattern in our application. To further access the interesting parts,
we should be able to give them variable names, represented in the part
string by a surrounding percentage sign (%). So our mask string would look like
Process: %proc% - Start Date: %date% Duration: %duration% - Description: %desc%
Ideally, we would run each line of the log file through this mask
and if it succeeds, we would query the variable "proc", "date" and
"duration" - and ignore "desc". If it fails, i.e. if the input string
does not match with the mask format, we would just continue with the
next log-line.
We need to extract version information from strings like:
<softwareA> v1.4<softwareB> v5<softwareC> v1.3.1 Beta 5<softwareD> v8.4.87.405 Alpha
The only thing these strings have in common is the space and lowercase-"v" right before the version number. Again, we are only interested in the italic parts: the plain version numbers without the postfixed "Alpha" or "Beta 5".
In this case, we would have two different masks:One with additional text after the version number and one with not, so the first mask would look like:
%software% v%version% %postfix%
where we have only two fixed elements:- the " v" and- the space between the version and the postfix
and another mask with no postfix
%software% v%version%
We would first check the one with, and if it fails (if there is no postfix) the one without postfix.(When checking the second mask only, it would always succeed and include the words "Beta" and "Alpha" as well - which we don't want).
The idea of handling strings that way makes it must easier to adapt to many different tasks without having to reprogram any additional post-tokenizer logic that is usually involved when extracting data from strings.
Originally, a very good MP3 tag editor allows extracting data like artist and track name information from the various formatted filenames on freedb.org by using placeholder variables in the way described above, which got me quickly attracted to it, as it is very easy to understand. Many times I wished to have access to such a function, and never found anything similar to it, so I decided to code it myself.
The string splitter contains three classes:
The main class CStringSplitter, which will be used by the application code, and the two helper classes CSearchStringChar and CSearchStringStr used by the other class to parse the mask and the string.
CStringSplitter
CSearchStringChar
CSearchStringStr
The usage of the string splitter is demonstrated in this small piece of code.
In the example, we use the percentage symbol '%' to indicate the start and end of a variable name:
#include <span class="code-string">"StringSplitter.h"</span>
CStringSplitter Split( _T('%'), _T('%') );;
CString strValue,
strMask = _T("Process: %proc% - Start Date: %date% Duration: %duration% - Description: %desc%");
while ( !isEndOfFile() )
{
strLogLine = getNextLine();
if ( Split.matchMask( strLogLine, strMask ) )
{
if ( Split.getValue( strValue, _T("proc") ) )
{
// do something with strValue (proc)
...
}
if ( Split.getValue( strValue, _T("date") ) )
{
// do something with strValue (date)
...
}
if ( Split.getValue( strValue, _T("duration") ) )
{
// do something with strValue (duration)
...
}
}
}
When using the default open- and close-brace characters to indicate the placeholders, the mask in the example above would be:Process: (proc) - Start Date: (date) Duration: (duration) - Description: (desc)
The following functionality is provided by the class to process a string.
The CStringSplitter class must be constructed with two
optional parameters to specify the start and end characters for the
variable names. These default to the opening and close braces '(' and
')'.
Both, the opening and close characters can be the same (e.g. '%' as in the code example above).
The method matchMask checks an input line against the mask. It returns true if the processing was successful, false if not, i.e. if the mask does not fit onto the input string or if the mask contains syntactical errors.
matchMask
true
false
After successfully processing the source string, the method getValue can be called to get the contents of the requested variable. Its first parameter is a string reference which will contain the value of the requested variable, if it exists. The return value is true if the variable is found or false if it does not exist.
getValue
Note: Variable names are treated case-insenstive! This can be changed in the getValue method by using the strcmp instead of the stricmp function.
strcmp
stricmp
When having thousands of lines to process with the same mask, the mask needs to be pre-parsed only once. This makes the string matching even faster.
The first step is to setup the mask by calling the setMask method with the mask string as the only parameter (which corresponds to the second parameter of matchMask). It will return true if the mask is valid or false if not.
setMask
Matching the strings can be done in a loop by calling the matchLastMask method using the string to be matches as the only parameter (which corresponds to the first parameter of matchMask). It returns true if the processing was successful, false if not, i.e. if the mask does not fit onto the input string.
matchLastMask
After success, the placeholder values can be retrieved as described above.
Here's the earlier example with the necessary changes (in bold):
CStringSplitter Split( _T('%'), _T('%') );;
CString strValue,
strMask = _T("Process: %proc% - Start Date: %date% Duration: %duration% - Description: %desc%");
Split.setMask( strMask );
while ( !isEndOfFile() )
{
strLogLine = getNextLine();
if ( Split.matchLastMask( strLogLine ) )
{
if ( Split.getValue( strValue, _T("proc") ) )
{
// do something with strValue (proc)
...
}
...
}
}
The parser is completely tolerant about typing errors, however, there are syntax rules to get the expected result.
At least one fixed character must separate them:
Parsing any string using the mask "(part1)(part2)" will, from a logical point, not reveal and usable results, as there is no separation between part1 and part2.
Given the following input string:
"Humidity %89"
When using the '%' as the variable start and end characters, any double-appearance of it in the fixed text section will be interpreted as one occurence of the character.
To handle the '%' sign in the fixed text, the mask string must be:
"Humidity %%%HUM%"
Note that there are three (3) sequential percentage signs:
The bold portion belongs to the fixed text, any double-start-characters are interpreted as one - "Humidity %".
The non-bold portion indicates the variable name one '%' as the start character, "HUM" as the variable name and the next '%' as the end character.
In order to prevent annoyances, the end-character is not allowed in the variable name, even if it is doubled.
Not terminating a variable at the end of a string will automatically terminate it.
To use this class in user input fields, the easiest way to check the validity of a mask is by simply calling setMask with the string. If it returns true, the mask can be used (hower, it cannot be guaranteed that the results are what the user intended - Microsoft's PSI-API is not yet ready for public use ;-)
The code is using some specifics or Visual Studio 2005, however it should be quickly portable to other platforms with no effort.
The first is MFC's CString
for internal storage of variables and placeholders and for returning
the variable's contents. This can be replaced by virtually any other
string class, as nothing more than simple assignment is used.
CString
The string processing itself is using the oldie-but-goldie C library functions strlen, strcpy, strchr, strstr and stricmp, i.e. their Visual Studio's _t-prefixed equivalents to achieve MBCS / UNICODE compatibility using the same code.The strcpy_s function of VS 2005 can be replaced by the corresponding "unsafe" strcpy function for other compilers without problems, as the memory for the string is allocated directly before copying.
strlen
strcpy
strchr
strstr
_t
strcpy_s
Since
the basic character handling functions are used instead of the
high-level string class routines, the mask parsing should be quite
fast, as these libraries are mostly assembly-optimized in most compiler
libraries.
1.0 2008-01-21 Public release
1.1 2008 -01-25 Problems if 1.0 fixed:
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
General News Suggestion Question Bug Answer Joke Rant Admin
Man throws away trove of Bitcoin worth $7.5 million
|
http://www.codeproject.com/Articles/23074/A-Tiny-Variable-String-Splitter?msg=2407548
|
CC-MAIN-2013-48
|
refinedweb
| 1,788
| 60.14
|
The world's most popular open source database
Russell Dyer is the editor for the MySQL Knowledge Base and the author of MySQL in a Nutshell (O'Reilly 2005). He has written on MySQL for several magazines including Unix Review, SysAdmin and ONlamp.com and lives in New Orleans.
By Russell Dyer.
MySQL can be embedded with C, Python, Visual Basic, and other programming languages. This article, though, will explain how to develop and compile a C program to work with the embedded MySQL server library. Some aspects are specific to C, but almost all of the concepts apply to all APIs. I will assume that you know the basics of C programming and skip over aspects that are strictly C. Additionally, I will assume that you have the GNU C Compiler (gcc) installed on your development computer and you are using Linux (although Linux is not required). This is basically all you will need. The embedded server library is contained in the libmysqld.a file, which is located in the lib sub-directory of the standard MySQL installation. To make this tutorial easier to follow, I will work through the development of a very simple C program which will retrieve data from a MySQL database using the embedded server library.
To start the example C program properly, and to make it simpler, we'll use a few header files. Using a text editor like vi, we will open a new filed called mysql_test.c and enter the following opening lines:
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include "mysql.h"
If you've worked with C before, the first three lines here are probably very familiar to you: they are header files that contain functions that are commonly used in a C program. The fourth line calls for a header file which contains functions and structures that will be needed to interface with MySQL databases and tables. These files are located in a directory which we will specify later when we compile the program. Next we will declare some variables based on structures provided by the mysql.h header file. This is done by adding the following lines to the program:
MYSQL *mysql; MYSQL_RES *results; MYSQL_ROW record;
The first line above sets up a pointer called mysql based on the structure MYSQL as defined in mysql.h. This will create an object for accessing the databases. The next line declares a complex data structure for the results set of a SELECT statement that will be executed later in the program. This is followed by a declaration of an array for temporarily holding a record or row that will be read from the results set later.
Even though the MySQL server daemon is not used, we still need to pass server options to the embedded server library. Server options are given in an array as an arguments to the mysql_server_init(), which initializes the server. So, in preparation we will set up two arrays related to server options like so:
static char *server_options[] = {"mysql_test", "--defaults-file=my.cnf"}; int num_elements = sizeof(server_options) / sizeof(char *); static char *server_groups[] = {"libmysqd_server", "libmysqd_client"};
The first array above contains the server options. The first element is a label which will be ignored by the mysql_server_init() function when deployed. This function is just for the embedded server, by the way. The server options follow the first element. I've only given one here. However, you can give as many as you would like, each within double-quotes, separated by commas. See the on-line documentation for a list of server options available. To minimize code, you can put the options that are common to your C programs in an options file. Then you would only have to give options that are needed by a particular program in the mysql_server_init() function, along with the --defaults-file option. This option is used to specify an options file other than the usual default one (i.e., /etc/my.cnf). In the example above, it's pointing to a file called my.cnf in the current directory since no path is given. This is handy for shipping the option file with compiled, embedded programs. The options file might look like this:
# my.cnf [libmysqd_server] datadir = ./data language = ./english skip-innodb [libmysqld_client] language = ./english
For the server group here, the --datadir option is given. This data directory is a sub-directory of the current directory--relative paths are allowed. Again, these settings and file locations are useful for shipping compiled programs with related files. Another option shown above is the --language option. It identifies the location of the character set and error message files. I've copied the directory english from /usr/local/mysql/share/mysql/english on my system and put it in the current directory for easy packaging. Although it may seem redundant, there has to be a separate program group for the client with at least the --language option. You can put any server or client options that you need in the options file.
Going back to the program code shown before this option file excerpt, the next line calculates the number of elements in the server_options[] array and stores that number in an integer variable called num_elements. This will be needed for the mysql_server_init() function later on. The last array (server_groups[]) above contains a list of server groups in the options file that the program is to use. It will ignore all other groups. This means that you can have different groups for different types of programs, all using the same options file.
Now that the header files have been called in, the initial variables and the like declared, and the options file created, we can begin the main() function, which will interface with the MySQL data.
To keep this program simple, we will just have it connect to one database and execute a basic SELECT statement. For the example program, we will use a database for a fictitious bookstore called bookstore. The first tasks after starting the standard C main() function will be to initialize the embedded server and the mysql object that was declared earlier:
int main(void) { mysql_server_init(num_elements, server_options, server_groups); mysql = mysql_init(NULL); mysql_options(mysql, MYSQL_READ_DEFAULT_GROUP, "libmysqld_client"); mysql_options(mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);
The first line of code within the main() function initializes the MySQL server, given the server options and server groups from the arrays set up in the previous section. The next line begins the client session: it initializes the MYSQL object, which will be referenced by mysql. Any name would do, by the way. Using the C API function mysql_options() with the MYSQL_READ_DEFAULT_GROUP option, the next line of code instructs the program, acting as a client, to use the options in my.cnf under the group heading [libmysqld_client] (shown before) as the default group. The mysql_options() function is used again above to specify explicitly that the client is to use the embedded server and not a local or remote MySQL server daemon.
Now that the server and client are initialized, the next task is to connect to the bookstore database so that queries can be executed. Using the standard C API function, mysql_real_connect(), the database is opened like so:
mysql_real_connect(mysql, NULL,NULL,NULL, "bookstore", 0,NULL,0);
Since the database is accessed directly and not through the network, the second, third, fourth, sixth, and seventh parameters are set to NULL (except for the sixty; it's set to 0). These are respectively the host, user name, password, TCP/IP port, and socket file. Again, these parameters aren't given because the program is not interfacing through the network or a daemon. With the exception of the data, it will all be contained within the compiled program. The only parameters that need to be given are the first and fifth, and possibly the last one. The first is the MYSQL object; the fifth is the name of the database to use; the last is for any special client flags.
By default, the embedded server doesn't require user authentication. However, you could require the user to authenticate if you'd like. You would do this by adding the --with-embedded-privilege-control to the server options (in server_options[]) for mysql_server_init(). You would also need to give the host address, user name, and password with the mysql_real_connect() function above. You would probably use variables and modify your program to collect the user name and password from the user. As for host, in addition to providing it for the client connection, it should be declared first with the mysql_options() function like so:
mysql_options(mysql, MYSQL_SET_CLIENT_IP, "10.1.1.2");
This will set the client IP to the address given. This means that you will need to add the user to the grants table and provide privileges for the user from this IP address.
At this point in the program, we can proceed as we would normally with a C API program that interfaces with MySQL. We just need to add a line with the mysql_server_end() function to close the embedded server when we're finished. So, as you can see, if you want to modify one of your C programs to use the embedded server, you would only need to modify a few lines of code. All of the C API functions will work with the embedded MySQL server library as they would with the regular MySQL server. You would have to compile the program differently, though. This is covered in a later section. For good measure, let's finish the example program.
To query the MySQL database named in the last section, the function mysql_query() or mysql_real_query() can be used. We'll use the former to issue a SELECT statement to get a list of books from a table called books. Using the mysql_store_results() function, the results of the query are then stored in the results array, as shown below:
mysql_query(mysql, "SELECT book_id, title FROM books"); results = mysql_store_result(mysql); while((record = mysql_fetch_row(results))) { printf("%s - %s \n", record[0], record[1]); }
Using a while statement and the mysql_fetch_row() function, the results are looped through, one record at a time, and printed. After all of the records have been displayed, everything that was opened needs to be closed, including the main() function. This is done with these few lines:
mysql_free_result(results); mysql_close(mysql); mysql_server_end(); return 0; }
The mysql_free_result() function is used to free the memory where the results set from the query is stored. The mysql_close() function will close the mysql object. You wouldn't do this if you want to perform more queries. The mysql_server_end() function is used to close the embedded server. The rest of the code above (including the closing curly-bracket) is used to close out the main() function. This completes the example program. A complete copy of it is presented at the end of this article if you would like to see it without comments in between. All that remains is to save the program and to compile it with the required libraries and files.
To compile the C program to include the necessary files to embed the MySQL server library into the compiled version of the program, we will use the GNU C compiler (gcc). The compiler will need to know where to find various files and need instructions on how to compile the program. Below is an example of how the program outlined in this article could be compiled from the command-line:
gcc mysql_test.c -o mysql_test -lz \ `/usr/local/mysql/bin/mysql_config --include --libmysqld-libs`
Immediately following the gcc command is the name of the C program file we just went through in text form, uncompiled. After it, the -o option is given to indicate that the file name that follows is the name that the compiler is to give to the output file, the compiled program. The back-slash indicates to the shell that more text follows on the next line. The next line of code basically says for the compiler to obtain the location of the include files and libraries and other settings for your particular system. Because of a problem with mysql_config, I've manually added -lz, which is used for compression. This setting should be given by it, but it doesn't. If you'd like to see the settings passed to the compiler, you can enter the text contained within the back-ticks separately. By the way, those are back-ticks, not single-quotes.
If a program you've developed with the C API compiles without errors, you can copy it, the options file, the data directory, and the language directory to a CD and ship it. Before doing this, you should familiarize yourself with MySQL's licensing requirements. You should also consider what data you're copying and whether you want the users to have unrestricted access to it. You may want to give users only the databases and data that they need. For instance, you probably won't need to copy the mysql database directory unless you require authentication. If you have the time zone tables in the mysql database, though, you could copy just those table files and not the tables related to user privileges. If authentication is enabled, you may want to remove all users that aren't needed in the packaged application. If everything is set up properly, your compiled program should be able to run without MySQL installed and without a network connection.
The program shown in this article is missing any error checking code and other methods normally used with C code. I presented a very simple program for tutorial purposes. As a result, hopefully it has helped you to understand how to develop a C API program with the embedded MySQL server library. The embedded server library can allow you to create powerful database applications and to simplify user installation greatly. It has excellent possibilities.
For your convenience, below is a copy of the example program described in this article. This code has been reviewed and tested. However, the code is not guaranteed to be bug-free or to work properly with all versions or platforms of MySQL. You may use it or modify it at your own risk. The author or MySQL AB accept no responsibility for any problems that occur from using it. It's intended for educational purposes only.
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include "mysql.h" MYSQL *mysql; MYSQL_RES *results; MYSQL_ROW record; static char *server_options[] = { "mysql_test", "--defaults-file=my.cnf" }; int num_elements = sizeof(server_options)/ sizeof(char *); static char *server_groups[] = { "libmysqld_server", "libmysqld_client" }; int main(void) { mysql_server_init(num_elements, server_options, server_groups); mysql = mysql_init(NULL); mysql_options(mysql, MYSQL_READ_DEFAULT_GROUP, "libmysqld_client"); mysql_options(mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL); mysql_real_connect(mysql, NULL,NULL,NULL, "tester", 0,NULL,0); mysql_query(mysql, "SELECT book_id, title FROM books"); results = mysql_store_result(mysql); while((record = mysql_fetch_row(results))) { printf("%s - %s \n", record[0], record[1]); } mysql_free_result(results); mysql_close(mysql); mysql_server_end(); return 0; }
|
http://dev.mysql.com/tech-resources/articles/embedding-mysql-server.html
|
crawl-002
|
refinedweb
| 2,485
| 62.58
|
Hi all
i was making a functionality to upload an image ..
the package import flash.filesystem.file works in desktop app but in web app i am unable to import the package..how come this...
Hi,
The package, flash.filesystem.file is available in AIR application not in Web application
is there alternate way for this web..i want to
use
var _fl:File;
_fl.browseForOpen(parameter);
the above function which is only possible in desktop not in web..any alternate function for this .i want that on click of a button a browse window should open an the image selected by user should be loaded in an image control
I'm afraid if there is a direct way to upload a image to image control. You can upload a file to server and download it from server and display the same in image control
Just take a look at this link ass/
Hello All, We have a requirement which involves reading a XML file through actionscript and setting the component's attribute value in mxml. We are using ActionScript 3.0, Eclipse IDE and ours is a Web Application.
Inorder to access the XML file, I tried using
import flash.filesystem.File;
But it did not workout.
Is there any workaround for it!
Actually, you can load an image directly into Flash Player using FileReference/load():
var file:FileReference = new FileReference(); stage.addEventListener(MouseEvent.CLICK, click); function click(e:MouseEvent):void { file.browse([new FileFilter("JPEG", "*.jpg")]); file.addEventListener(Event.SELECT, fileSelect); } function fileSelect(e:Event):void { trace(file.name) file.load(); file.addEventListener(Event.COMPLETE, fileComplete); } function fileComplete(e:Event):void { var loader:Loader = new Loader(); loader.loadBytes(file.data); addChild(loader); }
|
https://forums.adobe.com/thread/531045
|
CC-MAIN-2017-17
|
refinedweb
| 284
| 50.94
|
You have two cows
From Uncyclopedia, the content-free encyclopedia
You have two cows is the philosophical truth of the entire world. Category two may contain contributions from the Internet as well as Uncyclopedia contributors.
Correction. You had two cows.
Category One: Misc.
- U.S. Democracy
- You have two cows. People with funny hats from 1,000 miles away in distant towns whom you've never met elect the leader, who takes your cows away and then gets impeached for having sex with them. Then one of your cows in custody is killed by terrorists, and the government taxes you and bans your kids from school to finance war against cow-hating foreigners. Your other cow is being tortured at the Guantanamo Bay. Now you have no cows, and people with funny accents from 800 miles away accuse you of being unpatriotic for complaining.
- Palestine
- You have two cows, whose ancestors 2,000 years ago belonged to the Jews. The British then come over and give them to Israel. You get your neighbours to fight Israel, and Israel beats them up and takes their cows too. Israel then offers to give one cow back, which you refuse. You then bomb the cows out of spite. You and the Jews now bomb each other on a regular basis, even though the cows are all dead.
- D&D
- You have 1d20 cows. You roll 3d5 to determine how much milk they will give (in litres) and 1d7 to determine their hit die. They have a 1d20+5 chance of getting Mad Cow Disease, and in the Third Edition the disease no longer makes them sick but reduces their hit dice and milk by 1d3 and 2d2 litres respectively. They also take turns to get milked, even though you have enough workers to do it simultaneously, and you spend all night calculating the milking process. Your neighbours then accuse you of being a Satanist.
- Vampire: the Masquerade LARP
- You have—give me a test? *rock, paper, scissors*—two cows. One is, umm, an eleventh-generation Toreador with Dread Gaze and Heightened Senses, and the other one is a tenth-generation Gangrel with Eyes of the Beast and two levels of Fortitude. Okay, fine, one level of Fortitude and Wolf Claws. Give me another test? *rock, paper, scissors* What's your Mental? Do you have Awareness? No? Okay, you don't notice anything. Wait, what do you mean you activate Unseen Presence? You didn't notice anything! I don't care if your derangement is Paranoid!
- The Matrix
- Here before you are two cows: one red, one blue. Take the blue cow, the story ends. Take the red cow, and I show you just how deep the cow hole goes. What? You thought you have two cows? You do not have two cows. There are no cows. Cows only exist in the Matrix, an elaborate computer program designed to trick you into complacently accepting your fate until such time when machines harvest your body for its energy. Of course, you have to realize that it is not the cows that have disappeared from your world; it is you that has disappeared from theirs. Now here's what'll really cook your noodle: if you still thought that cows were real, would you still have two of them?
- Arts program in university
- You have two cows. You have gigantic orgies with them all the time. In the morning, you listen to lectures on how people think cows are oppressed, how cows are portrayed in art, how many cows were slaughtered from prehistoric times to the post-modern era, what the cowists did during the Second Era of Cowism, and the way cows moo in various languages and the significance thereof. You go home and copy what others have written about their cows on the Internet for your term papers, and get jealous of your roommate who probably showers the profs with cows and gets A's all the time.
- Unimaginative people
- You have two cows.
- Goths
- You have two death cows with feral eyes and bloody fangs who hang out at the local graveyard a lot. You write of the abyssal and profound darkness, which the cows have in melancholy embraced. Oh! The torment upon the blackest hour, which has dawned, screaming in pain and suffering. Oh! The distant fogs rolling down into the madness-stricken grief that is your cows, in the deathly quiet of the bloodstained night.
- Heroic Couplets
- You have two cows that stand atop the pastures,
Their livid eyes affix'd upon the gestures
Of cowherds training armed and dang'rous bears
To fend off dragons raiding from their lairs.
The bears are most heroic, as they fight
With Mars's sword and Zeus's thund'rous might!
The cows continue to be bless'd by Sibyl,
As heroes once again prevail o'er evil.
- Classical civilization
- You have two cows, one in Athens and one in Sparta. In Athens, the cow is the wise cowncillor of the city. In Sparta, the cow is the brave cownqueror. They both like to invade unintelligent sheep that go "baar baar" (called barbarians) for sport and then milk them. One day, the Spartan cow is sent to depose the cowncillor in Athens. The Spartan cow wins, and milks the cowncillor. Then the Romans come in, pours the milk into their inventions—sewers, eat both cows during an orgy, and vomit them out so their stomachs can take more. Everyone else comments on how civilized they are.
- Spam
- You have two cows, but are they good enough? Do they suffer from impotence? Try our cheapest bovinagra and cowalis on the Internet! Wait, they're female? Try our latest udder implant technology. Absolutely no side effects and 100% approved by the Cowvernment. Do you also want special education for your cows, in case they need diplomas and degrees now? We offer free elementary school diplomas! Buy LOLex automatic milking devices online at this URL:, join the army, and don't be a poor cow-'erd! Consolidate your debt. agrfronprache eeevnings zddalqrs qibody atni-spma-ftiler-rubisbh. Then Dima came in. "YOU ARE ALL NAKED HAHAHAHA" Then Dima shot them all with a machine gun.
- Representative Democracy
- You have seven cows. Instead of being an outright dictator, you make up the pretence of fairness and let them vote for representatives. You, your father, and your farm hand are the only candidates. The three of you campaign all week and annoy the cows. In the end only one cow votes successfully (for you), three cows' votes (for the farm hand) are thrown out, three cows are too lazy to get up and vote. In total, eight votes are counted in your favour because you are using the Diebold voting machine. You claim you have the Moodate to rule and so expect the cows to produce twice as much milk from now on. You then send the cows to invade your dictatorial neighbours so their sheep can have the same freedom too.
- Pig Latin
- Ouyai avehai wotai owscai. Heytai reaai eallirai nglisheai owscai, utbai ouyai nsistiai hattai heytai ebai alledcai atinlai igspai.
- Sour Grapes
- You have two category one cows, and they are both eating sour grapes.
- Fortean Phenomena
- You have one cow with two heads but it bilocates. UFOs are spotted in the sky and the cow is found mutilated. You buy some goats instead and the Chupacabras sucks them. It rains fish.
- Arcade Games
- You have two pixelated cows you must move the pixelated cows out the way of the falling pixelated asteroids. Every 500.
- Text-Based Adventure Games
- you have two cows. do you wish to milk cow one? do you wish to milk cow two? do you wish to milk both cows? do you wish to move north?
- Zork
- GET COW
- Cow taken.
- GET COW
- You already have the cow.
- MILK COW
- Milk appears at your feet!
- GET MILK
- What, with your bare hands?
- PUT MILK IN BOTTLE
- You need to open the bottle first.
- OPEN BOTTLE
- The bottle is now opened.
- PUT MILK IN BOTTLE
- The bottle is now filled with milk.
- Limericks
- There was a young chap they called Prouse
- Who owned two remarkable cows.
- The first one was blue
- And often said 'Moo'
- While the other was big as a house.
- Elmer Fudd
- You have two cows. Oh, dat scwewy wabbit! Peopwe wif funny hats fwom 1,000 miwes away in distant towns whom you've nevew met ewect the weadew, who takes youw cows away and then gets impeached fow having sex wif them. Den one of youw cows in custody is kiwwed by tewwowists, and the govewnment taxes you and bans youw kids fwom schoow to finance waw against cow-hating foweignews. Oh, dat scwewy wabbit! Youw othew cow is being towtuwed at the Guantanamo Bay. Now you have no cows, and peopwe wif funny accents fwom 800 miwes away accuse you of being unpatwiotic fow compwaining.
- High school
- You have two cows. One of them is irredeemably stupid but takes really easy classes and graduates at the top of its' class. The other is much smarter but takes all honours and AP courses and barely manages to graduate. You write angsty poetry on Livejournal.
- Light bulb Jokes
- How many cows does it take to change a light bulb?
- Two.
- Pants Vaporizers
- Your two cows no longer are wearing pants.
Category Two: Politicowl Junk
-.
- Bureaucratic Socialism
- Your cows are cared for by ex-chicken farmers. You have to take care of the chickens the government took from the chicken farmers. The government gives you as much milk and eggs the regulations say you should need.
- Cambodian Communism
- You have two cows. The government takes both and shoots you.
- Extreme Capitalism
- YOU HAVE TWO COWS.
- Capitalism
- You don't have any cows. The bank will not lend you money to buy cows, because you don't have any cows to put up as collateral. Go and sell your cows nightmares for a third of their original cost.
-.
- Environmentalism
- You have two cows. The government bans you from milking or killing them.
- Fascism
- You have two cows. The government takes both, hires you to take care of them, and sells you the milk.
- Fatalism
- You have two cows. You die.
- Feudalism
- You have two cows. Your lord takes some of the milk.
- Government cover-up
- Cows never crash landed in the New Mexico desert. In fact, cows never even existed. You never saw anything.
- Ingsoc
- You have two cows, and you provide them with plenty of fresh Feedcow and clean, cool Cowdrink. However, Mincow declares this to be a Cowcrime. You are taken away to have your Cowthink realigned with that of the Party. When you return you realize that your two cows are actually five.
- Libertarianism
- You have two cows. You exchange one for gold and rent out the other for more gold. You sit alone in your house with lots and lots of gold, slowly rotting away.
- Militarianism
- You have two cows. The government takes both and drafts you.
- Perestroika
- You have two cows. You have to take care of them, but the Mafia takes all the milk. You steal back as much milk as you can and sell it on the "free" market.
- Political Correctness
- You are associated with (the concept of "ownership" is a symbol of the phallo-centric, war mongering, intolerant past) two differently aged (but no less valuable to society) bovines of non-specified gender.
- Pure Anarchy
-.
- Pure Capitalism
- You have two cows. You sell one and buy a bull.
- Pure Communism
- You don't have cows. Your commune has two cows, and everyone shares them. You go home after work every day, content that you live in a classless society.
- Pure Democracy
- You have two cows. Your neighbours decide who gets the milk.
- Pure Socialism
- You have two cows. The government takes them and puts them in a barn with everyone else's cows. You have to take care of all of the cows. The government gives you all the milk you need.
- Real World Communism
- You share two cows with your neighbours. You and your neighbours bicker about who has the most "ability" and who has the most "need". Meanwhile, no one works, no one gets any milk, and the cows drop dead of starvation.
- Representative Democracy
- You have two cows. Your neighbours pick someone to tell you who gets the milk.
- Russian Communism
- You have two cows. You have to take care of them, but the government takes all the milk. You steal back as much milk as you can and sell it on the black market.
- Surrealism
- You have two giraffes. The government requires you to take harmonica lessons.
- Theocracy
- You have two cows. You may only milk them every third Sunday, or be stoned to death by the other cow owners. You must brush them from left to right, or be stoned. If you do not milk the cows, you are also stoned to death. Failure to participate in stoning is grounds for stoning.
- Third World Globalized "Democracy"
- Ten years ago, your village had two cows. One cow died from dehydration after Bechtel built a hydroelectric dam upstream. The other was sold to pay your debt to the World Bank for building the dam. After you threw stones at the dam employees in protest, a death squad shot you and your family as communists.
- Totalitarianism
- You have two cows. The government takes them and denies they ever existed. Milk is banned.
Category Three: The World of Cows
- dicovered on your land and the economy is miraculously saved.
- Britain
- You've two cows.
- Wales
- You hyve two cwws.
- Scotland
- You have two sheep.
-.
- Chinese
- You can have two cows, but only if you're an American and brought a lot of money.
- Danish
- You have two cows. You trade them for two pigs and sell their delicious bacon.
- Dutch
- You have two cows. It is illegal to grow milk, sell milk, or drink milk. However, if you have less than 5 grams of milk on you, the police won't arrest you. For 5 euros, you can have sex with one of the cows.
- very much and they both work in paper industry.
- You have two beautiful cows, but so does everyone else.
- German
- You have two cows obtained for free, but they came with gas masks and rubber suits. You're still not sure how to get the ball gag off.
-.
- Japanese
- You have two cows. Both of your cows have extravagant hairstyles. One of them has very long teats and likes to spray the other cow with milk.
-.
- Romanian
- You have two cows. I have three chickens, same shit in our corruption infested country where the guy who bribed the president got three cows and four chickens.
- Russian
- You have one cow, but you bought it off the Internet for an awful lot of money, it doesn't quite match the picture, and it's a lot more interested in eating grass than being eaten by you.
-.
- Soviet Russian
- In Soviet Russia, cows have you.
- The Borg
- We have 2765893452 cows, resistance is futile.
-.
- Star Wars Universe
- You have two cows. Both are children of a bull who turned to the dark side (whatever that means, since he was all black to begin with.) One of them saves the universe and the other one hooks up with a cocky pilot.
-.
Category π: The World Wide CoWeb
- The Best Page In The Universe
- For every two cows you don't eat, I'll eat six.
- The Straight Dope
- Cecil Adams says you have two cows.
- Homestar Runner
-.
- Goatse
- If you have two cows or find this image offensive, please don't look at it. Thank you!
- Zero Wing
- What happen? Somebody set up us two cows.
- Slashdot
- You have two cows. They have poor social skills and live in your basement. (Score:2, Informative)
- Slashdot 2
- The farm is down due to /. effect... try again later
- FARK
- [OBVIOUS] Scientists discover if you own two cows, you can drink milk from them. Duke sucks.
- Snopes
- My sister's best friend's mother said you have two cows so it must be true.
- Related articles:
- You have two cows.
- You have two cows.
- You have two cows.
- Chimp takes over MSNBC.
- You have two cows.
- You have two cows.
- Bash
- !
- weebl and bob
- You have two cows. You make pie out of them but never get to eat it.
- "Damm you weebull, you win this time."
- Douglas Adams
- You have 42 of something not entirely unlike Arcturian Mega-Cows, a towel, an infinite improbability drive, and no tea.
- The Price is Right
- Come on down! You have two cows!
- The Price is Right alternate
- Let's see the next item up for bid.
- Why, it's two lovely cows! And they can be yours if the price is right!
- AOL
- You've got cows!
- AOL 2
- Me too!
-.
- eBay
- L@@K!!! TWO COWS, MINT CONDITION! COULD BE YOURS, BID NOW!!!
- Newgrounds
- You gave "Two Cows" a 1 out of 5! This raises it's score from 0.3349 to 0.3352! If this movie is blammed, you get a blam point!
- Rather Good
- We love the cooooows! Cause you have two of them!
- Gmail
- Why have 2 megacows when you can have 1 gigacow?
Category Four: Software 'n Such
-. Their milk, however, must also be given away for free, and the milk of their children, and of their children's children..
- Sun
- You have one dying cow that gives coffee, but the coffee is slow and outdated. You are stabbing it to death.
- Linux
- You have a million rabbits. They run a lot faster than cows, but aren't as friendly. You can't even give them away. In order to use them, you must RTFM. Similar to GNU
- Apple
- You have two cows. They are beautiful and work perfectly, but no one will buy them, probably because their milk isn't compatible with the majority of cereal. They will buy your chicken, however, which helps your stock.
- Mac OS X
- You also never had two cows. But unlike Microsoft cows, you get tiny bits and pieces of cows in the mail every week, just to let you know that Apple McIntosh has your two cows. As it turns out, Mr. McIntosh is a better butcher than a CEO. Actually, McIntosh was never a CEO. He was too busy playing croquet in North Africa to even bother running a company. This explains why even though he has tastier, yummier cows, the cows were never really broken so that you could ride on them. And run things called programs on them. Meanwhile, you can't decide between whether you want an iSausage or an iSpleen.
- OpenBSD
- You have two cows, anyone can do whatever he or she wants with them. People can trample babies with them for all you care. You will never feed them undocumented feed or use undocumented equipment, because you believe in true Freedom.
- DOS
- You have two cows out of a maximum of 4. Only one can produce milk at a time.
- CATS
- ALL YOUR COWS ARE BELONG TO US. YOU HAVE NO MILK TO SURVIVE MAKE YOUR TIME.
- Diablo
- There is no cow level.
- Math
- You have two perfectly spherical cows.
- Algebra
- You have two cows. They follow the path y = 4x2 − 2. Solve for the cows.
- Geometry
- You have two cows. You will never use them again.
- Formal Calculus
- You have two cows. Take
.
, your cows are within ε of the derivative.
- Chemistry
- You have two cows. These cows combust according to the formula H2Cow + O2 → CowO2 + H2O + 512KJ. How much heat will be released in the combustion of 3.2×1023 cows with an excess of hydrogen and oxygen?
- Physics
- You have two cows. One gets in a spaceship and leaves Earth, travelling causes weird stuff like time travel..
- Spanish 1
- Tu tienes dos vacas. Como estan las vacas? Muy bien. Estan en un fieldo.
- Japanese
- You ale being have 2 cows !! Cows are be giving mirk !! You being are having cows ?? ^______^
- Chinese
- You have two woks.
-
- You had two cows, until one of them was banned. If you want to milk your remaining cow, it'll cost you $10. If you want to drink the milk, it'll cost you a further $10. Now you're banned.
- MediaWiki
-
Category Five: You Have More Than Two Programming Languages
- Python
cows = 2
- Java
Cow[] yourCows = new Cow[2];
- C#
using(new Farm()) { Cow[] cows = new Cow[2]; }
- Pascal
program two_cows; var cows : integer; begin cows := 2; writeln ('You have ',cows,' cows...'); end.
- PHP
<?php $cows = array(new Cow, new Cow); ?>
- Perl
my @cows = ( "cow" ) x 2;
- JavaScript
var cows = [new Cow(), new Cow()]; if(document.layers) commitSeppuku();
- TI-Basic
2 -> X Disp "NUM COWS=",X
- LISP
(setq cows '(cow1 cow2))
- C
#include "ruminants.h" COW *cows; cows = calloc(2,sizeof(COW));
- Fortran
PROGRAM two_cows IMPLICIT NONE CHARACTER, DIMENSION(3,2) :: cows cows(1:3,1) = (/ 'C', 'o', 'w' /) cows(1:3,2) = (/ 'C', 'o', 'w' /) END PROGRAM two_cows
- COBOL
IDENTIFICATION DIVISION. ENVIRONMENT DIVISION. CONFIGURATION SECTION. SOURCE-COMPUTER. VAX-VMS. OBJECT-COMPUTER. VAX-VMS. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT COWS-IN ASSIGN TO 'COWS.DAT'. SELECT LINE-OUT ASSIGN TO 'COWS-REPORT.DAT'. DATA DIVISION. FILE SECTION. FD COWS-IN LABEL RECORDS ARE STANDARD RECORD CONTAINS 80 CHARACTERS. 01 DATA-RECORD-IN. 05 COW-IN PIC 99. 05 FILLER PIC X(38). FD LINE-OUT LABEL RECORDS ARE OMITTED RECORD CONTAINS 104 CHARACTERS. 01 PRINT-REC PIC X(104). WORKING-STORAGE SECTION. 01 DETAIL-LINE-WS. 05 TEXT-WS PIC X(20). 05 COW-IN-WS PIC 99. PROCEDURE DIVISION. 0100-MAIN-MODULE. PERFORM 0200-INITALIZATION-MODULE. PERFORM 0500-DETAIL-LOOP UNTIL DONE. PERFORM 1000-FINAL-MODULE. STOP RUN. 0200-INITALIZATION-MODULE. OPEN INPUT COWS-IN OUTPUT LINE-OUT. 0500-DETAIL-LOOP UNTIL DONE. READ CONSTCO-IN AT END MOVE 'YES' TO EOF. MOVE COWS-IN TO COWS-IN-WS. MOVE 'Number of Cows: ' TO TEXT-WS. WRITE PRINT-REC FROM DETAIL-LINE-WS. 1000-FINAL-MODULE. CLOSE COWS-IN LINE-OUT.
- SQL
SELECT `animal` FROM `barn` WHERE `sound`='moo' LIMIT 2; CountOfCows: 2
- XML
<farm owner="You" cows="2">moo</farm>
- Ruby
cows << Cow cows << Cow
- RDF/XML
<rdf:Description <cw:has <cw:Cow> <cw:name>Cow A</cw:name> </cw:Cow> <cw:Cow> <cw:name>Cow B</cw:name> </cw:Cow> </cw:has> </rdf:Description>
- BASIC
10 PRINT "YOU HAVE TWO COWS" 20 GOTO 10
- C64 BASIC
10 POKE 808,237 20 PRINT "YOU HAVE TWO COWS" 30 GOTO 20
- DOS
@ECHO OFF SET COWS=2 ECHO YOU HAVE %COWS% COWS.
- Brainfuck
>+++++[>++++++++++<-]>.------------------.>+++++++++[>+++++++++++<-]>.++++++++++++.++++++++.----.
- ASM
ld a,2 call set_cows ret set_cows: push af .waitvlbnk: ld a,($FF44) cp $90 jr nz,.waitvblnk pop af ld (num_cows),a ret
- Visual Basic
Private Sub Form_Load NumCows = 2 End Sub
- Visual Basic.NET
Dim Cows as Integer Private Sub Form_Load Cows = 2 lblCows.Text = Cows End Sub
- HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <h>You Have Two Cows</h> </body> </html>
- C++
using namespace bovine; vector<cattle::cow> cows; cows.push_back("daisy"); cows.push_back("geraldine"); cout << "you have" << cows.size() << "cows" << endl;
- Visual C++
- You have two cows, but you were trying to create 5 chickens. They're heavier and slower than most cows, and sometimes explode when producing milk.
- HAL 9000
- I'm sorry, Dave. I can't do two cows.
- AI Bot
human: you have two cows aibot: what makes you think I have two cows? human: look! there they are! two cows! aibot: please calm down. tell me about your two cows human: they are not my cows, they are your cows aibot: what makes you think they are not your cows? ^C TELNET SESSION DISCONNECTED
- SmarterChild
v1xx13: You have two cows. SmarterChild: Yes, I guess I have two cows. v1xx13: I have two cows too. SmarterChild: You humans say interesting things. v1xx13: My two cows say even more interesting things. SmarterChild: For real? v1xx13: Yes. SmarterChild: K. v1xx13: They say "moo". SmarterChild: Aha.
- Electronic Brain AI Bot
Human: you have two cows Electronic Brain AI Bot: What makes you think I have it? Human: i can see them Electronic Brain AI Bot: How do they look? Human: pretty Electronic Brain AI Bot: Is that from something? Human: sorry? Electronic Brain AI Bot: There's no need to apologize.
Category 0110: You Have n Cows
- Unary
- You have 11 cows.
- Binary
- You have 10 cows.
- Octal
- You have 002 cows.
- Hexadecimal
- You have 0x0002 cows.
- Innumerate
- You have some cows.
- Floating-Point
- You have 0x40000000 cows.
- Integer
- You have 2 cows.
- Long
- You have 2.0 cows.
- Modulo 2
- You have 0 cows.
- 64-Bit Long
- You have 2LL cows.
- Scientific notation
- You have 2.0 × 100 cows.
- String
- printf("You have %d cows.\n",2);
- Shift
- YOU HAVE @ COWS>
- Japanese counting
- You have two cattle of cow, or You have 2*1 cows.
- Greek Numerals
- You have β´ cows.
- Roman Numerals
- You have II cows.
- Pebbles
- You have .. cows.
- Intel Pentium 60 - A80501-60
- You have 2.0000000056987983 cows.
- Natural numbers
- You have {{},{{}}} cows.
- Integers
- You have [5 - 3] cows.
- Rational numbers
- You have [4/2] cows.
- Real numbers
- You have [1 + 1/2 + 1/4 + 1/8 + ...] cows.
- Surreal numbers
- You have { -1, 0, 1 | } cows.
Category 0111: Literature
- 1984
- You have two cows. Your neighbour has two cows. Together you have five cows. Your child reveal that to the government and one day they come and take your cows. You have never had any cows. You love big brother.
- Animal Farm
- You have two cows. Two cows bad. Four cows good. (Comrade Napoleon is always right.)
- A different Animal Farm
- You have two cows and you fuck them on video. Unless you live in the U.S. Deep South this is probably illegal. Makes you wonder why it's called the Deep South though...
- Russia
- You have two coups.
- Two cows have you!
- Paranoia RPG
- Aren't you happy that Friend Computer gave you two cows, citizen?
What's that, citizen? The cows trampled you? They must have known you are a commie mutant traitor!
- COBRA Master plan
- The Joes have two cows. You steal the cows and attempt to crossbreed them with a snake to produce the milk-producing cowbra. The Joes discover your ridiculous plot and after causing several million dollars worth of damage to your private army retire to their base to drink Yo Joe! Cola and swap an amusing anecdote. Baroness Thatcher steals the milk anyway and makes the children cry.
- Shakespeare
- Alas poor Yorick. He had two cows, Horatio.
- Crime and Punishment
- You have no cows, but as you are a superior breed of man, you kill your elderly neighbour and take her cows. Then you go mad from guilt, turn yourself in, and are sent off to the gulag. They don't have cows there.
- Great Expectations
- You have no cows. You dream of getting your own cows, and then an old woman promises you love and cows. After the cows turn out to be provided by a convict butcher, you reflect. You find one of the cows again and walk off, but it doesn't really love you.
- Charles Dickens: A Tale of Two Cows
- It was the best of cows, it was the worst of cows.
- Catch-22
- You have two cows, but only if you don't want them. If you want them you can't have them. Nately's whore keeps trying to kill them.
- Traditional Haiku
- You have two cows, and
- cherry blossoms on the wind--
- The sound of mooing
- Ulysses
- Leonard Bloom ate with relish the internal organs of two cows.
- War of the Worlds
- You have many lovely English cows. Unfortunately the Martians invade and kill most of them with vastly superior technology. Just when all seems lost, the Martians catch the common cold and die.
- Lord of The Rings
- You have two cows, and one ring. The cows are killed on a long and arduous quest to destroy the ring.
- The Hobbit
- You had two cows, but then a bunch of greedy, freeloading dwarves and a wizard took over your home and made them into provisions so you could go on a long journey and kill some dragon. Lousy dwarves.
- Things Fall Apart
- You have two cows. But they are the White Man's Burden. So the white man takes them from you. You lose everything and commit suicide.
- 20,000 Leagues Under the Sea
- You have two cows, and are abducted by a crazy terrorist sea-pirate with a fantastic submarine. Unfortunately before you can get to any serious adventuring you are bored to death by endless pedantic descriptions of fish.
- At the Mountains of Madness
- You have two cows, and take them with you on an ill-fated expedition to Antarctica. Once there you find evidence of an ancient alien civilization whose language you more or less decode in fifteen minutes. The aliens abduct your cows and eat one, then are killed by a second race they had created as slaves, who eat the other. You barely make it out alive and begin to wonder if even tenure is worth this much trouble.
- Catcher in the Rye
- This one time, you had two cows, but then you got to thinking about all the phonies getting their milk and that made you kind of sad so you let them go.
- Dr. Jeckyl and Mr. Hyde
- You have one cow, but at night sometimes, it turns into a larger, meaner embodiment of the evil side of your cow and kills people.
- Portrait of an Artist as a Young Man
- "Once upon a time and a very good time it was there was a moocow coming down along the road and this moocow that was coming down along the road met a nicest little boy named baby tuckoo...."
- Old Testament
- You have two hundred she-goats and twenty he-goats, two hundred ewes and twenty rams, thirty milch camels and their colts, ten bulls, twenty she-asses, ten he-asses, and two cows. You guide them all safely into the Promised Land and then the LORD asks you to sacrifice them. You do as the LORD says, and you no longer have two cows. As you lay dying of hunger, you ask the LORD for guidance, and He saith unto you "You mean you actually killed them? It was just a test of faith, you were meant to get a message at the last minute - something along the lines of Don't Kill The Cows, Just Order Me A Pizza Or Something, That Will Be Fine. You didn't get that message? No? Oh bugger."
- The Scarlet Letter
- You have two cows, and are forced to wear a scarlet letter 'A' on your chest because of it. You are ostracized by Puritan villagers and forced to live alone in a crude shack, while your lover is eaten alive by guilt for seven years. In the end, he dies in an awfully melodramatic fashion for no discernable reason, leaving you utterly alone again.
- The Cows of Monte Cristo
- You are about to be married to the two cows you love, but are instead sent to a prison, never to be heard from again. Eventually you are able to escape, and seek to exact cow justice upon your accusers in the name of your love for your two cows.
- Bridget Jones
- Cows owned: 2. v.g.
- Harry Potter and the Two Cows
- You have two cows, but only because that sold someone else's book.
- Moby Dick
- A cow with only one leg hunts down a great white cow.
- Sophie's Choice
- You have two cows. One of them will be incinerated by Nazis; the other gets to live. Which cow do you choose?
- The Perks of Being a Wallflower
- You have two cows. One of them likes you but you don't think about her that way. The other you like, but you try not to think about her that way. A bull also likes you, which makes everything so confusing.
- Taxi Driver
- You talkin' to my two cows? You talkin' to my cows? You talkin' to my two cows? Well, who the hell else are you talkin' to? You talkin' to my cows? Well, they're the only cows here. Who the fuck do you think you're talkin' to?
- e e cummings
- in Just-
- spring when the world is mud-
- luscious the little
- lame balloon man
-
- whistles far and wee
-
- and two cows come
- running from grass and
- daisies and it's
- spring
- The Hitchhiker's Guide to the Galaxy
- Deep Thought: You have 42 cows.
- Marvin the Paranoid Android: Cows... Don't talk to me about cows.
- Ford Prefect: You've got to know where your towel and your two cows are.
- Dolphin: So long, and thanks for the two cows
- Slartibartfast: We built cows, you know.
- A Vogon: Oh freddled gruntbuggly, thy two cows are to me, as plurdled gabblebloitchits(...)
- Hamlet
- You have two cows, or not two cows; that is the question.
- The Picture of Dorian Grey
- You have a cow, and a picture of a cow. The cow is depraved, but looks perfect, and the picture looks depraved but is, well, a picture. This isn't science fiction, because no explanation is offered involving Quantum Entanglement is offered. Oscar Wilde is the King of the Universe.
- The Metamorphosis
- As your two cows awoke one morning from uneasy dreams they found themselves transformed in their pasture into gigantic insects.
- Lord of the Flies
- You have two cows. The nerdy one falls off a giant rock and dies.
- Macbeth
- You have two cows. One cow kills the other cow and becomes the king of Scotland. Unfortunately, the remaining cow goes batshit insane.
- Cyrano de Bergerac
- You have two cows. One has a big nose. He is in love with his cousin (the other cow), yet is not from the south.
- A Separate Peace
- You have two cows. One pushes the other off of a tree. Boring stuff happens, and then the other cow dies.
- Anthem
- We have two cows.
- The Prodigal Cow
- You have two cows. One cow runs away to a far-off land and lives 'la vida locow' while the other cow stays home and behaves herself, giving twice as much milk. The wandering cow returns to the stall and you throw a party for her. Everyone's happy except for the cow that stayed home and behaved. She's jealous and angry. So even though the wandering cow returned, you still have one that's lost.
Addendum. It is notable that in the original, when the prodigal cow returns, his father kills the fatted calf; this might doubly annoy the bloated stay at home one
- Ayn Rand
- Your two cows are not independent. This is wrong. But if you agree with me, you are not independent. That is wrong. You are caught in a logical paradox.
- Stephen King
- You have 2 cows, but it takes 700 pages of boring crap to find that out.
- Dean Koontz
- You have two cows. One used to belong to the military. One is basically helpless but pretty. They somehow become involved in a lame conspiracy involving at least one adorable calf, a town in California, mad science and/or hokey mystical powers and a golden retriever. Everything works out ok in the end, but then you realize that you've had these two cows before. Many, many times.
- Donald E. Knuth
- You are still waiting (after 40 years) for "The Art of Computer Programming: Volume 4" to come out so you can learn about how you have 2 cows
- Michael Crichton
- You had two cows. Then you began to write books about them based upon ever-more-ridiculous premises. Eventually no one took you seriously anymore and your books were sold almost exclusively in airport gift shops. So you killed your cows, blamed it on Greenpeace, and spent the rest of your days gibbering incoherently at random passers-by.
- H. P. Lovecraft
- You have two cows. Cthulhu drives you mad and eats them.
- Terry Pratchett
- You thought you had two cows, but in reality one was the Death of Cows and went 'MOO' all the time, whereas the other was actually someone who had severely annoyed a witch. This sort of thing happens an awful lot.
- Tom Clancy
- You have two cows. They go to war with each other. It takes 1,300 pages.
- Tom Clancy 2
- The Sum of all Cows is 2. Jack Ryan brought his two Holstein cows a bale of alfalfa hay with his John Deere 2620 front-end loader. Just then, his Motorola 3110 cell phone rang...
Ryan: Hello?
Admiral Greer: Jack, you and your cows need to get your asses back to Foggy Bottom, we've got a situation here!
Ryan: Admiral, I'm retired; I'm just a dairy farmer now!
Admiral: I know, you have two cows, some dairy farm Jack! You know you miss it.
Ryan: Miss what, getting shot at? (sigh) Cathy's going to kill me...
- Dan Brown
- Two cows are hidden in ancient churches in Florence. A university lecturer is woken by a phone call in the middle of the night that sends him on a thrilling race-against-time to discover the cows. An unknown stranger lights a barbeque in Barcelona.
- Francesca Lia Block
- You have two cows that feel like velvet starlight against your jangly-skeleton hands. Their eyes are delicate flowers in a dark alley, and their milk tastes like wet puppy kisses on a summer afternoon.
- Robert Jordan
- You have two cows. You plan to have fifteen, but you are busy beating them to death.
- Phillip K. Dick
- You have tw— The end.
- Chuck Palahniuk
- You have two cows. One has a complete lack of self-worth and an identity crisis. The other cow is either confident or awesome (but doesn't really exist), or the other cow is worthless, ridiculous, and loyal but presents a startling glimpse of truth in its mindless ramblings.
- Danielle Steel
- You have two cows, one gets raped while coming of age.
- Anne Rice
- You have two cows, they suck blood. One runs around Europe feeling sorry for himself and looking for God and/or a dead little girl, while the other one lies buried in a coffin in New Orleans and also feels bad for himself. No one has any problem with the sexual tension between the cows.
- Jacqueline Wilson
- You have two young girl cows who have experienced some deep problem in their family. They manage to come to terms with it, there is a happy ending and everyone learns something about friendship. Aww.
- R.L. Stine
- You have two cows. You think your cows might be ghosts. 100 pages later it turns out you're a ghost and the cows are real. Same thing happens next month under a different title.
Category 8: Religion
- Jehovah's Witnesses
- Knock! Knock! You have two cows.
- Gnasip sect
- You drink Pisang ambon. You use your psychic abilities.
- You conquer the world. You now got all the cows you want. You paint them green.
- Taoism
- You have two cows. It is good.
- Buddhism
- If you have two cows, they aren't really cows.
- Zen Buddhism
- Cows are, and are not.
- Zen Buddhism #2
- What is the sound of two cows happening?
- Hinduism
- These two cows have happened before.
- Islam
- If you have two cows, it is the will of Allah.
- Catholicism
- If you have two cows, you deserve them.
- Protestantism
- Let the two cows happen to someone else.
- Presbyterian
- These two cows were bound to happen.
- Episcopalian
- It's not so bad if you have two cows, as long as you serve the right wine with them.
- Methodist
- It's not so bad if you have two cows, as long as you serve grape juice with them.
- Lutheran
- If you have two cows and don't mind sharing, then you can really help us keep up the cream supply at coffee hour.
-.
- Judaism
- Why does two cows always happen to us?
- Orthodox Judaism
- Your two cows were milked on Shabbos. They must be killed, and the meat is forbidden. You are Chayev Kares.
- Calvinism
- You have two cows because you work.
- Seventh Day Adventism
- No cows shall be owned on Saturday.
- Creationism
- God made all cows.
- Secular Humanism
- Cows evolve.
- Christian Science
- When you have two cows, don't call a doctor—pray!
- Christian Science #2
- You having two cows is all in your mind.
- Unitarianism
- Come. Let us reason together about these two cows.
- Quakers
- Let us not fight over these two cows.
- The Other Quakers
- (Half of a) QUAD COWAGE!
- Darwinism
- Your two cows are food.
- Idolism
- Let's bronze your two cows.
- Mormonism
- God sent us these two cows. Dumdumdumdumdum.
- Mormonism #2
- God sent you two cows, but they are wearing funny garments. You must not remove the garments, even while milking, or you will not make it to the Celestial Temple.
- Wicca
- An it harm none, you have two cows
- Scientology
- If you have two cows, see "Dianetics", p.157.
- Scientology #2
- Millions of years ago, Xenu put your cows in a volcano and exploded it with a nuclear bomb. Now their ghosts haunt you and cause all your problems.
- Hare Krishna
- Two Cows, rama rama.
- Rastafarianism
- Let's smoke these cows!
- Zoroastrianism
- You have two cows half of the time.
- Discordianism
- You used to have 5 cows, but the Illuminati stole 23 of them.
- Church of SubGenius
- BoB has TWO cows.
- Agnostic
- You might have had two cows; then again, maybe not.
- Agnostic #2
- Did someone have two cows?
- Agnostic #3
- What are these cows?
- Dyslexic
- Ouy vaeh wot owcs.
- Satanism
- .SWOC OWT EVAH UOY
- Ariadnite
- The Goddess loves your two cows, but you still have to milk them yourself.
- Atheism
- What cows?
- Atheism #2
- I can't believe these cows!
- Existentialism
- How do you know you have two cows? All you have are unreliable memories and inconsistent experiences! Maybe they're my cows, did you ever think of that? My cows and I are leaving.
- Nihilism
- You don't have two cows.
- Hedonism
- You have two cows. You do what you want to them. All in the name of pleasure.
- Objectivism
- Two cows = two cows
-.
- Nudism
- You have two cows that keep staring at you.
- Feminism
- You have one cow, men have three.
- Postmodernism
- There is no such things as having absolutely two cows.
-!
- Romanticism
- The cows have each other.
Category 9: People
- The Reagan’s
- You have two cows. One of them is dead. The other underwent udder-reconstruction surgery.
-!
- The Count
- You have TWO! TWO COWS! Ah! Ah! Ah!
- Elmer Fudd
- You have two cows. Oh, dat scwewy wabbit!
- Yoda
- Cows two, you have.
- R2D2
- beep beep blip beep
- Darth Vader
- I find your lack of cows disturbing.
- Bo Jackson
- Bo knows you have two cows.
- Timmy
- Timmay!
- Kenny
- mfmfmfm mfmff mmffmfff
-!
- Michael Jackson
- Hey, are those calves?
- William Shatner
- You have.
- Two.
- Cows.
-." —Oscar Wilde
- Force."
- Emperor Palpatine #2
- "You have two cows. I have forseen it."
- Old McDonald
- "And on my farm I had two cows before the rest of you people."
Category 11: Famous Cows
- The Raven
- You have two cows. They sit on the bust of Pallas just above your chamber door. Which is a pity, because it was expensive.
- 'The Telltale Heart
- You have two cows. You kill them and bury them beneath the floorboards. The sound of their mooing drives you mad.
- William Wilson
- You have two cows. One of them is the doppelganger of the other. You, too, are one of the cows, though it's not clear which one. You go mad trying to figure out which is the original.
- Johnny Mnemonic
- I can carry nearly eighty gigs of cows in my head.
Category 13: Television
- Law & Order
- In the Cow Justice System the livestock are represented by two separate, yet equally important cows.
- Everybody Loves Raymond
- You have two cows in your own pen, but it is surrounded by neighbouring pens filled with obnoxious, abusive, angry cattle who make your own cows so miserable they'd probably kill themselves if they could figure out a method that didn't require opposable thumbs. For some unfathomable reason, other people think this is funny.
- CSI
- You had two cows, one of them is dead of an apparent suicide... But wait, how could she kill her self if she has no opposable thumbs? The disgusting autopsy reveals that her muscle tissue tastes best when grilled medium rare. All signs point to your other cow, she was the only other creature in the barn, but she doesn't have opposable thumbs either. In the last ten minutes we discover that your cows were part of an underground bestiality ring. Your cow was killed during "rough sex".
- Survivor
- Next week on Survivor: Which of these three cows will be voted off in the final of this series!? Who will make it to the final two cows?
- Fear Factor
- You are going to eat two cows and their faeces.
- Will & Grace
- You have two annoying cows living in a flat together. One is a gay man so they have to make lots of gay jokes. You shoot?
- Mr. Ed
- You have two cows. Ed is jealous. On Christmas Eve, when the cows are on their knees, Ed comes up behind them and whacks them with a bat. You explain to your wife that although Ed cannot talk, he can act.
- I Love Lucy
- You have two cows. The redheaded cow gets the older, fatter, blonde cow into a crazy scheme, which their two bulls always find out about.
- The Simpsons: Homer
- Mmmmm ... cows.
- The Simpsons: Bart
- You had two cows. Don't have another cow, man!
- The Simpsons: Mr. Burns
- You have two cows. Eeeexcellent!
- The Simpsons: Nelson
- You have two cows. Everyone else in your class at school has three cows. Ha-ha! You're poor!
- The Simpsons: Comic Book Guy
- Worst. Cow. Ever.
- Family Guy
- You have two cows. Cancel these cows and renew them several years later. Repeat ad infinitum.
- South Park
- Oh my god, those two cows killed Kenny! You bastards!
- Futurama
- Bite my two shiny metal cows' asses!
- King of the Hill
- You have two cows. Yep. Yep. Yep. Mmm-hmm.
- The Apprentice
- You have at least two cows. An egotistical little man decides which cow should work for him. The rest are fired, except for the really hot Eastern European one, which he marries.
- Feed the Children Commercial
- For just pennies a day, this impoverished Bolivian child can have two cows.
- Lost In Space
- Warning! Warning! Two Cows approaching! Danger, Will Robinson!
- Neon Genesis Evangelion
- You have two cows. You have a terrible father who makes you use them to fight angels.
- Star Wars
- You have two banthas. The Empire kills them.
- Star Wars 2
- May the cows be with you.
- Star Trek
- You have two cows. You replicate meat instead and have the cows pilot your shuttle craft.
- Star Trek: Enterprise
- You had two cows, but they were cancelled after UPN moved them from Wednesday night to Friday night.
- Arrested Development
- There's always two cows in the banana stand.
- BANZAI!
- PLAY SUPER HIDDEN COW DETECTOR!!! HOW MANY COWS YOU HAVE? ONE, TWO, THREE OR FOUR COWS? YOU DON'T KNOW? TIME TO BET! BET NOW! BET NOW! TIME UP! WRONG! YOU HAVE TWO COWS! YOU LOSE!!!
- Diff'rent Strokes
- A white cow adopts two black calves.
- The Benny Hill Show
- You have two cows. They chase you around at a fast pace while "Yakety Sax" plays in the background.
- NYPD Blue
- You have two foul-mouthed, naked cows.
- Sesame Street
- This article is sponsored by the letters "C", "O", "W", and "S", and by the number "2".
- The Golden Girls
- You have two old, oversexed cows who live in Florida.
- Dallas
- You had two cows, but J.R. swindled you and now you have none, so you sleep with his wife.
- Jeopardy
- ANSWER: It's the number of cows you have. QUESTION: What is two?
- Monty Python's Flying Circus
- And now for something completely bovine.
- MTV
- You used to have two cows, but now you just have a bunch of shows about cars and celebrities.
- Married with Children
- You used to play high school football. Now you sell shoes to women who weigh as much as two cows.
- The Facts of Life
- You take the good, you take the bad, you take them both and there you have two cows.
- Green Acres
- Mr. Haney tries to sell you two giraffes, claiming they are two cows.
Category Fourteen: Analysis
-.
- Descartian Analysis
- You think, therefore you have two cows.
- Kantian Analysis
- You exist, and your mind perceives two cows, therefore the two cows exist. You have difficulty trying to decide whether the cows continue to exist when you stop thinking about them, so you think about them continuously.
- Berkelian Analysis
- You have two cows. You put your cows in a drawer and close it, your two cows cease to exist.
-.
- Cowell Analysis
- Those are quite possibly the worst two cows I have ever heard.
Category 15: Speak the Language...of Cows
- Australian
- Fuck the cows, chuck another steak on the barby and get me a beer!
- Caveman
- Hrroom! Hrrum! Hrrussh! Hrruup!
- Cockney English
- Blimey! You 'ave a couple a' Chairman Maos. Nuff said, yeah?
- Dhivehi (Maldives)
- ތިބޭޅާ އަތްޕުޅުގަ އޮތީ ދެގެރި އިނގޭތޯ؟
- Early Modern English
- Thou hast two kine.
- Vous avez deux vaches... mais elles sont en grêve depuis que l'on veut vendre leur oncle en steak haché avec des freedom fries dans un McDo.
- Les quois?!
- Groundhogese
- Hehaa chitter ooat urp.
- Jive
- Youse have two cows.
- Middle English
- Thou hast twain kine. Mou.
- Pig Latin
- Youay avehay otway owscay.
- Portuguese
- Você tem duas vacas.
- Redneck English
- Yo' haf two cows.
- Redneck English 2
- Yup, ya got yerself coupla cows thar...yup..mmmmm hmmm.
- Scooby-Doo-ish
- Roo rav roo rows.
- Snoop Dogg
- Fo Shizzle Two Cavizzle Mah Nizzle
- Tamil (Madras)
- Unnaanda redndu maadu keethuba! maadu paal kudukkum, atha kuduchuttu ootaanda nalla kalaaikalaam!
Category XVI: Groups
- Anaesthesiologists
- We have numbed your two cows.
- Cable Repair Men
- We'll fix your cows sometime between 7:00am to 9:30pm on Wednesday.
- Conspiracy Theorists
- Your two cows actually never landed on the moon. They also discovered advanced technology by digging up a crashed alien spaceship.
- Generation X
- You have two cows, so what, you feel disenfranchised.
- Generation Y
- You have two cows... I have a PlayStation 2
- Internal Revenue Service
- 33% of your two cows belong to us.
- Porn Stars
- I had two cows yesterday. Slurp.
- System Administrators
- You had two cows, but due to a server crash (and lack of proper backup) they are yours no longer.
- Terrorists
- These infidel cows, sons of Satan shall be burned at the hands of Allah.
- Zoo Keepers
- Obviously, we have two cows... in the petting zoo.
Category 17: In the Moos
- Daily Mirror
- DISGUSTING ABUSE OF TWO COWS, PICS INSIDE
- The Daily Mail
- Two Cows Have Crippling Effect On House Prices
- Daily Express
- DEPORT THE TWO COWS
- The Grauniad
- Tow Cws Voet Lbieral Democrate
- Wall Street Journal
- Two Cows Bubble Bursts! Markets Crash!
- Weekly World News
- Two-headed cow weds space alien!!!
- Bat Boy has two cows!
- The Enquirer
- BOVINE COUPLE HAS ALIEN BABY!!!
- Private Eye
- New Technology Baffles Two Pissed Old Cows
- New York Times
- People have two fewer cows than under Clinton Administration
- New York Post
- MAYOR BLOOMBERG'S TWO COWS IN SCANDAL!
Category 18: The Sound of Moo-sic
(from his Fifth Symphmoony, Moo-vement 1; Also known as the "The Angry Fourth Cow")
- Black Sabbath
- No more war cows have the power!
- Hand of God has struck the hour!
- Oh Lord Yeah!
- Bob Marley
- You have no cows. No cry.
- Barbra Streisand
- People,
- People who have two cows
- Are the luckiest people in the world.
- Billy Ocean
- Get out of my dreams, get into my ranch.
- The Carpenters
- Why do cows suddenly appear
- Every time you are near?
- Just like me, they long to be
- Close to moo.
- Children's Songs
- Old MacDonald had a farm, E-I-E-I-O,
- And on this farm he had two cows, E-I-E-I-O.
- With a moo-moo here, And a moo-moo there,
- Here a moo, There a moo, Everywhere a moo-moo.
- Old MacDonald had a farm, E-I-E-I-O!
- Coldplay
- Yoooooou haaaaaave
- Twooooooo Coooows
- *cue piano chord progression that was in the last two singles*
- Daft Punk
-
- You have two cows
- You two
- Have cows
- Cows. Cows. Cows. Cows. Cows. Cows.
- Youyouyouyou...COWS.
- You have two cows.
- You have two cows.
- You have two cows. [Repeat, x27]
- David Bowie
- There are two cows, waiting in the sky,
- We'd like to go and milk them,
- But I think they'll blow our minds
- Everything But The Girl
- You had two cows, before today. One is missing, you walking wounded.
- Frank Sinatra
- Two cows in the night, exchanging glances,
- Wondering in the night, what were the chances
- We'd be sharing milk before the night was through.
- Frankie Goes To Hollywood
- You have two cows. They go to war. You score one point.
- Foo Fighters
- Somewhere they're taking cows, but you are like my favourite disease.
- Martin Grech
- Tending on my fragile cow.
- How it 'mooooooooos'.
- Where was more when I needed a few?
- All I ever wanted was two.
- Iron Maiden
- Two, two two
- The number of your!
- Metallica
- Bovines...imprisoning me
- all that I see...absolute horror
- lactating this, lactating that
- lactating all...over my ass
- nine inch nails
- all the cows are all lined up
- i give you all that you want
- take the milk and drink it up
- now doesn't that make you feel better?
- NOFX
- You have two fuckin' cows! Fuckin' Cows! FUCK-ING-COWS!!!!!!!!
- Oasis
- And maybe
- You're gonna be the cow that milks me
- And on to browse
- You shall have two cows
- (And they're the best cows. Not just now. Ever.)
- Ozzy Osborne
- Times have changed and times are strange
- Here I come, but I ain't the same
- Mama, I got two cows
- Times gone by seem to be
- You could have been a better rancher for me
- Mama, I got two cows
- Pearl Jam
- Yooooou have two coooowwwws, aw yeah
- But whyyyyy, oh whyyyyy, can't they beeeee miiiiiiiiiine?
- Awwwww, yeahhhh
- Peggy Lee
- You give me two cows,
- When you kiss me,
- Two cows when you hold me tight.
- Two cows in the morning.
- Two cows all through the night
- Pet Shop Boys
- You have two cows that look very bored. One is wearing a baseball cap.
- Sex Pistols
- You have two cows. Never mind the bullocks.
- Shania Twain
- You have two cows, but that don't impress me much.
All I wanna do is have two cows,
I got a feelin, that I'm not the only one.
All I wanna do is have two cows,
until the sun comes up over Santa Moo-nica Boulevard!
- Spice Girls
- You have two cows. Two become one. You have one cow.
- The Beatles
- I am the moo-cow, moo moo gajoob!
- The Smiths
- You have two cows,
- and the calf that you carve with a smile
- is MURDER
- Whitney Houston
- AND I-I-I-I-I-I-I-I-I-E-E-E-E-I-I-I-I-I-I WILL ALWAYS SAY MOO-O-O-O-O-O-O-O-O-O-O-O!
- Jim Morrison
- Cows are strange, when you're a stranger. Cows look ugly, when you're alone.
Category Dix-Neuf: Bovine Quotes
- Mohandes K. Gandhi
- You Have to Be the Cows you want to see in the world.
- Neil Armstrong
- That's a small step for a man, a tiny jump for two cows.
- Martin Luther King Jr.
- I have a dream, where white cows play with black cows.
- Muhammad Ali
- Float like a butterfly, sting like a cow.
- Kurt Cobain
- cows
- Winston Churchill
- Never, in the field of buttercups and daisies, was so much owed to two cows by so many.
|
http://uncyclopedia.wikia.com/wiki/You_have_two_cows?oldid=65171
|
CC-MAIN-2015-32
|
refinedweb
| 9,434
| 85.49
|
I am trying to create a method in a class that will create a console window to the desired size. However I am having some serious issues with this seemingly simple task. This code below is a hash together of code from Adrianxw's site and some stuff I found here.
This code here works exactly as expected. But the second I put this into a class and try it, it does not work (I cut and paste the code into a constructor). Also compiled this in another compiler (Visual C++) and it doesn't work. It is really frustrating me because this is a very simple peice of code. Of course the error messages returned from the functions are useless as it appears to be incorrect.
Code:
#include <windows.h>
#include <iostream.h>
int main()
{
HANDLE hOut;
CONSOLE_SCREEN_BUFFER_INFO SBInfo;
COORD NewSBSize;
int Status;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
NewSBSize.X = (short)90;
NewSBSize.Y = (short)31;
Status = SetConsoleScreenBufferSize(hOut, NewSBSize);
if (Status == 0)
{
Status = GetLastError();
cout << "Buffer: Failed! Error: " << Status << endl;
}
SMALL_RECT DisplayArea;
DisplayArea.Bottom = 30;
DisplayArea.Right = 89;
Status = SetConsoleWindowInfo(hOut, TRUE, &DisplayArea);
if (Status == 0)
{
Status = GetLastError();
cout << "Screen: Failed! Error: " << Status << endl;
}
cin.get();
return 0;
}
|
https://cboard.cprogramming.com/windows-programming/44086-console-resizing-printable-thread.html
|
CC-MAIN-2017-13
|
refinedweb
| 198
| 52.66
|
This looks at the top 1000 terms used in ooo-dev post subjects since
this project moved to Apache in June 2011. The only thing I removed
was "Re:", since that would have dominated the cloud and is machine,
not user written
In this particular cloud, I used all posts, including responses. So
if a term was used in a thread that had many responses, it would have
additional weight in this chart.
Technologies used:
Python's mailbox API to extract the post titles. Could have done this
with any number of command line text tools as well, but it is trivial
in Python as well:
import mailbox
box = mailbox.mbox(fileName)
for message in box:
print message['Subject']
Then I used Wordle.net to generate the graphic.
Based on the reaction given to the previous word cloud, I know that
some list subscribers are curious to see how often we write about
LibreOffice. So I'll help you find it in this graphic. Look for the
big "AOO", then under that see the "COMMIT". Under COMMIT you can
make out LIBREOFFICE, to the left of USERS.
Regards,
-Rob
|
http://mail-archives.apache.org/mod_mbox/incubator-ooo-dev/201206.mbox/%3CCAP-ksoiVK0x2gPtSCex=69dzB9a1nUwwQUtxCryHLvSyrLFgOw@mail.gmail.com%3E
|
CC-MAIN-2014-15
|
refinedweb
| 189
| 71.65
|
Hello,This is some of the things that I still need to do to get gnulib to the point of compiling on OpenVMS.
* Config.h OpenVMS needs __UNIX_PUTC macro defined for putc_unlocked and friends to be visible. * lib/passfd.c This needs "_X_OPEN_SOURCE_EXTENDED" for the XPG4 V2 features in the code to compile on OpenVMS. Specifically the "msg_control" and "msg_controllen" members of struct msghdr. This would need to be defined before any system header files are included. OpenVMS provides _CMSG_SPACE and _CMSG_LEN macros instead of CMSG_SPACE and CMSG_LEN. This looks like I would need to find out how gllib/sys/socket.h got generated. For the OpenVMS header files, enabling _X_OPEN_SOURCE_EXTENDED causes macros and symbols not defined by the applicable standard to be hidden from the compiler. There currently is no way to make them visible and have XPG4 V2 features enabled. So I either need to have lib/passfd.c for OpenVMS define the _X_OPEN_SOURCE_EXTENDED macro as such: #ifdef __VMS /* OpenVMS enable XPG4 V2 */ # define _X_OPEN_SOURCE_EXTENDED #endif #include <config.h> Or I need to have my build procedure create a file named lib/gnv$passfd.c_first that contains that macro definition. The cc emulation program in OpenVMS GNV will automatically treat such files as a "first_include". * The OpenVMS iconv.h header file has a bug where it does not include sys/types.h. * The OpenVMS math.h header file has a bug where it is missing NAN and INFINITY, these are found in the fp.h header file. * In gl_sublist.c, the OpenVMS compiler is generating a "MISSINGRETURN" warning because it does not realize that there is no return from an abort() call. This should fix that: #ifdef __DECC # pragma message disable missingreturn #endif So would adding a useless return statement, but that may cause some compilers to complain about unreachable code. I do see GCC specific pragmas in the source code. * The OpenVMS stropts.h header file definition for ioctl() is non-standard, which causes problems when it is wrapped in ioctl.h * OpenVMS sys/resource does not define RUSAGE_SELF or RUSAGE_CHILDREN. Comments say ru_stime member of rusage is present, but not implemented. * Because the replacement C99 routines are not prefixed with "RPL_" or another prefix, the OpenVMS C Compiler is generating a warning when encountering them:%CC-W-NOTINCRTL, Identifier "strtoumax" is reserved by the C99 standard and will be mapped to "DECC$STRTOUMAX" although it is not available in the CRTL available to the compiler.
These appear to be routines that the compiler would inline when the optimization level allows it. It looks like something in the configure tests determine if the prefix is generated for a replacement routine or not. OpenVMS generally always will need the prefix on a replacement routine. * Work out the how to patch the configure test for getdtablesize() to pass on OpenVMS. * The configure test for the real directory for OpenVMS system supplied header file fails because they are not in a real directory. They are in a library file. If OpenVMS does not find a header file in supplied paths header files or in the source, it junks the directory portion the the header file path, and just looks up the filename in the text library. I export some symbols to cause Configure on VMS to skip the test. export gl_cv_next_errno_h="<vms_fake_path/errno.h>"It looks like for some of these I need to find the appropriate m4 macros and others I need to find the templates for generating the local header files.
Any suggestions on the preferred way to implement patches for these would be appreciated.Any suggestions on the preferred way to implement patches for these would be appreciated.
Regards, -John
|
https://lists.gnu.org/archive/html/bug-gnulib/2017-07/msg00021.html
|
CC-MAIN-2019-47
|
refinedweb
| 613
| 64.81
|
C# - Partial Class
Each class in C# resides in a separate physical file with a .cs extension. C# provides the ability to have a single class implementation in multiple .cs files using the partial modifier keyword. The partial modifier can be applied to a class, method, interface or structure.
For example, the following MyPartialClass splits into two files, PartialClassFile1.cs and PartialClassFile2.cs:
public partial class MyPartialClass { public MyPartialClass() { } public void Method1(int val) { Console.WriteLine(val); } }
public partial class MyPartialClass { public void Method2(int val) { Console.WriteLine(val); } }
MyPartialClass in PartialClassFile1.cs defines the constructor and one public method, Method1, whereas PartialClassFile2 has only one public method, Method2. The compiler combines these two partial classes into one class as below:
public class MyPartialClass { public MyPartialClass() { } public void Method1(int val) { Console.WriteLine(val); } public void Method2(int val) { Console.WriteLine(val); } }
Partial Class Requirements:
- All the partial class definitions must be in the same assembly and namespace.
- All the parts must have the same accessibility like public or private, etc.
- If any part is declared abstract, sealed or base type then the whole class is declared of the same type.
- Different parts can have different base types and so the final class will inherit all the base types.
- The Partial modifier can only appear immediately before the keywords class, struct, or interface.
- Nested partial types are allowed.
Advantages of Partial Class
- Multiple developers can work simultaneously with a single class in separate files.
- When working with automatically generated source, code can be added to the class without having to recreate the source file. For example, Visual Studio separates HTML code for the UI and server side code into two separate files: .aspx and .cs files.
Partial Methods
A partial class or struct may contain partial methods. A partial method must be declared in one of the partial classes. A partial method may or may not have an implementation. If the partial method doesn't have an implementation in any part then the compiler will not generate that method in the final class. For example, consider the following partial method with a partial keyword:
public partial class MyPartialClass { partial void PartialMethod(int val); public MyPartialClass() { } public void Method2(int val) { Console.WriteLine(val); } }
public partial class MyPartialClass { public void Method1(int val) { Console.WriteLine(val); } partial void PartialMethod(int val) { Console.WriteLine(val); } }
PartialClassFile1.cs contains the declaration of the partial method and PartialClassFile2.cs contains the implementation of the partial method.
Requirements for Partial Method
- The partial method declaration must began with the partial modifier.
- The partial method can have a ref but not an out parameter.
- Partial methods are implicitly private methods.
- Partial methods can be static methods.
- Partial methods can be generic.
The following image illustrates partial class and partial method:
The compiler combines the two partial classes into a single final class:
- Use the partial keyword to split interface, class, method or structure into multiple .cs files.
- The partial method must be declared before implementation.
- All the partial class, method , interface or structs must have the same access modifiers.
|
https://www.tutorialsteacher.com/csharp/csharp-partial-class
|
CC-MAIN-2019-18
|
refinedweb
| 513
| 50.02
|
MS Dynamics CRM 3.0
I have a very simple SAX script from which I get results like 'Title1:Description','Title2:Description'. I want to split each result on the colon, using the two resulting elements as key/value pairs in a dictionary. I've tried a couple different approaches with lists etc, but I keep getting an 'IndexError: list index out of range' when I go to split the results. Probably an easy fix but it's my first hack at SAX/XML. Thank you!
from xml.sax import make_parser from xml.sax.handler import ContentHandler
class reportHandler(ContentHandler): def __init__(self): self.isReport = 0
def startElement(self, name, attrs): if name == 'title': self.isReport = 1 self.reportText = ''
def characters(self, ch): if self.isReport: self.reportText += ch
def endElement(self, name): if name == 'title': self.isReport = 0 print self.reportText
parser = make_parser() parser.setContentHandler(reportHandler()) parser.parse('')
However, SAX tends to make things much more complex than necessary, so you loose the sight on the real problems. Try a library like ElementTree or lxml to make your life easier. You might especially like lxml.objectify.
Stefan
-- Jerry
|
http://www.megasolutions.net/python/Splitting-SAX-results-78728.aspx
|
CC-MAIN-2013-48
|
refinedweb
| 189
| 52.76
|
From my observations as a Java developer working on Windows workstations, NTFS is slow compared to Linux filesystems. Question is, is there anything in the NTFS driver that can be manually tuned, for example give it more memory for cache? Enable some experimental algorithms? If that's not available, is there perhaps another filesystem that can be used on Windows, maybe even commercial, that's faster than NTFS?
To be clear, I'm not looking to improve compilation speeds for Maven projects, I'd like to get an overall improvement for the OS. I get a feeling that NTFS is long outdated and slow compared to Linux filesystems. It strikes me as weird that the most popular OS on planet has only one filesystem which still requires manual defragmentation. Perhaps there is an alternative?
Update: Here is what's slow according to my observations. I'm building/packaging a project, which means lots of read/write operations on disk. The build system is cross-platform (Java, Maven), so I can perform exactly the same actions when booted to Ubuntu, for example.
On Linux my builds are at least 1/3 faster. Hence the question about filesystem. I'm sorry if it's misplaced.
While I'd love to see something like ZFS available for Windows hosts, NTFS isn't a horrible filesystem. It supports most "modern" filesystem features (extended attributes, journaling, ACLs, you name it), but it's hampered by Explorer and most other apps not supporting any of these.
One thing that will absolutely kill its performance is having "too many" entries in a directory. Once you pass a couple thousand entries in one directory, everything slows to a crawl. Literally the entire machine will halt waiting for NTFS to create or remove entries when this is happening.
I used to work with an app that generated HTML-based docs for .NET assemblies; it would create one file per property, method, class, namespace, etc. For larger assemblies we'd see 20+k files, all nicely dumped into a single directory. The machine would spend a couple of hours during the build blocked on NTFS.
In theory, Windows supports filesystem plugins, which would make native ZFS, ext3 or whatever (even FUSE) possible. In practice, the APIs are undocumented, so you're completely on your own.
Now, since you're doing Java development, could you install a different OS on your machine, or use a VM on top of Windows?
Also, you might want to try some platform-independent filesystem benchmarks (iozone, bonnie... there are probably more modern ones I don't know off the top of my head, maybe even a few written in Java) to see if it's actually the filesystem holding you back, or if it's something else. Premature optimization and all that...
There is one file system which is supported by new Windows OS AND is faster than NTFS. It's exFAT. There's a possibility to use it for the system drive. But it's unknown what complications it might have.
You can certainly use it for other partitions though. It's faster with random read/write operations. Perfect for an SSD for example.
In order to answer more specifically, I would need to know more about how you use NTFS. For instance, are you using NTFS in a server or in a desktop computer? Are there some tasks for which you would specifically want to optimise your system for?
Also I have to disagree in that NTFS is the causing a system to slow down. From where I come from, a much more common bottleneck in a system is the lack of memory, which is the primary reason a system needs to re-read something from a hard drive in the first place.
Do you have an anti virus program running that's doing on access/write checking for your project folder?
Compiling involves reading and writing lots of small files in quick succession, which can overwhelm the virus scanner. Add your project folder to the list of excluded folders and see if that improves the situation.
On Linux you (probably) don't have any anti virus software....
I guess that the real solution would be to rewrite your build system so that it used the native windows file system API, instead of the unix API (fopen etc) itself underneath the portability framework. But that's not going to happen, so basically you are stuck with whatever level of performance they thought was acceptable.
Often when using systems not originally written for Windows, you find that directory traversal has been handled very poorly, so make sure you have a very flat directory tree.
By posting your answer, you agree to the privacy policy and terms of service.
asked
3 years ago
viewed
2095 times
active
2 years ago
|
http://superuser.com/questions/240731/windows-with-a-better-filesystem/240787
|
CC-MAIN-2014-42
|
refinedweb
| 805
| 64
|
I came across this construct in an Angular example and I wonder why this is chosen:
_ => console.log('Not using any parameters');
I understand that the variable _ means don't care/not used but since it is the only variable is there any reason to prefer the use of _ over:
() => console.log('Not using any parameters');
Surely this can't be about one character less to type. The () syntax conveys the intent better in my opinion and is also more type specific because otherwise I think the first example should have looked like this:
(_: any) => console.log('Not using any parameters');
In case it matters, this was the context where it was used:
submit(query: string): void { this.router.navigate(['search'], { queryParams: { query: query } }) .then(_ => this.search()); }
The reason why this style can be used (and possibly why it was used here) is that
_ is one character shorter than
().
Optional parentheses fall into the same style issue as optional curly brackets. This is a matter of taste and code style for the most part, but verbosity is favoured here because of consistency.
While arrow functions allow a single parameter without parentheses, it is inconsistent with zero, single destructured, single rest and multiple parameters:
let zeroParamFn = () => { ... }; let oneParamFn = param1 => { ... }; let oneParamDestructuredArrFn = ([param1]) => { ... }; let oneParamDestructuredObjFn = ({ param1 }) => { ... }; let twoParamsFn = (param1, param2) => { ... }; let restParamsFn = (...params) => { ... };
Although
is declared but never used error was fixed in TypeScript 2.0 for underscored parameters,
_ can also trigger
unused variable/parameter warning from a linter or IDE. This is a considerable argument against doing this.
_ can be conventionally used for ignored parameters (as the other answer already explained). While this may be considered acceptable, this habit may result in a conflict with
_ Underscore/Lodash namespace, also looks confusing when there are multiple ignored parameters. For this reason it is beneficial to have properly named underscored parameters (supported in TS 2.0), also saves time on figuring out function signature and why the parameters are marked as ignored (this defies the purpose of
_ parameter as a shortcut):
let fn = (param1, _unusedParam2, param3) => { ... };
For the reasons listed above, I would personally consider
_ => { ... } code style a bad tone that should be avoided.
I guess
_ => is just used over
() => because
_ is common in other languages where it is not allowed to just omit parameters like in JS.
_ is popular in Go and it's also used in Dart to indicate a parameter is ignored and probably others I don't know about.
It is possisble to distinguish between the two usages, and some frameworks use this to represent different types of callbacks. For example I think nodes express framework uses this to distinguish between types of middleware, for example error handlers use three arguments, while routing uses two.
Such differentiation can look like the example below:
const f1 = () => { } // A function taking no arguments const f2 = _ => { } // A function with one argument that doesn't use it function h(ff) { if(ff.length==0) { console.log("No argument function - calling directly"); ff() } else if (ff.length==1) { console.log("Single argument function - calling with 1"); ff(1) } } h(f1) h(f2)
When I wrote the post I was under the impression
_ was the only way to create arrow functions without
(), which led me to believe using
_ could have some minor advantages, but I was wrong. @Halt has confirmed in the comments that it behaves just like other variables, it is not a special language construct.
I want to mention one more thing I realized about these underscore arrow functions while testing myself I didn't find mentioned anywhere. You can use the underscore in the function as a parameter, although this probably isn't intended usage since it's supposed to represent an unused parameter. For clarity, I wouldn't really reccomend using it this way.
but it can be useful to know for things like codegolf, challenges where you write the shortest code (it turns out you can just use any character without
()). I could imagine some real use cases where libraries use this and you need to use it even if they didn't intend for that functionality.
Example:
// simple number doubling function f = _=> { _ = _ * 2; return _; } console.log(f(2)); // returns 4 console.log(f(10)); // returns 20
Tested with Chrome console, Version 76.0.3809.132 (Official Build) (64-bit)
The
()syntax conveys the intent better imho and is also more type specific
Not exactly.
() says that the function does not expect any arguments, it doesn't declare any parameters. The function's
.length is 0.
If you use
_, it explicitly states that the function will be passed one argument, but that you don't care about it. The function's
.length will be 1, which might matter in some frameworks.
So from a type perspective, it might be more accurate thing to do (especially when you don't type it with
any but, say,
_: Event). And as you said, it's one character less to type which is also easier to reach on some keyboards.
|
https://javascriptinfo.com/view/45617/using-underscore-variable-with-arrow-functions-in-es6-typescript
|
CC-MAIN-2020-50
|
refinedweb
| 858
| 62.27
|
I am trying to make a program that will convert a decimal number to its binary equivilant. It will output the first number but I am having trouble figuring out how to use the previously found quotient to find a new quotient. I tried using loops to do this and they are always infinite.
Here is the code I have written so far
Code:#include <iostream> using namespace std; void convert (int); int main () { int num; cout <<"Please enter a number to convert" <<endl; cin>>num; convert (num); return 0; } void convert (int num) { if (num>0) { double quotient,remainder; quotient=num/2; remainder=num%2; if (quotient==0) cout <<" "; else { if (remainder==0) cout<<"0"; else if (remainder==1) cout<<"1"; } } else cout<< " "; }
|
https://cboard.cprogramming.com/cplusplus-programming/71366-converting-decimal-binary-numbers-using-recursion.html
|
CC-MAIN-2017-17
|
refinedweb
| 124
| 51.72
|
CodePlexProject Hosting for Open Source Software
Aug 24
2:48 PM(1 post)
first post: sblankenship wrote: I noticed an issue this morning with date comparisons. they appear ...
Jan 25
9:08 PM(1 post)
first post: Xifeidanhu wrote: I try to use LessThanOrEqualTo to compare int, but it is not workin...
Jul 26, 2016
10:19 AM(1 post)
first post: muppetson76 wrote: I wasn't able to get the client side validation working so I dug in...
Apr 11, 2016
11:35 AM(1 post)
first post: crbaron wrote: I am using Foolproof Validation . When calling
[RequiredIfTrue("Com...
Jan 11, 2016
10:12 AM(3 posts)
first post: ageoghegan wrote: Is there any reason why your NugGet distributions are not strongly ...
Dec 4, 2015
6:14 PM(1 post)
first post: bmains wrote: Hello,
I have a complex form that validates a property using bot...
Aug 10, 2015
8:18 PM(1 post)
first post: mbenaventet wrote: Hello:
First of all thanks for a awesome extension for the DataAn...
Jun 18, 2015
4:08 PM(1 post)
first post: mnoreke wrote: I am doing unit testing of my validation logic in MVC using the fol...
1:41 PM(2 posts)
first post: blues_driven wrote: I need to conditionally require a date field based on a boolean. Th...
Apr 27, 2015
11:58 AM(2 posts)
first post: Robowski wrote: Model
public class WorkPattern
{
public int ID { get; ...
Filter
Unanswered only
|
http://foolproof.codeplex.com/discussions/topics/general
|
CC-MAIN-2017-39
|
refinedweb
| 242
| 78.28
|
Its not an uncommon request (in fact I got one in email today) to want to receive:
1. Non-XML data in a receive-port
2. XML messages of differing XML schemas within a single receive port
So how do you do that with BizTalk Server?
1. Set the messagetype property on your receive port to System.xml.xmldocument (yes I know in case 1 you are receiving non-XML data, but do it anyways)
2. Set-up a filter on the receive shape in orchestration which will pickup the message. Make sure you set your filter appropriately so you don’t pick-up all documents.
To access the data as a stream (if you want) then you can use this in an expression shape:
XLANGPart.RetrieveAs( typeof(Stream) )
Credits to Yossi
Glad to see this posted.. very helpful, thanks.
Also, for related issue search for thread titled ‘Distribution in BTS 2004’ on bt newsgroup at
this describes how to load a message if you only know a filename from within an orchestration, and can be ported to load any stream.
I assume this means that you can’t use promoted properties?
Thanks for that hint! I was looking for this for a long time.
However, I can’t get it working with a Web Service port while using the XML Reveive Pipeline. My intention was to use the pipeline to disassemble the message to get the namespace (message id) and then put it into the appropriate orchestration by filtering for the message id. When using a normal file port, this works fine. The message is decoded and the orchestration with the correct filter picks up the message.
However, when I switch to a web service port (request-response with string type response) I get a pipeline exception: ‘Document type "order" does not match any of the given schemas’. I’m still submitting the same message (in a soap envelope of course) and the schema is still deployed.
Switching to a pass through pipeline solves the problem but since the message id cannot be found I end up with a routing error.
Strangely, if I remove the schema with the namespace "order" from my schema assembly, the error is also solved (with the XML pipeline activated) and the message is correctly delivered to the orchestration. But since my mappings expect a schema with a different namespace now, all mappings fail…
Thanks for your support,
Roland
Hello maybe you can help,
i need to access the stream in the orchestration.
in the post it is stated that :
To access the data as a stream (if you want) then you can use this in an expression shape:
XLANGPart.RetrieveAs( typeof(Stream) )
But i can’t do that. Do i have to create a reference somewhere to do this.
Scott posted a message back in June about untyped receive ports inside on Orchestration. Untyped Messages
PingBack from
|
https://blogs.msdn.microsoft.com/scottwoo/2004/06/02/untyped-receive-ports-in-biztalk-server-2004/
|
CC-MAIN-2017-13
|
refinedweb
| 484
| 71.44
|
17 July 2008 17:11 [Source: ICIS news]
By Nigel Davis
LONDON (ICIS news)--The legal structures may have been agreed but the difficult work lies ahead for ?xml:namespace>
The opportunities are significant as polymer and petrochemicals demand grows on the back of the expanding economy.
The much larger Braskem is ahead of the newest company on the block, Quattor, and should be able to make progress. The company has ambitious expansion plans involving production facilities on South America’s
The increasing involvement of state-controlled Petrobras is key to sector development, Braskem’s polypropylene (PP) business director, Rui Chammas, said earlier this year.
Petrobras will support the sector and better project the Brazilian companies outside
Petrobras sold most of its petrochemicals assets in the 1990s but kept small stakes in a number of companies. More recently, it has spearheaded the drive to regroup the sector to provide greater critical mass.
The oil major, and the country’s sole naphtha producer, has stakes in Braskem and Quattor as well as petrochemical ambitions of its own. Development of the Comperj refinery project will give it greater aromatics and polyolefins capability.
The idea has been to consolidate petrochemicals assets into Braskem in the northeast and south and to create a southeast company, Quattor, which aggregates assets in
Braskem, created in 2002 through the merger of the petrochemical units of the Odebrecht and Mariani groups, has been on a consolidating spree of its own and is now a $10bn turnover player.
Its ambitions include the development of a big ethane-based petrochemical project in
Quattor CEO Vito Mallmann heads a company which combines nine production plants formerly operated by Unipar and Petrobras. Unipar holds 60% of Quattor and Petrobras 40%.
Its product slate covers base petrochemicals, intermediates and plastics. Turnover is expected to be $5.5bn in 2009 which would rank Quattor among the 20 largest companies in
Capacity upgrades under way now should mean that by the end of this year Quattor will be able to produce 2.8m tonnes of basic and intermediate petrochemicals and 1.9m tonnes/year of plastics.
It will have 40% of
Focused on two large production centres in
Quattor’s production facilities are close to
Mallmann admits that the challenge of running this new petrochemical company is enormous. But then so are the opportunities.
The CEO will have to drive synergies between the businesses hard to maximise efficiencies, drive profits and the potential for investment and future growth.
“
Mallmann knows the petrochemicals business and comes from a technical background. At Unipar he led the restructuring of the chemicals division.
Globally this is not the best time to be launching a new polyolefins player but
|
http://www.icis.com/Articles/2008/07/17/9141170/insight-quattor-to-make-mark-on-brazil-petchems.html
|
CC-MAIN-2014-41
|
refinedweb
| 449
| 51.38
|
This article defines the fundamentals of C# in detail.
Question 1: Variables and its DeclarationAnswer
A variable is an entity whose value can keep changing. For example,. Various types of data such as a character, an integer or a string can be stored in variables. Based on the type of data that needs to be stored in a variable, variables can be assigned various data types.In C#, memory is allocated to a variable at the time of its creation. When you are referring to a variable, you are actually referring to the value stored in that variable.
Syntax The following syntax is used to declare variables in C#:<Data type> <variable Name>;Where:Datatype: Is a valid data type in C#.VariableName: Is a valid variable name.The following syntax is used to initialize variables in C#:<VariableName> = <value>;=: Is the assignment operator used to assign values.Value: Is the data that is stored in the variable.
Snippet and Example
The following snippet declares two variables, namely empNumber and empName.int empNumber;String empName;The preceding lines declare an integer variable, empName, and a string variable, empName.Memory is allocated to hold data in each variable.Values can be assigned to variables using the assignment operator (=) as shown below.empNumber=100;empName="David Blake";You can also assign a value to a variable upon creation, as shown below.Int empNumber=100; Variable Naming RulesA variable needs to be declared before it can be referenced. You need to follow certain rules when declaring a variable:
DeclarationIn C#, you can declare multiple variables at the same time in the same way you declare a single variable. After declaring variables, you need to assign values to them. Assigning a value to a variable is called initialization. You can assign a value to a variable while declaring it or at a later time. The following code snippet demonstrates how to declare and initialize variables in C#.Question 2: Constant and its Declaration.AnswerA constant value cannot be changed at compile time and runtime. Need For ConstantConsider code that calculates the area of a circle. To calculate the area of the circle, the value of PI, ARC, and RADIUS must be provided in the formula. The value of PI is a constant value. This value will remain unchanged irrespective of the value of the radius provided.Similarly, constants in C# are fixed values assigned to identifiers that are not modified throughout the execution of the code. They are defined when you want to preserve values to reuse them later or to prevent any modification to the values.In C#, you can declare constants for all data types. You need to initialize a constant at the time of its declaration. Constants are declared for value types rather than for reference types. To declare an identifier as a constant, the const keyword is used in the identifier declaration. The compiler can identify constants at the time of compilation because of the const keyword.Question 3: Data TypesAnswer
You can store various types of values, such as numbers, characters or strings in different variables. But the compiler must know what kind of data a specific variable is expected to store. To identify the type of data that can be stored in a variable, C# provides many data types. When a variable is declared, a data type is assigned to the variable. This allows the variable to store values of the assigned data type. In the C# programming language, data types are divided into two categories. These are:1. Value Types
Variables of value types store actual values. These values are stored in a stack. The values can be either of a built-in data type or a user-defined data type. Most of the built-in data types are value types. The value type built-in data types are int, float, double, char and bool. Stack storage results in faster memory allocation to variables of value types. 2. Reference Types
Variables of reference type store the memory address of other variables in a heap. These values can either belong to a built-in data type that is a reference type. Most of the user-defined data types such as class are reference types. Classification
Reference data types store the memory reference of other variables. These other variables hold the actual values. Reference types can be classified type. A String type signifies Unicode character string values. Once strings are created, they cannot be modified.Class
A class is a user-defined structure that contains variables and methods. For example, the Employee class can be a user-defined structure that can contain variables such as empSalary, empName, and CalculateSalary (), that return the net salary of an employee. Delegate
A delegate is a user-defined reference type that stores the reference of one or more methods.Interface
An interface is a type of user-defined class for multiple inheritances.Array
An array is a user-defined data structure that contains values of the same data type, such as marks as marks of students. Question 4: Using LiteralsAnswer
A literal is a static value assigned to variables and constants. You can define literals for any data type of C #. Numeric literals might be suffixed with a letter to indicate the data type of the literal. This letter can be either in upper or lower case. For example, in the following declaration, string bookName = "Csharp", Csharp is a literal assigned to the variable bookName of type string. In C#, there are six types of literals. These are:
1. Boolean Literal
Boolean literals two values, true or false. For example: bool val=true;Where, true: Is a Boolean assigned to the variable val.2. Integer Literal
An integer literal can be assigned to an int, unit, long or ulong data types. A suffix for integer literals includes U, L, UL, or LU. U denotes unit or ulong, L denotes long. UL and LU denote ulong. For Example: long val = 53L;Where, 53L: Is an integer literal assigned to the variable val. 3. Real Literal
A real literal is assigned to float, double (default), and decimal data types.This is indicated by the suffix letter appearing after the assigned value. A real literal can be suffixed by F, D, or M. F denotes float, D denotes double and M denotes decimal. For example:float val = 1.66F; Where, 1.66F: Is a real literal assigned to the variable val. 4. Character Literal
A character literal is assigned to a char data type. A character literal is always enclosed in single quotes. For example:Char val = 'A';Where, A: Is a character literal assigned to the variable val. 5. String Literal
There are two types of string literals in C#, regular and verbatim. A regular string literal is a standard string. A verbatim string literal is similar to a regular string literal but is prefixed by the @ character. A string literal is always enclosed in double quotes. For example:
String mailDomain = "@gmail.com";
Where, @gmail.com: Is a verbatim string literal.
6. Null Literal
The null literal has only one value, null. For example:
String email = null;
Where, null: Specifies that email does not refer to any objects (reference)Question 5: KeywordsAnswerKeywords are reversed graphic lists the keywords used in C#: Question 6: Escape SequenceAnswerAn escape sequence character is a special character that is prefixed by a backslash (\). Escape sequence characters are used to implement special non-printing character such as a new line, a single space or a backspace. This non-printing character#.Question 7: Console OperationAnswer
Console operations are tasks performed on the command line interface using executable commands. The console operations are used in software applications because these operations are easily controlled by the operating system. This is because console operations are dependent on the input and output devices of the computer system.
A console application is one that performs operations at the command prompt. All console applications consist of three streams, that are a series of bytes. These streams are attached to the input and output devices of the computer system and they handle the input and output operations. The three streams are:1. Standard Output method
2. Standard input method
DEMO For ReadMethod
namespace ReadMethod
{
class Program
{
static void Main(string[] args)
{
string Name;
Console.Write("Enter your Name:-");
Name = Console.ReadLine();
Console.WriteLine("Your Name is:-" + Name);
Console.WriteLine("Yoyr Name is:- {0}", Name);
Console.ReadLine();
}
}
} 3. Standard err method
The standard err stream display messages on the monitor.
4. Placeholders
The WriteLine ( ) and Write ( ) methods accept a list of parameters to format text before displaying the output. The first parameter is a string containing markers in braces to indicate the potion where the values of the variables will be substituted. Each marker indicates a zero-based index based on the number of variables in the list. For example, to indicate the first parameter position, you write {0}, second you write {1} and so on. The numbers in the curly brackets are called placeholders. DEMO For Placeholder
namespace Placeholder
int Result, Number;
Number = 5;
Result = 100 * Number;
Console.WriteLine("The result is " + Result + " when 100 is multiply by" + Number);
Console.Write("The result is " + Result);
Console.WriteLine(" when 100 is multiply by " + Number);
Console.WriteLine("The result is {0} when 100 is multiply by {1}", Result, Number);
}
5. Convert Methods
The ReadLine () method can be used to accept integer values from the user. The data is accepted as a string and then converted into the int data type. C# provides a convert class base data type.DEMO For ConvertMethod
namespace ConvrtMethod
int Age;
double Salary;
Console.Write("Enter Your Name:-");
Console.Write("Enter your Age:-");
Age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter your Salary:-");
Salary = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("\nName is :-" + Name);
Console.WriteLine("Age is :-" + Age);
Console.WriteLine("Salary is :-" + Salary);
} Question 8: Programming Constructs or Control-Flow StatementAnswer
Welcome to the module C# Programming Constructs. Construct help in building the flow of a program. They are used for performing specific actions depending on whether certain is satisfied repeatedly or can transfer the control to another block. In this module, you will learn about:
Question 9: Selection or Conditional StatementsAnswer
A selection construct is a programming construct supported by C# that controls the flow of a program. It executes a specific block of statements based on a Boolean condition, that is an expression returning true or false. The selection constructs are referred to as decision-making constructs. Therefore, selection constructs allow you to take logical decisions about executing different blocks of a program to achieve the required logical output. C# supports the following decision-making constructs:
1. If construct or statements
Syntax
Demo Program
namespace IF_Ststement
int No1, No2;
Console.WriteLine("Enter Value one:-");
No1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Value second:-");
No2 = Convert.ToInt32(Console.ReadLine());
if (No1 > No2)
{
Console.WriteLine("First Value is Big");
}
if (No1 < No2)
Console.WriteLine("Second Value is Big");
} 2. IF..Else Construct or Statements
The if statements executes a block of statements only if the specified condition is true. However, in some situations, it is required to define an action for a false condition. This is done using the if..else construct.
The if..else construct starts with the if block followed by an else block. The else block starts with the else keyword followed by a block of statements. If the condition specified in the if statement evaluates to false then the statements in the else block are executed.
Syntax
Demo Program
namespace IF._._.Else_Statements
int No;
Console.WriteLine("Enter Any Number:-");
No = Convert.ToInt32(Console.ReadLine());
if (No > 0)
Console.WriteLine("Number is Positive");
else
Console.WriteLine("Number is Negative");
} 3. If..Else If Construct or Statements
The if..else if construct allows you to check multiple conditions and it executes a different block of code for each condition. This construct is also referred to as if..else if ladder. The construct starts with the if block followed by one or more else if blocks followed by an optional else block. The conditions specified in the if..else if construct are evaluated sequentially. The execution starts from the if statement. If a condition evaluates to false then the condition specified in the following else if statement is evaluated.
Demo Program
namespace IF._._ElseIF_Statement
int Num;
Num = Convert.ToInt32(Console.ReadLine());
if (Num < 0)
Console.WriteLine("The Number is Negative");
else if (Num % 2 == 0)
Console.WriteLine("The Number is odd");
Console.WriteLine("The Number is even");
} 4. Nested If Construct or Statements
Syntax Demo Program
namespace Nested_IF_Statement
int Salary, Service;
Console.Write("Enter Yrs Of Service:-");
Service = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Salary:-");
Salary = Convert.ToInt32(Console.ReadLine());
if (Service < 5)
if (Salary < 500)
{
Console.WriteLine("Provided Bonus:-> 100");
}
else
Console.WriteLine("Provided Bonus:-> 200");
else
Console.WriteLine("Provided Bonus:-> 700");
} 5. Switch .. Case Construct or Statements
A program is difficult to comprehend when there are too many if statements representing multiple selection constructs. To avoid using multiple if statements, in certain cases the switch .. case statement can be used as an alternative.
The switch .. case statement is used when a variable needs to be compared against different values.
Demo Program
namespace Switch_Case
int Day;
Console.WriteLine("Enter Your Choice:-");
Day = Convert.ToInt32(Console.ReadLine());
switch (Day)
case 1:
Console.WriteLine("Sunday");
break;
case 2:
Console.WriteLine("Monday");
break;
case 3:
Console.WriteLine("Tuesday");
case 4:
Console.WriteLine("Wednesday");
case 5:
Console.WriteLine("Thursday");
case 6:
Console.WriteLine("Friday");
case 7:
Console.WriteLine("Saturday");
default:
Console.WriteLine("Enter a Number between 1 to 7");
}
Question 10: Loop Construct and StatementsAnswer
Loops allow you to execute a single statements or a block of statements repeatedly. The most common uses of loops include displaying a series of numbers and tacking repetitive input. In software programming, a loop construct contains a condition that helps the compiler identify the number of times a specific block will be executed. If the condition is not specified then the loop continues infinitely and is called an infinite loop. The loop constructs are also referred to as iteration statements.C# supports four types of loop constructs. These are:
1. The "While" Loop
Demo Program
namespace While_Loop
int num = 1;
//Console.Write("Enter Number:-");
//num = Convert.ToInt32(Console.ReadLine());
while (num <= 11)
if ((num % 2) == 0)
Console.WriteLine(+num);
num = num + 1;
} 2. The "Do-While" Loop
namespace DO_While_Loop
int num;
Console.Write("Enter Number:-");
num = Convert.ToInt32(Console.ReadLine());
do
} while (num <= 11);
3. The "for" Loop
The for statement is similar to the while statement in its function. The statements within the body of the loop are executed as long as the condition is true. Here too, the condition is checked before the statements are executed.
SyntaxDemo Program
namespace For_Loop
int num, i;
for (i = num; i <= 11; i++)
if ((i % 2) == 0)
Console.WriteLine(+i);
} 4. Nested "for" Loop
namespace Nested_For_Loop
int i, j;
for (i = 0; i < 5; i++)
for (j = 0; j < 2; j++)
Console.WriteLine("Welcome To CCSIT");
}5. The "foreach" Loop
Demo Program
namespace foreach_Loop
// FOREACH LOOP IS USE FOR STRING
string[] Names = { "joy", "Mariya", "Jeni", "Wilson" };
Console.WriteLine("Employee Name");
foreach (string person in Names)
Console.WriteLine("{0}", person);
// FOREACH LOOP IS USE FOR INTEGER
int[] No = { 1, 2, 3, 4 };
Console.WriteLine("\nEmployee Number");
foreach (int Number in No)
Console.WriteLine("{0}", Number);
} Question 11: Jump StatementsAnswerJump statements are used to transfer control from one point in a program to another. There will be situations where you need to exit out of a loop prematurely and continue with the program. In such cases, jump statements are used. A Jump statement unconditionally transfers control of a program to a different location. The location to which a jump statement transfers control is called the target of the jump statement.C# supports four types of jump statements. These are:
1. Break Statement
The break statement is used in the selection and loop constructs. It is most widely used in the switch .. case construct and in the for and while loops. The break statement is denoted by the break keyword. In the switch .. case construct, it is used to terminate the execution of the construct. In this case, the control passes to the next statement following the loop. Syntax
namespace Break_Statement
int i;
double no, sum = 0, avg;
Console.WriteLine("Enter Number One by One:-");
Console.WriteLine("Enter Zero to stop Entry");
for (i = 1; i <= 1000; i++)
no = Convert.ToDouble(Console.ReadLine());
if (no == 0)
sum = sum + no;
Console.WriteLine("Sum =>" + sum);
2. The "continue" Statement
The continue statement is most widely used in loop constructs. This statement is denoted by the continue keyword. The continue statement is used to end the current iteration of the loop and transfer the program control returns back to the beginning of the loop. The statements of the loop following the continue statement are ignored in the current iteration.
namespace Continue_Statement
Console.WriteLine("Even numbers in the range of 1-10");
for (int i = 1; i <= 10; i++)
if (i % 2 != 0)
continue;
Console.Write(i + "\n");
} 3. The "goto" Statement
Demo Program
namespace Goto_Statement
int i = 0;
display:
Console.WriteLine("Hello Word");
i++;
if (i < 5)
goto display;
4. The "return" StatementThe return statement returns a value of an expression or transfers control to the method from which the currently executing method was invoked. The return statement is denoted by the return keyword. The return statement must be the last statement in the method block.Demo Program
namespace Return_Statement
int YrsofService = 5;
double salary = 1250;
double bonus = 0;
if (YrsofService <= 5)
bonus = 50;
return;
bonus = salary * 0.2;
Console.WriteLine("Salary amount:" + salary);
Console.WriteLine("Bonus amount:" + bonus);
} Question 12: StatementsAnswer
Example of Statements
Types of Statements C# statements are similar to statements in C and C++. C# statements are classified into seven categories depending on the function they perform. These categories are the following.Selection statementsA selection statement is a decision-making statement that checks whether a specific condition is true or false. The keyword associated with this statement are: if, else, switch and case.Iteration statementsAn iteration statement helps you to repeatedly execute a block of code. The keywords with this statement are: do, for, foreach, and while.Jump statementsA jump statement helps you transfer the flow from one block to another block in the program. The keywords associated with this statement are: break, continue, default, goto, return.Exception handling statementsAn exception handling statement manages unexpected situations that hinder the normal execution of the program. For example, if the code is dividing a number by zero, the program will not execute properly. To avoid this situation, you can use the following exception handling statements: throw, try-catch, try-finally and try-catch-finally.Checked and unchecked statementsThe checked and unchecked statements manage arithmetic overflows. An arithmetic overflow occurs if the resultant value is greater than the range of the target variable's data type. The checked statement halts the execution of the program whereas the unchecked statement assigns junk data to the target variable. The keywords associated with these statements are: checked and unchecked.Fixed statementThe fixed statement is required to tell the garbage collector not to move that object during execution. The keywords associated with this statement are: fixed and unsafe.Lock statementA lock statement in locking the critical code blocks. This ensures that no locking the critical code. These statements ensure security and only work with reference statements ensure security and only work with reference types. The keyword associated with this statement is: - lock. Question 13: Expressions
Answer
Expressions are used to manipulation data. Like in mathematics, expressions in programming languages, including C#, are constructed from the operands and operators. An expression statement in C# ends with a semicolon (;).
Expressions are used to:
Question 14: Difference between Statements andExpressionsAnswer Question 15: Introduction to ArraysAnswerAn array is a collection of related data with similar data types. Consider a program that stores the names of 100 students. To store the names, the programmer would create 100 variables of the string type.Creating and managing these 100 variables is very difficult but the programmer can create an array for storing the 100 names.An array is a collection of related values placed in a contiguous memory location and these values are referred to using a common array name. This simplifies the maintanance of these values. An array always stores values of a single data type. Each value is referred to as an element. These elements are accessed using subscripts or index numbers that determine the position of the element in the array list.C# supports zero-based index values in an array. This means that the first array element has index number zero while the last element has index number n-1, where n stands for the total number of elements in the array.This arrangement of sorting values helps in efficient storage of data, easy sorting of data and easy tracking of the data length. Declaration of array
Initializing Arrays
Syntax Demo Program
namespace Simple_Array
int[] count = new int[10];
int counter = 0, i;
for (i = 0; i < 10; i++)
count[i] = counter++;
Console.WriteLine("The Count value is:-" + count[i]);
} Types of Arrays
C# .Net mainly has three types of arrays, these are:
1. Single-Dimension Array
string[] students = new string[3] { "Jems", "Alex", "Joy" };
for (i = 0; i < students.Length; i++)
Console.WriteLine(students[i]);
}2. Multi-Dimension Array
There are two types of multi-dimensional array, these are:1. Rectangular Array.2. Jagged Array.1. Rectangular ArrayA rectangular array is a multi-dimensional array where all the specified dimensions have constant values. A rectangular array will always have the same number of columns for each row.
namespace Multi_Dimensional_array
int[,] dimension = new int[4, 5];
int numOne = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
dimension[i, j] = numOne;
numOne++;
Console.Write(dimension[i, j] + " ");
Console.WriteLine();
} 2. Jagged Array
namespace Jagged_Arrays
string[][] companies = new string[3][];
companies[0] = new string[] { "Intel", "AMD" };
companies[1] = new string[] { "IBM", "Microsoft", "Sun" };
companies[2] = new string[] { "HP", "Canon", "Lexmark", "Epson" };
for (int i = 0; i < companies.GetLength(0); i++)
Console.Write("List of companies in group" + (i + 1) + ":\t");
for (int j = 0; j < companies[i].GetLength(0); j++)
Console.Write(companies[i][j] + " ");
} 3. Using the "foreach"Loop for Arrays The foreach loop in C# is anextension of the for loop. This loop is used to perform specific actions on collections, such as arrays. The loop reads every element in the specified array and allows you to execute a block of code for each element in the array. This is particularly useful for reference types, such as strings. Syntax Demo Program
namespace Foreach_Loop_For_Array
string[] studentNames = new string[3] { "JAY", "MAHESH", "RAJ" };
foreach (string studName in studentNames)
Console.WriteLine("Congratulations!! " + studName + " You Have Selected for This Job");
Question 16: Type Casting
1. Implicit Conversions for C# Data Types Implicit typecasting refers to an automatic conversion of data types. This is done by the C# compiler. Implicitly typecasting is done only when the destination and source data types belong to the same hierarchy. In addition, the destination data type must hold a larger range of values than the source data type. Implicit conversion prevents the loss of data as the destination data type is always larger than the source data type. For example, if you have a value of int type then you can assign that value to the variable of long type. Snippet Demo Program
namespace Implicit_TypeCasting
int valOne = 20;
int valTwo = 30;
float valThree;
valThree = valOne + valTwo;
Console.WriteLine("Addition of Two variables:-" + valThree);
Rules
2. Explicit Conversions for C# Data Types Explicit typecasting refers to changing a data type of higher precision into a data type of lower precision. For example, using explicit type casting, you can manually convert the value of float type into int type. This typecasting might result in loss of data. This is because when you convert the float data type into the int data type, the digits after the decimal point are lost.
namespace Implicit_Typecasting
float side = 10.5F;
int area;
area = (int)(side * side);
Console.WriteLine("Area of the Squre = {0}", area);
} Question 17: Boxing and UnboxingAnswer Boxing and unboxing are concepts of C# data type system. Using these concepts, a value of any value type can be converted to a reference type and a value of any refeerance type can be converted to a value type. Boxing
Syntax Demo Program
namespace Boxing_Type
// Demo-1
int radious = 10;
double area;
area = 3.14 * radious * radious;
object boxed = area;
Console.WriteLine("DEMO-1 OUTPUT\n");
Console.WriteLine("Area of the circule= {0}\n", area);
//Demo-2
double bonus = 0.0;
double salary;
Console.WriteLine("DEMO-2 OUTPUT\n");
Console.WriteLine("Enter Salary:-");
salary = Convert.ToDouble(Console.ReadLine());
bonus = salary * 0.1;
object any = bonus;
Console.WriteLine("Bonus of Rs.{0} is Rs.{1}", salary, bonus);
} Unboxing
namespace UnBoxing_Type
//Demo-1
int length = 10;
int breadth = 20;
area = length * breadth;
int num = (int)boxed;
Console.WriteLine("Area of the Rectangle={0}\n", num);
double num2 = (double)bonus;
View All
View All
|
https://www.c-sharpcorner.com/UploadFile/d0a1c8/basics-content-in-C-Sharp-net/
|
CC-MAIN-2022-05
|
refinedweb
| 4,211
| 59.6
|
Definition of ATM Program in C
The ATM Program in C is written in C programming language which provides an ease to read and comprehend the instructions used. This program for using ATM machine is built on the concept of handling an account individually.
It can be defined as actually simple code structure of ATM transaction process to be understood by a user. For implementing this project, we may have to use function but in the meantime for easy coding, we may have to switch cause statement.
From this ATM program in C, we can even use the mini-program for checking the total balance, depositing the amount, and withdrawing the amount from the account definitely since it is not time overwhelming.
Syntax:
The C program executes ATM transaction having three forms of coding syntax:
1. Account balance checking
2. ATM Cash withdrawal
3. Deposition of cash
The process syntax structure includes the following procedures:
- Initially, we need to adjust or set the ATM pin along with the amount including a few random numbers.
- Taking ATM pin as the input.
- If the provided input pin is identical to the adjusted pin, then after that we can perform additional operations.
- We will implement the switch statement for executing the operations such as checking balance, withdrawal of cash amount, deposition of cash, and so on.
- Also, using a while loop to resume or terminate the procedure.
How ATM program work in C?
The ATM program follows three processes for proper transaction logically that includes cash withdrawing, depositing, and checking balance. This three-program sections are executed using the switch cases in C with initialized variables and functions with conditions. The conditions provide results accurately only if they are satisfied.
For example, using the ATM program in C, if the balance in the bank account is sufficient then only the withdrawal process will be proceeded otherwise go for another transaction or check the balance through options. Also, when a user deposits some amount into the account then on executing the code part, the ATM program will show the new balance present in the account. In the third technique, the user can check his/her account balance when the user performs any withdrawal or deposition actions through ATM transaction.
This ATM program using C language performs some strategic features for functioning the ATM Machine which is mentioned below:
- This C program code is able to show the ATM Transaction.
- For logging to the ATM Machine, it holds pin verification system.
- Using this ATM program, a user can also view the balance in the account.
- This ATM program in C even assists with cash withdrawal.
- We can also use this ATM machine program for cash deposition.
- ATM machine enables switch case allowing multiple transaction feature when one transaction is completed otherwise the user may exit which is done by a program to terminate.
Examples
Let us view an instance for the ATM program in C by the following process:
We will code for ATM transaction process in C using certain libraries and functions initializing as,
#include <stdio.h> // Defines standard input-output functions that are pre-defined
unsigned long amount=2000, deposition, withdrawal;
int pin, choice, k; // Defining few required variables in the transaction
char transaction ='y';
void main()
{
while (pin != 2025) // Using while loop to check for the condition on a pin number matching
{
printf("Type your secret pin number:");
scanf("%d", &pin);
if (pin != 2025) // Checking if the pin number types by the user is matched with the database record or not
printf("Please insert your valid password:\n");
}
do
{
printf("Hello! Welcome to our ATM Service\n");
printf("1. Balance Checking\n");
printf("2. Cash Withdrawal\n");
printf("3.Cash Deposition\n");
printf("4. Exit\n");
printf("*******?********?*\n\n");
printf("Please proceed with your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\n The account balance in Rs : %lu ", amount);
break;
case 2:
printf("\n Insert the amount to be withdrawal: ");
scanf("%lu", &withdrawal);
if (withdrawal % 100 != 0)
{
printf("\n You are requested to insert the amount in multiples of 100");
}
else if (withdrawal >(amount - 500))
{
printf("\n You are having an insufficient balance");
}
else
{
amount = amount - withdrawal;
printf("\n\n You can now collect the cash"); // after having a sufficient amount in the account the ATM machine will provide the cash amount.
printf("\n The current balance is%lu", amount);
}
break;
case 3:
printf("\n Insert the amount to be deposited");
scanf("%lu", &deposition);
amount = amount + deposition;
printf("The balance is %lu", amount); // Displays the new current balance after the cash deposition in the user’s account
break;
case 4:
printf("\n We are thankful to you for USING our ATM services!");
break;
default:
printf("\n You have made an invalid choice"); // Defines that the user have done something wrong with the ATM service options
}
printf("\n\n\n Would you like to have another ATM transaction?(y/n): \n");
fflush(stdin);
scanf("%c", &transaction);
if (transaction == 'n'|| transaction == 'N')
k = 1;
} while (!k);
printf("\n\n Thank you so much for your time to choose The our ATM services!");
// the ATM program terminates with a thank you note.
}
When we compile and run the code we will view the result as follows asking to enter the 4 digits pin number as:
Output:
If you type wrong pin number then it will you the output as below:
After this on typing the pin and clicking on Enter we will proceed towards the options of ATM transactions as shown in the image below:
On executing the code above in a C compiler, we can get the result as required by selecting the right choices provided. As follows:
This ATM program should be deployed properly in a bank system to get accurate results and perform the real ATM transaction where initially we can check if the program is working effectively or not.
Conclusion
Programming in C is perfect for beginners to code and therefore before proceeding it is essential to gain a few basic codes of C programming.
For creating an ATM machine program using C, we need to implement the four fundamental concepts of each ATM system that exists, it includes cash withdraw, cash deposit, account balance checks, and functionality for another transaction or termination.
Recommended Articles
This is a guide to ATM program in C. Here we discuss the Definition, syntax, How ATM program work in C?, examples with code implementation. You may also have a look at the following articles to learn more –
|
https://www.educba.com/atm-program-in-c/
|
CC-MAIN-2022-40
|
refinedweb
| 1,084
| 58.52
|
you today…
You see, over the past few weeks I’ve gotten some really great emails from fellow PyImageSearch readers. These emails were short, sweet, and to the point. They were simple “thank you’s” for posting actual, honest-to-goodness Python and OpenCV code that you could take and use to solve your own computer vision and image processing problems.
And upon reflection last night, I realized that I’m not doing a good enough job sharing the libraries, packages, and code that I have developed for myself for everyday use — so that’s exactly what I’m going to do today.
In this blog post I’m going to show you the functions in my transform.py module. I use these functions whenever I need to do a 4 point cv2.getPerspectiveTransform using OpenCV.
And I think you’ll find the code in here quite interesting…and you’ll even be able to utilize it in your own projects.
So read on. And checkout my 4 point OpenCV cv2.getPerspectiveTransform example.
Looking for the source code to this post?
Jump right to the downloads section.
OpenCV and Python versions:
This example will run on Python 2.7/Python 3.4+ and OpenCV 2.4.X/OpenCV 3.0+.
4 Point OpenCV getPerspectiveTransform Example
You may remember back to my posts on building a real-life Pokedex, specifically, my post on OpenCV and Perspective Warping.
In that post I mentioned how you could use a perspective transform to obtain a top-down, “birds eye view” of an image — provided that you could find reference points, of course.
This post will continue the discussion on the top-down, “birds eye view” of an image. But this time I’m going to share with you personal code that I use every single time I need to do a 4 point perspective transform.
So let’s not waste any more time. Open up a new file, name it transform.py, and let’s get started.
We’ll start off by importing the packages we’ll need: NumPy for numerical processing and cv2 for our OpenCV bindings.
Next up, let’s define the order_points function on Line 5. This function takes a single argument, pts , which is a list of four points specifying the (x, y) coordinates of each point of the rectangle.
It is absolutely crucial that we have a consistent ordering of the points in the rectangle. The actual ordering itself can be arbitrary, as long as it is consistent throughout the implementation.
Personally, I like to specify my points in top-left, top-right, bottom-right, and bottom-left order.
We’ll start by allocating memory for the four ordered points on Line 10.
Then, we’ll find the top-left point, which will have the smallest x + y sum, and the bottom-right point, which will have the largest x + y sum. This is handled on Lines 14-16.
Of course, now we’ll have to find the top-right and bottom-left points. Here we’ll take the difference (i.e. x – y) between the points using the np.diff function on Line 21.
The coordinates associated with the smallest difference will be the top-right points, whereas the coordinates with the largest difference will be the bottom-left points (Lines 22 and 23).
Finally, we return our ordered functions to the calling function on Line 26.
Again, I can’t stress again how important it is to maintain a consistent ordering of points.
And you’ll see exactly why in this next function:
We start off by defining the four_point_transform function on Line 28, which requires two arguments: image and pts .
The image variable is the image we want to apply the perspective transform to. And the pts list is the list of four points that contain the ROI of the image we want to transform.
We make a call to our order_points function on Line 31, which places our pts variable in a consistent order. We then unpack these coordinates on Line 32 for convenience.
Now we need to determine the dimensions of our new warped image.
We determine the width of the new image on Lines 37-39, where the width is the largest distance between the bottom-right and bottom-left x-coordinates or the top-right and top-left x-coordinates.
In a similar fashion, we determine the height of the new image on Lines 44-46, where the height is the maximum distance between the top-right and bottom-right y-coordinates or the top-left and bottom-left y-coordinates.
Note: Big thanks to Tom Lowell who emailed in and made sure I fixed the width and height calculation!
So here’s the part where you really need to pay attention.
Remember how I said that we are trying to obtain a top-down, “birds eye view” of the ROI in the original image? And remember how I said that a consistent ordering of the four points representing the ROI is crucial?
On Lines 53-57 you can see why. Here, we define 4 points representing our “top-down” view of the image. The first entry in the list is (0, 0) indicating the top-left corner. The second entry is (maxWidth - 1, 0) which corresponds to the top-right corner. Then we have (maxWidth - 1, maxHeight - 1) which is the bottom-right corner. Finally, we have (0, maxHeight - 1) which is the bottom-left corner.
The takeaway here is that these points are defined in a consistent ordering representation — and will allow us to obtain the top-down view of the image.
To actually obtain the top-down, “birds eye view” of the image we’ll utilize the cv2.getPerspectiveTransform function on Line 60. This function requires two arguments, rect , which is the list of 4 ROI points in the original image, and dst , which is our list of transformed points. The cv2.getPerspectiveTransform function returns M , which is the actual transformation matrix.
We apply the transformation matrix on Line 61 using the cv2.warpPerspective function. We pass in the image , our transform matrix M , along with the width and height of our output image.
The output of cv2.warpPerspective is our warped image, which is our top-down view.
We return this top-down view on Line 64 to the calling function.
Now that we have code to perform the transformation, we need some code to drive it and actually apply it to images.
Open up a new file, call transform_example.py , and let’s finish this up:. We’ll use two switches, --image , which is the image that we want to apply the transform to, and --coords , which is the list of 4 points representing the region of the image we want to obtain a top-down, “birds eye view” of.
We then load the image on Line 19 and convert the points to a NumPy array on Line 20.
Now before you get all upset at me for using the eval function, please remember, this is just an example. I don’t condone performing a perspective transform this way.
And, as you’ll see in next week’s post, I’ll show you how to automatically determine the four points needed for the perspective transform — no manual work on your part!
Next, we can apply our perspective transform on Line 24.
Finally, let’s display the original image and the warped, top-down view of the image on Lines 27-29.
Obtaining a Top-Down View of the Image
Alright, let’s see this code in action.
Open up a shell and execute the following command:
You should see a top-down view of the notecard, similar to below:
Let’s try another image:
And a third for good measure:
Figure 3: Yet another OpenCV getPerspectiveTranform example to obtain a birds eye view of the image.
As you can see, we have successfully obtained a top-down, “birds eye view” of the notecard!
In some cases the notecard looks a little warped — this is because the angle the photo was taken at is quite severe. The closer we come to the 90-degree angle of “looking down” on the notecard, the better the results will be.
Summary
In this blog post I provided an OpenCV cv2.getPerspectiveTransform example using Python.
I even shared code from my personal library on how to do it!
But the fun doesn’t stop here.
You know those iPhone and Android “scanner” apps that let you snap a photo of a document and then have it “scanned” into your phone?
That’s right — I’ll show you how to use the 4 point OpenCV getPerspectiveTransform example code to build one of those document scanner apps!
I’m definitely excited about it, I hope you are too.
Anyway, be sure to signup for the PyImageSearch Newsletter to hear when the post goes live!
Hello Adrian,
This was really a wonderful post it gave me a very insightful knowledge of how to apply the perspective transform. I just have a very small question about the part where you were finding the maxHeight and maxWidth. For maxHeight (just considering heightA) you wrote
np.sqrt(((tr[1] – br[1]) ** 2) + ((tr[1] – br[1]) ** 2))
but i think that the height should be
np.absolute(tr[1] – br[1])
because you know this gives us the difference in the Y coordinate
but the equation that you wrote gives us
1.4142 * difference of the y coordinates. Why is so?
Hi Vivek. The equation is utilizing the sum of squared differences (Euclidean distance), whereas the equation you proposed is just the absolute value of the differences (Manhattan distance). Try converting to the code to use the
np.absolutefunction and let me know how the results look.
I know this is old but still, I actually had the same question. Then I tried to replaced with
widthA = abs(br[0] – bl[0])
widthB = abs(tr[0] – tl[0])
heightA = abs(tr[1] – br[1])
heightB = abs(tl[1] – bl[1])
And I’m getting pretty similar results.
Hi Adrian,
is it possible, that you mixed up top and bottom in the comments of the function order_points() ? When I did an example rect[0] was BL, rect[1] was BR, rect[2] was TR and rect[3] was TL.
Hi Vertex. Hm, I don’t think so. The
dstarray assumes the ordering that I mentioned above and it’s important to maintain that order. If the order was not maintained then the results from applying the perspective transform would not be correct.
Hi Adrian, thanks for your answer, I have to say I am newbie and I tried the following to get a better understanding:
import numpy as np
rect = np.zeros((4, 2), dtype = “float32”)
# TL,BR,TR,BR
a = [[3,6],[3,3],[6,6],[6,3]]
rect[0] = np.argmin(np.sum(a,axis=1))
rect[2] = np.argmax(np.sum(a,axis=1))
rect[1] = np.argmin(np.diff(a,axis=1))
rect[3] = np.argmax(np.diff(a,axis=1))
print(rect)
[[ 1. 1.]
[ 3. 3.]
[ 2. 2.]
[ 0. 0.]]
I guess I got a faulty reasoning.
Ah, I see the problem. You are taking the argmin/argmax, but not grabbing the point associated with it. Try this, for example:
rect[0] = a[np.argmin(np.sum(a,axis=1))]
The argmin/argmax functions give you the index, which you can then apply to the original array.
Hi Adrian! I’m a newbie.
Spent lots of time mulling over this.
Lines 53-57
dst = np.array([
[0, 0],
[maxWidth – 1, 0],
[maxWidth – 1, maxHeight – 1],
[0, maxHeight – 1]], dtype = “float32”)
Isn’t
[0,0] – Bottom Left
[maxWidth – 1, 0] – Bottom Right
[maxWidth – 1, maxHeight – 1] – Top Right
[0, maxHeight – 1]] – Top Left
So it’s bl,br,tr,tl? I’m a bit confused. Could you please explain?
Hey Nithin, it’s actually:
Python arrays are zero-indexed, so we start counting from zero. Furthermore, the top-left corner of the image is located at point (0,0). For more information on the basics of image processing, including the coordinate system, I would definitely look at Practical Python and OpenCV. I have an entire chapter dedicated to learning the coordinate system and image basics.
might be super simple, but I still don’t get it why do you extract 1 from maxWidth and maxHeight for the tr, br and bl ?
In order to apply a perspective transform, the coordinates must be a consistent order. In this case, we supply them in top-left, top-right, bottom-right, and bottom-left order.
Great sample. My question is regarding the transformation matrix. Could it be used to tranform only a small region from the original image to a new image instead of warping the entire image? Say you used the Hello! example above but you wanted to only relocate the exclamation mark from the original image to a new image to end up with exactly the same output you have except without the “Hello” part, just the exclamation mark. I guess the question is whether you can use the TM directly without using the warping function.
Thanks!
Hi Ken, the transformation matrix
Mis simply a matrix. On its own, it cannot do anything. It’s not until you plug it into the transformation function that the image gets warped.
As for only warping part of an image, you could certainly only transform the exclamation point. However, this would require you to find the four point bounding box around the exclamation point and then apply the transform — which is exactly what we do in the blog post. And that point you’re better off transforming the entire index card and cropping out the exclamation point from there.
Hey Adrian,
I agree completely with what you say…I apologise, it was a poor example…what I was wondering about was how the mapping worked.
Fwiw, given the transformation matrix M you can calculate the mapped location of any source image pixel (x,y) (or a range of pixels) using:
dest(x) = [M11x + M12y + M13]/[M31x + M32y + M33]
dest(y) = [M21x + M22y + M23]/[M31x + M32y + M33]
Why bother?
I used this method to map a laser pointer from a keystoned camera image of a large screen image back onto the original image…allowing me to “draw” on the large screen.
Thanks!
Wow, that’s really awesome Ken! Do you have an example video of your application in action? I would love to see it.
Hi Adrian,
I am newbie in opencv.
is it possible to measuring angles in getPerspective Transform
can u give the function?
Thanks in advance
Hi Wiem, I’m not sure I understand what you’re asking? If you want to get the angle of rotation for a bounding box, you might want to look into the
cv2.minAreaRectfunction. I cover it a handful of times on the PyImageSearch blog, but you’ll want to lookup the actual documentation on how to get the angle.
Hi Adrian, thanks for your answer
I looked at “hello image” (original vs wraped) there is an angle of rotation.
i want to know how to get the angle.
sorry for my english
Hope to hear from you
Regards.
Hey, Wiem — please see my previous comment. To get the angle of rotation of the bounding box just use the
cv2.minAreaRectfunction, which you can read more about here. Notice how the angle of rotation is returned for the bounding box.
Ups yeah.
thanks for fast response.
Thank you very much
regards
Is there equivalent function for order_points(Rect ) in opencv for C++?
P.S. Thanks for your tutorials.
Thanks.
Hey Aamir, if there is a C++ version, I do not know of one. The
order_pointsfunction I created was entirely specific to Python and is not part of the core of OpenCV.
hiii Aamir,
Do you have the c++ version of this above code.
The code shows this error:
“TypeError: eval() arg 1 must be a string or code object”
thanks
Hi Palom, make sure you wrap the coordinates in quotes:
python transform_example.py --image images/example_01.png --coords "[(73, 239), (356, 117), (475, 265), (187, 443)]"
That(wrapping in quotes) is already done in the code and the problem persists!
Try removing the argument parsing code and then hardcoding the points, like this:
pts = np.array([(73, 239), (356, 117), (475, 265), (187, 443)], dtype = "float32")
error: (-215) src.cols > 0 && src.rows > 0 in function warpPerspective
I have a error after hardcoding
It sounds like the path you supplied to
cv2.imreaddoes not against. I would suggest reading up on NoneType errors.
It works in my Spyder on Debian:
coords_list = eval(eval(args[“coords”]))
pts = np.array(coords_list, dtype =”float32″)
Hey, i am trying to implement the same thing in java using openCV but I cant seem to find the workaround of the numpy function can you help me out please…..My aim is to implement document scanner in java(ref :)…..
Thanking you in anticipation
Hey Singh, I honestly don’t do much work in Java, so I’m probably not the best person to answer that question. But you could probably use something like jblas or colt.
Hey Adrian,
I believe your order_points algorithm is not ideal, there are certain perspective in which it will fail, giving non contiguous points, even for a rectangular subject. A better approach is to find the top 2 points and 2 bottom points on the y axis, then sort these pairs on the x axis.
Actually my solution can also fail.
If the points in the input are contiguous, the best would be to choose a begin point meeting a choosing arbitrary ordering constraint, whilst conserving their original order.
Otherwise, a correct solution involve tracing a polygon without intersection, e.g. using the gift wrapping algorithm — simplified for a quadrilateral.
Thanks for the tip Tarik!
i am receiving an error message no module named pyimageseach.transform any idea what i have missed?
Please download the source code using the form at the bottom of this post that includes the
pyimagesearchmodule.
Thanks for the quick reply.Okay i downloaded the file on my old laptop running windows 7 what do i do with it. Sorry for the stupid question I am a newbee and I am also old so i have two strikes against me,but if you learn from mistakes I should be a genius in no time!
Please see the “Obtaining a Top-Down View of the Image” section of this post. In that section I provide the example commands you need to run the Python script.
Hi Adrian,
Thanks so much for the code. I have tried your code and running well on my MacBook OSX Yosemite, Python 2.7.6 and openCV 3.0.
I am just wondering that if we can improve it by automatically detect the four points. So, the variable input will be only the image. 🙂 Should it be possible? What will be the algorithm to auto-detect the points?
🙂
Thanks!
Ari
Yep! We can absolutely automatically detect the points! Please see my post on building a document scanner.
Thanks for your kind sharing information about python & openCV.
Wonderful!
hi adrian,
thanks for sharing..
what is mean index 0 and 1 in equation widthA = np.sqrt(((br[0] – bl[0]) ** 2) + ((br[1] – bl[1]) ** 2)) ?
The
0index is the x-coordinate and the
1index is the y-coordinate.
Hi!
Thank you for the tutorial. Have you got any tutorial how to transform perspective for the whole image? So user chooses 4 reference points and then the whole image is transformed (in result image there are some black fragments added). I know that I should calculate appropriate points for input image, but I have no idea how to do it. Can you help?
Regards
Given your set of four input points, all you need to do is build your transformation matrix, and then apply a perspective warp, like this tutorial.
Excellent tutoroal! Would it be possible to do the opposite? I mean, given a top-view of an image produce a distorsioned one?
Sure, the same principles apply — just modify the transformation matrix prior to applying it.
Hi, Adrian
I’m passing by just to say this post is really helpful and thank you very much for it.
I’m starting studying Computer Vision and your blog it is really helping my development.
Well done and keep going. =)
Cheers,
Matheus Torquato
Thanks Matheus! 🙂
You have a slight typo in your description of line 21. It should say (i.e. y – x).
Hi Adrian,
Can the getPerspectiveTransform method return the angle that the image makes with the Y-axis?
Can you be more specific what you mean by “the angle the image makes with the y-axis”? I’m not sure I understand your question.
Do you happen to have the c++ version of this?
Sorry, I only have Python versions, I don’t do much C++ coding anymore.
I’m a complete newbie to OpenCV but shouldn’t warping perspective off a
Matusing the output of
minAreaRectbe a one-line command? I mean, you clearly have extracted some of these things out as ‘utils’ and a nice importable github repo for that, too, for which, we all thank you but don’t you think that if it were so “regularly used by devs for their image processing tasks”, they better lie in vanilla OpenCV? To be *really really* honest, my “duckduckgo-ing” about warping off a rect perspective led me to this post of yours among the very first results and I *knew* the code presented obviously works but I didn’t immediately start using it *ONLY AND ONLY* because I *believed* there would be something to the effect of
warpedMat = cv2.warpPerspective(imageToWarp, areaToWarp)
Ultimately, on asking my colleague on how to do it, she suggested goin’ ahead with your written utils only! 🙂
Adrian,
Thank you so much for your awesome tutorials!! I’ve been learning how to use the raspberry pi the past few weeks in order to make an automated testing system, and your tutorials have been so thorough and helpful. Thank you so so much for making these!!
Thanks Christine, I’m happy i could help 🙂
I tried this code and it’s pretty cool but it can’t handle images like this:
I tried to cut out the business card but I couldn’t. I got some strange results. Why and how can I fix it?
In order to apply a perspective transform (and get reasonable results), you need to be able to detect all four corners of the object. If you cannot, your results will look very odd indeed. Please see this post for more details on applying perspective transforms to rectangular objects.
Hi Adrian. sorry for my English. 🙂
I’m newbie in opencv. thank you so much for awesome tut 😀
i want crop this image with original on left and i want crop image on right. may u help me?
thanks in advance
If you are trying to manually crop the region, I would use something like the GUI code I detail in this blog post.
thanks your tut. it very excited!
in this image, i want to get the road, and outside will be black, white or other color, because i’m researching about raspberry pi, and i want it process
least as possible. do you have any idea?
Thank you sir. I accept you as my Guru.
Hi Adrian,
I dont understand how (x-y) will be minimum for the top right corner…. Consider this square:
tl= 0,0
tr= 1,0
br= 1,1
bl =0,1
(x-y) is minimum for bl, ie. 0-1 = -1, nd not tr… Am i going wrong somewhere??
The origin (x, y)-coordinates start at the top-left corner and increase going down and to the right. For what it’s worth, I recommend using this updated version of the coordinate ordering function.
I agree with Karthikey,
you made a mistake.
it should be y-x, not x-y
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmax(diff)]
rect[3] = pts[np.argmin(diff)]
Yes, there is actually an updated, better tutorial on ordering coordinates here.
I gave the input image of a irregular polygon formed after applying convex hull function to a set of points, supplying the four end pints of the polygon in the order you mentioned. However the output I get is a blank screen. No polygon in it.
Can you please tell how to give irregular polygons as input to the above code.
It’s hard to say without seeing an example, but I imagine your issue is that you did not supply the coordinates in top-left, top-right, bottom-left, and bottom-right order prior to applying the transformation.
Adrian, great post. I was trying to build this for a visiting card. My problem is that the card could be aligned in any arbitrary angle with respect to the desk as well as with respect to the camera.
When I use this logic, there are alignments at which the resultant image is like a rotated and shrieked one. In your case, the image is rotated towards the right to make it look correct. However, if the original card was rotated clockwise 90 degrees, then the logic of top right, top left does not work correctly.
I tried using the “width will always be greater than height” approach but that too fails at times.
Any suggestions?
This sounds like it may be a problem with the coordinate ordering prior to applying the perspective transform. I would suggest instead suggest using the updated implementation.
Hello Adrain,
I am quit new in opencv. i am working in Imageprocessing progam in python 2.7.Actually i am facing Problem during cropping of Image. I am working in diffferent Images having some black side background. The Picture is taken by camera maulally so the Image is also different in size. I want to crop the Image and separte it from balck Background. could you suggest how can i make a program that can detect the Image first and crop automatically.
Thanks
Hey Sandesh — do you have any examples of images that you’re working with?
Hi Adrian,
I have a doubt when thinking about the generalization of this example regarding the destiny points. This example is specifically aimed to quadrangular objects, right? I mean, you get the destiny image points because you simple say “hey, sure it will be a box, let’s get the max height, max width and that’s it”.
But wouldn’t be so easy if the original object would have had a different shape, right?
Thanks.
Yes, this example presumes that the object you are trying to transform is rectangular. I’m not sure I understand what you mean by the “generalization” of this technique?
I want to know if there is a way that the program can automatically detect the corners??
Absolutely. Please see the followup blog post to this one.
When the rectangular dimensions of the source target are known, the result is much better if you input x,y values for the destination image that conform to the x/y ratio of the source target. The estimation of the output size described here will only be perfect if the target is perpendicular to the viewpoint. This is why the distortion increases in proportion to the angle(s) away from perpendicular. Otherwise, you have to know the focal length of the camera, focus distance, etc. (much more complicated calculations…) to estimate the “real” proportions of the target’s dimensions (or x/y ratio).
As an example, the page size in your samples looks like “legal” 8.5 x 14 paper. Once this is established, if you replace the maxHeight calculation with “maxHeight = (maxWidth * 8) / 14”,
the output image(s) are much better looking as far as the x/y ratio is concerned (no apparent distortion on the last sample). Of course, one must know the target’s x/y ratio…
Good point, thanks for sharing Rene. If the aspect ratio is know then the output image can be much better. There are methods that can attempt to (automatically) determine the aspect ratio but they are outside the scope of this post. I’ll try to do a tutorial on them in the future.
Hi, this is really nice ! What bugs me is the way to find those four corners since the picture does not have the right perspective
If you want to automatically find the four corners, take a look at this blog post.
Hi Andrian, thanks for the tutorial. I cannot help noticing that you mentioned the difference of the coordinates is (x-y), but np.diff([x, y]) actually returns (y-x).
Traceback (most recent call last):
File “transformexple.py”, line 2, in
from pyimagesearch.transform import four_point_transform
ImportError: No module named pyimagesearch.transform
how can install it ????
Make sure you use the “Downloads” section to download the source code associated with this blog post. It includes the “pyimagesearch” directory structure for the project.
It is really nice way to get the bird’s eye view, but when I tried to use it in my algorithm i failed to get the bird’s eye
I want to get a top view of a lane and a car ?
This method is an example of applying a top-down transform using pre-defined coordinates. To automatically determine those coordinates you’ll have to write a script that detects the top of a car.
Hi Adrian,
Thanks a lot for the post, this is great for the app I’m trying to build. The thing is that I’m translating all your code to Java and I don’t know if everything is correctly translated because the image I get after the code is rotated 90º and flipped… I’m investigating what could be happening but maybe you think of something that could be happening. Thanks again for the post.
Hi Christian — thanks for the comment. However, I haven’t used the OpenCV + Java bindings in a long time, so I’m not sure what the exact issue is.
Well, thanks anyway. I’ll giving it a second shot today 🙂
Hi Adrian,
Would affine transform make any sense in this context?
This page provides a nice discussion on affine vs. perspective transforms. An affine transform is a special case of a perspective transform. In this case perspective transforms are more appropriate — we can make them even better if we can estimate the aspect ratio of the object we are trying to transform. See the link for more details.
There is another idea to order four points by
comparing centroid with the four points
there is one limitation when oriantation object =45 degree
Hi Adrian,
Thanks for sharing the example, very inspiring!
Perspective transform works great here as the object being warped is 2D. What if the object is 3D, like a cylinder,?
Hi Adrian,
I followed your tutorial in one of my projects but the object height decreases.
i used your tuturial ‘Building a Pokedex in Python’ part4 and 5 in order to have the corners points.
Can you tell me what im doing wrong.
Thanks in advance.
Hello Adrian,
Could you help with the following problem?
$ pip install pyimagesearch
Collecting pyimagesearch
Could not find a version that satisfies the requirement pyimagesearch (from versions: )
No matching distribution found for pyimagesearch
Also I’ve checked comments with similar problems, but all solutions still don’t work…
– downloaded examples on the bottom of the page
– replace them to the folder with python.
Thank you!
There is no “pyimagesearch” module available on PyPI, hence you error when installing via “pip”. You need to use the “Downloads” section at the bottom of this page, download the code, and put the “pyimagesearch” directory in the same directory as the code you are executing. Alternatively, you could place it in the
site-packagesdirectory of your Python install, but this is not recommended.
Hi Thanks for the cool tutorial helped me a lot ,but there were projection errors do u know how to Dewarp an image , for an example a page from a book.
Thanks in advance.
Hey Adrian,
Thanks for the tutorial.
I am porting the order_points func to C++, but I am being confused about:
diff = np.diff(pts, axis = 1)
The tutorial states that in order to find top right and bottom left points, find the diff of each point and the min will be the top right and max will be bottom left. The confusion is: is the function doing x – y or y – x or |x -y|?
I have a hunch that it’s |x – y|, I’ll try it out soon and post an update.
Hi Ahmad — please see my reply “Eugene”. I would port the function I linked to over to C++ instead.
Hi, Adrian
There is a bug in “order_points” function.
For input [(0,0),(20,0),(5,0),(5,5)] it classifies (20,0) as bottom-right, because 20+0 is largest sum. But it is top-right. Real bottom-right is (5,5)
It causes incorrect image processing in some cases
I fixed it . Code is less pretty, but works in all cases. Maybe you can rewrite it to make pretty 🙂
Hi Eugene — thanks for the comment. I actually provide an updated method to order the points in this post.
Why do we hard code this. Can we automate this like when we pass the input image it has to automatically detect coordiantes and warp it according to the reference image?How do we do that .Is it possible?
Yes, please see the follow up blog post where we build a document scanner that automatically determines the coordinates.
Hi Adrian!
Your solutions are helping me a lot building a Document Classifier with sklearn and other machine learning related libraries! I already managed to succesfully build the classifier model and now I’m trying to get documents from photos to predict their classes.
In order to make this work I get features from the documents I try to classify so I can build an array with them and pass it to the classifier to predict its class.
It’s very important for the classifier to get information about the colors of the document. I already applied your scanner but I’m struggling a lot to get the colors.
I understand it’s crucial to have do the COLOR_BGR2GRAY transformation for the code to work, either for getting the contour points and to do the warping. Is there any way I could achieve a colored pespective transformation?
Thank you for sharing your ideas! Sorry for my bad english! I hope my explanation makes sense. I’m a spanish speaker!
You can certainly obtain a color version of the warped image. Just resize the image as we do in the blog post, but keep a copy of the color image via the
.copy()method. From there you can apply the perspective transform to the resized (but still color) image. All other processing can be done on the grayscale image.
Hello Adrian,
thanks for the post! I had fun playing around with the code and managed to get a nice bird’s eye view for an image of my own.
I would have one interesting question: Let’s say that we have an image with circular pattern (imagine identical objects regularly inter-spaced along circumference of a circle, kind of like a clock). This pattern is viewed under perspective projection so it appears like an ellipse. My question is: what is the best way how to get the bird’s eye view for this pattern? (The approach presented above doesn’t seem directly applicable as there are now straight lines in the image of circular pattern).
Thanks a lot!
This is certainly a much more challenging problem. To start I would be concerned with how you would attempt the objects along the circumference of the circle under perspective transforms. Can each object be localized? If you can localize them then you could actually treat it like a 4 point perspective transform. You would basically use each of the detected objects and compute the bounding box for the entire circle. Since the bounding box would be a rectangle you could then apply the perspective transform.
What software license are you using for the code in this post/repo?
The license is MIT. I would appreciate attribution and a link back to the PyImageSearch blog if at all possible.
Is there any way we can automatically find out those four coordinates ?
Yes. Please see this tutorial.
when i run this code it just prints none, do not print any picture, why is that?
Hey Erdem — can you elaborate a bit more? Is the script automatically exiting? Are you receiving an error message of some kind?
Hi Adrian,
Thanks for the excellent post. I think the width & height calculation may have some problem. check the results at
For this case the width needs to be scaled, we can’t work with
“width is the largest distance between the bottom-right and bottom-left x-coordinates or the top-right and top-left x-coordinates” logic
This code does not handle the scaling of the width and height to maintain aspect ratio. You can update the code to do so if you wish.
Thanks , I was thinking about that but not sure how we can find aspect ratio from the image
Hello, Adrian. After reading your article, I learned a lot. But I have two confusions and I would like to ask you. The first problem, when acquiring contours, is because the image is noisy, and the points obtained are not four, so do not know what to do when building the dst matrix. If the contour has multiple points, can you construct the dst matrix? The dst I mean is the second parameter in cv2.getPerspectiveTransform(rect, dst). The second question, when I got the matrix M through cv2.getPerspectiveTransform(rect, dst), I want to change the perspective of the original image through M, not just changing the contents of the four points in the image. For example, you In the example, the blank part of the picture is OK? My English is not very good, is a tool to help me translate, I hope you can get your reply, I will be extremely grateful
The answer here is “contour approximation”. Take a look at this blog post to see how you can use contours, contour approximation, and a perspective transformation to obtain the desired result.
ap.add_argument(“-i”, “–image”, help = “path to the image file”)
The above line always gives error in WINDOWS OS in Python 3.6.4 , can you please help me out?
Your error can be resolved by reading up on command line arguments.
Hi Adrian,
Thanks for this great post. I was trying to follow along with this post with slight modifications. First I obtained four_point_transform of the given image. After getting the warped image, I plotted bounding box around text “Hello” using cv2.rectangle.
cv2.rectangle(warped, (37, 20), (222, 97), (255, 0, 0), 2)
Now, I want to plot the bounding box of text “Hello” in the warped image on the original image. I referred to a similar question on stackoverflow:.
But I do not have the coordinates on the source image so could not follow along. Any help would be very much appreciated.
I’m not sure what you mean by “warped image on the original image”. Could you clarify?
I have these coordinates (37, 20), (222, 97) on the warped image. Now I’ve to find out what would have been their coordinates on the original image? Hope it’s clear now.
Thank you for the clarification, I understand. You linked to the StackOverflow thread you read which contains the correct answer — you use an inverse perspective transform.
Many Thanks for sharing your expertise.
I worked out the code to show original image with matplotlib so I can select the coordinates of the points more easily.
I works quite fine.
Thanks for the sharing.
I found a typo in the blog post where you wrote, “Here we’ll take the difference (i.e. x – y) between the points using the np.diff function on Line 21.”
I think you mean y-x.
Hi Adrian,
How can we automatically know the coordinates of the input image , and don’t write it in the command ,So as to make this project more practical to use . Some reference links will do great help .
Thank you !!
This guide will show you how 🙂
Hi Adrian,
I’m trying to find all the rectangular contours and lines(strictly horizontal or vertical) in a screenshot image. For example I took screenshot of this page and would like to identify all the code blocks, image blocks, comment separation lines etc. Now since it is a screenshot image, I know that all my required rectangle contours edges are strictly horizontal and strictly vertical without any slant. In my scenario, the edges would be lines with some background or segment border
I’ve tried canny edge() followed by hough transform. I think I’m not able to decide the parameters. Need your help in understanding the parameters for hough transform and few suggestions of parameters or approaches would be great help.
Thank you
The Hough lines function can be a bit of a pain to tune the parameters to. You can actually use simple heuristics to detect text and code blocks in a screenshot. All you would need is the image gradients and some morphological operations. I would start by following this example and working from there.
I do not know what to say
Everything here is useful
I remember the day you published this post I did not care very much maybe I did not understand it
Today I’m after a long research I really benefited from
Thanks Adrian
Thanks Mohamed 🙂
Thank for the tutorial, it works wonderfully. I have a question regards to the transformation, say I have a point on the source image, and after wraptransform, how do I find out where this point in new image ?
Hi Adrian
I tested and saw that it may not transform perspective back to original dimension on top down view. If we already known the original dimensions of object, and scale the result to fit these dimensions(width x height), may it be returned to correct size ? How to do that?
If you know the original aspect ratio of the object you scale the output image width and height (the values you pass into the perspective transform) by that aspect ratio, making the output image match the original aspect ratio.
It works, and i use cv2.resize ,i wonder if interpolation = cv2.INTER_CUBIC is correct
In this scanning lesson, you referenced and challenged us to write an iPhone App that does this, I wasn’t aware that Apps can be written in Python. Can you please give me references on how to do this? I know this is not part of your course (at least I didn’t come across it yet), but reference for this would be great.
Does the new XCode for Apple support python driven iPhone apps? Or is there some other 3rd party outfit that offers this capability.
John
Sorry for any confusion there — I was providing you with an example implementation in Python. You could then translate the code into whatever language you wished and use it as a base for a mobile application.
Hi Adrian , that is a great post and good code…. can you pls let me know how to download the pyimagesearch?
You can use the “Downloads” section of the tutorial to download the source code and “pyimagesearch” module for the post.
Hello Adrian. Thanks for the great post. Really helps me as a new learner.
I would like to know if there is anyway to automatically detect the coordinates that has to be warpped? Because for my project I would require it to automatically detect the coordinates? Could you kindly help me with this?.
Thanks
Yes, absolutely. See this post.
The point sorting helper uses a member function for calculating the sum, but a free standing function for the diff. The later is actually more useful since it can deal with an “array-like” and not just a numpy matrix.
In other words, changing “pts.sum(axis = 1)” into “np.sum(pts, axis=1)” makes it more generic so you can pass a plain python list into four_point_transform().
Adrian, I want to thank you for the opportunity to work with your source code. I wonder if you have come across my situation as I can’t quite get it to process. Once I run the module, the python 2.7.14 shell comes with red message as such:
usage: scan.py [-h] -i IMAGE
scan.py: error: argument -i/–image is required
I went through all of the files needed for it to work and I can’t even find where IMAGE in all caps shows up? Maybe you would have some idea. Thanks!!
Your error is happening due to not properly understanding how command line arguments work. It’s okay if you are new to command line arguments but make sure you read this guide first to help you learn the fundamentals. From there you’ll be ready to go!
Hi, do you have an idea how can I detect the text area without the four points? (e.g the paper area’s four points is not visible in the image because it is skewed/rotated) Thank you so much!
Unfortunately you will need to be able to detect all four coordinates for a reliable perspective transform. If you could detect 3 points you could estimate the 4th point but I would encourage you to try to detect all four points.
Hello, I am extremely new to OpenCV. While running the code, I am getting an invalid syntax at transform_example.py. Can you please help me with it.
What is the exact error? If you’re new to OpenCV you should work through Practical Python and OpenCV. 1000’s of PyImageSearch readers have used the book to learn the fundamentals of computer vision and image processing — I have no doubt it will help you as well.
Hi Adrian,
Thanks for this amazig tutorial. I’d like to ask if there is a way to do the reversal of this project, so puthis particular text in perspective on the paper? Is that possible and is there a tutorial for it.
Thanks,
Igor
Hey Adrian,
I hope you doing amazing well. your tutorials are amazing.
I just want to know how you define the coordinates? did you randomly define them or you find them first and then pass those coordinates in a function
Thanks
AN
These were defined manually. To automatically find the coordinates see this tutorial.
Amazing Tutorial you helped me a lot , i have been following your tutorials for almost 2 years now . keep up the good work .
Thanks Ajay, I’m glad you’re enjoying the blog 🙂
Thanks for this tutorial. My 2 cents about quadrilateral points ordering:
Bellow is my code:
def order_points(pts):
# Step 1: Find center of object:
center = pts.sum(axis=0) / 4
# Step 2: Move coordinate system to center of object
shifted = pts – center
# find andlular component of the polar coordinate of each vertex
theta = np.arctan2(shifted[:, 0], shifted[:, 1])
# return vertices ordered by theta
return pts[theta.argsort]
Hello,
Great post, I have been looking for something like this all over the place!
I have a very similar problem. Imagine I have a camera mounted on dashboard of my car and it takes images of the road ahead. That “view” will be perspective view, right?
Now I want to transform that to something which should look like the plan or top view of the road (orthographic top view of the road)
Do you think I can use your algorithm?
Also, does it automatically correct for non linearity of the lens? For example:
at the bottom of the image….almost the entire width of the image will be equal to width of the road…but looking further away along the road into the horizon (top of the image) …the width of the road would correspond to only a small number of pixels. And this effect is non linear as the distance from camera increases. What do you think about that?
You calculate the width and the height of the output image, but when you are listing destination points of the output image you are subtracting 1 from width and height. wouldn’t that make the destination image smaller than the source and different from the output image shape? I don’t understand that step.
|
https://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/
|
CC-MAIN-2019-35
|
refinedweb
| 8,197
| 73.47
|
On 2010-11-29, Stefan Bodewig wrote:
> On 2010-11-23, Kevin Connor Arpe wrote:
>> Regarding the namespace issue, no one I talked to at my office knew
>> anything about classloaders. I wasn't sure how to describe it, but I
>> don't want users to need to be a Java expert to understand the docs...
> The problem is you need to understand a bit of Java classloading in
> order to understand what is going on. And as usual people who know a
> difficult issue - and had to learn them a long time ago - are often not
> the best people to describe them to newbies. I'll give it a shot when I
> get around to it.
Kevin, could you do me a favor and review the changes I've made in
<>, please -
they should become visible online within a few hours. It could be total
gibberish.
Would what I've written helped you back when you tried to write your
tasks? Do the people at your office understand it?
Thanks
Stefan
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org
For additional commands, e-mail: dev-help@ant.apache.org
|
http://mail-archives.apache.org/mod_mbox/ant-dev/201011.mbox/%3C87k4jwrtwa.fsf@v35516.1blu.de%3E
|
CC-MAIN-2014-52
|
refinedweb
| 191
| 72.56
|
Create and Deploy a Next.js and FaunaDB-Powered Node.js App with ZEIT Now
Create a Next.js and FaunaDB-Powered Node.js App and deploy it with ZEIT Now.
FaunaDB is a serverless cloud database that gives you low-latency access to your app data around the world.
This guide walks you through creating a Next.js app that receives data from a Node.js API powered by FaunaDB, and how to deploy it with ZEIT Now.
Step 1: Connecting to FaunaDB
To start, you need to have created a FaunaDB account. Once logged in to FaunaDB, create a child database named
zeit (names are case sensitive).
Creating a new database in the FaunaDB dashboard.
After clicking Save, you will be taken to the Database Overview page.
From here, the easiest way to create a demo schema with some data is to execute a Fauna Query Language (FQL) script file.
Select the Shell tab, then copy in this FQL script and click Run Query.
Adding data to a FaunaDB database from the dashboard using an FQL script.
After executing the script, the Collections page will present you with dummy data. You are now ready to create a connection to the database.
The Collections page on the FaunaDB dashboard after adding data to the database.
Step 2: Create an Access Key
Go to the Security page and create a new key. Enter the following data in the fields:
- Database:
zeit
- Role:
Admin
- Key Name:
access
Once you have entered the required data, save. FaunaDB will then take you to the Keys page.
On the Keys page, you will receive a unique hash called a Secret. The Secret is your method of securely identifying yourself to the database.
Create a Now Secret to store the access key received, this will be used later when accessing the database.
now secrets add FAUNADB_SECRET_KEY [your-access-key]
Adding the access key as a Now Secret.
Step 3: Creating Your Next.js App
Get started creating your Next.js by making a project directory with the required structure and moving into it:
mkdir -p faunadb-demo/pages/api && mkdir faunadb-demo/components && cd faunadb-demo
Creating and entering into the
/faunadb-demo directory.
Next, initialize the project:
npm init -y
Initializing the project, this creates a
package.json file.
Continue to install the FaunaDB JavaScript client which allows you to connect to, and query, the database, along with the required dependencies for Next.js:
npm i faunadb next react react-dom
Adding the
faunadb,
react and
react-dom dependencies to the project.
Inside of the
/pages directory, create an
index.js file with the code below:
import { useEffect, useState } from 'react' import Head from 'next/head' import TableRow from '../components/TableRow' export default () => { const [data, setData] = useState([]) useEffect(() => { async function getData() { const res = await fetch('/api') const newData = await res.json() setData(newData) } getData() }, []) return ( <main> <Head> <title>Next.js, FaunaDB and Node.js</title> </Head> <h1>Next.js, FaunaDB and Node.js</h1> <hr /> <div className="container-scroll"> <div className="container"> <h2>Customer Data</h2> <div className="table"> <h4>name</h4> <h4 className="telephone">telephone</h4> <h4 className="credit-card">credit card</h4> </div> {data.length > 0 ? ( data.map(d => ( <TableRow key={d.data.telephone} creditCard={d.data.creditCard.number} firstName={d.data.firstName} lastName={d.data.lastName} telephone={d.data.telephone} /> )) ) : ( <> <TableRow loading /> <TableRow loading /> <TableRow loading /> </> )} </div> </div> </main> ) }
Adding a
/pages/index.js file to the project.
Then, create a
TableRow.js file inside of the
/components directory with the code below:
export default ({ creditCard, firstName, loading, lastName, telephone }) => ( <div className="table table-row"> <p className={loading ? 'loading' : ''}> {firstName} {lastName} </p>{' '} <p className={`telephone ${loading ? 'loading' : ''}`}>{telephone}</p> <p className={`credit-card credit-card-number ${loading ? 'loading' : ''}`}> {creditCard && <img src="/icons/visa.svg" />} {creditCard} </p> </div> )
Adding a
/components/TableRow.js file to the project.
Add a build script to the
package.json file which will tell ZEIT Now how to build your project:
{ ... "scripts": { "build": "next build" } }
Adding a
build script to the
package.json file.
Step 4: Writing the Serverless Function
Create the Node.js API endpoint that will fetch the data from FaunaDB by adding an
index.js file to the
/pages/api directory.
The
index.js file will act as the default endpoint for getting information from your database. The file should contain the following code:
const faunadb = require('faunadb') // your secret hash const secret = process.env.FAUNADB_SECRET_KEY const q = faunadb.query const client = new faunadb.Client({ secret }) module.exports = async (req, res) => { try { const dbs = await client.query( q.Map( // iterate each item in result q.Paginate( // make paginatable q.Match( // query index q.Index('all_customers') // specify source ) ), ref => q.Get(ref) // lookup each result by its reference ) ) // ok res.status(200).json(dbs.data) } catch (e) { // something went wrong res.status(500).json({ error: e.message }) } }
An example
/pages/api/index.js file that retrieves information from the database.
Create a
now.json at the root of the project directory, this is used to make the Now Secret defined in step 2 available to the Serverless Function.
{ "env": { "FAUNADB_SECRET_KEY": "@faunadb_secret_key" } }
An example
now.json file that makes a Now Secret available to the application.
Step 5: Deploying
There are two ways to deploy with ZEIT Now. We recommend using a ZEIT Now for Git Integration for ease-of-use. Alternatively, Now CLI can be used to generate a manual Preview Deployment.
To deploy your Next.js + FaunaDB.
|
https://zeit.co/guides/deploying-nextjs-nodejs-and-faunadb-with-zeit-now
|
CC-MAIN-2020-16
|
refinedweb
| 913
| 61.33
|
GNOME 3.8 for openSUSE 12.3 – GO GET ITPosted on April 11th, 2013 45.
37 responses to “GNOME 3.8 for openSUSE 12.3 – GO GET IT”
Dear Dominique,
first of all thanks for the great work. I would like to report a couple of issues that I noticed:
1) First of all, during the installation zypper asks me to remove avahi. I did it, was it ok?
2) In the classic mode, the window list extensions does not work, giving me this error:
Error: Schema org.gnome.shell.extensions.window-list could not be found for extension window-list@gnome-shell-extensions.gcampax.github.com. Please check your installation.
Stack trace:
getSettings()@/usr/share/gnome-shell/extensions/window-list@gnome-shell-extensions.gcampax.github.com/convenience.js:89
()@/usr/share/gnome-shell/extensions/window-list@gnome-shell-extensions.gcampax.github.com/prefs.js:43
wrapper()@/usr/share/gjs-1.0/lang.js:213
buildPrefsWidget()@/usr/share/gnome-shell/extensions/window-list@gnome-shell-extensions.gcampax.github.com/prefs.js:76
(“window-list@gnome-shell-extensions.gcampax.github.com”)@/usr/share/gnome-shell/js/extensionPrefs/main.js:100
wrapper(“window-list@gnome-shell-extensions.gcampax.github.com”)@/usr/share/gjs-1.0/lang.js:213
([object GObject_Object])@/usr/share/gnome-shell/js/extensionPrefs/main.js:119
wrapper([object GObject_Object])@/usr/share/gjs-1.0/lang.js:213
(“window-list@gnome-shell-extensions.gcampax.github.com”)@/usr/share/gnome-shell/js/extensionPrefs/main.js:110
wrapper(“window-list@gnome-shell-extensions.gcampax.github.com”)@/usr/share/gjs-1.0/lang.js:213
([object Object])@/usr/share/gnome-shell/js/extensionPrefs/main.js:219
wrapper([object Object])@/usr/share/gjs-1.0/lang.js:213
_emit(“extensions-loaded”)@/usr/share/gjs-1.0/signals.js:124
([object GObject_Object])@/usr/share/gnome-shell/js/misc/extensionUtils.js:178
wrapper([object GObject_Object])@/usr/share/gjs-1.0/lang.js:213
done()@/usr/share/gnome-shell/js/misc/fileUtils.js:33
([object Array])@/usr/share/gnome-shell/js/misc/fileUtils.js:51
onNextFileComplete([object GObject_Object],[object GObject_Object])@/usr/share/gnome-shell/js/misc/fileUtils.js:21
main([object Array])@/usr/share/gnome-shell/js/extensionPrefs/main.js:276
@:1
3) The Gnome wallet seems not to open at login.
Apart from this, everything is ok! Thanks again
Valerio
If you had enabled forced fallback session, remember to disable it before update.
If you forgot and did the update and cannot log in anymore (just “Oops, something gone wrong. Logout”) press Ctrl+Alt+F1 login as your normal user and type command:
dbus-launch gsettings set org.gnome.desktop.session session-name gnome
Cheers!
Strangiato April 12th, 2013 at 03:07
My monitor goes to stand by mode when I press ctrl+alt+l to block session. Why?
Valerio Mariani April 12th, 2013 at 12:20
Dear Dominique,
I reinstalled and problems 1 and 3 disappeared, so I guess it was something on my side. Problem 2, with the window list extensions stays, however.
Kudos to you and the other developers. That is really the only problem I had. Very very stable release!
Valerio
Great work!
I have one small problem.
NetworkManager don’t provide a way to connect with 3G modem. It worked without problems with 3.6.
Else everything seems to work great!
Installing ModemManager-0.6.0.0 from 12.3 fixed my problem with 3G connections in NetworkManager.
David Mpagi April 13th, 2013 at 02:03
I have updated my openSuse 12.3 to gnome 3.8 but now i can no longer connect to the Internet using my modem. It is as if the system can no longer see my modem. I really need help guys
Valerio Mariani April 13th, 2013 at 11:36
Dear Dominique,
the last update fixed the problem with the Window list extension!
Thank you!
Valerio
David Mpagi April 13th, 2013 at 18:52
Thanks alot Dominique.
Downgrading ModemManager solved the problem. I can now connect Internet from the modem
pibarnas April 14th, 2013 at 02:34
Considering the long cycle of opensuse, why not an live-cd install with gnome 3.8?
Alastair Scott April 14th, 2013 at 16:16
Wonderful work! A couple of minor issues:
1. alacarte fails:
Traceback (most recent call last):
File “/usr/bin/alacarte”, line 22, in
from Alacarte.MainWindow import MainWindow
File “/usr/lib/python2.7/site-packages/Alacarte/MainWindow.py”, line 33, in
from Alacarte.MenuEditor import MenuEditor
File “/usr/lib/python2.7/site-packages/Alacarte/MenuEditor.py”, line 23, in
from Alacarte import util
File “/usr/lib/python2.7/site-packages/Alacarte/util.py”, line 28, in
from gi._glib import GError
ImportError: cannot import name GError
2. (Not part of the core installation, but installable afterwards) gnome-weather fails:
Unsatisfied dependency: Requiring GWeather, version 3.0: Typelib file for namespace ‘GWeather’, version ‘3.0’ not found
But these are minor issues.
Why don’t you give screenshots here? Readers wanna see them.
pandev92 April 21st, 2013 at 01:57
Thank you very much, for you help! now we will wait for 3.8.1 xD!
l300lvl April 21st, 2013 at 18:26
Hi Dominique. Haven’t talked to you in a while, but I was just curious: Is your broken/3.8 repo stable still? I switched over to stable and haven’t seen any updates in a couple days, will 3.8.1 make it to stable soon?
-Gratz,
Craig
l300lvl April 21st, 2013 at 19:02
Thanks! That’s exactly what I was wondering, I am excited, cant wait to see that update notification. 😀
I use openSUSE 12.3 64bit on an AMD quad core processor and yesterday I made the upgrade from Gnome 3.6.3.to 3.8 using the two zypper commands and all went well. It took a while to download and install but on reboot it was all there.
I did the upgrade because I was frustrated with a bug that was in Evolution mail that hung whenever I scrolled through my mails. Thank the Lord that 3.8 has cured that problem.
I notice a few small quirks that that aren’t major.
1. I added a new email address in Evolution’s contacts and the contact list disappeared. It wouldn’t come back until I reloaded Evolution. It happened again moving from mail to contacts. Unfortunately (or is it fortunately?) it has stopped now and I haven’t been able reproduce it. Maybe someone else has experienced this too.
2. Sometimes when I switch to Activities I will just see the outline of the active windows. It’s no big deal as you still have the description under each window. I can’t produce this on demand so can’t help you put a finger on it.
The Activities Classic view is okay but I still prefer the categories we used to have on the right. I find using the Search a pain. It would be nice if one could offer both.
Otherwise it seems to be working great.
Brandon April 24th, 2013 at 22:56
@Strangiato, because the gnome devs have decided your computer screen should behave the same way as a tablet
Brandon April 25th, 2013 at 00:10
Upgraded today, almost no problems, you guys did a great job packaging this, much better than ubuntu’s gnome 3.8 ppa 🙂
Only problem I have is that the yast software manager gtk UI really seems to dislike gnome 3.8. Whenever I open it the window is unusably small so I have to manually resize it every single time 🙁
Brandon April 25th, 2013 at 00:19
@Garth
I have the same problem in the overview where I sometimes only see the “outline” of the windows (well I can sort of see the window but its like 80% transparent)
intel graphics?
Markus Kohler April 25th, 2013 at 11:01
Alacarte does not fully work for me.
“New Item” seems to be broken:
File “/usr/lib/python2.7/site-packages/Alacarte/MainWindow.py”, line 258, in on_new_item_button_clicked
editor = LauncherEditor(self.main_window, file_path)
AttributeError: ‘MainWindow’ object has no attribute ‘main_window’
Anyone has the same problem?
Regards,
Markus
Dustin April 25th, 2013 at 23:06
@Brandon I am also experiencing those two issues. The activities thing doesn’t bother me at all, but the YaST windows drive me insane!! I am also running intel graphics (surprise, surprise lol) Let me know if someone finds an explanation and/or solution to this. One other issue I am having is with the tracker constantly showing IO on the hard drive and using way too much ram unless I kill it. It was at 680MB earlier. I have not had a chance to research this so the answer may just be a google search away. I can honestly say that these are minor quirks and, when it comes down to it, 3.8 is a must have upgrade 😀
Arnel Borja May 3rd, 2013 at 12:15
The update yesterday broke NetworkManager in my notebook. /etc/resolv.conf is no longer updated automatically by NetworkManager, and I have to update it manually when I change connections. I reinstalled the older packages using:
sudo zypper in –oldpackage /var/cache/zypp/packages/GS38/x86_64/libnm-glib4-0.9.8.0-2.1.x86_64.rpm /var/cache/zypp/packages/GS38/x86_64/libnm-glib-vpn1-0.9.8.0-2.1.x86_64.rpm /var/cache/zypp/packages/GS38/x86_64/libnm-util2-0.9.8.0-2.1.x86_64.rpm /var/cache/zypp/packages/GS38/x86_64/NetworkManager-0.9.8.0-2.1.x86_64.rpm /var/cache/zypp/packages/GS38/x86_64/typelib-1_0-NetworkManager-1_0-0.9.8.0-2.1.x86_64.rpm /var/cache/zypp/packages/GS38/x86_64/typelib-1_0-NMClient-1_0-0.9.8.0-2.1.x86_64.rpm
and now it’s working again.
Paul Heine May 4th, 2013 at 15:05
Hi Dominique
Gnome-weather extension not working properly in openSUSE 12.3 / Gnome 3.8
Although info displays for US city, South African city does not display properly.
Solanuz May 13th, 2013 at 12:04
Hi Dominique,
thanks a lot for your work… I have two main issues and one additional question now:
* I can’t seem to get my Open-VPN connection going in my second account (on the account I created during installation, it works) [also, related: the network indicator doesn’t indicate anything on that particular account – not Wifi, not 3G, and of course no VPN either]
* Firefox doesn’t seem to show web fonts any more, so pages like arstechnica.com look very broken (which is curious given that Firefox is not Gnome software, but it worked on the live CD, so I assume your repo broke something there) [yes, I tried with a clean OS user on a clean FF profile; and I tried downgrading FF to version 19 again, too]
* Also, the question: Is there some way to get XInput 2.3, so we all get to experience the improvements made to the messaging tray or is that just too much work?
Solanuz May 13th, 2013 at 20:24
Hi Dominique,
thanks for the quick answer & helpful hints!
I fixed #2 with the fontconfig version from M17N, as I already had the newest version available from the GS3.8 repo. So, that’s much better now.
In the case of #1, adding more groups and permissions didn’t help so far. Also, the problem appears even on a clean new account. I may try with a bug report…
And #3 is of course no biggie. 🙂
Thomas50 May 14th, 2013 at 20:59
Hi Dominique,
thanks for the great work, folks.
I run 12.3 with Gnome 3.8.1 now, and it looks like to work properly. Have changed from LinuxMint Maya.
So please go on in this way. Well done.
Greetings from Germany,
Thomas 50
Brandon May 15th, 2013 at 15:40
@Dominique Leuenberger
Could we get a new libmozjs in this repo? Gnome 3.6 has a massive memory leak:
Its fixed in 3.8, but ONLY with a newer libmozjs package. opensuse 12.3 does not seem to have a new enough package because I still see the leak after updating from gnome:stable. Easily reproduced by rapidly clicking the calendar in the panel, watch the memory usage rise 1-2mb with each click and never go down. I’m not sure exactly what verion is supposed to fix it though.
I installed just now and Eclipse with Android Development Tools (ADT bundle) stopped working. It would start and then crash during a compile or some help popup rendering. Uninstall did not solve the problem. I recovered by re-installing the whole OS.
chojin August 29th, 2013 at 06:55
I tried upgrading to Gnome 3.8, but I get some dependancy errors
# zypper dup –from GS38
Probleem: tracker-miner-firefox-0.14.4-2.1.2.x86_64 vereist tracker = 0.14.4, Maar aan deze eis kan niet voldaan worden
Probleem: gtali-lang-3.6.1-2.8.1.noarch vereist gtali = 3.6.1, Maar aan deze eis kan niet voldaan worden
I can live with the missing gtali-lang package, as this is only a lang package. But tracker-miner-firefox-0.16 seems to be missing from the GS38 repo?
8 Trackbacks / Pingbacks
Instalar el repositorio estable de GNOME 3.8 en openSUSE 12.3 | La mirada del replicante April 12th, 2013 at 10:58
[…] segura, en forma de repositorio experimental para testing. Dominique Leuenberger nos vuelve a anunciar en su blog, que después de trabajar día y noche, el equipo de openSUSE GNOME ha conseguido liberar el […]
[…] well, some critical package is not there, I assume. Did you follow the procedure described here ? GNOME 3.8 for openSUSE 12.3 – GO GET IT @ Dominique a.k.a. DimStar (Dim*) GNOME 3.6.2 / openSUSE Release 12.3 (Dartmouth) 64-bit Kernel Linux 3.7.10-1.1-desktop […]
[…] и activities На днях появился стабильный репозиторий с 3.8 GNOME 3.8 for openSUSE 12.3 – GO GET IT @ Dominique a.k.a. DimStar (Dim*) Но проблему с переключением языка в шеле по-моему не […]
[…] you heard all the buzz about installing GNOME 3.8 on openSUSE 12.3? You love GNOME, but still are ‘stuck’ in the old way of working and heard that the […]
[…] RAID 1) for /home. I am running openSUSE 12.3 and I upgraded to Gnome 3.8 via a repo available here. So I have two problems on the table. For one, if I install the Nvidia drivers, my desktop goes […]
[…] a fairly safe, as a repository for experimental testing. Dominique Leuenbergerreturns us to advertise on your blog , that after working day and night, the openSUSE GNOME team has successfully unleashed the […]
[…] agréable, Gnome y est proposé en version 3.6 (mise à jours vers Gnome-3.8 disponible via le => dépôt Gnome-Stable). Le cycle de développement d‘OpenSuse est (je trouve) assez intéressant, dans le sens où […]
[…] However, if you are not an English speaking user, Dominique warns: […]
-
Valerio Mariani April 12th, 2013 at 00:37
|
http://dominique.leuenberger.net/blog/2013/04/gnome-3-8-for-opensuse-12-3-go-get-it/
|
CC-MAIN-2016-30
|
refinedweb
| 2,524
| 59.6
|
>>
Shortest Word Distance II in C++
Suppose there is a class that receives a list of words in the constructor, there will be a method that takes two words word1 and word2 and find the shortest distance between these two words in the list. That method will be called repeatedly many times with different parameters.
Let us assume that words = ["practice", "makes", "perfect", "skill", "makes"].
So, if the input is like word1 = “skill”, word2 = “practice”, then the output will be 3
To solve this, we will follow these steps −
Define one map m
The initializer takes an array of words
for initialize i := 0, when i < size of words, update (increase i by 1), do −
insert i at the end of m[words[i]]
Define a function shortest(), this will take word1, word2,
Define an array arr1 := m[word1]
Define an array arr2 := m[word2]
i := 0, j := 0
ret := infinity
while (i < size of arr1 and j < size of arr2), do −
ret := minimum of ret and |arr1[i] - arr2[j]|
if arr1[i] < arr2[j], then −
(increase i by 1)
Otherwise
(increase j by 1)
return ret
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class WordDistance { public: unordered_map <string, vector <int< > m; WordDistance(vector<string<& words) { for(int i = 0; i < words.size(); i++){ m[words[i]].push_back(i); } } int shortest(string word1, string word2) { vector<int<& arr1 = m[word1]; vector<int<& arr2 = m[word2]; int i = 0; int j = 0; int ret = INT_MAX; while (i < arr1.size() && j < arr2.size()) { ret = min(ret, abs(arr1[i] - arr2[j])); if (arr1[i] < arr2[j]) { i++; } else j++; } return ret; } }; main(){ vector<string< v = {"practice", "makes", "perfect", "skill","makes"}; WordDistance ob(v); cout << (ob.shortest("skill", "practice")) << endl; cout << (ob.shortest("makes", "skill")); }
Input
{"practice", "makes", "perfect", "skill", "makes"} Call shortest("skill", "practice") Call shortest("makes", "skill")
Output
3 1
- Related Questions & Answers
- Shortest Word Distance III in C++
- Shortest Completing Word in Python
- Word Break II in Python
- Word Search II in Python
- Word Pattern II in C++
- Shortest distance between objects in JavaScript
- Corresponding shortest distance in string in JavaScript
- Shortest Distance to Target Color in C++
- Shortest Distance from All Buildings in C++
- Finding shortest word in a string in JavaScript
- Word Ladder (Length of shortest chain to reach a target word) in C++
- C++ code to get shortest distance from circular stations
- Find Shortest distance from a guard in a Bankin Python
- C++ Program to find the Shortest Distance to a character
- Program to find distance of shortest bridge between islands in Python
|
https://www.tutorialspoint.com/shortest-word-distance-ii-in-cplusplus
|
CC-MAIN-2022-33
|
refinedweb
| 438
| 51.65
|
This patch adds notification whenever a vm starts or stops. Signed-off-by: Anthony Liguori <aliguori us ibm com> diff --git a/vl.c b/vl.c index f78cabb..ca0bcf9 100644 --- a/vl.c +++ b/vl.c @@ -164,6 +164,8 @@ int main(int argc, char **argv) #include "libslirp.h" #endif +#include "wait.h" + //#define DEBUG_UNUSED_IOPORT //#define DEBUG_IOPORT //#define DEBUG_NET @@ -3545,6 +3547,11 @@ static void vm_state_notify(int running, int reason) { VMChangeStateEntry *e; + if (running) + qemu_notify_event("vm-state", "start", ""); + else + qemu_notify_event("vm-state", "stop", ""); + for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) { e->cb(e->opaque, running, reason); } diff --git a/wait-events.c b/wait-events.c index 3617ca6..ecd26d2 100644 --- a/wait-events.c +++ b/wait-events.c @@ -31,10 +31,24 @@ typedef struct EventClassDesc } EventClassDesc; static const EventDesc vm_state_events[] = { + { "start", "the VM was started", + "This event occurs whenever a VM's state changes from stopped to\n" + "started. A vm initially is in a stopped state so a start event will\n" + "always occur when the vm is first launched unless the -S option is\n" + "provided.", + NULL, }, + { "stop", "the VM was stopped", + "This event occurs whenever a VM's state changes from started to stopped\n" + "A vm initially is in the stopped state but no notification is generated\n" + "by this.", + NULL, }, { 0 }, }; static const EventClassDesc vm_event_classes[] = { + { "vm-state", "the VM start/stop state has changed", + "These events occur whenever a VM's state changes.", + vm_state_events, }, { 0 }, };
|
https://www.redhat.com/archives/libvir-list/2009-April/msg00182.html
|
CC-MAIN-2015-11
|
refinedweb
| 243
| 58.69
|
J...
object is used for returning the URL of the current JSP page.Example
:
Implicit Objects In JSP
;
config : An implicit object config, specifies the
configuration of JSP page'... : An implicit object page, specifies the current
JSP page. This object is an instance...Implicit Objects In JSP
In this section we will read about the implicit
implicit objects in jsp
implicit objects in jsp hello,
how many implicit objects in jsp???
hello,
I am giving implicit object
out,config,page,application,request,page context,response,session
JSP implicit object "application"
JSP IMPLICIT OBJECT application
In this section, we will discuss about JSP implicit object 'application'
and it's uses with an example. Using... in an application. It means the "application" object is
accessed by any JSP
JSP Implicit object "session"
JSP IMPLICIT OBJECT "SESSION"In this Section , we will discuss about JSP implicit object "session" with an
example. Session Object... of
object as string's value and you can get this value in other JSP page
JSP implicit object out
JSP implicit object out
In this Section, we will discuss about implicit object out & it's methods.
Out object denotes the Output
stream...;jsp.JspWriter". This object is instantiated implicitly from JSP Writer
class
JSP implicit object "pagecontext"
JSP IMPLICIT OBJECT pagecontext
A PageContext instance provides access to all the namespaces associated with
a JSP page, provides access to several... and pageContext are implicit JSP Objects.
The page object represents
JSP Implicit Objects
JSP Implicit Objects What are implicit objects in JSP? and provide List them?
Thanks in advance
Hi,
In the JSP, the web container... request, page, and application. The list of this type of object is:
request
Request Object In JSP
Request Object In JSP
This section illustrates more about the JSP implicit
object called... to the server, is received by the HTTP request
object of the JSP. To access
Page object - JSP-Servlet
of PAGE object of implicit JSP object. If this is possible explain me about....... Hi friend,
Implicit Objects in JSP are objects that are automatically available in JSP. Implicit Objects are Java objects that the JSP
Binding Component Value to an Implicit Object
provides list of implicit objects. These objects
can be referred in value attribute of component in the JSP page.
Implicit Object
Description...Binding Component Value to an Implicit Object
JSP Implicit Objects
Implicit objects in jsp are the objects that are
created by the container... objects. Here is the list of
all the implicit objects:
Application: This object
JSP Implicit Objects
JSP Implicit Objects
Implicit objects in jsp are the objects that are
created... stream.
Page: This object has a page scope and is an instance of
the JSP
Insert an object with the add(Object) method
at the end of a list
using the add(Object) method. Here is an example that
provides the usage of the add(Object) method in more detail.
Create a class "...
Insert an
object with the add(Object) method
More than 1 preparedStatement object - Java Beginners
More than 1 preparedStatement object Hey but I want to use more than one prepared Statement object using batch update..
Explain with a code using java...
Thanks Hi Friend,
You can use more than one prepared
Insert an element with the add(int, Object) method
an element at the specified position using the add(int,
Object) method.
Here is an example that provides the usage of the add(int, Object) method in
more detail...
Insert an element with the add(int, Object) method
implect object
implect object how i implment implect object
Hi Friend,
Please visit the following links:
Thanks
jsp object retrieval - Spring
jsp object retrieval I have a controller which calls a Service to build a List of data from the database. I want to pass the List to the jsp to use.... However, I am concerned this object could be huge in some instances. Any
bean object
;
For more information, visit the following links:... in jsp page.
1)Bean.java:
package form;
import java.sql.*;
import...);
RequestDispatcher rd = req.getRequestDispatcher("/jsp/beandata.jsp
Implicit objects
Implicit objects What are the implicit objects
jsp
jsp In any jsp all implicit objects are available directly, in such a case why we need PageContext object again
Html tag inside out implicit object
Html tag inside out implicit object
... a html tag inside a
out object. out object is used to display the content on the browser. To make
this program run use out object inside which define some html
JSP
what are the implicit el objects in JSP what are the implicit el objects in jsp
Implicit objects in jsp are the objects.../o/jsp-implicit-objects.shtml
JSP
what are the implicit el objects in jsp what are the implicit el objects in jsp
Implicit objects in jsp are the objects.../jsp-implicit-objects.shtml
Accessing Session Object
a jsp page for viewing the session
object, session context and session time...Accessing Session Object
... resources like the session object, session context and
the last accessed session
ADD ROW - JSP-Servlet
ADD ROW Hi Sir,
How to use add row and delete row concept in jsp . Hi Friend,
Please visit the following link:
Thanks
JavaScript add method
a dropdown list in
HTML and we have added a button which will add one more option... will click on the "Add" button
it will add one more option to the list...
JavaScript add method
Replace an object with set(int, Object) method
that provides the usage of the set(int, object) method in
more detail.
Create... objects using the add(int,object) method.
Now replace an object from a particular...
Replace an object with set(int, Object) method
JSP
JSP what are different implicit objects of jsp
mplicit... the following link:
..., visit the following... will have a name-value pair attribute.
JSP has a built in object request
how to add the calendar to the dynamic rows in html or jsp page - JSP-Servlet
how to add the calendar to the dynamic rows in html or jsp page ...,no and i have 2 button in my jsp page ADD and delete button. when i click on add... can save the 2 or more row values at a time but i need to add the calenadar
More About Triggers
Calendar object
to add and exclude with it:
HolidayCalendar hcal = new HolidayCalendar...
More About Triggers
... (not java.util.Calendar) objects
can be associated with triggers object at the time
Preventing the creation of a Session in a Jsp Page
have been provided the implicit session
object. In jsp the session... of the field by using the
request.getParameter(), request is the implicit object...Preventing the creation of a Session in a Jsp
Page is denoted with this object. The response object handles the output
JSP Session Object
JSP Session Object JSP Session Object?
Session Object... or the interface name of the object session is http.HttpSession. The object session is written as:
Javax.servlet.http.httpsession.
The Session Object provides
more circles - Java Beginners
more circles Write an application that uses Circle class you created... createCircle() that
o reads a radius of a circle from the user
o creates a circle object, and
o returns the object.
? The program creates a circle object by using
EL Implicit Objects
- Implicit Objects</title>
</head>
<body>
<h6>JSP...EL Implicit Objects
EL is the JSP 2.0 Expression Language Interpreter from
getQueryString() Method Of The Request Object
the getQueryString()
method of the request object. Here, you will learn more... getQueryString() Method Of The Request Object... of the method and how to implement it
into your JSP application code. You can directly copy
JSP Request Object
JSP Request Object JSP Request Object ?
request object in JSP is used to get the values that the client passes to the web server during an HTTP request. The request object is used to take the value from the client?s
removeAttribute() Method Of The Request Object
the removeAttribute()
method of the request object in JSP by learning through... removeAttribute() Method Of The Request Object... for the method removeAttribute()
of the request object. This method removes
Track user's session using 'session' object in JSP
Track user's session using 'session' object in JSP
This section is about tracking user identity across different JSP pages using
'session... provides an implicit object called session which can be
used to work add
How to add Hi,
I want to make a website which will recommend users books according to the genre selected by them. I am using PHP, JavaScript and mySQL.
The problem is that there will me almost more than 100 books
load more with jquery
load more with jquery i am using jquery to loadmore "posts" from my... box its is going to display php posts and after that when i click on load more...);
$('#loadmorebutton').html('Load More
getParameterValues() Method Of The Request Object
retrieved by the getParameterValues() method of the request
object.
Here is the JSP...
getParameterValues() Method Of The Request Object... about the getParameterValues()
method of the request object. Here, you will learn
JSP FUNDAMENTALS
:
It
is also an implicit object of class...:
It
is also an implicit object of class...JSP
FUNDAMENTALS
Object
Object
An object...). In an
object, variables store values for later use and methods are the unit... are the basic units
of the object-oriented programming.
Objects are the part of our day
getParameterNames() Method Of The Request Object
getParameterNames() Method Of The Request Object... the detailed explanation about
the getParameterNames() method of the request object. You
will learn more about the procedure of using the getParameterNames()
method
how to add two object in a particular file - Java Beginners
how to add two object in a particular file Hi frend..
I have two arraylist object in which there is some data..............now i want to add...{
JButton ADD,RETRIEVE;
JPanel panel,pan;
JLabel
java - JSP-Interview Questions
java 1. why implicit object "Exception" is difference from other implicit objects?
2. what is the meaning of exception page & exception in jsp directive" />
<
ArrayList object
ArrayList object i have am ArrayList object it containg data base records in it,
now i want to display this ArrayList object data in my jsp programe,
plz help me
object as argument
object as argument what happens when we pass a object into a method???if java is pass by value how does this makes a difference.....pllzzz give me more clarification on why we pass objects in a margument
object array
object array Hi
i have array that is object[] obj= { new string("hi"), new vector().add(10), new hashmap().setkey()}
display(obj);
display(object{[] obj) {}
Now my question is what is the string length and how to retrieve
Session Object
be saved in a Session Object ?
There is no such limit on the amount of information that can be saved in a Session Object. The only limit is the Session ID length , which should not exceed more than 4K
request object - JSP-Servlet
object and method
object and method a college would like to automate managing courses... number of students allowed (quota) which is 10. a user should be able to add\drop... and an application that creates the necessary object
Add and Delete Element Using Javascript in JSP
Add and Delete Element Using Javascript in JSP... :
Add one person :
Add more then one person... developed an application to
add and delete element using javascript . We created two
more doubts sir. - Java Beginners
in the bottom of the page.sir i also need to add some more buttons as in internet exoplorer such as search bar and some more buttons.Sir help me out...more doubts sir. Hello sir,
Sir i have executed your code
Java Object
Java Object
Object is the basic entity of object oriented
programming language. Object... properties of the class or its group. Java object
is an instance of the class. It takes
Request Object In JSP.
move an object
");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Ball
JSP Tutorials - Page2
In JSP
This section illustrates more about the JSP implicit
object... in
kilobytes i.e. used by the out object to handle output generated by the JSP page... object. You
will learn more about the procedure of using the getParameterNames
J2EE - JSP-Servlet
friend,
Difference between JSP and Servlet :
Jsp have implicit object but servlet are not.
Jsp is more convenient to write (and to modify!) regular HTML than... class..whereas jsp is not
Servlet is more faster than JSP, but JSP is....
9)You jsp program will then display the output on the browser.
For more
Bussiness Object API - JSP-Servlet
Bussiness Object API I m feteching the reports from CMS server and displaying the report on web page . the problem is that displaying a report takes... = (IReportSourceFactory)enterpriseSession.getService("PSReportFactory");
Object
JavaScript remove method
;
As JavaScript's add() method is used to add more option elements... :
select_object.remove(selected_index);
Where select_object holds... removeItem() takes the element object and then removes
the element.selectedIndex item
remove and add div jquery
remove and add div jquery I want to enable my users to remove or add DIV using JQuery.
$('.add_more').click(function(){
var description = $('#description').val();
$newEl = $('<div class="description_text
session in jsp - Java Beginners
Hi friend,
session is implicit object in jsp.
using session oject in jsp.
first u set using following methods
String name... let me know how to create a session in jsp.
Session for jsp with two side
PHP Date add 1 year
program.
<?php
//Example to add 1 year to a date object...
Adding 1 year to a php date object is sometimes useful to solve some programming problem. You can add 365 days to year, but the php provides method
java - JSP-Servlet
implicit objects, No need to instantiate any which is easier.
Jsp error... and reload the page.
For Read More Information: what is the difference between jsp and servlet?
Hi
java - JSP-Servlet
difference between Jsp and Servlet
Jsp is better for view web pages, while servlet is good for request processing.
Jsp has also all implicit objects... More Information:
javascript add seconds to time.
will not exceed to 59.If it is more than 59 then convert seconds into minutes and add...javascript add seconds to time. <html>
<head>
<title>Add seconds to current times</title>
<script type="text/javascript
Container - add() - Framework
Container - add() add(Component comp)
Appends the specified component to the end of this container.
This add method from Container class... to add the component c2 but at the same time, I want to delete the component entry
Introduction to the JSP Java Server Pages
This section illustrates more about the JSP implicit
object called Request... the Jsp page.
Html
tag inside out implicit object... the user data and objects
throughout the application. JSP provide an implicit
javascript add seconds to time.
will not exceed to 59.If it is more than 59 then convert seconds into minutes and add...javascript add seconds to time. I want to add seconds to time. How can I do this?
<html>
<head>
<title>Add seconds
add record to database - JDBC
add record to database How to create program in java that can save record in database ? Hi friend,
import java.io.*;
import java.sql....
-------------------------------------
read for more information,
http
|
http://www.roseindia.net/tutorialhelp/comment/22946
|
CC-MAIN-2014-52
|
refinedweb
| 2,556
| 57.16
|
One of the most useful things you can do with an Arduino is use it to control higher voltage electronic devices. Any device you normally plug into a wall outlet can be activated by a sensor or controlled in other ways with the Arduino. The possibilities are endless considering the variety of sensors and modules available to us today.
In this tutorial, we’ll be using a 5V relay to switch the current to a power outlet on and off. We’ll use the Arduino and a sensor to control when the relay switches. To learn more about the 5V relay and it’s different modes of operation, see our article “How to Set Up a 5V Relay on the Arduino“.
We could always wire the relay directly to the device we want to control, but it’s more practical to go one step closer to the source and switch the power at the outlet. That way you can use it for multiple devices without having to re-wire the relay or cut into the device’s power supply. In this project, we’ll connect a power outlet box to a grounded extension cord and install a 5V relay inside the box so we can control it with the Arduino.
Building the Arduino Controlled Power Outlet
WARNING!! – THIS PROJECT INVOLVES WORKING WITH HIGH VOLTAGES THAT CAN CAUSE SERIOUS INJURY, DEATH, AND/OR SET YOUR HOUSE ON FIRE. PLEASE PROCEED WITH CAUTION, AND ALWAYS MAKE SURE CIRCUITS ARE UN-PLUGGED BEFORE WORKING ON THEM.
We will install the 5V relay in-line with the positive (hot) wire of the 120-240V power outlet in the normally open configuration. The negative (neutral) wire and the ground wire will be connected directly from the power cord to the outlet. The 5V relay will turn on the current to the outlet whenever it receives a 5V signal from the Arduino.
Here’s a diagram that outlines the connections:
Gather the Parts
The parts I used are listed below, but you can use other types. This is just what I found at my local Home Depot. I’ve included links to these parts on Amazon so you can get an idea of what they cost, but I got everything (except the Arduino) for under $22.00 USD.
- Arduino UNO R3
- SRD-05VDC-SL-C 5V Relay
- Electrical Outlet Box
- Electrical Outlet
- Electrical Outlet Box Cover Plate
- 3/8″ NM/SE Connector
- Power Strip
- Signal, Vcc, and Ground Wires
/>
Constructing the Box
Cut the cord on the power strip and determine which wire connects to each prong on the plug with a homemade continuity tester. My cord has three wires. The neutral (white) wire is connected to the larger prong, the hot (black) wire is connected to the smaller prong, and the ground (green) wire is connected to the round prong:
/>
Remove one of the knock out plugs from the electrical outlet box:
/>
Install the NM/SE Connector:
/>
/>
Remove about 3 to 4 inches of the outer plastic sheathing from the electrical cord, then feed it into the box through the NM/SE connector:
/>
Wiring the Relay
Cut a 4 inch piece of the hot wire and strip off about 1/4 inch of the insulation. Insert it into the NO terminal of the relay and tighten the screw on the relay terminal to make a secure connection. Now is a good time to strip the other end of this wire so we can connect it to the electrical outlet later:
/>
Connect the signal, Vcc, and ground wires to the relay:
/>
Strip the neutral and ground wires on the electrical cord so they have about 3/4 inch of exposed copper. We’ll connect these to the power outlet later. The hot wire only needs about 1/4 inch since it will be inserted into the C terminal of the relay:
/>
Insert the hot wire from the electrical cord into the common (C) terminal of the relay. Double check that both terminals of the relay are securely screwed down:
/>
Connecting the Hot, Neutral, and Ground Wires to the Electrical Outlet
/>
The right side of the power outlet with the smaller slot is the hot side of the outlet. The hot (black) wire from the NO terminal of the relay will be screwed to the hot terminal with one of the gold colored screws:
/>
The left side of the outlet with the larger slot is the neutral side. The neutral (white) wire from the power cord will be screwed to the neutral terminal with one of the silver colored screws:
/>
The D shaped slots are for the ground prong. The ground (green) wire from the power cord will be screwed to the ground terminal with the green screw:
/>
Before connecting the wires to the outlet, position the relay and all of the wires inside the box to make sure it fits well. Now is a good time to trim the wires and tighten the screws on the NM/SE connector:
/>
Now connect the ground wire to the ground terminal of the outlet:
/>
Connect the neutral wire to the neutral terminal of the outlet:
/>
Connect the hot wire from the relay to the hot terminal of the outlet:
/>
Now that all of the electrical connections have been made we can screw the outlet into place in the electrical outlet box:
/>
Attach the electrical box cover plate:
/>
And we’re done. Now we have a 120V electrical outlet that can be controlled by an Arduino. Everything looks clean, and the relay control wires are ready for a breadboard:
/>
/>
Testing it Out
Let’s test out the Arduino controlled power outlet by programming a light fixture to turn off when the humidity gets above a certain point. To make this circuit you’ll need a DHT11 humidity and temperature sensor.
Connecting the Arduino
Follow this diagram to make the connections:
/>
Programming the Arduino
After making all of the connections, we’re ready to program the Arduino. Upload this program to the board to control the outlet with the DHT11:
#include <dht.h>); }
This program takes the humidity data output by the DHT11 and tells the Arduino to output a HIGH signal at pin 8 until the humidity reaches 40% or greater. Therefore, the light bulb will be on below 40% relative humidity. If the humidity goes above 40%, the program tells the Arduino to output a LOW signal at pin 8, and the light bulb will be switched off.
You can change the humidity at which the relay turns on/off in line 20 (if (DHT.humidity <= 40){). You can also use the temperature data instead of the humidity (or use both) by changing DHT.humidity to DHT.temperature.
/>
Thanks for reading! This has probably been one of the most useful things I’ve built so far. You should definitely build one for yourself, especially if you’re interested in controlling devices around your home. Let me know in the comments if you have any questions about this project, and be sure to share it if you know someone else that might enjoy it too!
Just a simple 5V or 12V relay is enough to achieve this TECH…
Hey, I just wanted to let you know that I really enjoy and benefit from your projects! I think you have done a great job laying things out in a step by step manner that doesn’t miss anything, which makes it much easier to learn and follow along. Great job NOT leaving out any necessary bits of info!!! Keep up the good work, and I hope to see more your stuff in the future. Thanks!
Thanks a lot! I try to make sure to include everything necessary to set up a project, but let me know if I miss anything or if something doesn’t work!
HI im hving problem with the coding. when i want to verify, it says erorr compiling.
“Arduino: 1.6.5 (Windows 7), Board: “Arduino/Genuino Uno”
sketch_aug24b.ino:1:17: fatal error: dht.h: No such file or directory
compilation terminated.
Error compiling.
This report would have more information with
“Show verbose output during compilation”
enabled in File > Preferences.”
how do i solve this?
That means that the file “dht.h” on line 17 you are calling doesn’t exist or you don’t have it in the folder.
thankyou for responding. Do you have any idea on how to solve this? your help is really appreciated.
There is no button to reply to you so I’ll reply here.
Basically if you need that file, it’s just an import file, then you can remove the line. If u need it then you have to keep it.
thanks for responding again Ben.
i wanna make the lights off if i blow the sensor.
can put this on line 20 in the coding.
“if (DHT.humidity = 57){ // RELAY TURNS OFF ”
is it right? because it doesnt work after i upload it on board.
hello leveraging your project may indicate how to install other rele temperature
Reley 1 35.5ºc temperature (on 34-35 of 35.5)
Reley 2 humidity 40% (on 35-39 of 40)
greetings
Would an outlet like this work triggering an aquarium water pump running at like 4 or possibly 15 W ?
Yeah it would… You can use any sensor to trigger the relay, I just used a DHT11 as an example
I love the article but just had a question. Seems to be a weird senerio…
So I believe everything is hooked up correctly, but I have a GFCI outlet and the reset engages every time the signal gets sent. So if I start with the 5v pin out, as soon as it starts to go in, I blow the outlet. Same with the 8 pin.
Any help would be great!
Turn off arduino, unplug outlet. Plug in pins, then plugin arduino and outlet. Does that work?
I prefer to use a solid state relay. Easier and beefier.
Same for me, the reset engages every time the signal is sent. Did you get a solution for this?
My solution was to just change it to a non GFCI outlet. I never had any problems. I had it plugged into a surg protected outlet anyway.
I assume it was because of spikes of current or something, but not my expertise. But never had problems after switching.
thanks for this
Beware: 240V in most American homes is available as the voltage between (2) 120V “hot” phases (wires); interrupting only one of them means that the other remains “hot”, and potentially lethal, at the load–even when it’s “off.”
Instead, use a DPDT breaker, something like this:
to interrupt bofth the hot legs.
Or websearch this (which today led me to ebay.ca):
5V 2 Channel Relay Module Shield For Arduino ARM PIC AVR DSP MCU Electronic F5
Then follow the instructions above, using one channel for each leg.
Good job. everything (even these chats) was helpful. great. THANK YOU VERY MUCH..
Hi.Tanx for all your help. My problem is with the sketch. Where can i find dht.h library?
Does this just connect one if the outlets to the Arduino? Is it possible to split the hot wire and run it through a two channel switch to control each outlet separately? Thank you for the tutorial it looks great!
Yes, I actually did this at home. It was super fun. One control for top, one control for bottom, one for both together.
I just ran a hot wire and split it two two using a wire nut and ran one wire into each relay (two relay module). Then one wire going to top, one wire to bottom.
You do have to break the copper bridge in between the top and bottom on the side of the outlet. I am not sure how much you know about electrical, but I learned at this. So this might not be the best way but it works.
5V Two 2 Channel Relay Module With optocoupler Compatible With Arduino PIC AVR DSP ARM by Atomic Market
Just an example of where you can buy a 2 channel relay.
Hi !
First of all I really loved your article, it was very useful and explicative. Is it possible to adapt this project to control the light switches, I mean I want my lights (those ones that the switches are on the wall) to be smart, and replace those switches with a relay and an Arduino in order to turn on the lights at night. I know the answer is yes but I don’t know pretty much about electrical connections. Thank you in advance.
Dear friend
Thank you for your soooo well explained example.. I just followed it step by step and.. it worked!
I did a couple of pictures and uploaded a post to my own blog
Next step: Now i would like to make it work from an smartphone.. :)
Thank you
Thanks for the info! I’m looking to do basically what you have shown except the device I need to power is a little more heavy duty. I would need a relay that has a 5vdc coiled well because I’m using an arduino, but need to power a 240v ac 20amp device. Anyone have a suggestion on a good relay for this ? Thank you.
Anything like this works. No matter the voltage. It is controlled by 5v but can run high volts through it.
That’s a really illustrative go through for novices such as me into arduino and pi stuff for automation. I was hoping I could bother you with a few questions. I have been wanting to build a cheap water filter for heavy metal remediation and it asks for a time interval based control of a 240 V aquarium air pump to allow periodic pumping of a volume of water through the filtration media. What would be the best possible source to obtain the lay out or instructions for such a similar build illustrating the time based control of a 240 V appliance using arduino/pi?
Can you please write the program for the following temp. and humidity conditions:
The light should be on (i.e. pinOut, HIGH) for
1) RH>=70 AND Temp>=25
2) RH>=70 AND Temp<=25
3) RH=25
While, the light should remain off (i.e. pinOut, LOW) for
1) RH<=70 AND Temp<=25
I am trying to build something similar but instead of turning the appliance on or off I want to vary the current going to it over time. I wanted to use a digital potentiometer connected to a programmed Arduino. What specifications should I look for in the potentiometer? Also is there a better way of varying the current going to an appliance? Do I still need a relay if I’m using a potentiometer? Thanks
How do I connect the power outlet into an 8 channel 5V DC Relay Board? Is it the same process?
Hey man, could you find any info?
Hey, did you find any info about this?
this is not working.. i changed dht to DHT to match the library name
#include);
}
Do you fixed it now? Is it working now sir?
Hello,
Am doing a project ; Fingerprint Authenticated Device switcher.
Am trying to use the fingerprint scanner to switch on and off the outputs of my arduino. Meaning;
– Only when i insert my fingerprint, the arduino will be switched on giving access to my bluetooth module in my arduino so that i can access the devices connected to the outputs of the arduino.
– And when i re-insert my fingerprint, the arduino will close or switch off all connections linked to it.
My problem is; i can’t figure out how to write the program to do these tasks.
You’ve got any advice or helpfor me?
How to connect 3 dht11 to arduino in the same time?
Yo your link led me to a scam site. It probably was one of the ads?
Can I put LCD too??
can you do this? but with a Raspberry PI instead of an Arduino UNO?
Thank you for the guide but 1 major issue above is about powering the Arduino itself. A compact solution would be to use a battery but unless u make it rechargeable, eventually u will need to change it. Another way would be to use an ac-dc adapter connected to 1 of the twin ac sockets above but that has got to be always on instead of being controlled. That can be achieved by using 2 individual sockets and daisy-chaining the Live and Neutral wires accordingly. So you will end up with twin sockets but 1 will always have power (for the Arduino) and the other can be used as a controlled socket for other appliances.
Nice
Hye sir,im just curious why you dont use any step down transformer in that project? Is it okey using arduino without step down transformer?
The project above is not powering the Arduino at all. To do so either an on-circuit or external step down transformer needs to be included.
😍😍😍
Jonas Hansen
This is great! One question, if I were to use an adafruit Itsy Bitsy how would I be able to leach off the already supplied 110 power to also power the Arduino rather than use another power source?
Thanks!
Besides using an old usb charger?
Can i connect it to my C# program i created in Visual Studio?
Well done , great article well documented, with plenty of pictures, highly detailed and … not skipping on safety. You should become a teacher.
Pls is there an additional file because i am being told that i don’t have a file by name dht.h and i should try and get that file . Due to this, i keep on receiving an error message
hi,
i need help, how to purchase this device for one villa and connect to an electric switch panel. I also looking business level
I am not able to get output due to error in code as it says ‘dht’ does not name a type..how should i proceed now
Even if i changed it to any other thing then i am getting a error in “if” statement such that unexpected token error…
Hi
If I wanted to control 12v led bulbs, could I use the same setup as above except that I need to use a transformer from the actual mains and use the step down output into the electrical switch?
I’m concerned about the power requirements for the transistor. Arduino I/O pins are only rated at 40ma. The relay datasheet () indicates that at 5V VCC, you will need 71.4ma to activate the relay. Seems to me that powering your relay switch directly from the Arduino is a bad idea.
Gosh, nvm. The power pins can source 500ma-1A depending on the power to the Arduino.
You shouldnt put the Low voltage relay inside of that electrical box. It doesnt follow electrical code and can be a fire hazard. I would recomend a double gang high/low voltage box so you would have the Relay in its own compartment.
Hello,
Thank you for putting this together. I’m having trouble with the sketch. While compiling I’m getting the following error: expected primary-expression before ‘.’ token. I’m getting this or lines 15, 17, 19 and 20.
You made the blog becomes useful to every household that deals with the power outlet problem. There are things to consider before doing a DIY. Make sure you know how to fix it before trying it.
Hello, I would like to know if I can do a blink program with a strip of LEDs using this circuit? Thanks
So, what do you do with the unusable power strip, now that its
cord has been amputated? Why not just obtain a cord, and
avoid ruining a perfectly good power strip?
Hey y’all I got everything together except for the temp humidity sensor hooked up. The reason I’m stuck is because my sensor is a 4 pin not a 3.
Can someone help me adapt the code and wiring? I’m fairly new to this
|
https://www.circuitbasics.com/build-an-arduino-controlled-power-outlet/?recaptcha-opt-in=true
|
CC-MAIN-2020-29
|
refinedweb
| 3,384
| 71.75
|
## no critic (Modules::ProhibitExcessMainComplexity) package DateTime; use 5.008004; use strict; use warnings; use warnings::register; use namespace::autoclean 0.19; our $VERSION = '1.54'; use Carp; use DateTime::Duration; use DateTime::Helpers; use DateTime::Locale 1.06; use DateTime::TimeZone 2.44; use DateTime::Types; use POSIX qw( floor fmod ); use Params::ValidationCompiler 0.26 qw( validation_for ); use Scalar::Util qw( blessed ); use Try::Tiny; ## no critic (Variables::ProhibitPackageVars) our $IsPurePerl; { my $loaded = 0; unless ( $ENV{PERL_DATETIME_PP} ) { try { require XSLoader; XSLoader::load( __PACKAGE__, exists $DateTime::{VERSION} && ${ $DateTime::{VERSION} } ? ${ $DateTime::{VERSION} } : 42 ); $loaded = 1; $IsPurePerl = 0; } catch { die $_ if $_ && $_ !~ /object version|loadable object/; }; } if ($loaded) { ## no critic (Variables::ProtectPrivateVars) require DateTime::PPExtra unless defined &DateTime::_normalize_tai_seconds; } else { require DateTime::PP; } } # for some reason, overloading doesn't work unless fallback is listed # early. # # 3rd parameter ( $_[2] ) means the parameters are 'reversed'. # see: "Calling conventions for binary operations" in overload docs. # use overload ( fallback => 1, '<=>' => '_compare_overload', 'cmp' => '_string_compare_overload', q{""} => 'stringify', bool => sub {1}, '-' => '_subtract_overload', '+' => '_add_overload', 'eq' => '_string_equals_overload', 'ne' => '_string_not_equals_overload', ); # Have to load this after overloading is defined, after BEGIN blocks # or else weird crashes ensue require DateTime::Infinite; sub MAX_NANOSECONDS () {1_000_000_000} # 1E9 = almost 32 bits sub INFINITY () { 100**100**100**100 } sub NEG_INFINITY () { -1 * ( 100**100**100**100 ) } sub NAN () { INFINITY - INFINITY } sub SECONDS_PER_DAY () {86400} sub duration_class () {'DateTime::Duration'} my ( @MonthLengths, @LeapYearMonthLengths, @QuarterLengths, @LeapYearQuarterLengths, ); BEGIN { @MonthLengths = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); @LeapYearMonthLengths = @MonthLengths; $LeapYearMonthLengths[1]++; @QuarterLengths = ( 90, 91, 92, 92 ); @LeapYearQuarterLengths = @QuarterLengths; $LeapYearQuarterLengths[0]++; } { # I'd rather use Class::Data::Inheritable for this, but there's no # way to add the module-loading behavior to an accessor it # creates, despite what its docs say! my $DefaultLocale; sub DefaultLocale { shift; if (@_) { my $lang = shift; $DefaultLocale = DateTime::Locale->load($lang); } return $DefaultLocale; } } __PACKAGE__->DefaultLocale('en-US'); { my $validator = validation_for( name => '_check_new_params', name_is_optional => 1, params => { year => { type => t('Year') }, month => { type => t('Month'), default => 1, }, new { my $class = shift; my %p = $validator->(@_); Carp::croak( "Invalid day of month (day = $p{day} - month = $p{month} - year = $p{year})\n" ) if $p{day} > 28 && $p{day} > $class->_month_length( $p{year}, $p{month} ); return $class->_new(%p); } } sub _new { my $class = shift; my %p = @_; Carp::croak('Constructor called with reference, we expected a package') if ref $class; # If this method is called from somewhere other than new(), then some of # these defaults may not get applied. $p{month} = 1 unless exists $p{month}; $p{day} = 1 unless exists $p{day}; $p{hour} = 0 unless exists $p{hour}; $p{minute} = 0 unless exists $p{minute}; $p{second} = 0 unless exists $p{second}; $p{nanosecond} = 0 unless exists $p{nanosecond}; $p{time_zone} = $class->_default_time_zone unless exists $p{time_zone}; my $self = bless {}, $class; $self->_set_locale( $p{locale} ); $self->{tz} = ( ref $p{time_zone} ? $p{time_zone} : DateTime::TimeZone->new( name => $p{time_zone} ) ); $self->{local_rd_days} = $class->_ymd2rd( @p{qw( year month day )} ); $self->{local_rd_secs} = $class->_time_as_seconds( @p{qw( hour minute second )} ); $self->{offset_modifier} = 0; $self->{rd_nanosecs} = $p{nanosecond}; $self->{formatter} = $p{formatter}; $self->_normalize_nanoseconds( $self->{local_rd_secs}, $self->{rd_nanosecs} ); # Set this explicitly since it can't be calculated accurately # without knowing our time zone offset, and it's possible that the # offset can't be calculated without having at least a rough guess # of the datetime's year. This year need not be correct, as long # as its equal or greater to the correct number, so we fudge by # adding one to the local year given to the constructor. $self->{utc_year} = $p{year} + 1; $self->_maybe_future_dst_warning( $p{year}, $p{time_zone} ); $self->_calc_utc_rd; $self->_handle_offset_modifier( $p{second} ); $self->_calc_local_rd; if ( $p{second} > 59 ) { if ( $self->{tz}->is_floating || # If true, this means that the actual calculated leap # second does not occur in the second given to new() ( $self->{utc_rd_secs} - 86399 < $p{second} - 59 ) ) { Carp::croak("Invalid second value ($p{second})\n"); } } return $self; } # Warning: do not use this environment variable unless you have no choice in # the matter. sub _default_time_zone { return $ENV{PERL_DATETIME_DEFAULT_TZ} || 'floating'; } sub _set_locale { my $self = shift; my $locale = shift; if ( defined $locale && ref $locale ) { $self->{locale} = $locale; } else { $self->{locale} = $locale ? DateTime::Locale->load($locale) : $self->DefaultLocale; } return; } # This method exists for the benefit of internal methods which create # a new object based on the current object, like set() and truncate(). sub _new_from_self { my $self = shift; my %p = @_; my %old = map { $_ => $self->$_() } qw( year month day hour minute second nanosecond locale time_zone ); $old{formatter} = $self->formatter if defined $self->formatter; my $method = delete $p{_skip_validation} ? '_new' : 'new'; return ( ref $self )->$method( %old, %p ); } sub _handle_offset_modifier { my $self = shift; $self->{offset_modifier} = 0; return if $self->{tz}->is_floating; my $second = shift; my $utc_is_valid = shift; my $utc_rd_days = $self->{utc_rd_days}; my $offset = $utc_is_valid ? $self->offset : $self->_offset_for_local_datetime; if ( $offset >= 0 && $self->{local_rd_secs} >= $offset ) { if ( $second < 60 && $offset > 0 ) { $self->{offset_modifier} = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY; $self->{local_rd_secs} += $self->{offset_modifier}; } elsif ( $second == 60 && ( ( $self->{local_rd_secs} == $offset && $offset > 0 ) || ( $offset == 0 && $self->{local_rd_secs} > 86399 ) ) ) { my $mod = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY; unless ( $mod == 0 ) { $self->{utc_rd_secs} -= $mod; $self->_normalize_seconds; } } } elsif ($offset < 0 && $self->{local_rd_secs} >= SECONDS_PER_DAY + $offset ) { if ( $second < 60 ) { $self->{offset_modifier} = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY; $self->{local_rd_secs} += $self->{offset_modifier}; } elsif ($second == 60 && $self->{local_rd_secs} == SECONDS_PER_DAY + $offset ) { my $mod = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY; unless ( $mod == 0 ) { $self->{utc_rd_secs} -= $mod; $self->_normalize_seconds; } } } } sub _calc_utc_rd { my $self = shift; delete $self->{utc_c}; if ( $self->{tz}->is_utc || $self->{tz}->is_floating ) { $self->{utc_rd_days} = $self->{local_rd_days}; $self->{utc_rd_secs} = $self->{local_rd_secs}; } else { my $offset = $self->_offset_for_local_datetime; $offset += $self->{offset_modifier}; $self->{utc_rd_days} = $self->{local_rd_days}; $self->{utc_rd_secs} = $self->{local_rd_secs} - $offset; } # We account for leap seconds in the new() method and nowhere else # except date math. $self->_normalize_tai_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} ); } sub _normalize_seconds { my $self = shift; return if $self->{utc_rd_secs} >= 0 && $self->{utc_rd_secs} <= 86399; if ( $self->{tz}->is_floating ) { $self->_normalize_tai_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} ); } else { $self->_normalize_leap_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} ); } } sub _calc_local_rd { my $self = shift; delete $self->{local_c}; # We must short circuit for UTC times or else we could end up with # loops between DateTime.pm and DateTime::TimeZone if ( $self->{tz}->is_utc || $self->{tz}->is_floating ) { $self->{local_rd_days} = $self->{utc_rd_days}; $self->{local_rd_secs} = $self->{utc_rd_secs}; } else { my $offset = $self->offset; $self->{local_rd_days} = $self->{utc_rd_days}; $self->{local_rd_secs} = $self->{utc_rd_secs} + $offset; # intentionally ignore leap seconds here $self->_normalize_tai_seconds( $self->{local_rd_days}, $self->{local_rd_secs} ); $self->{local_rd_secs} += $self->{offset_modifier}; } $self->_calc_local_components; } sub _calc_local_components { my $self = shift; @{ $self->{local_c} }{ qw( year month day day_of_week day_of_year quarter day_of_quarter) } = $self->_rd2ymd( $self->{local_rd_days}, 1 ); @{ $self->{local_c} }{qw( hour minute second )} = $self->_seconds_as_components( $self->{local_rd_secs}, $self->{utc_rd_secs}, $self->{offset_modifier} ); } { my $validator = validation_for( name => '_check_from_epoch_params', name_is_optional => 1, params => { epoch => { type => t('Num') }, formatter => { type => t('Formatter'), optional => 1 }, locale => { type => t('Locale'), optional => 1 }, time_zone => { type => t('TimeZone'), optional => 1 }, }, ); sub from_epoch { my $class = shift; my %p = $validator->(@_); my %args; # This does two things. First, if given a negative non-integer epoch, # it will round the epoch _down_ to the next second and then adjust # the nanoseconds to be positive. In other words, -0.5 corresponds to # a second of -1 and a nanosecond value of 500,000. Before this code # was implemented our handling of negative non-integer epochs was # quite broken, and would end up rounding some values up, so that -0.5 # become 0.5 (which is obviously wrong!). # # Second, it rounds any decimal values to the nearest microsecond # (1E6). Here's what Christian Hansen, who wrote this patch, says: # # Perl is typically compiled with NV as a double. A double with a # significand precision of 53 bits can only represent a nanosecond # epoch without loss of precision if the duration from zero epoch # is less than ≈ ±104 days. With microseconds the duration is # ±104,000 days, which is ≈ ±285 years. if ( int $p{epoch} != $p{epoch} ) { my ( $floor, $nano, $second ); $floor = $nano = fmod( $p{epoch}, 1.0 ); $second = floor( $p{epoch} - $floor ); if ( $nano < 0 ) { $nano += 1; } $p{epoch} = $second + floor( $floor - $nano ); $args{nanosecond} = floor( $nano * 1E6 + 0.5 ) * 1E3; } # Note, for very large negative values this may give a # blatantly wrong answer. @args{qw( second minute hour day month year )} = ( gmtime( $p{epoch} ) )[ 0 .. 5 ]; $args{year} += 1900; $args{month}++; my $self = $class->_new( %p, %args, time_zone => 'UTC' ); $self->_maybe_future_dst_warning( $self->year, $p{time_zone} ); $self->set_time_zone( $p{time_zone} ) if exists $p{time_zone}; return $self; } } sub now { my $class = shift; return $class->from_epoch( epoch => $class->_core_time, @_ ); } sub _maybe_future_dst_warning { shift; my $year = shift; my $tz = shift; return unless $year >= 5000 && $tz; my $tz_name = ref $tz ? $tz->name : $tz; return if $tz_name eq 'floating' || $tz_name eq 'UTC'; warnings::warnif( "You are creating a DateTime object with a far future year ($year) and a time zone ($tz_name)." . ' If the time zone you specified has future DST changes this will be very slow.' ); } # use scalar time in case someone's loaded Time::Piece sub _core_time { return scalar time; } sub today { shift->now(@_)->truncate( to => 'day' ) } { my $validator = validation_for( name => '_check_from_object_params', name_is_optional => 1, params => { object => { type => t('ConvertibleObject') }, locale => { type => t('Locale'), optional => 1, }, formatter => { type => t('Formatter'), optional => 1, }, }, ); sub from_object { my $class = shift; my %p = $validator->(@_); my $object = delete $p{object}; if ( $object->isa('DateTime::Infinite') ) { return $object->clone; } my ( $rd_days, $rd_secs, $rd_nanosecs ) = $object->utc_rd_values; # A kludge because until all calendars are updated to return all # three values, $rd_nanosecs could be undef $rd_nanosecs ||= 0; # This is a big hack to let _seconds_as_components operate naively # on the given value. If the object _is_ on a leap second, we'll # add that to the generated seconds value later. my $leap_seconds = 0; if ( $object->can('time_zone') && !$object->time_zone->is_floating && $rd_secs > 86399 && $rd_secs <= $class->_day_length($rd_days) ) { $leap_seconds = $rd_secs - 86399; $rd_secs -= $leap_seconds; } my %args; @args{qw( year month day )} = $class->_rd2ymd($rd_days); @args{qw( hour minute second )} = $class->_seconds_as_components($rd_secs); $args{nanosecond} = $rd_nanosecs; $args{second} += $leap_seconds; my $new = $class->new( %p, %args, time_zone => 'UTC' ); if ( $object->can('time_zone') ) { $new->set_time_zone( $object->time_zone ); } else { $new->set_time_zone( $class->_default_time_zone ); } return $new; } } { my $validator = validation_for( name => '_check_last_day_of_month_params', name_is_optional => 1, params => { year => { type => t('Year') }, month => { type => t('Month') }, last_day_of_month { my $class = shift; my %p = $validator->(@_); my $day = $class->_month_length( $p{year}, $p{month} ); return $class->_new( %p, day => $day ); } } sub _month_length { return ( $_[0]->_is_leap_year( $_[1] ) ? $LeapYearMonthLengths[ $_[2] - 1 ] : $MonthLengths[ $_[2] - 1 ] ); } { my $validator = validation_for( name => '_check_from_day_of_year_params', name_is_optional => 1, params => { year => { type => t('Year') }, day_of_year => { type => t('DayOfYear') }, from_day_of_year { my $class = shift; my %p = $validator->(@_); Carp::croak("$p{year} is not a leap year.\n") if $p{day_of_year} == 366 && !$class->_is_leap_year( $p{year} ); my $month = 1; my $day = delete $p{day_of_year}; if ( $day > 31 ) { my $length = $class->_month_length( $p{year}, $month ); while ( $day > $length ) { $day -= $length; $month++; $length = $class->_month_length( $p{year}, $month ); } } return $class->_new( %p, month => $month, day => $day, ); } } sub formatter { $_[0]->{formatter} } sub clone { bless { %{ $_[0] } }, ref $_[0] } sub year { Carp::carp('year() is a read-only accessor') if @_ > 1; return $_[0]->{local_c}{year}; } sub ce_year { $_[0]->{local_c}{year} <= 0 ? $_[0]->{local_c}{year} - 1 : $_[0]->{local_c}{year}; } sub era_name { $_[0]->{locale}->era_wide->[ $_[0]->_era_index ] } sub era_abbr { $_[0]->{locale}->era_abbreviated->[ $_[0]->_era_index ] } # deprecated *era = \&era_abbr; sub _era_index { $_[0]->{local_c}{year} <= 0 ? 0 : 1 } sub christian_era { $_[0]->ce_year > 0 ? 'AD' : 'BC' } sub secular_era { $_[0]->ce_year > 0 ? 'CE' : 'BCE' } sub year_with_era { ( abs $_[0]->ce_year ) . $_[0]->era_abbr } sub year_with_christian_era { ( abs $_[0]->ce_year ) . $_[0]->christian_era } sub year_with_secular_era { ( abs $_[0]->ce_year ) . $_[0]->secular_era } sub month { Carp::carp('month() is a read-only accessor') if @_ > 1; return $_[0]->{local_c}{month}; } *mon = \&month; sub month_0 { $_[0]->{local_c}{month} - 1 } *mon_0 = \&month_0; sub month_name { $_[0]->{locale}->month_format_wide->[ $_[0]->month_0 ] } sub month_abbr { $_[0]->{locale}->month_format_abbreviated->[ $_[0]->month_0 ]; } sub day_of_month { Carp::carp('day_of_month() is a read-only accessor') if @_ > 1; $_[0]->{local_c}{day}; } *day = \&day_of_month; *mday = \&day_of_month; sub weekday_of_month { use integer; ( ( $_[0]->day - 1 ) / 7 ) + 1 } sub quarter { $_[0]->{local_c}{quarter} } sub quarter_name { $_[0]->{locale}->quarter_format_wide->[ $_[0]->quarter_0 ]; } sub quarter_abbr { $_[0]->{locale}->quarter_format_abbreviated->[ $_[0]->quarter_0 ]; } sub quarter_0 { $_[0]->{local_c}{quarter} - 1 } sub day_of_month_0 { $_[0]->{local_c}{day} - 1 } *day_0 = \&day_of_month_0; *mday_0 = \&day_of_month_0; sub day_of_week { $_[0]->{local_c}{day_of_week} } *wday = \&day_of_week; *dow = \&day_of_week; sub day_of_week_0 { $_[0]->{local_c}{day_of_week} - 1 } *wday_0 = \&day_of_week_0; *dow_0 = \&day_of_week_0; sub local_day_of_week { my $self = shift; return 1 + ( $self->day_of_week - $self->{locale}->first_day_of_week ) % 7; } sub day_name { $_[0]->{locale}->day_format_wide->[ $_[0]->day_of_week_0 ] } sub day_abbr { $_[0]->{locale}->day_format_abbreviated->[ $_[0]->day_of_week_0 ]; } sub day_of_quarter { $_[0]->{local_c}{day_of_quarter} } *doq = \&day_of_quarter; sub day_of_quarter_0 { $_[0]->day_of_quarter - 1 } *doq_0 = \&day_of_quarter_0; sub day_of_year { $_[0]->{local_c}{day_of_year} } *doy = \&day_of_year; sub day_of_year_0 { $_[0]->{local_c}{day_of_year} - 1 } *doy_0 = \&day_of_year_0; sub am_or_pm { $_[0]->{locale}->am_pm_abbreviated->[ $_[0]->hour < 12 ? 0 : 1 ]; } sub ymd { my ( $self, $sep ) = @_; $sep = '-' unless defined $sep; return sprintf( '%0.4d%s%0.2d%s%0.2d', $self->year, $sep, $self->{local_c}{month}, $sep, $self->{local_c}{day} ); } *date = sub { shift->ymd(@_) }; sub mdy { my ( $self, $sep ) = @_; $sep = '-' unless defined $sep; return sprintf( '%0.2d%s%0.2d%s%0.4d', $self->{local_c}{month}, $sep, $self->{local_c}{day}, $sep, $self->year ); } sub dmy { my ( $self, $sep ) = @_; $sep = '-' unless defined $sep; return sprintf( '%0.2d%s%0.2d%s%0.4d', $self->{local_c}{day}, $sep, $self->{local_c}{month}, $sep, $self->year ); } sub hour { Carp::carp('hour() is a read-only accessor') if @_ > 1; return $_[0]->{local_c}{hour}; } sub hour_1 { $_[0]->{local_c}{hour} == 0 ? 24 : $_[0]->{local_c}{hour} } sub hour_12 { my $h = $_[0]->hour % 12; return $h ? $h : 12 } sub hour_12_0 { $_[0]->hour % 12 } sub minute { Carp::carp('minute() is a read-only accessor') if @_ > 1; return $_[0]->{local_c}{minute}; } *min = \&minute; sub second { Carp::carp('second() is a read-only accessor') if @_ > 1; return $_[0]->{local_c}{second}; } *sec = \&second; sub fractional_second { $_[0]->second + $_[0]->nanosecond / MAX_NANOSECONDS } sub nanosecond { Carp::carp('nanosecond() is a read-only accessor') if @_ > 1; return $_[0]->{rd_nanosecs}; } sub millisecond { floor( $_[0]->{rd_nanosecs} / 1000000 ) } sub microsecond { floor( $_[0]->{rd_nanosecs} / 1000 ) } sub leap_seconds { my $self = shift; return 0 if $self->{tz}->is_floating; return $self->_accumulated_leap_seconds( $self->{utc_rd_days} ); } sub stringify { my $self = shift; return $self->iso8601 unless $self->{formatter}; return $self->{formatter}->format_datetime($self); } sub hms { my ( $self, $sep ) = @_; $sep = ':' unless defined $sep; return sprintf( '%0.2d%s%0.2d%s%0.2d', $self->{local_c}{hour}, $sep, $self->{local_c}{minute}, $sep, $self->{local_c}{second} ); } # don't want to override CORE::time() *DateTime::time = sub { shift->hms(@_) }; sub iso8601 { $_[0]->datetime('T') } sub rfc3339 { my $self = shift; return $self->datetime('T') if $self->{tz}->is_floating; my $secs = $self->offset; my $offset = $secs ? DateTime::TimeZone->offset_as_string( $secs, q{:} ) : 'Z'; return $self->datetime('T') . $offset; } sub datetime { my ( $self, $sep ) = @_; $sep = 'T' unless defined $sep; return join $sep, $self->ymd('-'), $self->hms(':'); } sub is_leap_year { $_[0]->_is_leap_year( $_[0]->year ) } sub month_length { $_[0]->_month_length( $_[0]->year, $_[0]->month ); } sub quarter_length { return ( $_[0]->_is_leap_year( $_[0]->year ) ? $LeapYearQuarterLengths[ $_[0]->quarter - 1 ] : $QuarterLengths[ $_[0]->quarter - 1 ] ); } sub year_length { $_[0]->_is_leap_year( $_[0]->year ) ? 366 : 365; } sub is_last_day_of_month { $_[0]->day == $_[0]->_month_length( $_[0]->year, $_[0]->month ); } sub is_last_day_of_quarter { $_[0]->day_of_quarter == $_[0]->quarter_length; } sub is_last_day_of_year { $_[0]->day_of_year == $_[0]->year_length; } sub week { my $self = shift; $self->{utc_c}{week_year} ||= $self->_week_values; return @{ $self->{utc_c}{week_year} }[ 0, 1 ]; } # This algorithm comes from # sub _week_values { my $self = shift; my $week = int( ( ( $self->day_of_year - $self->day_of_week ) + 10 ) / 7 ); my $year = $self->year; if ( $week == 0 ) { $year--; return [ $year, $self->_weeks_in_year($year) ]; } elsif ( $week == 53 && $self->_weeks_in_year($year) == 52 ) { return [ $year + 1, 1 ]; } return [ $year, $week ]; } sub _weeks_in_year { my $self = shift; my $year = shift; my $dow = $self->_ymd2rd( $year, 1, 1 ) % 7; # Years starting with a Thursday and leap years starting with a Wednesday # have 53 weeks. return ( $dow == 4 || ( $dow == 3 && $self->_is_leap_year($year) ) ) ? 53 : 52; } sub week_year { ( $_[0]->week )[0] } sub week_number { ( $_[0]->week )[1] } # ISO says that the first week of a year is the first week containing # a Thursday. Extending that says that the first week of the month is # the first week containing a Thursday. ICU agrees. sub week_of_month { my $self = shift; my $thu = $self->day + 4 - $self->day_of_week; return int( ( $thu + 6 ) / 7 ); } sub time_zone { Carp::carp('time_zone() is a read-only accessor') if @_ > 1; return $_[0]->{tz}; } sub offset { $_[0]->{tz}->offset_for_datetime( $_[0] ) } sub _offset_for_local_datetime { $_[0]->{tz}->offset_for_local_datetime( $_[0] ); } sub is_dst { $_[0]->{tz}->is_dst_for_datetime( $_[0] ) } sub time_zone_long_name { $_[0]->{tz}->name } sub time_zone_short_name { $_[0]->{tz}->short_name_for_datetime( $_[0] ) } sub locale { Carp::carp('locale() is a read-only accessor') if @_ > 1; return $_[0]->{locale}; } sub utc_rd_values { @{ $_[0] }{ 'utc_rd_days', 'utc_rd_secs', 'rd_nanosecs' }; } sub local_rd_values { @{ $_[0] }{ 'local_rd_days', 'local_rd_secs', 'rd_nanosecs' }; } # NOTE: no nanoseconds, no leap seconds sub utc_rd_as_seconds { ( $_[0]->{utc_rd_days} * SECONDS_PER_DAY ) + $_[0]->{utc_rd_secs}; } # NOTE: no nanoseconds, no leap seconds sub local_rd_as_seconds { ( $_[0]->{local_rd_days} * SECONDS_PER_DAY ) + $_[0]->{local_rd_secs}; } # RD 1 is MJD 678,576 - a simple offset sub mjd { my $self = shift; my $mjd = $self->{utc_rd_days} - 678_576; my $day_length = $self->_day_length( $self->{utc_rd_days} ); return ( $mjd + ( $self->{utc_rd_secs} / $day_length ) + ( $self->{rd_nanosecs} / $day_length / MAX_NANOSECONDS ) ); } sub jd { $_[0]->mjd + 2_400_000.5 } { my %strftime_patterns = ( 'a' => sub { $_[0]->day_abbr }, 'A' => sub { $_[0]->day_name }, 'b' => sub { $_[0]->month_abbr }, 'B' => sub { $_[0]->month_name }, 'c' => sub { $_[0]->format_cldr( $_[0]->{locale}->datetime_format_default ); }, 'C' => sub { int( $_[0]->year / 100 ) }, 'd' => sub { sprintf( '%02d', $_[0]->day_of_month ) }, 'D' => sub { $_[0]->strftime('%m/%d/%y') }, 'e' => sub { sprintf( '%2d', $_[0]->day_of_month ) }, 'F' => sub { $_[0]->strftime('%Y-%m-%d') }, 'g' => sub { substr( $_[0]->week_year, -2 ) }, 'G' => sub { $_[0]->week_year }, 'H' => sub { sprintf( '%02d', $_[0]->hour ) }, 'I' => sub { sprintf( '%02d', $_[0]->hour_12 ) }, 'j' => sub { sprintf( '%03d', $_[0]->day_of_year ) }, 'k' => sub { sprintf( '%2d', $_[0]->hour ) }, 'l' => sub { sprintf( '%2d', $_[0]->hour_12 ) }, 'm' => sub { sprintf( '%02d', $_[0]->month ) }, 'M' => sub { sprintf( '%02d', $_[0]->minute ) }, 'n' => sub {"\n"}, # should this be OS-sensitive? 'N' => \&_format_nanosecs, 'p' => sub { $_[0]->am_or_pm }, 'P' => sub { lc $_[0]->am_or_pm }, 'r' => sub { $_[0]->strftime('%I:%M:%S %p') }, 'R' => sub { $_[0]->strftime('%H:%M') }, 's' => sub { $_[0]->epoch }, 'S' => sub { sprintf( '%02d', $_[0]->second ) }, 't' => sub {"\t"}, 'T' => sub { $_[0]->strftime('%H:%M:%S') }, 'u' => sub { $_[0]->day_of_week }, 'U' => sub { my $sun = $_[0]->day_of_year - ( $_[0]->day_of_week + 7 ) % 7; return sprintf( '%02d', int( ( $sun + 6 ) / 7 ) ); }, 'V' => sub { sprintf( '%02d', $_[0]->week_number ) }, 'w' => sub { my $dow = $_[0]->day_of_week; return $dow % 7; }, 'W' => sub { my $mon = $_[0]->day_of_year - ( $_[0]->day_of_week + 6 ) % 7; return sprintf( '%02d', int( ( $mon + 6 ) / 7 ) ); }, 'x' => sub { $_[0]->format_cldr( $_[0]->{locale}->date_format_default ); }, 'X' => sub { $_[0]->format_cldr( $_[0]->{locale}->time_format_default ); }, 'y' => sub { sprintf( '%02d', substr( $_[0]->year, -2 ) ) }, 'Y' => sub { return $_[0]->year }, 'z' => sub { DateTime::TimeZone->offset_as_string( $_[0]->offset ) }, 'Z' => sub { $_[0]->{tz}->short_name_for_datetime( $_[0] ) }, '%' => sub {'%'}, ); $strftime_patterns{h} = $strftime_patterns{b}; sub strftime { my $self = shift; # make a copy or caller's scalars get munged my @patterns = @_; my @r; foreach my $p (@patterns) { $p =~ s/ (?: %\{(\w+)\} # method name like %{day_name} | %([%a-zA-Z]) # single character specifier like %d | %(\d+)N # special case for %N ) / ( $1 ? ( $self->can($1) ? $self->$1() : "\%{$1}" ) : $2 ? ( $strftime_patterns{$2} ? $strftime_patterns{$2}->($self) : "\%$2" ) : $3 ? $strftime_patterns{N}->($self, $3) : '' # this won't happen ) /sgex; return $p unless wantarray; push @r, $p; } return @r; } } { # It's an array because the order in which the regexes are checked # is important. These patterns are similar to the ones Java uses, # but not quite the same. See #. my @patterns = ( qr/GGGGG/ => sub { $_[0]->{locale}->era_narrow->[ $_[0]->_era_index ] }, qr/GGGG/ => 'era_name', qr/G{1,3}/ => 'era_abbr', qr/(y{3,5})/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->year ) }, # yy is a weird special case, where it must be exactly 2 digits qr/yy/ => sub { my $year = $_[0]->year; my $y2 = length $year > 2 ? substr( $year, -2, 2 ) : $year; $y2 *= -1 if $year < 0; $_[0]->_zero_padded_number( 'yy', $y2 ); }, qr/y/ => sub { $_[0]->year }, qr/(u+)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->year ) }, qr/(Y+)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->week_year ) }, qr/QQQQ/ => 'quarter_name', qr/QQQ/ => 'quarter_abbr', qr/(QQ?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->quarter ) }, qr/qqqq/ => sub { $_[0]->{locale}->quarter_stand_alone_wide->[ $_[0]->quarter_0 ]; }, qr/qqq/ => sub { $_[0]->{locale} ->quarter_stand_alone_abbreviated->[ $_[0]->quarter_0 ]; }, qr/(qq?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->quarter ) }, qr/MMMMM/ => sub { $_[0]->{locale}->month_format_narrow->[ $_[0]->month_0 ] }, qr/MMMM/ => 'month_name', qr/MMM/ => 'month_abbr', qr/(MM?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->month ) }, qr/LLLLL/ => sub { $_[0]->{locale}->month_stand_alone_narrow->[ $_[0]->month_0 ]; }, qr/LLLL/ => sub { $_[0]->{locale}->month_stand_alone_wide->[ $_[0]->month_0 ]; }, qr/LLL/ => sub { $_[0]->{locale} ->month_stand_alone_abbreviated->[ $_[0]->month_0 ]; }, qr/(LL?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->month ) }, qr/(ww?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->week_number ) }, qr/W/ => 'week_of_month', qr/(dd?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->day_of_month ) }, qr/(D{1,3})/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->day_of_year ) }, qr/F/ => 'weekday_of_month', qr/(g+)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->mjd ) }, qr/EEEEE/ => sub { $_[0]->{locale}->day_format_narrow->[ $_[0]->day_of_week_0 ]; }, qr/EEEE/ => 'day_name', qr/E{1,3}/ => 'day_abbr', qr/eeeee/ => sub { $_[0]->{locale}->day_format_narrow->[ $_[0]->day_of_week_0 ]; }, qr/eeee/ => 'day_name', qr/eee/ => 'day_abbr', qr/(ee?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->local_day_of_week ); }, qr/ccccc/ => sub { $_[0]->{locale}->day_stand_alone_narrow->[ $_[0]->day_of_week_0 ]; }, qr/cccc/ => sub { $_[0]->{locale}->day_stand_alone_wide->[ $_[0]->day_of_week_0 ]; }, qr/ccc/ => sub { $_[0]->{locale} ->day_stand_alone_abbreviated->[ $_[0]->day_of_week_0 ]; }, qr/(cc?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->day_of_week ) }, qr/a/ => 'am_or_pm', qr/(hh?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->hour_12 ) }, qr/(HH?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->hour ) }, qr/(KK?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->hour_12_0 ) }, qr/(kk?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->hour_1 ) }, qr/(jj?)/ => sub { my $h = $_[0]->{locale}->prefers_24_hour_time ? $_[0]->hour : $_[0]->hour_12; $_[0]->_zero_padded_number( $1, $h ); }, qr/(mm?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->minute ) }, qr/(ss?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->second ) }, # The LDML spec is not 100% clear on how to truncate this field, but # this way seems as good as anything. qr/(S+)/ => sub { $_[0]->_format_nanosecs( length($1) ) }, qr/A+/ => sub { ( $_[0]->{local_rd_secs} * 1000 ) + $_[0]->millisecond }, qr/zzzz/ => sub { $_[0]->time_zone_long_name }, qr/z{1,3}/ => sub { $_[0]->time_zone_short_name }, qr/ZZZZZ/ => sub { DateTime::TimeZone->offset_as_string( $_[0]->offset, q{:} ); }, qr/ZZZZ/ => sub { $_[0]->time_zone_short_name . DateTime::TimeZone->offset_as_string( $_[0]->offset ); }, qr/Z{1,3}/ => sub { DateTime::TimeZone->offset_as_string( $_[0]->offset ) }, qr/vvvv/ => sub { $_[0]->time_zone_long_name }, qr/v{1,3}/ => sub { $_[0]->time_zone_short_name }, qr/VVVV/ => sub { $_[0]->time_zone_long_name }, qr/V{1,3}/ => sub { $_[0]->time_zone_short_name }, ); sub _zero_padded_number { my $self = shift; my $size = length shift; my $val = shift; return sprintf( "%0${size}d", $val ); } sub format_cldr { my $self = shift; # make a copy or caller's scalars get munged my @p = @_; my @r; foreach my $p (@p) { $p =~ s/\G (?: '((?:[^']|'')*)' # quote escaped bit of text # it needs to end with one # quote not followed by # another | (([a-zA-Z])\3*) # could be a pattern | (.) # anything else ) / defined $1 ? $1 : defined $2 ? $self->_cldr_pattern($2) : defined $4 ? $4 : undef # should never get here /sgex; $p =~ s/\'\'/\'/g; return $p unless wantarray; push @r, $p; } return @r; } sub _cldr_pattern { my $self = shift; my $pattern = shift; ## no critic (ControlStructures::ProhibitCStyleForLoops) for ( my $i = 0; $i < @patterns; $i += 2 ) { if ( $pattern =~ /$patterns[$i]/ ) { my $sub = $patterns[ $i + 1 ]; return $self->$sub(); } } return $pattern; } } sub _format_nanosecs { my $self = shift; my $precision = @_ ? shift : 9; my $exponent = 9 - $precision; my $formatted_ns = floor( ( $exponent < 0 ? $self->{rd_nanosecs} * 10**-$exponent : $self->{rd_nanosecs} / 10**$exponent ) ); return sprintf( '%0' . $precision . 'u', $formatted_ns ); } sub epoch { my $self = shift; return $self->{utc_c}{epoch} if exists $self->{utc_c}{epoch}; return $self->{utc_c}{epoch} = ( $self->{utc_rd_days} - 719163 ) * SECONDS_PER_DAY + $self->{utc_rd_secs}; } sub hires_epoch { my $self = shift; my $epoch = $self->epoch; return undef unless defined $epoch; my $nano = $self->{rd_nanosecs} / MAX_NANOSECONDS; return $epoch + $nano; } sub is_finite {1} sub is_infinite {0} # added for benefit of DateTime::TimeZone sub utc_year { $_[0]->{utc_year} } # returns a result that is relative to the first datetime sub subtract_datetime { my $dt1 = shift; my $dt2 = shift; $dt2 = $dt2->clone->set_time_zone( $dt1->time_zone ) unless $dt1->time_zone eq $dt2->time_zone; # We only want a negative duration if $dt2 > $dt1 ($self) my ( $bigger, $smaller, $negative ) = ( $dt1 >= $dt2 ? ( $dt1, $dt2, 0 ) : ( $dt2, $dt1, 1 ) ); my $is_floating = $dt1->time_zone->is_floating && $dt2->time_zone->is_floating; my $minute_length = 60; unless ($is_floating) { my ( $utc_rd_days, $utc_rd_secs ) = $smaller->utc_rd_values; if ( $utc_rd_secs >= 86340 && !$is_floating ) { # If the smaller of the two datetimes occurs in the last # UTC minute of the UTC day, then that minute may not be # 60 seconds long. If we need to subtract a minute from # the larger datetime's minutes count in order to adjust # the seconds difference to be positive, we need to know # how long that minute was. If one of the datetimes is # floating, we just assume a minute is 60 seconds. $minute_length = $dt1->_day_length($utc_rd_days) - 86340; } } # This is a gross hack that basically figures out if the bigger of # the two datetimes is the day of a DST change. If it's a 23 hour # day (switching _to_ DST) then we subtract 60 minutes from the # local time. If it's a 25 hour day then we add 60 minutes to the # local time. # # This produces the most "intuitive" results, though there are # still reversibility problems with the resultant duration. # # However, if the two objects are on the same (local) date, and we # are not crossing a DST change, we don't want to invoke the hack # - see 38local-subtract.t my $bigger_min = $bigger->hour * 60 + $bigger->minute; if ( $bigger->time_zone->has_dst_changes && $bigger->is_dst != $smaller->is_dst ) { $bigger_min -= 60 # it's a 23 hour (local) day if ( $bigger->is_dst && do { my $prev_day = try { $bigger->clone->subtract( days => 1 ) }; $prev_day && !$prev_day->is_dst ? 1 : 0; } ); $bigger_min += 60 # it's a 25 hour (local) day if ( !$bigger->is_dst && do { my $prev_day = try { $bigger->clone->subtract( days => 1 ) }; $prev_day && $prev_day->is_dst ? 1 : 0; } ); } my ( $months, $days, $minutes, $seconds, $nanoseconds ) = $dt1->_adjust_for_positive_difference( $bigger->year * 12 + $bigger->month, $smaller->year * 12 + $smaller->month, $bigger->day, $smaller->day, $bigger_min, $smaller->hour * 60 + $smaller->minute, $bigger->second, $smaller->second, $bigger->nanosecond, $smaller->nanosecond, $minute_length, # XXX - using the smaller as the month length is # somewhat arbitrary, we could also use the bigger - # either way we have reversibility problems $dt1->_month_length( $smaller->year, $smaller->month ), ); if ($negative) { for ( $months, $days, $minutes, $seconds, $nanoseconds ) { # Some versions of Perl can end up with -0 if we do "0 * -1"!! $_ *= -1 if $_; } } return $dt1->duration_class->new( months => $months, days => $days, minutes => $minutes, seconds => $seconds, nanoseconds => $nanoseconds, ); } sub _adjust_for_positive_difference { ## no critic (Subroutines::ProhibitManyArgs) my ( $self, $month1, $month2, $day1, $day2, $min1, $min2, $sec1, $sec2, $nano1, $nano2, $minute_length, $month_length, ) = @_; if ( $nano1 < $nano2 ) { $sec1--; $nano1 += MAX_NANOSECONDS; } if ( $sec1 < $sec2 ) { $min1--; $sec1 += $minute_length; } # A day always has 24 * 60 minutes, though the minutes may vary in # length. if ( $min1 < $min2 ) { $day1--; $min1 += 24 * 60; } if ( $day1 < $day2 ) { $month1--; $day1 += $month_length; } return ( $month1 - $month2, $day1 - $day2, $min1 - $min2, $sec1 - $sec2, $nano1 - $nano2, ); } sub subtract_datetime_absolute { my $self = shift; my $dt = shift; my $utc_rd_secs1 = $self->utc_rd_as_seconds; $utc_rd_secs1 += $self->_accumulated_leap_seconds( $self->{utc_rd_days} ) if !$self->time_zone->is_floating; my $utc_rd_secs2 = $dt->utc_rd_as_seconds; $utc_rd_secs2 += $self->_accumulated_leap_seconds( $dt->{utc_rd_days} ) if !$dt->time_zone->is_floating; my $seconds = $utc_rd_secs1 - $utc_rd_secs2; my $nanoseconds = $self->nanosecond - $dt->nanosecond; if ( $nanoseconds < 0 ) { $seconds--; $nanoseconds += MAX_NANOSECONDS; } return $self->duration_class->new( seconds => $seconds, nanoseconds => $nanoseconds, ); } sub delta_md { my $self = shift; my $dt = shift; my ( $smaller, $bigger ) = sort $self, $dt; my ( $months, $days, undef, undef, undef ) = $dt->_adjust_for_positive_difference( $bigger->year * 12 + $bigger->month, $smaller->year * 12 + $smaller->month, $bigger->day, $smaller->day, 0, 0, 0, 0, 0, 0, 60, $smaller->_month_length( $smaller->year, $smaller->month ), ); return $self->duration_class->new( months => $months, days => $days ); } sub delta_days { my $self = shift; my $dt = shift; my $days = abs( ( $self->local_rd_values )[0] - ( $dt->local_rd_values )[0] ); $self->duration_class->new( days => $days ); } sub delta_ms { my $self = shift; my $dt = shift; my ( $smaller, $greater ) = sort $self, $dt; my $days = int( $greater->jd - $smaller->jd ); my $dur = $greater->subtract_datetime($smaller); my %p; $p{hours} = $dur->hours + ( $days * 24 ); $p{minutes} = $dur->minutes; $p{seconds} = $dur->seconds; return $self->duration_class->new(%p); } sub _add_overload { my ( $dt, $dur, $reversed ) = @_; if ($reversed) { ( $dur, $dt ) = ( $dt, $dur ); } unless ( DateTime::Helpers::isa( $dur, 'DateTime::Duration' ) ) { my $class = ref $dt; my $dt_string = overload::StrVal($dt); Carp::croak( "Cannot add $dur to a $class object ($dt_string).\n" . ' Only a DateTime::Duration object can ' . " be added to a $class object." ); } return $dt->clone->add_duration($dur); } sub _subtract_overload { my ( $date1, $date2, $reversed ) = @_; if ($reversed) { ( $date2, $date1 ) = ( $date1, $date2 ); } if ( DateTime::Helpers::isa( $date2, 'DateTime::Duration' ) ) { my $new = $date1->clone; $new->add_duration( $date2->inverse ); return $new; } elsif ( DateTime::Helpers::isa( $date2, 'DateTime' ) ) { return $date1->subtract_datetime($date2); } else { my $class = ref $date1; my $dt_string = overload::StrVal($date1); Carp::croak( "Cannot subtract $date2 from a $class object ($dt_string).\n" . ' Only a DateTime::Duration or DateTime object can ' . " be subtracted from a $class object." ); } } sub add { my $self = shift; return $self->add_duration( $self->_duration_object_from_args(@_) ); } sub subtract { my $self = shift; my %eom; if ( @_ % 2 == 0 ) { my %p = @_; $eom{end_of_month} = delete $p{end_of_month} if exists $p{end_of_month}; } my $dur = $self->_duration_object_from_args(@_)->inverse(%eom); return $self->add_duration($dur); } # Syntactic sugar for add and subtract: use a duration object if it's # supplied, otherwise build a new one from the arguments. sub _duration_object_from_args { my $self = shift; return $_[0] if @_ == 1 && blessed( $_[0] ) && $_[0]->isa( $self->duration_class ); return $self->duration_class->new(@_); } sub subtract_duration { return $_[0]->add_duration( $_[1]->inverse ) } { my $validator = validation_for( name => '_check_add_duration_params', name_is_optional => 1, params => [ { type => t('Duration') }, ], ); ## no critic (Subroutines::ProhibitExcessComplexity) sub add_duration { my $self = shift; my ($dur) = $validator->(@_); # simple optimization return $self if $dur->is_zero; my %deltas = $dur->deltas; # This bit isn't quite right since DateTime::Infinite::Future - # infinite duration should NaN foreach my $val ( values %deltas ) { my $inf; if ( $val == INFINITY ) { $inf = DateTime::Infinite::Future->new; } elsif ( $val == NEG_INFINITY ) { $inf = DateTime::Infinite::Past->new; } if ($inf) { %$self = %$inf; bless $self, ref $inf; return $self; } } return $self if $self->is_infinite; my %orig = %{$self}; try { $self->_add_duration($dur); } catch { %{$self} = %orig; die $_; }; } } sub _add_duration { my $self = shift; my $dur = shift; my %deltas = $dur->deltas; if ( $deltas{days} ) { $self->{local_rd_days} += $deltas{days}; $self->{utc_year} += int( $deltas{days} / 365 ) + 1; } if ( $deltas{months} ) { # For preserve mode, if it is the last day of the month, make # it the 0th day of the following month (which then will # normalize back to the last day of the new month). my ( $y, $m, $d ) = ( $dur->is_preserve_mode ? $self->_rd2ymd( $self->{local_rd_days} + 1 ) : $self->_rd2ymd( $self->{local_rd_days} ) ); $d -= 1 if $dur->is_preserve_mode; if ( !$dur->is_wrap_mode && $d > 28 ) { # find the rd for the last day of our target month $self->{local_rd_days} = $self->_ymd2rd( $y, $m + $deltas{months} + 1, 0 ); # what day of the month is it? (discard year and month) my $last_day = ( $self->_rd2ymd( $self->{local_rd_days} ) )[2]; # if our original day was less than the last day, # use that instead $self->{local_rd_days} -= $last_day - $d if $last_day > $d; } else { $self->{local_rd_days} = $self->_ymd2rd( $y, $m + $deltas{months}, $d ); } $self->{utc_year} += int( $deltas{months} / 12 ) + 1; } if ( $deltas{days} || $deltas{months} ) { $self->_calc_utc_rd; $self->_handle_offset_modifier( $self->second ); } if ( $deltas{minutes} ) { $self->{utc_rd_secs} += $deltas{minutes} * 60; # This intentionally ignores leap seconds $self->_normalize_tai_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} ); } if ( $deltas{seconds} || $deltas{nanoseconds} ) { $self->{utc_rd_secs} += $deltas{seconds}; if ( $deltas{nanoseconds} ) { $self->{rd_nanosecs} += $deltas{nanoseconds}; $self->_normalize_nanoseconds( $self->{utc_rd_secs}, $self->{rd_nanosecs} ); } $self->_normalize_seconds; # This might be some big number much bigger than 60, but # that's ok (there are tests in 19leap_second.t to confirm # that) $self->_handle_offset_modifier( $self->second + $deltas{seconds} ); } my $new = ( ref $self )->from_object( object => $self, locale => $self->{locale}, ( $self->{formatter} ? ( formatter => $self->{formatter} ) : () ), ); %$self = %$new; return $self; } sub _compare_overload { # note: $_[1]->compare( $_[0] ) is an error when $_[1] is not a # DateTime (such as the INFINITY value) return undef unless defined $_[1]; return $_[2] ? -$_[0]->compare( $_[1] ) : $_[0]->compare( $_[1] ); } sub _string_compare_overload { my ( $dt1, $dt2, $flip ) = @_; # One is a DateTime object, one isn't. Just stringify and compare. if ( !DateTime::Helpers::can( $dt2, 'utc_rd_values' ) ) { my $sign = $flip ? -1 : 1; return $sign * ( "$dt1" cmp "$dt2" ); } else { my $meth = $dt1->can('_compare_overload'); goto $meth; } } sub compare { shift->_compare( @_, 0 ); } sub compare_ignore_floating { shift->_compare( @_, 1 ); } sub _compare { my ( undef, $dt1, $dt2, $consistent ) = ref $_[0] ? ( undef, @_ ) : @_; return undef unless defined $dt2; if ( !ref $dt2 && ( $dt2 == INFINITY || $dt2 == NEG_INFINITY ) ) { return $dt1->{utc_rd_days} <=> $dt2; } unless ( DateTime::Helpers::can( $dt1, 'utc_rd_values' ) && DateTime::Helpers::can( $dt2, 'utc_rd_values' ) ) { my $dt1_string = overload::StrVal($dt1); my $dt2_string = overload::StrVal($dt2); Carp::croak( 'A DateTime object can only be compared to' . " another DateTime object ($dt1_string, $dt2_string)." ); } if ( !$consistent && DateTime::Helpers::can( $dt1, 'time_zone' ) && DateTime::Helpers::can( $dt2, 'time_zone' ) ) { my $is_floating1 = $dt1->time_zone->is_floating; my $is_floating2 = $dt2->time_zone->is_floating; if ( $is_floating1 && !$is_floating2 ) { $dt1 = $dt1->clone->set_time_zone( $dt2->time_zone ); } elsif ( $is_floating2 && !$is_floating1 ) { $dt2 = $dt2->clone->set_time_zone( $dt1->time_zone ); } } my @dt1_components = $dt1->utc_rd_values; my @dt2_components = $dt2->utc_rd_values; foreach my $i ( 0 .. 2 ) { return $dt1_components[$i] <=> $dt2_components[$i] if $dt1_components[$i] != $dt2_components[$i]; } return 0; } sub is_between { my $self = shift; my $lower = shift; my $upper = shift; return $self->compare($lower) > 0 && $self->compare($upper) < 0; } sub _string_equals_overload { my ( $class, $dt1, $dt2 ) = ref $_[0] ? ( undef, @_ ) : @_; if ( !DateTime::Helpers::can( $dt2, 'utc_rd_values' ) ) { return "$dt1" eq "$dt2"; } $class ||= ref $dt1; return !$class->compare( $dt1, $dt2 ); } sub _string_not_equals_overload { return !_string_equals_overload(@_); } sub _normalize_nanoseconds { use integer; # seconds, nanoseconds if ( $_[2] < 0 ) { my $overflow = 1 + $_[2] / MAX_NANOSECONDS; $_[2] += $overflow * MAX_NANOSECONDS; $_[1] -= $overflow; } elsif ( $_[2] >= MAX_NANOSECONDS ) { my $overflow = $_[2] / MAX_NANOSECONDS; $_[2] -= $overflow * MAX_NANOSECONDS; $_[1] += $overflow; } } { my $validator = validation_for( name => '_check_set_params', name_is_optional => 1, params => { year => { type => t('Year'), optional => 1, }, month => { type => t('Month'), optional => 1, }, day => { type => t('DayOfMonth'), optional => 1, }, hour => { type => t('Hour'), optional => 1, }, minute => { type => t('Minute'), optional => 1, }, second => { type => t('Second'), optional => 1, }, nanosecond => { type => t('Nanosecond'), optional => 1, }, locale => { type => t('Locale'), optional => 1, }, }, ); ## no critic (NamingConventions::ProhibitAmbiguousNames) sub set { my $self = shift; my %p = $validator->(@_); if ( $p{locale} ) { carp 'You passed a locale to the set() method.' . ' You should use set_locale() instead, as using set() may alter the local time near a DST boundary.'; } my $new_dt = $self->_new_from_self(%p); %$self = %$new_dt; return $self; } } sub set_year { $_[0]->set( year => $_[1] ) } sub set_month { $_[0]->set( month => $_[1] ) } sub set_day { $_[0]->set( day => $_[1] ) } sub set_hour { $_[0]->set( hour => $_[1] ) } sub set_minute { $_[0]->set( minute => $_[1] ) } sub set_second { $_[0]->set( second => $_[1] ) } sub set_nanosecond { $_[0]->set( nanosecond => $_[1] ) } # These two are special cased because ... if the local time is the hour of a # DST change where the same local time occurs twice then passing it through # _new() can actually change the underlying UTC time, which is bad. { my $validator = validation_for( name => '_check_set_locale_params', name_is_optional => 1, params => [ { type => t( 'Maybe', of => t('Locale') ) }, ], ); sub set_locale { my $self = shift; my ($locale) = $validator->(@_); $self->_set_locale($locale); return $self; } } { my $validator = validation_for( name => '_check_set_formatter_params', name_is_optional => 1, params => [ { type => t( 'Maybe', of => t('Formatter') ) }, ], ); sub set_formatter { my $self = shift; my ($formatter) = $validator->(@_); $self->{formatter} = $formatter; return $self; } } { my %TruncateDefault = ( month => 1, day => 1, hour => 0, minute => 0, second => 0, nanosecond => 0, ); my $validator = validation_for( name => '_check_truncate_params', name_is_optional => 1, params => { to => { type => t('TruncationLevel') }, }, ); my $re = join '|', 'year', 'week', 'local_week', 'quarter', grep { $_ ne 'nanosecond' } keys %TruncateDefault; my $spec = { to => { regex => qr/^(?:$re)$/ } }; ## no critic (Subroutines::ProhibitBuiltinHomonyms) sub truncate { my $self = shift; my %p = $validator->(@_); my %new; if ( $p{to} eq 'week' || $p{to} eq 'local_week' ) { my $first_day_of_week = ( $p{to} eq 'local_week' ) ? $self->{locale}->first_day_of_week : 1; my $day_diff = ( $self->day_of_week - $first_day_of_week ) % 7; if ($day_diff) { $self->add( days => -1 * $day_diff ); } # This can fail if the truncate ends up giving us an invalid local # date time. If that happens we need to reverse the addition we # just did. See. try { $self->truncate( to => 'day' ); } catch { $self->add( days => $day_diff ); die $_; }; } elsif ( $p{to} eq 'quarter' ) { %new = ( year => $self->year, month => int( ( $self->month - 1 ) / 3 ) * 3 + 1, day => 1, hour => 0, minute => 0, second => 0, nanosecond => 0, ); } else { my $truncate; foreach my $f (qw( year month day hour minute second nanosecond )) { $new{$f} = $truncate ? $TruncateDefault{$f} : $self->$f(); $truncate = 1 if $p{to} eq $f; } } my $new_dt = $self->_new_from_self( %new, _skip_validation => 1 ); %$self = %$new_dt; return $self; } } sub set_time_zone { my ( $self, $tz ) = @_; if ( ref $tz ) { # This is a bit of a hack but it works because time zone objects # are singletons, and if it doesn't work all we lose is a little # bit of speed. return $self if $self->{tz} eq $tz; } else { return $self if $self->{tz}->name eq $tz; } my $was_floating = $self->{tz}->is_floating; my $old_tz = $self->{tz}; $self->{tz} = ref $tz ? $tz : DateTime::TimeZone->new( name => $tz ); $self->_handle_offset_modifier( $self->second, 1 ); my $e; try { # if it either was or now is floating (but not both) if ( $self->{tz}->is_floating xor $was_floating ) { $self->_calc_utc_rd; } elsif ( !$was_floating ) { $self->_calc_local_rd; } } catch { $e = $_; }; # If we can't recalc the RD values then we shouldn't keep the new TZ. RT # #83940 if ($e) { $self->{tz} = $old_tz; die $e; } return $self; } sub STORABLE_freeze { my $self = shift; my $serialized = q{}; foreach my $key ( qw( utc_rd_days utc_rd_secs rd_nanosecs ) ) { $serialized .= "$key:$self->{$key}|"; } # not used yet, but may be handy in the future. $serialized .= 'version:' . ( $DateTime::VERSION || 'git' ); # Formatter needs to be returned as a reference since it may be # undef or a class name, and Storable will complain if extra # return values aren't refs return $serialized, $self->{locale}, $self->{tz}, \$self->{formatter}; } sub STORABLE_thaw { my $self = shift; shift; my $serialized = shift; my %serialized = map { split /:/ } split /\|/, $serialized; my ( $locale, $tz, $formatter ); # more recent code version if (@_) { ( $locale, $tz, $formatter ) = @_; } else { $tz = DateTime::TimeZone->new( name => delete $serialized{tz} ); $locale = DateTime::Locale->load( delete $serialized{locale} ); } delete $serialized{version}; my $object = bless { utc_vals => [ $serialized{utc_rd_days}, $serialized{utc_rd_secs}, $serialized{rd_nanosecs}, ], tz => $tz, }, 'DateTime::_Thawed'; my %formatter = defined $$formatter ? ( formatter => $$formatter ) : (); my $new = ( ref $self )->from_object( object => $object, locale => $locale, %formatter, ); %$self = %$new; return $self; } ## no critic (Modules::ProhibitMultiplePackages) package # hide from PAUSE DateTime::_Thawed; sub utc_rd_values { @{ $_[0]->{utc_vals} } } sub time_zone { $_[0]->{tz} } 1; # ABSTRACT: A date and time object for Perl __END__ =pod =encoding UTF-8 =head1 NAME DateTime - A date and time object for Perl =head1 VERSION version 1.54 =head1); =head1 DESCRIPTION DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project. For details on this project please see L<>. The DateTime site has a FAQ which may help answer many "how do I do X?" questions. The FAQ is at L<DateTime::Infinite|DateTime::Infinite> module. =head1 USAGE =head2 0-based Versus 1-based Numbers The C<_0>. So for example, this class provides both C<day_of_week> and C<day_of_week_0> methods. The C<day_of_week_0> method still treats Monday as the first day of the week. All I<time>-related numbers such as hour, minute, and second are 0-based. Years are neither, as they can be both positive or negative, unlike any other datetime component. There I<is> a year 0. There is no C<quarter_0> method. =head2 Error Handling Some errors may cause this module to die with an error string. This can only happen when calling constructor methods, methods that change the object, such as C<set>, or methods that take parameters. Methods that retrieve information about the object, such as C<year> or C<epoch>, will never die. =head2 Locales All the object methods which return names or abbreviations return data based on a locale. This is done by setting the locale when constructing a DateTime object. If this is not set, then C<"en-US"> is used. =head2 B<do not> mix these with floating datetimes. =head2 Math If you are going to be doing date math, please read the section L<How DateTime Math Works>. =head2 Determining the Local Time Zone Can Be Slow If C<$ENV{TZ}> is not set, it may involve reading a number of files in. =head2 Far Future DST Do not try to use named time zones (like "America/Chicago") with dates very far in the future (thousands of years). The current implementation of C<DateTime::TimeZone> will use a huge amount of memory calculating all the DST changes from now until the future date. Use UTC or the floating time zone and you will be safe. =head2 Globally Setting a Default Time Zone B<Warning: This is very dangerous. Do this at your own risk!> By default, C<DateTime> uses either the floating time zone or UTC for newly created objects, depending on the constructor. You can force C<DateTime> to use a different time zone by setting the C<PERL_DATETIME_DEFAULT_TZ> environment variable. As noted above, this is very dangerous, as it affects all code that creates a C<DateTime> object, including modules from CPAN. If those modules expect the normal default, then setting this can cause confusing breakage or subtly broken data. Before setting this variable, you are strongly encouraged to audit your CPAN dependencies to see how they use C<DateTime>. Try running the test suite for each dependency with this environment variable set before using this in production. =head2 Upper and Lower Bounds Internally, dates are represented the number of days before or after 0001-01-01. This is stored as an integer, meaning that the upper and lower bounds are based on your Perl's integer size (C<). =head1 METHODS DateTime provides many methods. The documentation breaks them down into groups based on what they do (constructor, accessors, modifiers, etc.). =head2 Constructors All constructors can die when invalid parameters are given. =head3 I<really> slow (minutes). All warnings from DateTime use the C<DateTime> category and can be suppressed with: no warnings 'DateTime'; This warning may be removed in the future if L<DateTime::TimeZone> is made much faster. =head3 DateTime->new( ... ) my $dt = DateTime->new( year => 1966, month => 10, day => 25, hour => 7, minute => 15, second => 47, nanosecond => 500000000, time_zone => 'America/Chicago', ); This class method accepts the following parameters: =over 4 =item * year An integer year for the DateTime. This can be any integer number within the valid range for your system (See L</Upper and Lower Bounds>). This is required. =item * month An integer from 1-12. Defaults to 1. =item * day An integer from 1-31. The value will be validated based on the month, to prevent creating invalid dates like February 30. Defaults to 1. =item * hour An integer from 0-23. Hour 0 is midnight at the beginning of the given date. Defaults to 0. =item * minute An integer from 0-59. Defaults to 0. =item * second An integer from 0-61. Values of 60 or 61 are only allowed when the specified date and time have a leap second. Defaults to 0. =item * nanosecond An integer that is greater than or equal to 0. If this number is greater than 1 billion, it will be normalized into the second value for the DateTime object. Defaults to 0 =item * locale A string containing a locale code, like C<"en-US"> or C<"zh-Hant-TW">, or an object returned by C<< DateTime::Locale->load >>. See the L<DateTime::Locale> documentation for details. Defaults to the value of C<< DateTime->DefaultLocale >>, or C<"en-US"> if the class default has not been set. =item * time_zone A string containing a time zone name like "America/Chicago" or a L<DateTime::TimeZone> object. Defaults to the value of C<$ENV{PERL_DATETIME_DEFAULT_TZ}> or "floating" if that env var is not set. See L</Globally Setting a Default Time Zone> for more details on that env var (and why you should not use it). A string will simply be passed to the C<< DateTime::TimeZone->new >> method as its C<name> parameter. This string may be an Olson DB time zone name ("America/Chicago"), an offset string ("+0630"), or the words "floating" or "local". See the C<DateTime::TimeZone> documentation for more details. =item * formatter An object or class name with a C<format_datetime> method. This will be used to stringify the DateTime object. This is optional. If it is not specified, then stringification calls C<< $self->iso8601 >>. =back Invalid parameter types (like an array reference) will cause the constructor to die. =head4 Parsing Dates B<This module does not parse dates!> That means there is no constructor to which you can pass things like "March 3, 1970 12:34". Instead, take a look at the various L<DateTime::Format::*|> modules on CPAN. These parse all sorts of different date formats, and you're bound to find something that can handle your particular needs. =head4 C<set_time_zone> method to change the time zone. This is a good way to ensure that the time is not ambiguous. =head4. =head3 DateTime->from_epoch( epoch => $epoch, ... ) This class method can be used to construct a new DateTime object from an epoch time instead of components. Just as with the C<new> method, it accepts C<time_zone>, C<locale>, and C<formatter> parameters. If the epoch value is a non-integral value, it will be rounded to nearest microsecond. By default, the returned object will be in the UTC time zone. =head3 DateTime->now( ... ) This class method is equivalent to calling C<from_epoch> with the value returned from Perl's C<time> function. Just as with the C<new> method, it accepts C<time_zone> and C<locale> parameters. By default, the returned object will be in the UTC time zone. If you want sub-second resolution, use the L<DateTime::HiRes> module's C<< DateTime::HiRes->now >> method instead. =head3 DateTime->today( ... ) This class method is equivalent to: DateTime->now(@_)->truncate( to => 'day' ); =head3 DateTime->last_day_of_month( ... ) This constructor takes the same arguments as can be given to the C<new> method, except for C<day>. Additionally, both C<year> and C<month> are required. =head3 DateTime->from_day_of_year( ... ) This constructor takes the same arguments as can be given to the C<new> method, except that it does not accept a C<month> or C<day> argument. Instead, it requires both C<year> and C<day_of_year>. The day of year must be between 1 and 366, and 366 is only allowed for leap years. =head3 DateTime->from_object( object => $object, ... ) This class method can be used to construct a new DateTime object from any object that implements the C<utc_rd_values> method. All C<DateTime::Calendar> modules must implement this method in order to provide cross-calendar compatibility. This method accepts a C<locale> and C<formatter> parameter If the object passed to this method has a C<time_zone> method, that is used to set the time zone of the newly created C<DateTime> object. Otherwise, the returned object will be in the floating time zone. =head3 $dt->clone This object method returns a new object that is replica of the object upon which the method is called. =head2 "Get" Methods This class has many methods for retrieving information about an object. =head3 $dt->year Returns the year. =head3 $dt->ce_year Returns the year according to the BCE/CE numbering system. The year before year 1 in this system is year -1, aka "1 BCE". =head3 $dt->era_name Returns the long name of the current era, something like "Before Christ". See the L</Locales> section for more details. =head3 $dt->era_abbr Returns the abbreviated name of the current era, something like "BC". See the L</Locales> section for more details. =head3 $dt->christian_era Returns a string, either "BC" or "AD", according to the year. =head3 $dt->secular_era Returns a string, either "BCE" or "CE", according to the year. =head3 $dt->year_with_era Returns a string containing the year immediately followed by the appropriate era abbreviation, based on the object's locale. The year is the absolute value of C<ce_year>, so that year 1 is "1" and year 0 is "1BC". See the L</Locales> section for more details. =head3 $dt->year_with_christian_era Like C<year_with_era>, but uses the C<christian_era> method to get the era name. =head3 $dt->year_with_secular_era Like C<year_with_era>, but uses the C<secular_era> method to get the era name. =head3 $dt->month Returns the month of the year, from 1..12. Also available as C<< $dt->mon >>. =head3 $dt->month_name Returns the name of the current month. See the L</Locales> section for more details. =head3 $dt->month_abbr Returns the abbreviated name of the current month. See the L</Locales> section for more details. =head3 $dt->day Returns the day of the month, from 1..31. Also available as C<< $dt->mday >> and C<< $dt->day_of_month >>. =head3 $dt->day_of_week Returns the day of the week as a number, from 1..7, with 1 being Monday and 7 being Sunday. Also available as C<< $dt->wday >> and C<< $dt->dow >>. =head3 $dt->local_day_of_week Returns the day of the week as a number, from 1..7. The day corresponding to 1 will vary based on the locale. See the L</Locales> section for more details. =head3 $dt->day_name Returns the name of the current day of the week. See the L</Locales> section for more details. =head3 $dt->day_abbr Returns the abbreviated name of the current day of the week. See the L</Locales> section for more details. =head3 $dt->day_of_year Returns the day of the year. Also available as C<< $dt->doy >>. =head3 $dt->quarter Returns the quarter of the year, from 1..4. =head3 $dt->quarter_name Returns the name of the current quarter. See the L</Locales> section for more details. =head3 $dt->quarter_abbr Returns the abbreviated name of the current quarter. See the L</Locales> section for more details. =head3 $dt->day_of_quarter Returns the day of the quarter. Also available as C<< $dt->doq >>. =head3 $dt->weekday_of_month Returns a number from 1..5 indicating which week day of the month this is. For example, June 9, 2003 is the second Monday of the month, and so this method returns 2 for that date. =head3 C<< $dt->ymd >> method is also available as C<< $dt->date >>. =head3 $dt->hour Returns the hour of the day, from 0..23. =head3 $dt->hour_1 Returns the hour of the day, from 1..24. =head3 $dt->hour_12 Returns the hour of the day, from 1..12. =head3 $dt->hour_12_0 Returns the hour of the day, from 0..11. =head3 $dt->am_or_pm Returns the appropriate localized abbreviation, depending on the current hour. =head3 $dt->minute Returns the minute of the hour, from 0..59. Also available as C<< $dt->min >>. =head3 $dt->second Returns the second, from 0..61. The values 60 and 61 are used for leap seconds. Also available as C<< $dt->sec >>. =head3 $dt->fractional_second Returns the second, as a real number from 0.0 until 61.999999999 The values 60 and 61 are used for leap seconds. =head3 $dt->millisecond Returns the fractional part of the second as milliseconds (1E-3 seconds). Half a second is 500 milliseconds. This value will always be rounded down to the nearest integer. =head3 $dt->microsecond Returns the fractional part of the second as microseconds (1E-6 seconds). Half a second is 500,000 microseconds. This value will always be rounded down to the nearest integer. =head3 $dt->nanosecond Returns the fractional part of the second as nanoseconds (1E-9 seconds). Half a second is 500,000,000 nanoseconds. =head3 $dt->hms($optional_separator) Returns the hour, minute, and second, all zero-padded to two digits. If no separator is specified, a colon (:) is used by default. Also available as C<< $dt->time >>. =head3 $dt->datetime($optional_separator) This method is equivalent to: $dt->ymd('-') . 'T' . $dt->hms(':') The C<$optional_separator> parameter allows you to override the separator between the date and time, for e.g. C<< $dt->datetime(q{ }) >>. This method is also available as C<< $dt->iso8601 >>, but it's not really a very good ISO8601 format, as it lacks a time zone. If called as C<< $dt->iso8601 >> you cannot change the separator, as ISO8601 specifies that "T" must be used to separate them. =head3 $dt->rfc3339 This formats a datetime in RFC3339 format. This is the same as. =head3 $dt->stringify This method returns a stringified version of the object. It is also how stringification overloading is implemented. If the object has a formatter, then its C<format_datetime> method is used to produce a string. Otherwise, this method calls C<< $dt->iso8601 >> to produce a string. See L</Formatters And Stringification> for details. =head3 $dt->is_leap_year This method returns a boolean value indicating whether or not the datetime object is in a leap year. =head3 $dt->is_last_day_of_month This method returns a boolean value indicating whether or not the datetime object is the last day of the month. =head3 $dt->is_last_day_of_quarter This method returns a boolean value indicating whether or not the datetime object is the last day of the quarter. =head3 $dt->is_last_day_of_year This method returns a boolean value indicating whether or not the datetime object is the last day of the year. =head3 $dt->month_length This method returns the number of days in the current month. =head3 $dt->quarter_length This method returns the number of days in the current quarter. =head3 $dt->year_length This method returns the number of days in the current year. =head3 $dt->week my ( $week_year, $week_number ) = $dt->week; Returns information about the calendar week for the date. The values returned by this method are also available separately through the C<< $dt->week_year >> and. =head3 $dt->week_year Returns the year of the week. See C<< $dt->week >> for details. =head3 $dt->week_number Returns the week of the year, from 1..53. See C<< $dt->week >> for details. =head3 I<before> the week with the first Thursday will be week 0. =head3 ". =head3 $dt->time_zone This returns the L<DateTime::TimeZone> object for the datetime object. =head3 $dt->offset This returns the offset from UTC, in seconds, of the datetime object's time zone. =head3 $dt->is_dst Returns a boolean indicating whether or not the datetime's time zone is currently in Daylight Saving Time or not. =head3 $dt->time_zone_long_name This is a shortcut for C<< $dt->time_zone->name >>. It's provided so that one can use "%{time_zone_long_name}" as a strftime format specifier. =head3 $dt->time_zone_short_name This method returns the time zone abbreviation for the current time zone, such as "PST" or "GMT". These names are B<not> definitive, and should not be used in any application intended for general use by users around the world. That's because it's possible for multiple time zones to have the same abbreviation. =head3 $dt->strftime( $format, ... ) This method implements functionality similar to the C<strftime> method in C. However, if given multiple format strings, then it will return multiple scalars, one for each format string. See the L<strftime Patterns> section for a list of all possible strftime patterns. If you give a pattern that doesn't exist, then it is simply treated as text. Note that any deviation from the POSIX standard is probably a bug. DateTime should match the output of C<POSIX::strftime> for any given pattern. =head3 $dt->format_cldr( $format, ... ) This method implements formatting based on the CLDR date patterns. If given multiple format strings, then it will return multiple scalars, one for each format string. See the L<CLDR Patterns> section for a list of all possible CLDR patterns. If you give a pattern that doesn't exist, then it is simply treated as text. =head3 . =head3 $dt->hires_epoch Returns the epoch as a floating point number. The floating point portion of the value represents the nanosecond value of the object. This method is provided for compatibility with the C<1325376000> because adding C<0.000000004> to C<1325376000> returns C<1325376000>. =head3 $dt->is_finite, $dt->is_infinite These methods allow you to distinguish normal datetime objects from infinite ones. Infinite datetime objects are documented in L<DateTime::Infinite>. =head3 $dt->utc_rd_values Returns the current UTC Rata Die days, seconds, and nanoseconds as a three element list. This exists primarily to allow other calendar modules to create objects based on the values provided by this object. =head3 $dt->local_rd_values Returns the current local Rata Die days, seconds, and nanoseconds as a three element list. This exists for the benefit of other modules which might want to use this information for date math, such as L<DateTime::Event::Recurrence>. =head3 $dt->leap_seconds Returns the number of leap seconds that have happened up to the datetime represented by the object. For floating datetimes, this always returns 0. =head3 $dt->utc_rd_as_seconds Returns the current UTC Rata Die days and seconds purely as seconds. This number ignores any fractional seconds stored in the object, as well as leap seconds. =head3 $dt->locale Returns the datetime's L<DateTime::Locale> object. =head3 $dt->formatter Returns the current formatter object or class. See L<Formatters And Stringification> for details. =head2 "Set" Methods The remaining methods provided by ); =head3 $dt->set( .. ) This method can be used to change the local components of a date time. This method accepts any parameter allowed by the C<new> method except for C<locale> or C<time_zone>. Use C<set_locale> and C<set_time_zone> for those instead. This method performs parameter validation just like the C<new> method. B<Do not use this method to do date math. Use the C<add> and C<subtract> methods instead.> =head3 $dt->set_year, $dt->set_month, etc. DateTime has a C<set_*> method for every item that can be passed to the constructor: =over 4 =item * $dt->set_year =item * $dt->set_month =item * $dt->set_day =item * $dt->set_hour =item * $dt->set_minute =item * $dt->set_second =item * $dt->set_nanosecond =back These are shortcuts to calling C<set> with a single key. They all take a single parameter. =head3 $dt->truncate( to => ... ) This method allows you to reset some of the local time components in the object to their "zero" values. The C<to> parameter is used to specify which values to truncate, and it may be one of C<"year">, C<"quarter">, C<"month">, C<"week">, C<"local_week">, C<"day">, C<"hour">, C<"minute">, or C<"second">. For example, if C<"month"> is specified, then the local day becomes 1, and the hour, minute, and second all become 0. If C<"week"> is given, then the datetime is set to the Monday of the week in which it occurs, and the time components are all set to 0. If you truncate to C<"local_week">, then the first day of the week is locale-dependent. For example, in the C<"en-US"> locale, the first day of the week is Sunday. =head3 $dt->set_locale($locale) Sets the object's locale. You can provide either a locale code like C<"en-US"> or an object returned by C<< DateTime::Locale->load >>. =head3 $dt->set_time_zone($tz) This method accepts either a time zone object or a string that can be passed as the C<name> parameter to C<< DateTime::TimeZone->new >>. If the new time zone's offset is different from the old time zone, then the I I?" =head3 $dt->set_formatter($formatter) Sets the formatter for the object. See L<Formatters And Stringification> for details. You can set this to C<undef> to revert to the default formatter. =head2 Math Methods Like the set methods, math related methods always return the object itself, to allow for chaining: $dt->add( days => 1 )->subtract( seconds => 1 ); =head3 $dt->duration_class This returns L<C<"DateTime::Duration">|DateTime::Duration>, but exists so that a subclass of C<DateTime> can provide a different value. =head3 $dt->add_duration($duration_object) This method adds a L<DateTime::Duration> to the current datetime. See the L<DateTime::Duration> docs for more details. =head3 $dt->add( parameters for DateTime::Duration ) This method is syntactic sugar around the C<< $dt->add_duration >> method. It simply creates a new L<DateTime::Duration> object using the parameters given, and then calls the C<< $dt->add_duration >> method. =head3 $dt->add($duration_object) A synonym of C<< $dt->add_duration($duration_object) >>. =head3 $dt->subtract_duration($duration_object) When given a L<DateTime::Duration> object, this method simply calls C<< $dur->inverse >> on that object and passes that new duration to the C<< $self->add_duration >> method. =head3 $dt->subtract( DateTime::Duration->new parameters ) Like C<< $dt->add >>, this is syntactic sugar for the C<< $dt->subtract_duration >> method. =head3 $dt->subtract($duration_object) A synonym of C<< $dt->subtract_duration($duration_object) >>. =head3 $dt->subtract_datetime($datetime) This method returns a new L<DateTime::Duration> object representing the difference between the two dates. The duration is B<relative> to the object from which C<. =head3 $dt->delta_md($datetime) =head3 $dt->delta_days($datetime) Each of these methods returns a new L<DateTime::Duration> object representing some portion of the difference between two datetimes. The C<< $dt->delta_md >> method returns a duration which contains only the month and day portions of the duration is represented. The C<< $dt->delta_days >> method returns a duration which contains only days. The C<< $dt->delta_md >> and C<< $dt->delta_days >> methods truncate the duration so that any fractional portion of a day is ignored. Both of these methods operate on the date portion of a datetime only, and so effectively ignore the time zone. Unlike the subtraction methods, B<these methods always return a positive (or zero) duration>. =head3 $dt->delta_ms($datetime) Returns a duration which contains only minutes and seconds. Any day and month differences are converted to minutes and seconds. This method B<always returns a positive (or zero) duration>. =head3 $dt->subtract_datetime_absolute($datetime) This method returns a new L C<< $dt->epoch >>. =head3 $dt->is_between( $lower, $upper ) Checks whether C<$dt> is strictly between two other DateTime objects. "Strictly" means that C<$dt> must be greater than C<$lower> and less than C<$upper>. If it is I<equal> to either object then this method returns false. =head2 Class Methods =head3 DateTime->DefaultLocale($locale) This can be used to specify the default locale to be used when creating DateTime objects. If unset, then C<"en-US"> is used. This exists for backwards compatibility, but is probably best avoided. This will change the default locale for every C<DateTime> object created in your application, even those created by third party libraries which also use C<DateTime>. =head3 C<sort> function; it returns C<-1> if C<< $dt1 < $dt2 >>, C<0> if C<$dt1 == $dt2>, C<1> if C<< C<utc_rd_values> method. =head2 Testing Code That Uses DateTime If you are trying to test code that calls uses DateTime, you may want to be to explicitly set the value returned by Perl's C<time> builtin. This builtin is called by C<< DateTime->now >> and C<< DateTime->today >>. You can override C<CORE::GLOBAL::time>, but this will only work if you do this B<before> loading DateTime. If doing this is inconvenient, you can also override C<DateTime::_core_time>: no warnings 'redefine'; local *DateTime::_core_time = sub { return 42 }; DateTime is guaranteed to call this subroutine to get the current C<time> value. You can also override the C<_core_time> sub in a subclass of DateTime and use that. =head2 How DateTime Math Works It's important to have some understanding of how datetime math is implemented in order to effectively use this module and L<DateTime::Duration>. =head3 Making Things Simple If you want to simplify your life and not have to think too hard about the nitty-gritty of datetime math, I have several recommendations: =over 4 =item * I'); =item *; =item * math on non-UTC time zones If you need to do date math on objects with non-UTC time zones, please read the caveats below carefully. The results C<DateTime> produces L<Leap Seconds and Date Math> =item * date vs datetime math If you only care about the date (calendar) portion of a datetime, you should use either C<< $dt->delta_md >>> or C<< $dt->delta_days >>, not C<< $dt->subtract_datetime >>. This will give predictable, unsurprising results, free from DST-related complications. =item * C<< $dt->delta_days >> ensures that this formula always works, regardless of the time zones of the objects involved, as does using C<< $dt->subtract_datetime_absolute >>. Other methods of subtraction are not always reversible. =item * never do math on two objects where only one is in the floating time zone The date math code accounts for leap seconds whenever the C<DateTime> object is not in the floating time zone. If you try to do math where one object is in the floating zone and the other isn't, the results will be confusing and wrong. =back =head3. C L<DateTime::Duration> object represents, you have to add it to a datetime to find out, so you could do: my $now = DateTime->now( time_zone => 'UTC' ); my $later = $now->clone->add_duration($duration); my $seconds_dur = $later->subtract_datetime_absolute($now); This returns a L<DateTime::Duration> which only contains seconds and nanoseconds. If we were add the duration to a different C<DateTime> object we might get a different number of seconds. L C<"wrap"> for positive durations and C<"preserve"> for negative durations. See L<DateTime::Duration> for a detailed explanation of these algorithms. If you need to do lots of work with durations, take a look at the L<DateTime::Format::Duration> module, which lets you present information from durations in many useful ways. There are other subtract/delta methods in C<DateTime> to generate different types of durations. These methods are C<< $dt->subtract_datetime >>, C<< $dt->subtract_datetime_absolute >>, C<< $dt->delta_md >>, C<< $dt->delta_days >>, and C<< $dt->delta_ms >>. =head3 C<$dt2> in the above example still leaves the clock time at "01:00:00". This time we are accounting for a 25 hour day. =head3 Reversibility Date math operations are not always reversible. This is because of the way that addition operations are ordered. As was discussed earlier, adding 1 day and 3 minutes in one call to C<< $dt->add >>> is not the same as first adding 3 minutes and 1 day in two separate calls. If we take a duration returned from C<$dt1>. This can be facilitated by the L<DateTime::Duration> class's C<< $dur->calendar_duration >> and C<< $dur->clock_duration >> methods: $dt2->subtract_duration( $dur->clock_duration ) ->subtract_duration( $dur->calendar_duration ); =head3 ); =head3 I! =head2, C<eq> or C<ne>, will use the string value to compare with non-DateTime objects. DateTime objects do not have a numeric value, using C<==> or C<< <=> >> to compare a DateTime object with a non-DateTime object will result in an exception. To safely sort mixed DateTime and non-DateTime objects, use C<sort { $a cmp $b } @dates>. The module also overloads stringification using the object's formatter, defaulting to C<iso8601> method. See L<Formatters And Stringification> for details. =head2 Formatters And Stringification You can optionally specify a C<formatter>, which is usually a C<format_datetime> method. This method will be called with just the C<DateTime> object as its argument. =head2 CLDR Patterns The CLDR pattern language is both more powerful and more complex than strftime. Unlike strftime patterns, you often have to explicitly escape text that you do not want formatted, as the patterns are simply letters without any prefix. For example, C<, C<"h"> represents the current hour from 1-12. If you specify C< C<DateTime::TimeZone>, and I<do not follow the CLDR spec>. The output of a CLDR pattern is always localized, when applicable. CLDR provides the following patterns: =over 4 =item * G{1,3} The abbreviated era (BC, AD). =item * GGGG The wide era (Before Christ, Anno Domini). =item * GGGGG The narrow era, if it exists (but it mostly doesn't). =item * y and y{3,} The year, zero-prefixed as needed. Negative years will start with a "-", and this will be included in the length calculation. In other, words the "yyyyy" pattern will format year -1234 as "-1234", not "-01234". =item * yy This is a special case. It always produces a two-digit year, so "1976" becomes "76". Negative years will start with a "-", making them one character longer. =item * Y{1,} The year in "week of the year" calendars, from C<< $dt->week_year >>. =item * u{1,} Same as "y" except that "uu" is not a special case. =item * Q{1,2} The quarter as a number (1..4). =item * QQQ The abbreviated format form for the quarter. =item * QQQQ The wide format form for the quarter. =item * q{1,2} The quarter as a number (1..4). =item * qqq The abbreviated stand-alone form for the quarter. =item * qqqq The wide stand-alone form for the quarter. =item * M{1,2] The numerical month. =item * MMM The abbreviated format form for the month. =item * MMMM The wide format form for the month. =item * MMMMM The narrow format form for the month. =item * L{1,2] The numerical month. =item * LLL The abbreviated stand-alone form for the month. =item * LLLL The wide stand-alone form for the month. =item * LLLLL The narrow stand-alone form for the month. =item * w{1,2} The week of the year, from C<< $dt->week_number >>. =item * W The week of the month, from C<< $dt->week_of_month >>. =item * d{1,2} The numeric day of the month. =item * D{1,3} The numeric day of the year. =item * F The day of the week in the month, from C<< $dt->weekday_of_month >>. =item * g{1,} The modified Julian day, from C<< $dt->mjd >>. =item * E{1,3} and eee The abbreviated format form for the day of the week. =item * EEEE and eeee The wide format form for the day of the week. =item * EEEEE and eeeee The narrow format form for the day of the week. =item * e{1,2} The I<local> numeric day of the week, from 1 to 7. This number depends on what day is considered the first day of the week, which varies by locale. For example, in the US, Sunday is the first day of the week, so this returns 2 for Monday. =item * c The numeric day of the week from 1 to 7, treating Monday as the first of the week, regardless of locale. =item * ccc The abbreviated stand-alone form for the day of the week. =item * cccc The wide stand-alone form for the day of the week. =item * ccccc The narrow format form for the day of the week. =item * a The localized form of AM or PM for the time. =item * h{1,2} The hour from 1-12. =item * H{1,2} The hour from 0-23. =item * K{1,2} The hour from 0-11. =item * k{1,2} The hour from 1-24. =item * j{1,2} The hour, in 12 or 24 hour form, based on the preferred form for the locale. In other words, this is equivalent to either "h{1,2}" or "H{1,2}". =item * m{1,2} The minute. =item * s{1,2} The second. =item * S{1,} The fractional portion of the seconds, rounded based on the length of the specifier. This returned I<without> a leading decimal point, but may have leading or trailing zeroes. =item * A{1,} The millisecond of the day, based on the current time. In other words, if it is 12:00:00.00, this returns 43200000. =item * z{1,3} The time zone short name. =item * zzzz The time zone long name. =item * Z{1,3} The time zone offset. =item * ZZZZ The time zone short name and the offset as one string, so something like "CDT-0500". =item * ZZZZZ The time zone offset as a sexagesimal number, so something like "-05:00". (This is useful for W3C format.) =item * v{1,3} The time zone short name. =item * vvvv The time zone long name. =item * V{1,3} The time zone short name. =item * VVVV The time zone long name. =back =head3 C<2008-02-05T18:30:30> as our example datetime value, and see how this is rendered for the C<"en-US"> and C<"fr-FR"> locales. =over 4 =item * C<MMMd> The abbreviated month and day as number. For C<en-US>, we get the pattern C<MMM d>, which renders as C<Feb 5>. For C<fr-FR>, we get the pattern C<d MMM>, which renders as C<5 févr.>. =item * C<yQQQ> The year and abbreviated quarter of year. For C<en-US>, we get the pattern C<QQQ y>, which renders as C<Q1 2008>. For C<fr-FR>, we get the same pattern, C<QQQ y>, which renders as C<T1 2008>. =item * C<hm> The 12-hour time of day without seconds. For C<en-US>, we get the pattern C<h:mm a>, which renders as C<6:30 PM>. For C<fr-FR>, we get the exact same pattern and rendering. =back The available formats for each locale are documented in the POD for that locale. To get back the format, you use the C<< $locale->format_for >> method. For example: say $dt->format_cldr( $dt->locale->format_for('MMMd') ); =head2 strftime Patterns The following patterns are allowed in the format string given to the C<< $dt->strftime >> method: =over 4 =item * %a The abbreviated weekday name. =item * %A The full weekday name. =item * %b The abbreviated month name. =item * %B The full month name. =item * %c The default datetime format for the object's locale. =item * %C The century number (year/100) as a 2-digit integer. =item * %d The day of the month as a decimal number (range 01 to 31). =item * %D Equivalent to %m/%d/%y. This is not a good standard format if you want folks from both the United States and the rest of the world to understand the date! =item * %e Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space. =item * %F Equivalent to %Y-%m-%d (the ISO 8601 date format) =item * ) =item * %g Like %G, but without century, i.e., with a 2-digit year (00-99). =item * %h Equivalent to %b. =item * %H The hour as a decimal number using a 24-hour clock (range 00 to 23). =item * %I The hour as a decimal number using a 12-hour clock (range 01 to 12). =item * %j The day of the year as a decimal number (range 001 to 366). =item * %k The hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank. (See also %H.) =item * %l The hour (12-hour clock) as a decimal number (range 1 to 12); single digits are preceded by a blank. (See also %I.) =item * %m The month as a decimal number (range 01 to 12). =item * %M The minute as a decimal number (range 00 to 59). =item * %n A newline character. =item * %N The fractional seconds digits. Default is 9 digits (nanoseconds). %3N milliseconds (3 digits) %6N microseconds (6 digits) %9N nanoseconds (9 digits) This value will always be rounded down to the nearest integer. =item * %p Either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale. Noon is treated as `pm' and midnight as `am'. =item * %P Like %p but in lowercase: `am' or `pm' or a corresponding string for the current locale. =item * %r The time in a.m. or p.m. notation. In the POSIX locale this is equivalent to `%I:%M:%S %p'. =item * %R The time in 24-hour notation (%H:%M). (SU) For a version including the seconds, see %T below. =item * %s The number of seconds since the epoch. =item * %S The second as a decimal number (range 00 to 61). =item * %t A tab character. =item * %T The time in 24-hour notation (%H:%M:%S). =item * %u The day of the week as a decimal, range 1 to 7, Monday being 1. See also %w. =item * %U The week number of the current year as a decimal number, range 00 to 53, starting with the first Sunday as the first day of week 01. See also %V and %W. =item * . =item * %w The day of the week as a decimal, range 0 to 6, Sunday being 0. See also %u. =item * %W The week number of the current year as a decimal number, range 00 to 53, starting with the first Monday as the first day of week 01. =item * %x The default date format for the object's locale. =item * %X The default time format for the object's locale. =item * %y The year as a decimal number without a century (range 00 to 99). =item * %Y The year as a decimal number including the century. =item * %z The time-zone as hour offset from UTC. Required to emit RFC822-conformant dates (using "%a, %d %b %Y %H:%M:%S %z"). =item * %Z The short name for the time zone, typically an abbreviation like "EST" or "AEST". =item * %% A literal `%' character. =item * %{method} Any method name may be specified using the format C<%{method}> name where "method" is a valid C<DateTime> object method. =back =head2 DateTime and Storable C<DateTime> implements L<Storable> hooks in order to reduce the size of a serialized C<DateTime> object. =head1 THE DATETIME PROJECT ECOSYSTEM This module is part of a larger ecosystem of modules in the DateTime family. =head2 L<DateTime::Set> The L<DateTime::Set> module represents sets (including recurrences) of datetimes. Many modules return sets or recurrences. =head2 Format Modules The various format modules exist to parse and format datetimes. For example, L C<formatter> with a DateTime object. All format modules start with L<DateTime::Format::|>. =head2 Calendar Modules There are a number of modules on CPAN that implement non-Gregorian calendars, such as the Chinese, Mayan, and Julian calendars. All calendar modules start with L<DateTime::Calendar::|>. =head2 Event Modules There are a number of modules that calculate the dates for events, such as Easter, Sunrise, etc. All event modules start with L<DateTime::Event::|>. =head2 Others There are many other modules that work with DateTime, including modules in the L<DateTimeX namespace|> namespace, as well as others. See L<MetaCPAN|> for more modules. =head1 KNOWN BUGS The tests in. =head1 SEE ALSO L<A Date with Perl|> - a talk I've given at a few YAPCs. L<datetime@perl.org mailing list|> L<> =head1 SUPPORT Bugs may be submitted at L<>. There is a mailing list available for users of this distribution, L<mailto:datetime@perl.org>. I am also usually active on IRC as 'autarch' on C<irc://irc.perl.org>. =head1 SOURCE The source code repository for DateTime can be found at L<>. =head1 L<>. =head1 AUTHOR Dave Rolsky <autarch@urth.org> =head1 CONTRIBUTORS =for stopwords Ben Bennett Christian Hansen Daisuke Maki Dan Book Stewart David E. Wheeler Precious Doug Bell Flávio Soibelmann Glock Gianni Ceccarelli Gregory Oschwald Hauke D Iain Truskett Jason McIntosh Joshua Hoblitt Karen Etheridge Mark Overmeer Michael Conrad R. Davis Mohammad S Anwar M Somerville Nick Tonkin Olaf Alders Ovid Paul Howarth Philippe Bruhat (BooK) philip r brenan Ricardo Signes Richard Bowen Ron Hill Sam Kington viviparous =over 4 =item * Ben Bennett <fiji@limey.net> =item * Christian Hansen <chansen@cpan.org> =item * Daisuke Maki <dmaki@cpan.org> =item * Dan Book <grinnz@gmail.com> =item * Dan Stewart <danielandrewstewart@gmail.com> =item * David E. Wheeler <david@justatheory.com> =item * David Precious <davidp@preshweb.co.uk> =item * Doug Bell <madcityzen@gmail.com> =item * Flávio Soibelmann Glock <fglock@gmail.com> =item * Gianni Ceccarelli <gianni.ceccarelli@broadbean.com> =item * Gregory Oschwald <oschwald@gmail.com> =item * Hauke D <haukex@zero-g.net> =item * Iain Truskett <deceased> =item * Jason McIntosh <jmac@jmac.org> =item * Joshua Hoblitt <jhoblitt@cpan.org> =item * Karen Etheridge <ether@cpan.org> =item * Mark Overmeer <mark@overmeer.net> =item * Michael Conrad <mike@nrdvana.net> =item * Michael R. Davis <mrdvt92@users.noreply.github.com> =item * Mohammad S Anwar <mohammad.anwar@yahoo.com> =item * M Somerville <dracos@users.noreply.github.com> =item * Nick Tonkin <1nickt@users.noreply.github.com> =item * Olaf Alders <olaf@wundersolutions.com> =item * Ovid <curtis_ovid_poe@yahoo.com> =item * Paul Howarth <paul@city-fan.org> =item * Philippe Bruhat (BooK) <book@cpan.org> =item * philip r brenan <philiprbrenan@gmail.com> =item * Ricardo Signes <rjbs@cpan.org> =item * Richard Bowen <bowen@cpan.org> =item * Ron Hill <rkhill@cpan.org> =item * Sam Kington <github@illuminated.co.uk> =item * viviparous <viviparous@prc> =back =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2003 - 2020 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) The full text of the license can be found in the F<LICENSE> file included with this distribution. =cut
|
https://metacpan.org/release/DateTime/source/lib/DateTime.pm
|
CC-MAIN-2021-04
|
refinedweb
| 13,497
| 54.52
|
Introduction
Overview
Bookmarks are widely-used part of the World Wide Web browsers. They are a mechanism through which a user can return to specific sites already visited, much like their book counterparts.
Recently, bookmarks have become a feature for user with regards to browsing their file system, as a way to access recently used, or often used, places.
Even the list of recently used files can be seen as being composed of short-lived bookmarks.
Objectives of this specification
This specification aims to do the following things:
- Provide a standard mechanism for storing and accessing a list of bookmarks (in form of URI);
- Provide per-application and per-task bookmarks;
- Replace the Recent Files Storage Specification, providing a single specification for both bookmarks and recent files; Applications implementing the following specification will have the ability to access all, or just a part of, the bookmarks, which will be stored in a system-wide fashion instead of re-implementing their bookmark system. This way, all the bookmarks associated to an application will be available to each instance of said application, and to other applications performing the same tasks. Also, a notification mechanism should be implemented so that every change inside the bookmarks should be propagated to each application using the bookmarks.
Storage format
For different desktops and applications to have access to the same information, a protocol for storing the bookmarks list has to be determined.
Base layout
A valid, UTF-8 encoded XML document will be used for storing the desktop bookmarks. The storage format will conform to the XBEL DTD with custom meta-data; see the XBEL specification for the contents of the bookmark, title, desc and info elements used in this specification.
A valid desktop bookmark stream must conform to the 1.0 version of the XBEL Specification. The root element must be the
xbel element, with its
version attribute set to "1.0". No
folder element should be used, as well as no
alias and
separator elements; if any of those elements are found, they should be ignored.
Each bookmark must have the
bookmark element as root node. The target URI of the bookmark must be stored in the
href attribute of the bookmark element.
Each
bookmark element should have its
added,
modified and
visited attributes set with date and time specified as a string conformant to the ISO 8601 specification. The time should be relative to UTC time; local time should be converted to UTC before encoding, and converted back after reading the attribute payload.
Desktop Bookmarks meta-data
The owner for all the meta-data elements defined in this specification must be Freedesktop.Org. Thus, the
owner attribute of the meta-data element containing the following elements must be set to. Other meta-data, enclosed inside a
metadata element with another, or no owner, should be ignored.
All meta-data defined in this specification belongs to a namespace, named
bookmark whose URI is, except for the
mime-type element, whose namespace is to be named
mime and must have this URI:.
Each
metadata element might contain any combination of the following elements, in any order:
- The
mime-typeelement is mandatory. It must contain the MIME Type of the target pointed by the URI, as defined by the Shared MIME Database.
- The
groupselement contains a list of
groupelements, each containing a group name. See the Registered Group Names section for more details on the group names defined by this specification. The groups element is not mandatory.
- The
applicationselement contains a list of
applicationelements, each referring to an application that has registered the bookmark.
- Each
applicationelement has a number of attributes: || modified || Yes || The last time, expressed as a string conformant to the ISO 8601 specification and relative to UTC, that the application registered the bookmark. Each application element must have this attribute set
See the Applications section for the correct behaviour when handling duplicate application registrations.
The
applications element is mandatory; every bookmark must have at least one valid
application element.
- The
iconelement, if present, specifies the icon that should be associated to the bookmark. The icon element must have the following attributes: Implementors should use the file specified inside the href or the name attributes of the icon element when showing the bookmark. If both the href and the name attributes are specified, the href element takes precedence.
- The
privateelement, if present, alters the visibility of the bookmark. A bookmark should be considered private to the groups where it belongs and to the applications that have registered it. See the Visibility section.
Storage Files
Desktop bookmarks file might contain a variable number of bookmarks. Each bookmark file should contain at least one bookmark stored using the format described previously. The default extension for the desktop bookmarks file should be
xbel. Imlementors should use the same ordering of the bookmarks stored inside the bookmarks file when displaying them, and should take care into storing the bookmarks inside a bookmarks file using the same order in which they are displayed.
Implementors should also take care of avoiding concurrent accesses to these files; for instance, by using file locking techniques.
File location
Standard locations for bookmark files defined in this specification are:
Application specific desktop bookmark files should be stored under the $XDG_DATA_DIRS/desktop-bookmarks directory. Each directory in the search path should be used. When two desktop bookmark files have the same name, the one appearing earlier should be used. Only files with the
xbel extension are used; other files are ignored.
File encoding
All text in the file should be stored in the UTF-8 encoding. Standard encoding rules for XML and XBEL documents applies the desktop bookmark files. No local paths are allowed in the URI tag; they should be converted to a valid URI with a "file" scheme. Items with the same URI are not allowed.
Change notification
Notification should be accomplished by simply monitoring the files for changes. This can be done by either polling the file every so often, or using a libraries like FAM, d-notify or i-notify.
Registered meta-data
The meta-data associated to this spec will contain informations about the applications that have registered a bookmark, the groups to which a bookmark belongs and its visibility in relation to applications and groups.
Applications
Bookmarks must have at least an application registration.
Bookmarks might be registered by more than one application. For each application registering a bookmark, will be stored the application's name, the application's command line, the number of registrations for the application and the last time the application registered a bookmark, the timestamp (seconds from the system's epoch) of the registration time.
If an application tries to register again a bookmark, that is: if there already is an application tag with its name attribute set to the same name passed by the application, then the application tag should have the content of the timestamp attribute updated, and the content of the count attribute increased by one.
List of valid exec attribute variables
Each exec attribute of the application element may take a number of arguments which will be expanded by the implementor.
Literal % characters must be escaped as %%. Each unrecognised variable should be left unexpanded.
Recognised variables are as follows:
Groups
Groups implement meta-classes of bookmarks. The bookmarks belonging to a group (or a set of groups) will be shared across each member of the group.
For instance, each email client application could register its bookmarks under the group Mail, so that each other mail-related application could access those bookmarks.
For a list of registered group names, see the Registered group names section.
Visibility
The privacy hint of a bookmark is set using the private element. Each item with this hint set should be visible only for the groups and applications that registered it.
Appendix A: Implementation recommendations
Any implementor of this specification should conform to these recommendations:
- Implementors should use the command line inside the exec attribute of the application element, when launching a bookmark with a specific application. If no exec attribute was found, implementors should try the application's name stored inside the name attribute, followed by a space character and the bookmark's URI. If this fails, the default application for the bookmark's MIME type should be invoked using the bookmark's URI.
- No duplicate entries should be found inside a valid desktop bookmark data stream. If two or more applications register a bookmark to the same URI, implementors should update the modified attribute of the bookmark element; a new application element should be added for each application that is registering the bookmark; if any of the applications is also adding group names, all of these must be merged with the previously set group names; the private element should be set the first time an application requires it. If the same application registers the same bookmark, only the modified attribute of the bookmark element, the timestamp and count attributes of the application element with the same application's name set into the name attribute and the private element should be modified.
- If an icon for the bookmark item is shown, it should be taken from the image file stored inside the href attribute of the icon element; if no such element exists inside the meta-data for the bookmark item, the icon should be the thumbnail of the resource (if available), retrieved using the thumbnail managing specification, or - if no thumbnail is present - the icon associated to the MIME type of the resource.
Appendix B: Registered group names
Remember, these are case-sensitive. When using a group name described in the list below it is strongly recommended to also include the group listed under Related Groups. If a group has multiple related groups the most suitable related group should be included.
Appendix C: How to add a new desktop bookmark file
In order to properly install a new desktop bookmark file, third party applications should:
- Install new desktop bookmark files inside $XDG_DATA_DIR/desktop-bookmarks for each desktop bookmark file. Please, namespace the filename, as in "vendor-foo.xbel", or use a subdirectory or $XDG_DATA_DIR/desktop-bookmarks so you have "vendor/foo.xbel." Please ensure all desktop bookmark entries are valid.
Author: Emmanuele Bassi
Version: 0.8.5
|
http://www.freedesktop.org/wiki/Specifications/desktop-bookmark-spec/?action=Load
|
CC-MAIN-2013-20
|
refinedweb
| 1,712
| 50.57
|
A metricset is the part of a Metricbeat module that fetches and structures the data from the remote service. Each module can have multiple metricsets. In this guide, you learn how to create your own metricset. If you want to create your own Beat that uses Metricbeat as a library, see Creating a Beat based on Metricbeat.
When creating a metricset for the first time, it generally helps to look at the implementation of existing metricsets for inspiration.
To create a new metricset:
Run the following command inside your beat directory:
make create-metricset
You’ll be prompted to enter a module and metricset name. Only use characters
[a-z]and, if required, underscores (
_). No other characters are allowed.
When you run
make create-metricset, it creates all the basic files for your metricset, along with the required module files if the module does not already exist. See Creating a Metricbeat Module for more details about the module files.
We use
{metricset},
{module}, and
{beat}in this guide as placeholders. You need to replace these with the actual names of your metricset, module, and beat.
The metricset that you created is already a functioning metricset and can be compiled.
Compile your new metricset by running the following command:
make collect make
The first command,
make collect, updates all generated files with the most recent files, data, and meta information from the metricset. The second command,
make, compiles your source code and provides you with a binary called
{beat}in the beat folder. You can run the binary in debug mode with the following command:
./{beat} -e -d "*"
After running the make commands, you’ll find the metricset, along with its generated files, under
module/{module}/{metricset}. This directory
contains the following files:
\{metricset}.go
_meta/docs.asciidoc
_meta/data.json
_meta/fields.yml
Let’s look at the files in more detail next.
{metricset}.go Fileedit
The first file is
{metricset}.go. It contains the logic on how to fetch data from the service and convert it for sending to the output.
The generated file looks like this:
package {metricset} import ( "github.com/elastic/beats/libbeat/common" "github.com/elastic/beats/libbeat/common/cfgwarn" "github.com/elastic/beats/metricbeat/mb" ) // init registers the MetricSet with the central registry as soon as the program // starts. The New function will be called later to instantiate an instance of // the MetricSet for each host defined in the module's configuration. After the // MetricSet has been created then Fetch will begin to be called periodically. func init() { mb.Registry.MustAddMetricSet("{module}", "{metricset}", New) } // MetricSet holds any configuration or state information. It must implement // the mb.MetricSet interface. And this is best achieved by embedding // mb.BaseMetricSet because it implements all of the required mb.MetricSet // interface methods except for Fetch. type MetricSet struct { mb.BaseMetricSet counter int } // New creates a new instance of the MetricSet. New is responsible for unpacking // any MetricSet specific configuration options if there are any. func New(base mb.BaseMetricSet) (mb.MetricSet, error) { cfgwarn.Experimental("The {module} {metricset} metricset is experimental.") config := struct{}{} if err := base.Module().UnpackConfig(&config); err != nil { return nil, err } return &MetricSet{ BaseMetricSet: base, counter: 1, }, nil } // Fetch methods implements the data gathering and data conversion to the right // format. It publishes the event which is then forwarded to the output. In case // of an error set the Error field of mb.Event or simply call report.Error(). func (m *MetricSet) Fetch(report mb.ReporterV2) { report.Event(mb.Event{ MetricSetFields: common.MapStr{ "counter": m.counter, }, }) m.counter++ }
The
package clause and
import declaration are part of the base structure of each Golang file. You should only
modify this part of the file if your implementation requires more imports.
Initialisationedit
The init method registers the metricset with the central registry. In Golang the
init() function is called
before the execution of all other code. This means the module will be automatically registered with the global registry.
The
New method, which is passed to
AddMetricSet, will be called after the setup of the module and before starting to fetch data. You normally don’t need to change this part of the file.
func init() { if err := mb.Registry.AddMetricSet("{module}", "{metricset}", New); err != nil { panic(err) } }
Definitionedit
The MetricSet type defines all fields of the metricset. As a minimum it must inherit the
mb.BaseMetricSet fields,
but can be extended with additional entries. These variables can be used to persist data or configuration between
multiple fetch calls.
You can add more fields to the MetricSet type, as you can see in the following example where the
username and
password string fields are added:
type MetricSet struct { mb.BaseMetricSet username string password string }
Creationedit
The
New function creates a new instance of the MetricSet. The setup process
of the MetricSet is also part of
New. This method will be called before
Fetch
is called the first time.
The
New function also sets up the configuration by processing additional
configuration entries, if needed.
func New(base mb.BaseMetricSet) (mb.MetricSet, error) { config := struct{}{} if err := base.Module().UnpackConfig(&config); err != nil { return nil, err } return &MetricSet{ BaseMetricSet: base, }, nil }
Fetchingedit
The
Fetch method is the central part of the metricset.
Fetch is called every
time new data is retrieved. If more than one host is defined,
Fetch is
called once for each host. The frequency of calling
Fetch is based on the
period
defined in the configuration file.
Fetch must return a
common.MapStr object, which is then sent to Elasticsearch.
If an error happens, the error must be returned and then is sent instead
to Elasticsearch. This means that Metricbeat always sends an event, even on failure.
You must make sure that the error message helps to identify the actual error.
The following example shows a metricset
Fetch method with a counter that is
incremented for each
Fetch call:
func (m *MetricSet) Fetch() (common.MapStr, error) { event := common.MapStr{ "counter": m.counter, } m.counter++ return event, nil }
Fetch must return a
common.MapStr, which will be translated to the JSON content.
The JSON output will be identical to the naming and structure you use in
common.MapStr. For more details about
MapStr and its functions, see the
MapStr API docs.
Multi Fetchingedit
Metricbeat has two different
Fetch interfaces. One of the interfaces, which you saw in the
previous example, fetches a single event. In some cases, every fetch returns a list of events.
Instead of using an array inside a JSON document, we recommend that you create a list of events.
For this kind of data, you can use the following
Fetch interface:
(m *MetricSet) Fetch() ([]common.MapStr, error)
The only difference between this and the previous example is that the second example returns
[]common.MapStr.
Metricbeat will add the same timestamp to all the events in the list to make it possible to correlate the events.
Parsing and Normalizing Fieldsedit
In Metricbeat we aim to normalize the metric names from all metricsets to respect a common set of conventions. This makes it easy for users to find and interpret metrics. To simplify parsing, converting, renaming, and restructuring of the object read from the monitored system to the Metricbeat format, we have created the schema package that allows you to declaratively define transformations.
For example, assuming this input object:
input := map[string]interface{}{ "testString": "hello", "testInt": "42", "testBool": "true", "testFloat": "42.1", "testObjString": "hello, object", }
And the requirement to transform it into this one:
common.MapStr{ "test_string": "hello", "test_int": int64(42), "test_bool": true, "test_float": 42.1, "test_obj": common.MapStr{ "test_obj_string": "hello, object", }, }
You can use the following code to make the transformations:
import ( s "github.com/elastic/beats/libbeat/common/schema" c "github.com/elastic/beats/libbeat/common/schema/mapstrstr" ) var ( schema = s.Schema{ "test_string": c.Str("testString"), "test_int": c.Int("testInt"), "test_bool": c.Bool("testBool"), "test_float": c.Float("testFloat"), "test_obj": s.Object{ "test_obj_string": c.Str("testObjString"), }, } ) func eventMapping(input map[string]interface{}) common.MapStr { return schema.Apply(input) }
In the above example, note that it is possible to create the schema object once and apply it to all events.
Configuration Fileedit
The configuration file for a metricset is handled by the module. If there are multiple metricsets in one module, make sure you add all metricsets to the configuration. For example:
metricbeat: modules: - module: {module-name} metricsets: ["{metricset1}", "{metricset2}"]
Make sure that you run
make collect after updating the config file
so that your changes are also applied to the global configuration file and the docs.
For more details about the Metricbeat configuration file, see the topic about Modules in the Metricbeat documentation.
What to Do Nextedit
This topic provides basic steps for creating a metricset. For more details about metricsets and how to extend your metricset further, see Metricset Details.
|
https://www.elastic.co/guide/en/beats/devguide/6.2/creating-metricsets.html
|
CC-MAIN-2019-43
|
refinedweb
| 1,464
| 50.94
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.