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
|
|---|---|---|---|---|---|
Stories are a popular UI component these days. Social and news apps are integrating them into their feeds. In this codelab we'll build a story component with lit-element and TypeScript.
This is what the story component will look like at the end:
We can think of a social media or news "story" as a collection of cards to be played sequentially, sort of like a slideshow. Actually, stories are literally slideshows. The cards are typically dominated by an image or autoplaying video, and can have additional text on top. Here's a what we'll build:
Feature List
- Cards with an image or video background.
- Swipe left or right to navigate the story.
- Autoplaying videos.
- Ability to add text or otherwise customize cards.
As far as this component's developer experience, it'd be nice to specify story cards in plain HTML markup, like this:
<story-viewer> <story-card> <img slot="media" src="some/image.jpg" /> <h1>Title</h1> </story-card> <story-card> <video slot="media" src="some/video.mp4" loop playsinline></video> <h1>Whatever</h1> <p>I want!</p> </story-card> </story-viewer>
So let's also add that to the feature list.
Feature List
- Accept a series of cards in HTML markup.
This way anyone can use our story component simply by writing HTML. This is great for programmers and non-programmers alike, and works everywhere HTML does: content management systems, frameworks, etc.
Prerequisites
- A shell where you can run
gitand
npm
- A text editor
Start by cloning this repo: story-viewer-starter
git clone git@github.com:PolymerLabs/story-viewer-starter.git
The environment is already set up with lit-element and TypeScript. Just install the dependencies:
npm i
For VS Code users, install the lit-plugin extension to get autocompletion, type-checking, and linting of lit-html templates.
Start the development environment by running:
npm run dev
You're ready to begin coding!
When building compound components, it's sometimes easier to start with the simpler sub-components, and build up. So, let's start by building
<story-card>. It should be able to display a full-bleed video or an image. Users should be able to further customize it, for instance, with overlay text.
The first step is to define our component's class, which extends
LitElement. The
customElement decorator takes care of registering the custom element for us. Now is a good time to make sure you enable decorators in your tsconfig with the
experimentalDecorators flag (if you're using the starter repo, it's already enabled).
Put the following code into story-card.ts:
import { LitElement, customElement } from 'lit-element'; @customElement('story-card') export class StoryCard extends LitElement { }
Now
<story-card> is a useable custom element, but there's nothing to display yet. To define the element's internal structure, define the
render instance method. This is where we'll provide the template for the element, using lit-html's
html tag.
What should be in this component's template? The user should be able to provide two things: a media element, and an overlay. So, we'll add one
<slot> for each of those.
Slots are how we specify children of a custom element should be rendered. For more info, here's a great walkthrough on using slots.
import { html } from 'lit-html'; export class StoryCard extends LitElement { render() { return html` <div id="media"> <slot name="media"></slot> </div> <div id="content"> <slot></slot> </div> `; } }
Separating the media element into its own slot will help us target that element for things like adding full-bleed styling and autoplaying videos. Put the second slot (the one for custom overlays) inside a container element so we can provide some default padding later.
The
<story-card> component can now be used like this:
<story-card> <img slot="media" src="some/image.jpg" /> <h1>My Title</h1> <p>my description</p> </story-card>
But, it looks terrible:
Adding style
Let's add some style. With lit-element, we do that by defining a static
styles property and returning a template string tagged with
css. Whatever CSS written here applies only to our custom element! CSS with shadow DOM is really nice in this way.
Let's style the slotted media element to cover the
<story-card>. While we're here, we can provide some nice formatting for elements in the second slot. That way, component users can drop in some
<h1>s,
<p>s, or whatever, and see something nice by default.
import { css } from 'lit-element'; export class StoryCard extends LitElement { static styles = css` #media { height: 100%; } #media ::slotted(*) { width: 100%; height: 100%; object-fit: cover; } /* Default styles for content */ #content { position: absolute; top: 0; right: 0; bottom: 0; left: 0; padding: 48px; font-family: sans-serif; color: white; font-size: 24px; } #content > slot::slotted(*) { margin: 0; } `; }
Now we have story cards with background media, and we can put whatever we want on top. Nice! We'll return to the
StoryCard class in a bit to implement autoplaying videos.
Our
<story-viewer> element is the parent of
<story-card>s. It'll be responsible for laying out the cards horizontally and letting us swipe between them. We'll kick it off the same way we did for
StoryCard. We want to add story cards as children of the
<story-viewer> element, so add a slot for those children.
Put the following code in story-viewer.ts:
import { LitElement, customElement, html } from 'lit-element'; @customElement('story-viewer') export class StoryViewer extends LitElement { render() { return html`<slot></slot>`; } }
Next up is a horizontal layout. We can approach this by giving all of the slotted
<story-card>s absolute positioning, and translating them according to their index. We can target the
<story-viewer> element itself using the
:host selector.
static styles = css` :host { display: block; position: relative; /* Default size */ width: 300px; height: 800px; } ::slotted(*) { position: absolute; width: 100%; height: 100%; }`;
The user can control the size of our story cards just by externally overriding the default height and width on the host. Like this:
story-viewer { width: 400px; max-width: 100%; height: 80%; }
To keep track of the currently viewed card, let's add an instance variable
index to the
StoryViewer class. Decorating it with LitElement's
@property will cause the component to re-render whenever its value changes.
import { property } from 'lit-element'; export class StoryViewer extends LitElement { @property({type: Number}) index: number = 0; }
Each card needs to be translated horizontally into position. Let's apply these translations in lit-element's
update lifecycle method. The update method will run whenever an observed property of this component changes. Usually, we would query for the slot and loop over
slot.assignedElements(). However, since we only have one unnamed slot, this is the same as using
this.children. Let's use
this.children, for convenience.
import { PropertyValues } from 'lit-element'; export class StoryViewer extends LitElement { update(changedProperties: PropertyValues) { const width = this.clientWidth; Array.from(this.children).forEach((el: Element, i) => { const x = (i - this.index) * width; (el as HTMLElement).style.transform = `translate3d(${x}px,0,0)`; }); super.update(changedProperties); } }
Our
<story-card>s are now all in a row. It still works with other elements as children, as long as we take care to style them appropriately:
<story-viewer> <!-- A regular story-card child... --> <story-card> <video slot="media" src="some/video.mp4"></video> <h1>This video</h1> <p>is so cool.</p> </story-card> <!-- ...and other elements work too! --> <img style="object-fit: cover" src="some/img.png" /> </story-viewer>
Go to
build/index.html and uncomment the rest of the story-card elements. Now, let's make it so we can navigate to them!
Next, we'll add a way to navigate between the cards, and a progress bar.
Let's add some helper functions to
StoryViewer for navigating the story. They'll set index for us while clamping it to a valid range.
In story-viewer.ts, in the
StoryViewer class, add:
/** Advance to the next story card if possible **/ next() { this.index = Math.max(0, Math.min(this.children.length - 1, this.index + 1)); } /** Go back to the previous story card if possible **/ previous() { this.index = Math.max(0, Math.min(this.children.length - 1, this.index - 1)); }
To expose navigation to the end-user, we'll add "previous" and "next" buttons to the
<story-viewer>. When either button is clicked, we want to call either the
next or
previous helper function. lit-html makes it easy to add event listeners to elements; we can render the buttons and add a click listener at the same time.
Update the
render method to the following:
export class StoryViewer extends LitElement { render() { return html` <slot></slot> <svg id="prev" viewBox="0 0 10 10" @click=${() => this.previous()}> <path d="M 6 2 L 4 5 L 6 8" stroke="#fff" fill="none" /> </svg> <svg id="next" viewBox="0 0 10 10" @click=${() => this.next()}> <path d="M 4 2 L 6 5 L 4 8" stroke="#fff" fill="none" /> </svg> `; } }
Check out how we can add event listeners inline on our new svg buttons, right in the
render method. This works for any event. Just add a binding of the form
@eventname=${handler} to an element.
Add the following to the
static styles property to style the buttons:
svg { position: absolute; top: calc(50% - 25px); height: 50px; cursor: pointer; } #next { right: 0; }
For the progress bar, we'll use CSS grid to style little boxes, one for each story card. We can use the
index property to conditionally add classes to the boxes for indicating whether they've been "seen" or not. We could use a conditional expression such as
i <= this.index : 'watched': '', but things could get verbose if we add more classes. Luckily, lit-html vends a directive called
classMap to help out. First, import
classMap:
import { classMap } from 'lit-html/directives/class-map';
And add the following markup to the bottom of the
render method:
<div id="progress"> ${Array.from(this.children).map((_, i) => html` <div class=${classMap({watched: i <= this.index})} @click=${() => this.index = i} ></div>` )} </div>
We also threw in some more click handlers so users can skip straight to a specific story card if they want.
Here are the new styles to add to
static styles:
::slotted(*) { position: absolute; width: 100%; /* Changed this line! */ height: calc(100% - 20px); } #progress { position: relative; top: calc(100% - 20px); height: 20px; width: 50%; margin: 0 auto; display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; grid-gap: 10px; align-content: center; } #progress > div { background: grey; height: 4px; transition: background 0.3s linear; cursor: pointer; } #progress > div.watched { background: white; }
Navigation and progress bar complete. Now let's add some flair!
To implement swiping, we'll utilize the Hammer.js gesture control library. Hammer detects special gestures like pans, and dispatches events with relevant info (like delta X) that we can consume.
Here's how we can use Hammer to detect pans, and automatically update our element whenever a pan event occurs:
import { internalProperty } from 'lit-element'; import 'hammerjs'; export class StoryViewer extends LitElement { // Data emitted by Hammer.js @internalProperty() _panData: {isFinal?: boolean, deltaX?: number} = {}; constructor() { super(); this.index = 0; new Hammer(this).on('pan', (e: HammerInput) => this._panData = e); } }
The constructor of a LitElement class is another great place to attach event listeners on the host element itself. The Hammer constructor takes an element to detect gestures on. In our case, it's the
StoryViewer itself, or
this. Then, using Hammer's API, we tell it to detect the "pan" gesture, and set the pan information onto a new
_panData property.
By decorating the
_panData property with
@internalProperty, LitElement will observe changes to
_panData and perform an update, but the property will NOT be reflected to an attribute.
Next, let's augment the
update logic to use the pan data:
// Update is called whenever an observed property changes. update(changedProperties: PropertyValues) { // deltaX is the distance of the current pan gesture. // isFinal is whether the pan gesture is ending. let { deltaX = 0, isFinal = false } = this._panData; // When the pan gesture finishes, navigate. if (!changedProperties.has('index') && isFinal) { deltaX > 0 ? this.previous() : this.next(); } // We don't want any deltaX when releasing a pan. deltaX = isFinal ? 0 : deltaX; const width = this.clientWidth; Array.from(this.children).forEach((el: Element, i) => { // Updated this line to utilize deltaX. const x = (i - this.index) * width + deltaX; (el as HTMLElement).style.transform = `translate3d(${x}px,0,0)`; }); // Don't forget to call super! super.update(changedProperties); }
We can now drag our story cards back and forth. To make things smooth, let's go back to
static get styles and add
transition: transform 0.35s ease-out; to the
::slotted(*) selector:
::slotted(*) { ... transition: transform 0.35s ease-out; }
Now we have smooth swiping:
The last feature we'll add is autoplaying videos. When a story card enters the focus, we want the background video to play, if it exists. When a story card leaves the focus, we should pause its video.
We'll implement this by dispatching ‘entered' and ‘exited' custom events on the appropriate children whenever the index changes. In
StoryCard, we'll receive those events and play or pause any existing videos. Why choose to dispatch events on the children instead of calling ‘entered' and ‘exited' instance methods defined on StoryCard? With methods, the component users would have no choice but to write a custom element if they wanted to write their own story card with custom animations. With events, they can just attach an event listener!
Let's refactor
StoryViewer's
index property to use a setter, which provides a convenient code path for dispatching the events:
class StoryViewer extends LitElement { @internalProperty() private _index: number = 0 get index() { return this._index } set index(value: number) { this.children[this._index].dispatchEvent(new CustomEvent('exited')); this.children[value].dispatchEvent(new CustomEvent('entered')); this._index = value; } }
To finish off the autoplay feature, we'll add event listeners for "entered" and "exited" in the
StoryCard constructor that play and pause the video.
Remember that the component user may or may not give the
<story-card> a video element in the media slot. They may not even provide an element in the media slot at all. We have to be careful to not call
play on an img, or on null.
Back in story-card.ts, add the following:
import { query } from 'lit-element'; class StoryCard extends LitElement { constructor() { super(); this.addEventListener("entered", () => { if (this._slottedMedia) { this._slottedMedia.currentTime = 0; this._slottedMedia.play(); } }); this.addEventListener("exited", () => { if (this._slottedMedia) { this._slottedMedia.pause(); } }); } /** * The element in the "media" slot, ONLY if it is an * HTMLMediaElement, such as <video>. */ private get _slottedMedia(): HTMLMediaElement|null { const el = this._mediaSlot && this._mediaSlot.assignedNodes()[0]; return el instanceof HTMLMediaElement ? el : null; } /** * @query(selector) is shorthand for * this.renderRoot.querySelector(selector) */ @query("slot[name=media]") private _mediaSlot!: HTMLSlotElement; }
Autoplay complete. ✅
Now that we have all of the essential features, let's add one more: a sweet scaling effect. Let's go back one more time to the
update method of
StoryViewer. Some math is done to get the value in the
scale constant. It will equal
1.0 for the active child and
minScale otherwise, interpolating between these two values as well.
Change the loop in the
update method in story-viewer.ts to be:
update(changedProperties: PropertyValues) { // ... const minScale = 0.8; Array.from(this.children).forEach((el: Element, i) => { const x = (i - this.index) * width + deltaX; // Piecewise scale(deltaX), looks like: __/\__ const u = deltaX / width + (i - this.index); const v = -Math.abs(u * (1 - minScale)) + 1; const scale = Math.max(v, minScale); // Include the scale transform (el as HTMLElement).style.transform = `translate3d(${x}px,0,0) scale(${scale})`; }); // ... }
That's all, folks! In this post we covered a lot, including some LitElement and lit-html features, HTML slot elements, and gesture control.
For a completed version of this component, visit:.
|
https://codelabs.developers.google.com/codelabs/lit-story-viewer
|
CC-MAIN-2020-50
|
refinedweb
| 2,657
| 58.69
|
poobrains is a webframework written in python on top of Flask and peewee.
This snippet might explain it better:
import poobrains @poobrains.app.expose('/') class Foo(poobrains.storage.Storable): blah = poobrains.storage.fields.CharField(null=True) fasel = poobrains.storage.fields.BooleanField()
These few lines of code will fold out to a complete website with administration area, exposing a paginated list of teasers of all Foo instances in the database on the frontpage ('/') and full views of Foo instances at /Foo.id (i.e. Foo instance with id 42 at '/42').
poobrains main intended features are security, good DX (Developer eXperience) and UX (as well done as possible without javascript).
Authentication (login) is done with TLS client certificates in order to avoid problems like password re-use and to gain the security of public key cryptography.
The permission system is restrictive, flexible and extensible. It supports permissions assigned to groups as well as users.
Lastly, it DOES NOT CONTAIN ANY JAVASCRIPT.
There also is a nice little theming system offering things like SCSS integration, inheritance of theme resources (templates, scss files, graphics, etc) and templatable SVG (with compiled-in SCSS, too).
Sadly, poobrains isn't production-grade software yet. Currently, it's still in a pre-alpha stage:
- No documentation - Well, there's a ~1.5k word "quick"start now…
- UX slowly approaching acceptable
- a good bunch of templates still need to be written
- Good deal of housecleaning still needed for better DX
- pyreverse recursively and reliably fails analyzing poobrains. Oops. ¯\_(ツ)_/¯
- No tests
- No code review (though "I have a guy"™)
|
http://phryk.net/projects/poobrains/
|
CC-MAIN-2019-22
|
refinedweb
| 263
| 57.37
|
RationalWiki:Saloon bar/Archive268
Contents
- 1 Maajid Nawaz continues to prove that he is a garbage human being!
- 2 Is the 'World of Lucid Dreaming [WoLD]' woo?
- 3 Falun Gong
- 4 Carrie Fisher is gone
- 5 With respect....
- 6 On the dire need for resources like RW
- 7 Religious gibberish, apparently this is a big deal in the era of Trump
- 8 I made a poll on a talk page
- 9 When writing an article, should I use Qur'an or Koran?
- 10 To whoever posted the Glenn Greenwald article alleging that the Guardian manipulated an interview with Assange to make the latter seem more pro-Trump...
- 11 The radical right has won
- 12 Something that adds to the stigma towards the mentally ill
- 13 Thoughts on Rent Control
- 14 How likely do you think Californians would be to vote for Calexit?
- 15 Snowflakes
- 16 I was thinking of creating a page on the pseudoscience promoter David Dewitt
- 17 MuslimStatistics.Wordpress.com
- 18 David Pakman wrecks Gad Saad on the death penalty.
- 19 I hope the scientific community will be able to stand against Trump
- 20 Predictions for 2017
- 21 Fun: Favorite memories of 2016
- 22 Hey Ya'll
- 23 About the elections in France
- 24 From one faulty walnut to another
- 25 "US Govt Data Shows Russia Used Outdated Ukrainian PHP Malware"
- 26 Why am I not eligible to vote in the Moderator Election?
- 27 Bikram Choudhury (of Bikram Yoga) just lost everything.
- 28 The United States should just cut its losses and dump Israel as an ally
- 29 Why the alt-right is bad for the acceptance of science
- 30 A Confederacy Of Dunces
- 31 Uncle Joe did it again!
- 32 New level of stupidity
- 33 RationalWiki in 2016
- 34 This seriously takes stupidity to the next level.
- 35 Fuck me
- 36 Inaccurate creationist lies in Israeli history curriculum
- 37 Climate Change
- 38 Claim YOUR $25,000 survival bunker TODAY!
- 39 Trump sides with Assange and Russia over U.S. intelligence
- 40 The assault of a disabled man in Chicago
- 41 What if Trump was mature
- 42 Washington Post makes Ken Ham look smarter than he actually is
- 43 Some weird things
- 44 Check out this stupidity from Huffpo.
- 45 The Institute for Creation Research Graduate School
- 46 I think itsnobody.blogspot.com should get a page here
- 47 Community question: WIGOW vs WIGOB
- 48 A school I unintentionally came across that could make a good article
- 49 @ MTV
- 50 Pentagon chief is wrong
- 51 For the Fundie School page (I know matters on specific articles should go on the talk page but there are very few people who use them anyway)
- 52 Workplace democracy
- 53 Difference between "Welfare capitalism" and socialism
- 54 There's a moderator election on
Maajid Nawaz continues to prove that he is a garbage human being![edit]
This is especially for you, Reverend. You thought I was trying to manufacture this dude's dickishness? Please visit his Twitter page and read how he embarrasses himself vis-a-vis the UN resolution against Israeli settlements and Obama's refusal to veto said resolution. Bear in mind, if you do, this is a guy who criticises the whatabouttery of some on the Left.
For those of you that cannot be bothered to visit his Twitter page, here's the gist. Nawaz argues that Iran nuclear deal (which is meant to cut off Iran's path to a nuke) empowered/strengthen the Iran theocracy (this guy is meant to be a liberal remember?), and that Obama instead chose to make an example of Israel (despite the fact that Obama just gave Israel $38 billion and this resolution being the first of such a resolution against Israel in 8 years).
Everytime someone, like Rupert Myers, like Kyle Kulinski, would point this out to him, he would retort with "whatabout Iran's actions in Syria? Whatabout Saudi Arabia?"
It's such a weak line of argument,that you almost feel as though he doesn't really believe it.
When his whatabouttery is pointed out to him, several times, his response is:
No,it's not "whatabouttery" to comment on US / Mid East alliance from Israel to Iran.It's commenting on a misguided regional strategic pivot
In other words,there are other people in the region breaking international law. Go after them instead! Leave Israel alone!
Just how powerful are the pro-Israeli lobbies? Even the ADL criticised the resolution!
Also, Reverend, if you're reading, I'm not done editing his (Nawaz's) page. I am committed to ensuring everyone who visits his page knows that he is a dick; and possibly a Israeli settlement expansion apologist now too, or at the very least, a neocon useful idiot. –--Levi Ackerman (talk) 08:13, 24 December 2016 (UTC)
- So what you're saying is that you have an axe to grind with Maajid Nawaz and if you have to molehill mountaineer to do it then by God you're going to mount those molehills. You're not going to get very far, there's hardly even a concensus on this very wiki about Israel/Palaestine situation beyond a rough agreement both should exist in one way or another, though we have had a handful of fanatics on one side or the other cough cough. I mean I'm even willing to cede the claim of "whatabbouterry" to you, even though it's somewhat questionable because it has more to do with (according to Nawaz) choosing who to appease and who not to already complicated Middle East foreign policy instead of actually absolving Israel but regardless it's still not exactly a smoking gun. ClothCoat (talk) 09:31, 24 December 2016 (UTC)
- I don't have an axe to grind with him. I just think his page ought to reflect his "asshattery". After all, Sam Harris' does; Glenn Greenwald's does; Noam Chomsky's does.
- Also, in what way am I molehill mountaineering? He has a page on Rationalwiki. Ought not it reflect that he thinks the international community should turn a blind eye to Israel's breach of international law?
Levi Ackerman (talk) 10:13, 24 December 2016 (UTC)
- lol, someone call Mona Lord Aeonian (talk) 20:08, 24 December 2016 (UTC)
- 1) I'm surprised you're still here. I thought you would have taken your ball and bat home after your sidekick (or what it the other way around), Aneris, was sent packing; and 2) why don't you call Mona yourself? Why are you deferring? Levi Ackerman (talk) 20:22, 24 December 2016 (UTC)
- ??? I just made a saloon topic a few days ago. You Westerners are insufferable, a shame the USSR didn't win to put you in your place. Hopefully, China still will. Lord Aeonian (talk) 04:32, 25 December 2016 (UTC)
- Please explain what exactly makes us Westerners insufferable. I'm sure there's been some sort of communication failure somewhere along the line here and I'd like to understand your point of view better. MyNameIsMudd (talk) 06:12, 25 December 2016 (UTC)
- RE: Lord Aeonian, lol. Someone call nobs.Levi Ackerman (talk) 06:14, 25 December 2016 (UTC)
- Let's assume for a moment the demographic argument - that Palestinians at some point will be 50% in a Greater Israel - is inevitable, wouldn't continued infrastructure improvements be beneficial and work too the Palestinians advantage? nobs 13:09, 25 December 2016 (UTC)
- @nobs, you know what they say about "assume". It makes an "ass" out of "u" and "me". Levi Ackerman (talk) 15:29, 25 December 2016 (UTC)
- It would be, nobs, if that's what Israel was actually doing. Israel is not improving the infrastructure of Palestinian people's lands. Also, the idea of "we're just benign occupiers trying to improve the infrastructure of the land" is bullshit, the same excuses the French made in Algeria, the Japanese made in frickin every East Asian country ever, etc. Did Cecil Rhodes's plans for great African railway and telegraph line justify Britain's occupation of Africa? I think not. PBfreespace (talk) 18:57, 26 December 2016 (UTC)
- What I'm saying is, in 30-50 years Palestinians will be living in those houses Israelis are building now under various demographic scenarios. And that's a big improvement from the shitholes they live in now. And aside, you don't believe the French or British brought any economic benefit to the indigenous people of Africa? Japan however, is quite a different matter. nobs 05:12, 27 December 2016 (UTC)
Damn that man known as Nawaz. He must be the Imperial Guard Captain Al'Rahem in disguise! Maim!Kill!Burn! 03:05, 29 December 2016 (UTC)
Update[edit]
Maajid Nawaz and Kyle Kulinski got into it on Twitter over this same issue and well, it was just glorious. I wouldn't do it any justice if I described it to you, so I recommend you check it out for yourselves on Twitter:
Is the 'World of Lucid Dreaming [WoLD]' woo?[edit]
Somehow on my travels across the Internet, I've stumbled across this Now, I have a difficult time to decide if this is woo or not (I am currently working on enhancing my skepticism skills) and it does seem to contain woo in its articles, additionally, them selling courses to learn how to lucid dream seems very fishy to me. I just need some help to conclude if and how woo it is and the evidence for either position. Thank you in advance.--WMS (talk) 18:12, 26 December 2016 (UTC)
- Lucid dreaming exists as a measurable phenomenon. That's... about as far as you should trust that site. It's otherwise bullshitty dream anecdotes. Which are okay. That's harmless woo. More harmless even that dream interpretation, in that it doesn't replace real psychological treatment with bullshit. ikanreed You probably didn't deserve that 18:21, 26 December 2016 (UTC)
- Lucid dreaming is certainly a thing. I know because I've done it often - it's pretty cool. There is also scientific literatures which backs it up. But it's also a great opportunity for woo-merchants.--Bob"Life is short and (insert adjective)" 18:41, 26 December 2016 (UTC)
- Now having read a few of the articles on the site it's not that bad. Its suggestions on how do reality checks while dreaming, what to do about false awakenings - where people dream they have woken up multiple times - along with their description of sleep paralysis are all pretty good. Just don't buy any supplements or machines.--Bob"Life is short and (insert adjective)" 19:03, 26 December 2016 (UTC)
- Yes, but also, dreaming won't enable you to suddenly understand 5th dimensional math(there's deffo some bullshit there). ikanreed You probably didn't deserve that 19:13, 26 December 2016 (UTC)
- nth dimensional mathematics is mostly just taking the same equations to produce desired results (say, a shape in space) and running then through some functions to convert them into n dimensions. It looks very messy but fundamentally nothing is changing and it's easy to understand, just not visualize. The flip side is that there could very well be applications and concepts in higher dimensional space that we can't see because we can't comprehend and visualize upper dimensional spaces. For instance, an entity which exists and can only comprehend in one dimensional space would be unable to imagine something like a curve, or a circle, or any of the other things we can draw on a two dimensional graph besides a straight line. In turn, ideas like calculus, which are based on curves and rates of change, would never be discovered by entities unable to comprehend two dimensional space. There could well be many fields like calculus in 4+ dimensional space that we don't know about because we can't comprehend those types of spaces, but that doesn't mean anything for the present. Anyone claiming to use higher dimensional-anything, and making some novel breakthrough or learning something because of it, is talking BS. Lord Aeonian (talk) 02:11, 27 December 2016 (UTC)
Yes, this is woo — you were right to be suspicious. I mean, lucid dreaming exists — it's one of many, many intermediary states that occur in the borderlands between wakefulness and sleep. But the site you linked to is a woo nest. Took me one click to reach here — a mishmash of new age-inspired folk psychology, Jungian symbolism and unfounded claims. They also peddle lucid dreaming supplements, lucid dreaming books, lucid dreaming products and the likes. The woman running the site, Rebecca, also offers an expensive lucid dreaming course, which she uses the site to advertise for. The entire site is a nonsense recruitment tool — all the claims are spurious, all the articles are ads, all the evidence is anecdotal... This is classic bull. If you're actually interested in the topic lucid dreaming, stick to this, this and this (and use those three to expand this). Reverend Black Percy (talk) 13:56, 27 December 2016 (UTC)
- Alrighty, thank you all for helping me with this website- I'm glad that my 'skeptical senses' tingled to decided to post the website here. Thank you all :). Also, thank you RBP for providing links to actually reliable sources on lucid dreaming :D.--WMS (talk) 02:29, 29 December 2016 (UTC)
Lucid dreaming is a real and awesome thing... although it has been pretty much hijacked by the woo people. It is an awesome "brain hack" but not much else. TheGrandmother (talk) 12:39, 30 December 2016 (UTC)
- Yeah. Heck, I had a lucid dream just tonight! It was fun, but that's about it. Again; it's just yet another fuzzily bordered area along the spectrum of altered states of consciousness, not unlike wakefulness, "regular" dreaming, or indeed sleep itself. Certainly nothing magical about it, and I would actually caution against woo that claims you can "transform your life" or "live your life better" by literally trying to live more in your fantasies. That's risky reasoning, fam — the human creature is solipsistic enough without overtly emigrating into a dream world. Reverend Black Percy (talk) 12:59, 30 December 2016 (UTC)
Falun Gong[edit]
Anyone with knowledge of Falun Gong might care to weigh in on the talk page about it: Is it a cult, a religion, a pseudoscience, or something else? A newbie (Deepthought) has been pushing for a revision. Bongolian (talk) 06:21, 27 December 2016 (UTC)
- In my view, Falun Gong qualifies as all of the above. Worth nothing is that the "revision" being pushed for by Deepthought appears to be a classic whitewashing attempt. Let's not forget that the missionality of Falun Gong stems directly from it being bullshit. Reverend Black Percy (talk) 13:42, 27 December 2016 (UTC)
- Have to agree with the Rev., Deepthought's edits have all the hallmarks of apologetic whitewashing: Longwinded posts with examples of this or that professor using this or that term other than religion or cult, meandering arguments of the "not really a religion variety" that either don't define what a religion/cult is or adopt obviously flawed definitions (see Christianity is not a religion), alternative designations that are either ludicrously specific ("cultivation system", indeed...) or so broad and vague as to be useless as categorisations, oh, and trying to get Falun Gong relabelled via its RW talk page is literally the only thing Deepthought has done around here so far (although going to the talk page and not simply starting to change the article is one thing that I'll give Deepthought credit for). I may be jaded from my prior to encounters with similar apologetic/whitewashing "rebranding" around here, but I really don't think there's much merit to Deepthought's case and the arguments presented so far for removing the religion/cult designation from our Falun Gong article are rather underwhelming in my eyes. ScepticWombat (talk) 12:54, 29 December 2016 (UTC)
Carrie Fisher is gone[edit]
I'm not good with fancy words but I hope ya'll can cut me some slack for Carrie Fisher. The original badass space princess. She was open and proud about her struggles and anyone who didn’t like it could go sit on a cactus and spin. An inspiration to women and folks struggling with mental illness everywhere. You’re getting up to mischief with the angels now Carrie. I’ll miss you. MyNameIsMudd (talk) 19:12, 27 December 2016 (UTC)
- -【DiamondDisc1】 (talk) 19:14, 27 December 2016 (UTC)
Oh no :C I just found out... Reverend Black Percy (talk) 19:16, 27 December 2016 (UTC)
- She drowned in moonlight, strangled by her own bra. It's what she would have wanted. ŴêâŝêîôîďMethinks it is a Weasel 23:36, 27 December 2016 (UTC)
God damn it now her mom's gone too. She must have passed away from grief. Fuck this shit. MyNameIsMudd (talk) 02:27, 29 December 2016 (UTC)
- Yes, I read that the loss of Carrie had apparently been very stressful on her mother in the hours leading up to her fatal stroke... I have no words. Reverend Black Percy (talk) 01:10, 30 December 2016 (UTC)
With respect....[edit]
Why is news about Carrie Fisher's death and that of her mother on the "...in the world" page? I get it, Carrie Fisher was a cultural icon. I'm not a fan of Star Wars myself, but news about her death doesn’t exactly fit in with our mission statement. Furthermore, it's not exactly news flying under the radar. You'd have to be living under a rock not to have heard about her death, so widespread news about it was. It hardly needs to be repeated here. Levi Ackerman (talk) 09:06, 29 December 2016 (UTC)
- RW did it for Lemmy too. I don't think it's so cut and dry that the passing of a cultural icon goes unremarked in the WIGOs. If folks here think it's significant it's not going to get downvoted to death. MyNameIsMudd (talk) 09:15, 29 December 2016 (UTC)
- I could look it up, since I'm on the internet, and thereby preempt the need to ask this question, but who the hell is Lemmy and why was he/she/it so important to RW's mission statement as to warrant being featured on RW's newspage? Levi Ackerman (talk) 09:30, 29 December 2016 (UTC)
- Nevermind. I looked him up. I wasn't a member of RW at the time of his death, but if I had been, I would have taken the exact same issue. It's not news worthy of RW. I'm sorry. Levi Ackerman (talk) 09:35, 29 December 2016 (UTC)
- If you see something you think doesn't belong in a WIGO just downvote it dude. MyNameIsMudd (talk) 09:43, 29 December 2016 (UTC)
- Noted. Thanks. :)Levi Ackerman (talk) 09:53, 29 December 2016 (UTC)
- @MyNameIsMudd Reverend Black Percy (talk) 12:33, 29 December 2016 (UTC)
- This discussion should really be on the WIGO talk page. Personally I'm not really a big fan of the non-mission-related death/obituary entries as they seem to just arbitrarily reflect the pop culture tastes of the editorship rather than their significance as news items (hence Carrie Fischer is on there but not George Michael or Richard Adams). Meanwhile we don't usually WIGO other pop culture stuff (e.g. new film, book, album releases) unless it relates to regular RW missions & themes. ЩєазєюіδMethinks it is a Weasel 21:17, 29 December 2016 (UTC)
- Though, keep in mind that the denizens of RW — being socially conscious skeptics — are all part of the rebel alliance and a bunch of traitors. And we just lost our princess. ;__; Reverend Black Percy (talk) 01:05, 30 December 2016 (UTC)
- She was taken from this world too soon, it was very unexpected :,(.--WMS (talk) 01:10, 30 December 2016 (UTC)
- What RBP and WMS said. MyNameIsMudd (talk) 01:16, 30 December 2016 (UTC)
On the dire need for resources like RW[edit]
So I stumbled upon this old gem (from 2014), with results from the National Science Foundation. You can take the quiz yourself and see where you place — I was a bit disconcerted to see myself place better than 94% of the American public, based on that quiz.
"But it's so simple", you might argue. Yep — though, apparently complex enough for most. Anything harder than these questions is argued to be a luxury afforded to just 6% of the American general populace. As I understand it — within that 6% slice, the full range of science educations (ranging from that of Carl Sagan to that of those who just barely nailed all 12 quiz questions) reside. So if you thought that that quiz was utterly basic, congratulations — but imagine the gaps in the science education of the average American citizen.
And to pose one small sampling against another — a Russian state poll (from 2011) concluded that 1/3 of russians seem to subscribe to geocentrism.
Moving beyond small polls and quizzes, I Googled (ever so slightly less) lazily and ran into these two studies — one American study from 2004 ("Science & Engineering Indicators") and one European study from 2005 ("Europeans, Science & Technology").
In both studies, I've decided to bold the text that seems particularly relevant to the mission of RW, and to our implicit role as science popularizers by extension of our overt role as pseudoscience resisters.
The American study concluded that:
Most Americans recognize and appreciate the benefits of S&T. The public is also highly supportive of the government’s role in funding basic research. By most measures, American attitudes about S&T are considerably more positive than attitudes in Europe.
In both the United States and Europe, however, residents do not know much about S&T. The percentage of correct responses to a battery of questions designed to assess the level of knowledge and understanding of scientific terms and concepts has not changed appreciably in the past few years. In addition, approximately 70 percent of Americans do not understand the scientific process, technological literacy is weak, and belief in pseudoscience is relatively widespread and may be growing.
Although Americans generally have very positive attitudes about S&T and high regard for the science community, some harbor reservations about S&T, and 70 percent believe that scientific research does not pay enough attention to moral values. Although Americans are overwhelmingly opposed to human cloning, they are more evenly divided about stem cell research.
Americans continue to get most of their information about the latest developments in S&T from watching television. However, the Internet has made inroads and is now the leading source of information on specific scientific issues.
The European study concluded that:
The results of this latest Eurobarometer on “Europeans, Science and Technology” have shown us that there is a latent interest among European citizens for science and technology, as well as an implicit demand for more information. Indeed, we have noted that Europeans consider themselves poorly informed on issues concerning science and technology, and we can observe a link between low interest and the feeling of lack of information.
Nevertheless, progress has clearly been made since 2001 in terms of basic scientific knowledge. The “science and society” action plan put into place by the European Commission in 2001 seems to have had a positive impact. However, the gap between science and society still exists. Efforts must namely be made in order to bring science and technology closer to certain categories of people who are less exposed to the scientific field, and who therefore have a more sceptic perception of science and technology. These categories are more often women, older people and those with a lower level of education.
In spite of the existence of this gap and the lack of information there is however a very positive and optimistic perception of what science and technology can actually do for humanity in terms of medical research, the improvement of the quality of life, as well as the opportunities for future generations.
Although such strong confidence in science and technology subsists, a somewhat stereotyped vision seems nonetheless to exist, which bases itself on the classic image of “machine against man”. We can notice this especially where the economic and spiritual dimensions of individuals are concerned: the negative effect of technological developments on employment and the distress scientific and technological progress causes in the daily lives of individuals is reflected in the results of this survey.
This duality is also valid for the image Europeans have of scientists: on the one side, there is the recognition of the positive role scientists play in society, and also the wish to see policy-makers take more into consideration the expertise of these scientists. On the other hand, we can note a criticism towards scientist’s obscurity concerning the results of their achievements and the way they handle information towards the public. Furthermore, a certain fear of scientists is expressed in two manners: in a more open way concerning scientist’s excessive power (due to their high knowledge), and in a more implicit way concerning the risks of scientific research going beyond the limits set by ethics and morality.
As a matter of fact, in the opinion of Europeans ethics must play a crucial role in scientific research. Citizens request a certain harmony between the methods as well as the goals of scientific research and the moral and ethical principals. Even though citizens draw such a limit for the boundaries of scientific research, European citizens nevertheless want to allow scientists to work freely without letting the apprehensions of potential risks deriving from further research slow them down. In this sense, it seems that Europeans would like to impose a balance between ethics and scientific progress, which will certainly demand much effort on behalf of the scientific community as well as the public authorities who are expected to impose the legal basis of such a control through ethics.
Europeans are also a clear majority wishing to see more women implicated in the field of science and further integrated into the scientific community, which should reflect more equal opportunities between genders.
Results also make clear that Europeans’ hopes for future scientific and technological development lie in the hands of the younger generations who should show more interest and participate more intensively in the field of science. It seems therefore that action must be taken by public authorities throughout Europe in order to make this possible.
Finally, the report also shows that Europeans have a rather critical perception of Europe compared to the United States when it comes to fields related to research: the deficiency in the education of scientists in Europe has probably lead Europe to take up a position behind the United States in scientific discoveries and technological advances.
Keep up the good work, everyone. From creationism to water fluoridation to cryonics to GMOs — and everything inbetween (pun intended) — at our best, we're like a breath of fresh air on a crowded subway train. Reverend Black Percy (talk) 13:44, 29 December 2016 (UTC)
- Great find!-【DiamondDisc1】 (talk) 02:08, 30 December 2016 (UTC)
- This would be a great addition to Essay:Why we need RationalWiki. cough. Herr FuzzyKatzenPotato (talk/stalk) 22:30, 30 December 2016 (UTC)
Religious gibberish, apparently this is a big deal in the era of Trump[edit]
So apparently someone who does not believe in the Nicene creed as dictated by Constantine will pray at Trump's installation as supreme leader. This prompted this gibberish (especially the weird video comment on the initial gibberish). Can anybody explain to me why this seems to be such a big deal to some? Oh also, the video ends with "wake up America". 77.22.253.4 (talk) 17:51, 29 December 2016 (UTC)
- The Nicene creed basically established the Trinity as a requisite belief for Christians. Denial of the Trinity is a big no-no among most fundies and all Catholics. Bongolian (talk) 19:24, 29 December 2016 (UTC)
- The hypostasis of the Trinity formalized the the Nicene Creed is foundational to all branches of mainstream Christianity, and Christian denominations that deny it (like Mormonism), are seen as "other", and outside the fold of Protestant/Catholic/Orthodox ecumenicism. But, at the end of the day, 99% of Christians would have a hard time distinguishing the theological differences between Arianism and mainstream Christianity anyway, so yeah... The normalizing of the Prosperity Gospel, which isn't exclusive to Arianism, should be far more troubling to mainstream Christians. Petey Plane (talk) 21:14, 29 December 2016 (UTC)
I made a poll on a talk page[edit]
If you know a bit about the politician, please vote.
What category should Mélenchon be in.
Feel free to argue about it. Diacelium (talk) 22:41, 29 December 2016 (UTC)
When writing an article, should I use Qur'an or Koran?[edit]
-【DiamondDisc1】 (talk) 04:50, 30 December 2016 (UTC)
- It's preferable, but not required, to use "Qur'an" because that's title of the RW page. Bongolian (talk) 05:01, 30 December 2016 (UTC)
- The romanization can be "quranic", "koranic", and "qur'anic" and can be capitalized. There's no official rule to romanization besides sounding close. I guess use the existing article title. You can use whatever spelling you want in an article so long as it is consistent within the article.—Hamburguesa con queso con un cara (talk • stalk) 17:21, 30 December 2016 (UTC)
- Qur'an, afaik. Reverend Black Percy (talk) 05:11, 30 December 2016 (UTC)
- Koran was the preferred spelling before 1945, and in fact usually prevailed before 1980s. In matters of usage like this, it's best to let pre-WWII usage be the guide. - Smerdis of Tlön, LOAD "*", 8, 1. 21:48, 30 December 2016 (UTC)
To whoever posted the Glenn Greenwald article alleging that the Guardian manipulated an interview with Assange to make the latter seem more pro-Trump...[edit]
...your link has been relocated from "WIGO...in the world" to "WIGO...in the blogosphere", as it is an op-ed. It's not "news".Levi Ackerman (talk) 10:13, 30 December 2016 (UTC)
- Nice of you to alert people! However;
- 1. This belongs in Talk:WIGO
- 2. Please don't go for topic headlines that rival your very post in symbol count. Reverend Black Percy (talk) 11:32, 30 December 2016 (UTC)
- Duely noted. Levi Ackerman (talk) 12:28, 30 December 2016 (UTC)
The radical right has won[edit]
We call the era after ca. 1500 'modern period' as opposed to 'middle ages'. It's not that for at least 3 centuries after that the life of most people changed in any conscious way. It is we who retrospectively focus our attention on the historically novel elements to distinguish them from the old even as the former are still found to be for a long time numerically inferior and yet absolutely decisive for the future. Apply this to the radical right. It is still not found as often as the more orthodox right but trends are pointing towards a (near) future where it will dominate. The reason for that is not the 'foolishness of the establishment' as some intellectually robust yet socially anemic and dying remnants of the left say or the implacability and intransigence of SWJs as some elements of the up-and-coming fascistic right have it.
The true reason is found in the socio-political shifts occasioned by the crash of 2008 marking the end of wall street domination and in parallel the steady emergence and significance of hungering titans like China. Pluralism and values tolerance can only exist where goods exist in abundant supply. This is precisely what's changing. If these conditions are lacking tolerance will cease to be the officially-championed doctrine and ideologies will flourish which will legitimize stringent hierarchies along social and racial lines. This is logically unavoidable. The only idea that can combat the universalist idea of tolerance is the relativist idea of natural incompatibility between 'different' peoples and cultures and the support for intolerance to remedy the world's problems. In the west racialism and various forms of xenophobia will inevitably prevail. In the rest of the world anti-western sentiments will become more and more common.
Regardless what global-warming denier imbeciles tout in their (un)willful blindness global warming is very real and very serious. On the other hand however, and this is where I break with most of you folks, there's no feasible alternative to fossil fuel energy and there's no realistic future model of mass production despite what a few utopian visions suggest. Energy Skeptic illustrates the reasons for that very well. The logic of resource scarcity, state ownership, energy dependence and forceful requisition, territorial dispute and all-round ecological degradation still stands.
Karl Marx predicted a utopia for western societies and this came to be in a certain sense although it is a caricature of what was envisioned in the perspective of then-current classic liberal educational ideals. In the minds of the fathers of communism Utopia would resemble a place full of small and great Shakespears and Goethes and not exactly the massive multi-colored and multi-patterned triviality and idiocy of life in a mass democratic society. Regardless, we were the first societies to extinguish through mass production and technological innovation the endemic scarcity of goods that had haunted all previous societies thus introducing in the masses a never-before-seen hedonistic live-and-let-live attitude. After a utopia was realized on a western level expect a dystopia to be realized on the global level. Expect the 'global order' and 'stability' you have experienced for so many decades to degenerate into a world where only constant brutality and irrationality can maintain a semblance of an order and stability always seemingly teetering on the edge. Expect the fluidic and aerobatic disorder of tolerance to be succeeded by a hardcore, iron order. Expect hedonism and hope to become an endless nightmare. Expect 'reason' and 'consensus' to succumb to the monolithic theory and the practice of witch-hunting and scapegoating.
Don't be disheartened that the 'irrationals' and the 'cranks' have won. Do not curse at them, do not lament them, do not deplore them. Understand them. Look upon their puerile fears and superstitions with the compassion we see them in a child who will one day grow to be a man. Their world will not be a better one and their actions won't have the consequences that they hope will have. The heterogony of ends is the law governing history's Werden. There will be no cleaner and no whiter world. On the contrary civilization in the 21st century will face complete annihilation and 'western civilization' will succumb too.
Skeptic friends, do not expressly or implicitly treat skepticism as a moral value to advance the good of society. Give up on the notions that Popper has popularized. When skepticism ceases to be a moral value it simply becomes nihilism. Give up, give in. Lay down your prejudices forever to experience the world without hope, without fear. Gewgtweg (talk) 18:52, 18 December 2016 (UTC)
- there's no feasible alternative to fossil fuel energy
- Uh. Nuclear power. Google "generation 4 reactor" if you're still unconvinced. Fuzzy. Cat. Potato! (talk/stalk) 19:28, 18 December 2016 (UTC)
- Nuclear power is a great alternative ... if done right; it can create a massive amount of energy but has major consequences for a screw up (don't build reactors along a coast *cough*fukushima*cough*). Solar power is another good alternative. After all, the sun is free and oil is just converted sun energy.—Hamburguesa con queso con un cara (talk • stalk) 19:37, 18 December 2016 (UTC)
Are euro-centric Marxist diatribes which reduce every conceivable social movement or ideology to zero sum economics (which describes pretty much every Marxist diatribe, now that I think about it) supposed to be understandable? Lord Aeonian (talk) 21:09, 18 December 2016 (UTC)
- @Gewgtweg You're deluded. The radical right's victory is not all powerful and all consuming. Clinton was an extraordinarily weak candidate, hamstrung by thirty years of scandal both real and imagined, with a horrible ground game and she still won the popular vote and lost in the Rust Belt states by only about eighty thousand votes. The Republican's primary base is dying off, my generation and the youth is increasingly liberal. Technological breakthroughs are still happening, progress is still happening. The next few years will be tough, there will surely be struggle, but we can see it through. MyNameIsMudd (talk) 21:10, 18 December 2016 (UTC)
- I agree with Mudd, except on the weak-candidate point. Clinton got as many votes as Obama did in 2012 -- as Mudd notes, about 80k votes in three states made all the difference. And, though this is rarely remembered, Clinton was running as a third-term Democrat. It is extraordinarily rare for a party to keep the White House for more than 8 years. I do think she could have been stronger (eg, if Sanders hadn't run, the "corrupt Clinton" meme would never have started; if she had fucking released the emails, it wouldn't have been an issue; and so on) but I think it is a mistake to call her weak. (One might respond by noting that Trump is a weak candidate. I think that would ignore the Mitt "47%" Romney and Sarah Palin catastrophes of '12 and '08 for the Republicans, when the performed similar to now.) 32℉uzzy; 0℃atPotato (talk/stalk) 21:32, 18 December 2016 (UTC)
- I say she's a weak candidate because she had precious little charisma, has made numerous documented gaffes over the years and didn't reach out to the Rust Belt voters enough. Again, I point to the horrible ground game in Michigan where they were so convinced that their win was idiot proof (har har) that they turned away people offering to canvas votes for them and didn't have the usual pamphlets and info tracking paraphernalia that you're supposed to. Maybe she wasn't exactly weak, but she was weak enough that it allowed the greatest threat to democracy in our time to slip right on through to the White House and that makes all the difference in the world. MyNameIsMudd (talk) 21:42, 18 December 2016 (UTC)
- Hillary Clinton was chiefly hamstrung by carrying the name of and being married to the Democrat president who abandoned the New Deal in favor of deregulation and free trade, and threw the Democrats' labor constituencies under the bus. Enough people remembered what the Clintons stood for that she failed to carry key Rust Belt states, and all the enthusiasm was on the Trump side. She was weak and she was exactly the wrong candidate for this cycle. If heads don't roll at the DNC, we're going to need a third party. - Smerdis of Tlön, LOAD "*", 8, 1. 22:26, 18 December 2016 (UTC)
- Thankfully Sanders has been given a position, Warren is moving on up to shore up her lack of foreign policy chops and Ellison is lining up endorsement after endorsement, a full list of which can be found at this article. If anyone has any other good news on the progressive Dem front feel free to share. MyNameIsMudd (talk) 22:41, 18 December 2016 (UTC)
- To say that youth is "increasingly liberal" is wishful thinking on your part. I (a millennial) went to numerous Trump rallies, and met tons of fellow millennials there. There were tons of girls there, who didn't seem bothered in the least about the controversies the Clinton campaign attempted to drum up. They weren't just white-trash or spoiled little rich kids, there were state college kids there. There were black and Hispanic kids there. This was in a swing state, not some deeply red state full of rednecks where the Dems had no chance. In 2008, I think it's fair to say most of my peers supported Obama, but many of those same people no longer support Obama, many now supporting Trump. In 2008, some kids were begging their parents to vote for Obama, but in 2016, kids were begging (and sometimes successfully convincing) their parents to vote for Trump. Conservative colleges like Liberty University and Pensacola Christian College are rapidly expanding, and so is the homeschooling movement. Members of Anonymous, who are mostly youthful individuals, are actively attacking the Democrats. Snowflakes will always be snowflakes, and there will always be some gullible youth who take liberalism hook, line, and sinker, but I would say my generation is moving away from liberalism rather than moving towards it. The youth were very liberal in the 60s with the hippie movement, and today's youth are nothing like the hippies. They don't even have to draft people to staff the military anymore. Youth are becoming annoyed by dumb celebrities like Kim Kardashian, which means the liberal entertainment industry is having less influence on young minds. Liberal newspapers and television news broadcasters are also having less influence on a generation turning to the internet for its news, while online sources like Breitbart and Info Wars are appealing to a tech-savvy population. 76.5.20.58 (talk) 16:07, 27 December 2016 (UTC)
- Gee, anecdotal evidence much? As for the "snowflake" thing...I'd rather be a snowflake than a proto-fascist, you ass. MyNameIsMudd (talk) 16:18, 27 December 2016 (UTC)
- One of the interesting things about the phenomenon is that the "liberal" (anti-White) tactic of name calling isn't effective anymore. Like when you get called a racist fascist Nazi for supporting your ethnic interest like everybody else and you're just like "yeah, so what?". 85.90.229.202 (talk) 16:35, 27 December 2016 (UTC)
- "Anti-white" huh? I'm white, jerk. Load up your disgusting philosophy with as many pretty words as you like, identitarianism, ethnic interest, cultural pride, whatever. If it looks like a jackbooted thug and talks like a jackbooted thug...you get what I'm saying? MyNameIsMudd (talk) 16:45, 27 December 2016 (UTC)
- It's entirely possible and in fact common for Whites to support anti-White policies and sentiments. We call them cucks, race-traitors, shitlibs, brainwashed mindless sheep, etc. We can do name calling too.
- "If it looks like a jackbooted thug and talks like a jackbooted thug...you get what I'm saying?"
- No. 185.4.118.141 (talk) 17:22, 27 December 2016 (UTC)
- Whatever prick. Go cry about it on 8chan, or maybe Stormfront. I don't give a shit. MyNameIsMudd (talk) 18:30, 27 December 2016 (UTC)
@LordAeonian Euro-centric? Only in the sense that Marxists are really, or at least were the last remnants of the bourgeois legacy (yes it sounds paradoxical but it's true) and the bourgeois era, an era that was really Euro-centric. But the bourgeois period is long, long dead and after WWII, the Euro-centric period is permanently dead too. Marxism in the philosophic-historical/utopian sense passed away with the Soviet giant forever. The modern utopia is represented by right-wing and left-wing liberalism with their emphasis on technology and innovation and their global social promise, the promise of a post-industrial utopia with boundless and 'clean' energy. The terrifying resource conflicts of this century will bury this vision.
A more economic state of affairs will be necessarily enforced in the future but it will be done using hierarchical and not egalitarian criteria. Thus the world will be equalized and made more egalitarian in a reverse, brutal fashion. Advanced mass societies will slowly eat its own insides and less advanced societies will break down and fail (as it happens in the Mid-East and Africa) or be eaten up by more powerful neighbors (In Eastern Europe, Russia and the Franco-German economic axis (the EU) are the predators while in the Balkans it's Turkey and the EU that are the predators) and the most vulnerable groups like minorities in the US will perish or suffer persecutions and severe discrimination which they're already suffering. War might not even be the real threat at all. Growing global unrest is equally dangerous. This is already reality in some areas of the planet.
The two parties represent two sectors of the establishment. The Reds represent capital and the Blues banking. Clinton represented a dying establishment that was fatally wounded in the crash of 2008. People like Obama are the cute faces of that establishment and I fear Sanders would have been the same. Someone elected on a progressive platform but who failed to deliver (for objective reasons). It is nevertheless true that other members of the party didn't trust him.
After the Bush experience when the GOP lost political capital, the Tea Party especially after 2008 become a platform for safeguarding plutocratic interests in the wake of the crisis of global finance in 2008. The rhetoric of the Tea Party itself (essentially establishment republican) forced other elements of the outer republican sphere to move further to the edges of the right. But it wasn't just emerging macroeconomic instability and the inability of both sectors of the establishment represented by the two parties to remedy it that made identity resentment widespread again. The experience with ISIL and terrorism was psychologically catalytic in instigating existential, animal-like fears in the western public. The fact that we had a black president serving two terms made identity rhetoric a very effective tactic for the GOP again.
An unexpected consequence of all that was the likes of Trump, Farage, LePen and other such figures arguing in favor of protectionism and an economically and politically more sealed-off world. These figures can be called the radical right, or anti-establishment right. I don't believe that there is or could be a left-counterpart to that that's of social significance. At best, it gives the radical right its targets or its nourishment. Some of you here have wondered, 'why is the left blamed for everything'? The answer is simple. It's easy to target what's half-dead and incurably weak. The modern left is just too decent, too benign, too honorable and too vegetarian to survive. They are a disgrace and thankfully Lenin is not here to see what has become of them.
Many of you don't want to understand it, but it's true. The end of the Soviet Union essentially crippled the left. You also don't want to understand that there's no alternative to fossil fuel energy in order to sate the demands of the modern past-paced world. Go tell India to give up on coal. Tell China to shut down its coal-fired power plants. Tell Russia to stop selling its natural gas. Have a 3D printer create water to irrigate the world's crops. Have the world's great military mammoths run on batteries. Finance massive geoengineering to halt the rapid progress of global warming. Do all that, and then we'll talk.
If even Germany can't pull off its Energiewende, then it's not looking good for the rest of the world at all. Gewgtweg (talk) 13:38, 19 December 2016 (UTC)
- Lenin was a bad guy. I don't give two shits what he'd think about the modern progressive movements. You remind me of an old "friend" of mine that was always riding Lenin and Stalin's rotten dead dicks, bleating about communism being the One True WayTM and the inevitable downfall of filthy capitalist civilization. He wrote just like you do too, using ten words when one will do and producing diatribes far in excess of what it takes to make your point. MyNameIsMudd (talk) 15:21, 19 December 2016 (UTC)
- Before you move to declare me verbose and redundant, idiot, at least pretend that you understand what I am actually saying. You're writing as if I'm advocating for communism here. In fact I'm not even a leftist; I am not political at all. I am a nihilist; straight and simple. Tell me right here, right now where in my text you found any suggestion that I am championing any cause at all. When I call modern progressive moments weak and feckless it's because they ARE not because I personally despise them. And by the way, capitalism will collapse too, just like feudalism collapsed. Nothing is here to stay forever, if history is any guide. I do not believe it will survive the century. If the 20th spelled the end for the communist utopia the 21st will annihilate liberalism and no left and no right wisdom will help ease the crushing burden of disaster to befall the good earth. Gewgtweg (talk) 19:10, 19 December 2016 (UTC)
- Oh joy, a person hiding behind a philosophy that gives an excuse to lay down, uncritically accept one's fate and die. I've never seen the like/sarcasm. No, no we will not go passively into that dark night. If everyone thought like you we'd be a listless, hopeless and meandering species until we all passed away of apathy. "The arc of the universe bends towards justice," to paraphrase MLK Jr., and I believe that with every fiber of my being. If they're so weak and feckless, why do the people of my generation have more rights than the last? Hm? And the people of the generation before mine had more rights than the ones them. Progress isn't a straight line by any means, there are trips and fumbles and struggles, but it's human nature to strive towards goodness and fairness. MyNameIsMudd (talk) 19:24, 19 December 2016 (UTC)
- Seriously, Mudd is right about your verbosity. Try to condense your posts. Walls of flowery text are difficult to read, difficult to interpret, and difficult to respond to succinctly. Regardless of your opinions, it'd make it easier to have a conversation with you. B) talk 20:27, 19 December 2016 (UTC)
Reading both of the posts by you guys has left me wondering if my posts are too simple despite being long or if they are too complex because they're long thus making response difficult. If I am simple I am already comfortably dense; if not I need condensing. Which of the two is the case? At any rate, my post wasn't simple enough for Mudd so as not to misunderstand it. As for you Shaw, I wonder, do you never read books because they're too long and too complex? Do you still read children's books instead? Be that as it may, don't worry about being unable to contribute your precious opinion because of your difficulty to 'read', to 'interpret' and to 'respond'. If something is uncomfortable and painful to read, just don't read it and by all means, do spare us your response.
You folks have to decide sometime. Is nihilism about 'laying down and dying', 'fatalism' and 'depression' or is it about 'living life to the fullest' about 'being the best you can be', and 'hedonism'? The idea that the life, the universe, man etc. lack any objective meaning to guide them, that they lack a fixed objectively discernible value is not just a 'philosophy'. It's not just a man's version of the truth; it's not just a 'way to see things'. It is the truth. It is a necessary frame that makes up the framework of reality and it is indispensable to any understanding thereof. You talk about 'goodness' and 'progress' as if these are the most obvious things in the world. As if different people do not have different ideas about what it means to 'truly' progressed and to 'truly' do good.
A white supremacist for example has entirely different ideas about how society can finally move forward and get rid of what's keeping it back or what it means to do the good, decent thing 'for your people'. Of course they wouldn't use the slogan of 'progress'; they have other slogans. But whoever uses slogans as a way of measuring social reality doesn't understand social reality.
Sure your generation has even more material and social rights than the previous one. But have you ever wondered if that has anything to do with the fact that you live in one of the world's most affluent regions? That you live in a pluralistic society where hedonistic and emancipatory social stances inevitably prevail? More importantly, do you have any idea how the pressure of communism was instrumental in changing western societies themselves and making them more liberal? Read my essays on marxism and communism and you'll learn. Gewgtweg (talk) 11:51, 20 December 2016 (UTC)
- I say this sincerely and not to antagonize you: you'll probably gain a more receptive audience if you 1) reply to specific points individually where they are made, instead of in a dislocated block, 2) revise your posts to make them more concise before you submit them, 3) avoid absolute statements like "it is the truth" when speaking of propositional attitudes, 4) stop acting like your presence here is an undeserved gift to inferiors, and 5) lay off the ad hom. B) talk 04:32, 21 December 2016 (UTC)
- @Gewtweg Aren't pluralistic societies largely the norm throughout history? I mean occasionally one nation or another will veer off the deep end into ethnic cleansing but by and large civilization has always been more or less multi-ethnic and multicultural. I also question the effectiveness of communism as the law of the land, since every time that's been tried it has ended in blood to my knowledge. I don't know everything under the sun and make no claim to that, I'm white trash from Alabama that barely graduated out of high school. I just want to do right by folks and stand up where I see injustice, not abandon skepticism and everything I believe in because of some cosmic mandate from on high about society's inevitable shift into brutal blood spilling tyranny. MyNameIsMudd (talk) 05:21, 21 December 2016 (UTC)
@Bshaw My replies do reply to specific points made by previous commenters. Show me a concrete example where I didn't do that. In this post I briefly outlined some reasons why I believe the radical right will win because of favorable conditions. The space I take and the way I express this (and I admit that I'm not every enjoyable to read) is something that I partly can't really help. It's the nature of my writing and of my thought structure and in the final analysis it's my own business. I have the tendency to keep it long and if this doesn't conform to your aesthetic ideal I'm sorry. Unless I have to rent space off of you in order to do that which we are after all supposed to do here in the first place, i.e. to write, I will continue following my natural inclinations and ignore you totally and provocatively.
Oh you are not antagonizing me? Sure when someone is accused of 'acting like his presence here is a gift to inferiors', when he's guided to 'avoid absolute statements when speaking of propositional attitudes (sic)', when he's told to reply to 'specific points individually' as if I'm replying instead to some mysterious black hole, when my post is called a 'dislocated block', then sure that's 'sincerely', like very 'sincerely', not a bit antagonizing at all. Well my friend, keep your 'sincerity' to yourself and save your replies and your obviously precious energy for the posts you deem worthy of replying and the reading of which is easy and digestible enough for you to stomach smoothly.
When Richard Dawkins famously said 'Evolution by natural selection is not a version of the truth. It IS the truth' was he merely just being strident and shrill about it? Was he being 'absolute' and not 'prepositional' about it? If you believe that I'm wrong and nihilism is not in fact empirically-founded truth and that objective values beyond the human perspective do somehow exist, then show me, fool. Don't you people always argue against nihilism or the postmodernists that we supposedly 'ignore reality'? Well by using the expression 'it is the truth', I am definitely not ignoring reality. Yes, I am antagonizing you. Prove to me that I am wrong. Reply to these specific polemic points I made, right here, right now. If, as I suspect, you will not or cannot say anything on the matter, go and amicably advise somebody else about what and how they should write.
@Mudd No, pluralistic societies are not the norm throughout history. Multi-ethnic empires have existed, lords and subjects have lived side by side but pluralism was never before considered a value to safeguard nor was hedonism the dominant social stance in any past society before western mass democracy. In other words no previous society was as socially mobile as our own. The plethora of cultures, civilizations and beliefs throughout history and the definition of each culture, each civilization and each ideological system as pluralistic is two different things. Before the European modern era when globalism started to make its advances, cultures divided their borders using violence such as it happened for example with the Frankish and Arab cultural greenhouses. Today material, intellectual and cultural goods have created a global culture. The championed ideology is a mixture of tolerance, universalism and relativism void of any overarching principle such as Reason or God. I will post an essay on that matter very soon. Maybe you'd be interested to have a look. About communism I have written a couple of essays that address your points. You could reach them through my page. You could maybe have a look and I'd be happy if you commented on the talk page.
I don't believe that man is incurably 'bad' or something such and contrary to what many people believe misanthropy or anthropological pessimism are neither logically nor historically (necessarily) connected with relativism and nihilism. But I definitely don't believe that conflicts, including lethal conflicts between humans could ever cease or that they could at least become unlikely or less as harmful or less historically as decisive. This is not a 'mandate from high above' but it is based on a complex set of anthropological reasons, at any rate secular and immanent reasons. The victory of every sort of 'justice' is therefore only temporary. I don't want to deprive people of illusions that give their life meaning. This sounds condescending of course but I really don't. Not only don't I see people with opposing views as more or less mutations of humans beings (and most people basically just do that to be honest) but instead I feel compassion about man's efforts to create meaning and to fight for that meaning.
Aye, I feel compassion for the agony and pain humans experience in their pursuit to address existential challenges. In that way, not only we nihilists aren't numb to people's suffering throughout the past and present but we're in fact the only ones that are really willing to show selflessly, impersonally and solemnly, a degree of genuine understanding to them. I find it interesting and astounding that atop this planet, matter or energy, whatever you like, became aware of itself, that there are beings who produce meaning and who destroy others and destroy themselves in the name of that meaning. Gewgtweg (talk) 15:37, 21 December 2016 (UTC)
As a follower of Khorne, I am happy that I can get more bloodshed and less of these weak cowards from Tzeentch and Slaneesh. We as Chaos followers were hoping for the radical right to help. Race wars and ethnic conflict=more sacrifices for the Blood God Khorne, for he cares not from whence the blood flows, only that it flows. As a Chaos Marine, I shall collect more skulls for the skull throne to make America great again. Maim!Kill!Burn! 02:55, 29 December 2016 (UTC)
Reverend Black Percy (talk) 19:22, 1 January 2017 (UTC)
Something that adds to the stigma towards the mentally ill[edit]
When people say religion is mental illness. That really steams my beans because I do not see believing in a higher power is insane. While it is true that there are some people who take religion and twist it around for irrational purposes, it does help some mentally ill people stay sane (In my case anyway). For people who do have religion but are mentally ill, it probably makes them feel worse about themselves; the American Psychiatric Association does not list religion as mental illness, I guess people who do say that must have never heard of the scientific method--Rationalzombie94 (talk) 19:25, 22 December 2016 (UTC)
- That doesn't seem to be that wide-spread a belief and I think most people would agree that having irrational beliefs is not necessarily a sign of mental illness. Is there some context as to why you bring it up? If there are pages here they imply that religious belief is a mental illness, then those should be changed. Petey Plane (talk) 19:58, 22 December 2016 (UTC)
- oops, forgot "not" there, completely misrepresenting myself. Petey Plane (talk) 21:06, 22 December 2016 (UTC)
- No, not any of the pages. Someone on Facebook said it. I do agree that taking religion out of context to fuel psychiatric delusions is mental illness but saying religion in general as a mental illness is just wrong--Rationalzombie94 (talk) 20:05, 22 December 2016 (UTC)
- As someone suffering from Depression and formerly believing BS, i can get where they come from but the similarity is at best a superfically odd behaviour(and only if you know Mental illnesses from Movies and TV). A lot of these new Atheist are the same kind of Atheists that adhere to the MRA and anti Social Justice mindset, they like to diminish other People they percieve as wrong. And they don't give a shit about the innocent bystanders they hurt.--Benaresh (talk) 21:00, 22 December 2016 (UTC)
- Religion in general provides inspiration, comfort, explanations, an ethical system, etc for many people, and can provide a means of stability for at least some people with problems. Whether one is of a particular faith, believes 'that there is more to heaven and earth than purely scientific explanations' or atheist one can accept that 'religion in some form' can have a positive role.
- However some people use religion in negative ways (as a means of control - whether or not in cults; or to justify their destructive tendencies etc) and in some cases religious beliefs can interact with mental health issues in a destructive way.
- A simplification of the two extremes perhaps (but not necessarily invalid as a result). 86.146.100.116 (talk) 22:51, 22 December 2016 (UTC)
I have nothing but empathy for your basic position; that accusing religious people of being mentally ill is both wrong and negatively adds to the stigma of mental illness. That being said, however... It has to be possible to philosophically explore any possible overlap between belief and mental illness, as with Carrier's talk "Are Christians Delusional?". And I do believe that these kinds of explorations, which enter into the territory of what may or may not be legitimately considered psychopathy or delusion, are actually quite relevant. Reverend Black Percy (talk) 18:56, 27 December 2016 (UTC)
This is what your post had, dear reverend, and many discussion regarding this matter lack: nuance, sources and a tone of consideration. I agree there is a psychological component to the more extreme of religous people that rarely is talked about.--Benaresh (talk) 16:45, 30 December 2016 (UTC)
- Well, thank you! About the one thing I consistently try to do is to prevent myself from falling headlong into splitting. "There's nobody so good there's not some bad in him, and there's nobody so bad there's not some good in him" and all that (and the same goes for ideologies/movements/theories/etc). That being said however, the ratios of "bad" to "good" when it comes to most ideologies/movements/theories/etc is not anything like 50%/50%, and we need to keep that in mind as well... Anyways, I'm ranting (and I suspect I'm off topic already). So regardless — thank you for your kind words. I'll try my best to earn them in the future as well. Reverend Black Percy (talk) 19:13, 30 December 2016 (UTC)
Religion is not a mental illness, but as a fundamental Baptist, I can appreciate the fact that sometimes people who are mentally ill use religion as a front. Case in point, people who hear voices, claiming that the Christian God is telling them to do things that contradict the Bible. 76.5.20.117 (talk) 07:01, 1 January 2017 (UTC)
- So you agree with the old adage; "If you talk to God, you're religious — if God talks to you, you're psychotic"? Worth pointing out is that I certainly wouldn't equate religiosity with mental illness or anything of the likes (which would be doing a disservice to religiosity and mental illness alike) — though admittedly, were it not a direct product of our apealoid neurology, the religious impulse would still basically constitute a form of widespread "neurosis". Reverend Black Percy (talk) 19:37, 1 January 2017 (UTC)
Thoughts on Rent Control[edit]
Like does it work, should it be implemented, etc. Just curious. RoninMacbeth (talk) 04:31, 26 December 2016 (UTC)
- Quoting Wikipedia- ."--Rationalzombie94 (talk) 04:34, 26 December 2016 (UTC)
- Rent control is commie bullshit. Moscow had rent control from 1928 to 1992. When a window got broken, the landlord (in this case, tbe government) never had enough money in a fund dedicated to maintainance, upkeep, and replacement costs. Same as broken plumbing or electrical fixtures. If you wanted to keep living there, it was your problem. And apartments generally have common areas that must be maintained by the collective rents paid by all tenents. These generally are the first to go unrepaired and unmaintained, making the whole property a shithole to live in. In short, the property value deteriorates (as does the tax base consequently). But commie city councilmen woukd like you to believe they really care about you, to get your vote. nobs 05:07, 26 December 2016 (UTC)
- "Rent control is bullshit. *Long, winded strawmanning because almost all rent control isn't Soviet by definition* Damn commmmies!!!!1!1!1" - Robert Smothers
- Really? Let's actually talk about what rent control would do. Part off the reason Soviet landlords didn't have enough money to repair their apartments is they were dirt poor Russians living in 1953. Kind of a big factor you ignored there Rob. Look, you could do a whole five-part podcast on why Soviet Russia failed as a society, so I'm not gonna be able to cover it all in a forum post, but suffice it to say there are a metric FUCKTON of reasons why rent control wouldn't have worked in a poor economy like that of old Russia. Where would a system of more equal rent payment and thus more even wealth distribution work? Oh I dunno, AMERICA, the richest fucking country on the face of the goddamn EARTH? A country where no landlord in New York is every gonna have to worry about feeding the kids or repairing the apartment?
- The annoying thing about Rob's position on this is that as a capitalist, he should absolutely LOVE rent control. Reducing the costs of tenants gives them more purchasing power, in turn boosting the local economy, creating jobs, and increasing tax revenue. It's a little price control that can go a long way. PBfreespace (talk) 16:00, 26 December 2016 (UTC)
- Fundamentally it's a wealth redistribution tactic, but an incredibly imprecise one that operates in a capitalist system and often fails to account for many of the side-effects that a free market will push: reduction in incentive to create more housing and/or cost control in other places leading to run down buildings. On the other side of things, if there is an entrenched landlord class, the loss of income from rent control could actually push them out of the game and increase overall competition, relaxing the need for rent control. My biggest problem with it is it's often done by people who don't put in the research on how to enact their goals, but instead purely as a symbolic, populist measure. Democratic socialism can be hard to do, if done incorrectly. ikanreed You probably didn't deserve that 16:10, 26 December 2016 (UTC)
- Why is rent control commie bullshit? Like the minimum wage, it sets up a strawman argument - that the greedy evil businessman-landlord-employer is out to fuck the little guy, and only the politcal class of government bureaucrats can protect the strugglng masses. Never mind the fundamental facts that landlords and employers supply something mutuslly beneficial that people want and need - housing and jobs. The bureaucrats, government, and ideologies sure as fuck cannot deliver jobs and housing. nobs 13:36, 27 December 2016 (UTC)
- here's some commie bullshit, feel free to ignore it: houses should be built to house people, not to sit empty because it wouldn't be profitable to house people who don't have any money. we've got more empty houses than homeless people, at least in the "developed" world. why should shelter be a commodity when the people who need it most will never be able to afford it? and please don't use something like "property rights" as your answer, especially when you decry "ideologies". Frederick♠♣♥♦ 08:14, 29 December 2016 (UTC)
- In theory, rent control can serve to internalize the externality of community destruction through gentrification and allocate the friction inherent in the rental market to short-term rentals from long term rentals. In practice, rent control schema have resulted in substantial rent-seeking behavior by both owners and tenants, and do very little to inhibit the negative impacts of gentrification (though often doing a great job of inhibiting the positives). Hipocrite (talk) 01:48, 27 December 2016 (UTC)
- With rent control, improvements aren't done, the property deterioates,and its value goes down. Since landlords can't make money, new construction stops. Then you're faced with a housing shortage, which ordinarily would make properties more valueable and put upward pressure on rents, the only housing stock available are cheap, unimproved units that continue to deteriorate. Additionally, there's a stampede among landlords to get out of the business, which puts a glut of unimproved rental properties on the market simultaneously and further depresses real estate prices.
- And look at it from the taxing authority's perspective: a municipality is dependent on property taxes for its revenue. By limiting their revenue through rent control and artificially depressing real estate values below market value, the municipality can't deliver the services to the same people they supposedly were trying to help. nobs 04:59, 27 December 2016 (UTC)
I may be wrong about this, but I heard that NYC's housing issues are partly caused by rent controls/rent ceilings. For instance, one elderly woman was able to own an entire floor and a half (!!!) do to a rent ceiling. The idea seems to be, first of all, that people may buy more than they need or otherwise would because they can, which removes housing and further drives up prices in non-regulated housing, and second of all, that developers are discouraged from building new housing despite demand because of the lack of profit potential. Lord Aeonian (talk) 02:17, 28 December 2016 (UTC)
- It's being dicussed in San Fransisco right now where average rent is $3500/mo - about three times higher then cities of simi!iar size & demographics. Why this is so I'd speculate due to two factors: (1) limited space. San Fransisco has no where toO grow but skyward; and (2) California's high taxes. But you're absolutely right. When the government caps your income, you are going to pull your money out of the investment and go elsewhere or a different business. Because the property as an investment doesn't return its full potential, it will sell for less now. This attracts a different kind of buyer, not someone who is looking to provide housing to tenents, rather a bargain hunter willing to wait for conditions to change. The new owner, getting screwed cause the tenents aren't paying what the poperty is worth, has no intention to maintain or improve the property. He'd just as soon bulldoze the place rather than deal with the headaches of being a landlord, and wait for the inevitable repeal of the law as demand for housing rises. Then with his bargain basement investment sell for a big return, or once again, get the tenents paying for maintainance, upkeep, and improvements through their rents, rather than dumping a ton of his own money into a property he already owns to bring it up to standard. nobs 04:08, 28 December 2016 (UTC)
- California has some high taxes, but property taxes are the exact opposite of that thanks to Proposition 13, which doesn't allow year-to-year property taxes to rise proportionally to property value. Prop 13 restricts property taxes to 1% of a property's value AND caps annual property tax increases at 2% relative to land value. What results is effective property tax rates in Los Angeles County of 0.79% and in San Francisco of 0.68%, and falling as property values continue to rise. Since taxes are re-assessed at sale or when significant construction occurs, there is a huge financial disincentive for property owners to develop and increase the density of development. Combine that with general NIMBYism and conflated with rapidly increasing property values are what has led to the death spiral of increasing rent costs we're seeing now. "Rent Control" is treating the symptoms, not the underlying problem: if you think you need rent controls, you have a shortage of housing. Start building. TheMayor (talk) 15:48, 28 December 2016 (UTC)
- That's a very good way to put it. Rent control results in the exact opposite: rather than new construction and improvements to older properties, you get a decreased supply of housing stock consisting of older, unimroved, ramshackle properties. nobs 21:24, 28 December 2016 (UTC)–
- Of course, nobs' apocalyptic scenario depends on such a draconian/idiotic rent control system as to remove any profits from improvements/new construction. It's basically the same argument that Republicans are using to argue against taxing "job creators" at all: Start from a reductio as absurdum (if not allowed to profit, no one will invest) and then jump to the conclusion (which does not follow) that any reduction in the profit margin will have a significant, negative effect on investment. Also, rent control can address the potentially extremely lopsided bargaining positions of tenant and landlord by limiting the latter's ability to arbitrarily raise the rent or threaten to do so to force concessions from the tenant. Unless there is a huge excess of housing, it will always be harder and more expensive for a tenant to move than for a landlord to get a new tenant. Also, any law limiting arbitrary eviction would be pointless if not accompanied by legislation limiting arbitrary rent increases as these can obviously be used as de facto evictions ("No your honour, I didn't evict the tenants, I merely quadrupled their rent which they were then unable to pay"). ScepticWombat (talk) 22:17, 30 December 2016 (UTC)
- Buildings have a limited useful life. They depreciate over time. The cost of maintainance, upkeep, and improvements, which is a constant variable, is paid by the tenant (in his/her rent), not the landlord. The cost of building materials and contractors wages are not regulated where there is rent control. Over time, the structure falls into disrepair. It's tragic, when at a time of high demand, and improvements would make the property appreciate, a governing authority mandates ghettoization of its own property tax base. nobs 13:58, 31 December 2016 (UTC)
On the other hand, rent control could be the solution to Israeli settlements and building an integrated Greater Israel. People of means will move elsewhere, while a lower class element (in this case Palestinians) move in and fail to maintain the properties, lowerng their resale value. nobs 01:44, 1 January 2017 (UTC)
- No, the solution to Israeli settlements is any combination of BDS, a withdrawal of all US military aid, and a trade embargo and travel ban. PB (talk) 03:30, 1 January 2017 (UTC)
- US miltary aid to Israel is not a bi-lateral agreement. It us a tri-lateral agreement. Under the Camp David Accords the US pledged to give Eygpt the exact same dollar amount in aid it gives to Israel. Reneging on the pledge would be (1) withdrawing from the peace agreement and tantamount to reinstating a state of war on the US part; (2) violating our pledge to help the Eygptian government keep the Eygptian Islamic Jihad in check. Al Qaede for example, despite its noted Saudi financier bin Laden, has always principally drawn its manpower strength from exiled Egyptan jihadis whom the government chased out of the country in compliance with the Camp David peace agreement and with the money given in US aid (see RW article on Al Qaeda and its current leader Zawahiri for more information). Keeping jihadi elements within your borders is dangerous, as Gadhaffi and Assad can attest. (3) We could not cut aid to Israel and continue funding Eygpt, as that would then violate the agreement we have with Israel, and would be tantamount to declaring war on Israel. nobs 04:15, 1 January 2017 (UTC)
- nobs, you're still assuming a rent control regime that removes any profit from improvements/new construction, rather than putting a ceiling on the profit margin. And no, the US is not forced by the Camp David Accords "to give Eygpt the exact same dollar amount in aid it gives to Israel", or at least I'm unable to find any such wording in the text of the Accords. So I'm wondering what your source is for this claim? Also, the US currently provides Israel with markedly more military aid than it does Egypt, although both subsidies are huge in and of themselves. As mpires this 2015 CNN story reported, annual US military aid to Egypt is huge, being around $1.3 billion in 2014, but at a whopping $3.1 billion in 2014 the military aid to Isral still far outstrips that to Egypt and the numbers are similar in terms of foreign economic aid ($1.5 billion for Egypt in 2014 vs. $3.1 billion for Israel). ScepticWombat (talk) 07:00, 1 January 2017 (UTC)
- It's quite simple. Israel itself is also an arms producer and supplier to the world market, and the IDF has quite different objectives than the Eygptian military had. Eygpt's military exists primarily for one purpose: to defend against an internal enemy. It had no design (prior to the Obama era) to carry out military actions on neighboring states, and doesn't feel threatened by any foreign power such as the US, Israel, Russia, Nato, or the Britsh and French empires (like during the Suez crisis). Yet it is the Eygptian military (not a people's democracy or religious theocracy) that runs the country. The figures to look at is the amount of US aid to Eygpt, the size of Eygpt's government budget, the size of Eygpt's mi!itary budget, and the proportion of Eygptian government spending to GDP. The conclusion you'll reach is without US sid, there is no Eygptisn government, military, or GDP. nobs 11:10, 1 January 2017 (UTC)
How likely do you think Californians would be to vote for Calexit?[edit]
If it got on the ballot. I personally think a lot of Californians would vote for it.-【DiamondDisc1】 (talk) 21:04, 26 December 2016 (UTC)
- Practically none of the Republicans would vote for it. Let's give an optimistic scenario though. Let's say that all Green and Libertarian voters would vote for it. Take the percentage of Democratic votes in 2016 (a good ideological indicator) and divide that number by two-thirds (perhaps the number who'd vote for secession). Then add the percentage of Libertarians and Greens to get your final number. Your vote is gonna look something like that. In this case, it's 47%, which is close, but not enough. PBFЯЗЭSPДCЗ (talk) 21:08, 26 December 2016 (UTC)
- If only California had its own mini electoral college that gave LA and San Fran disproportionate representation. The downside here is that Democrats would lose any hope of regaining control if Cali left, but maybe they'd have to appeal to the working class to get more votes, which would be a plus. Applesauce (talk) 21:22, 26 December 2016 (UTC)
- Probably not many, & those who do will do so for shitty reasons. "We hate Trump" & "we're the bit with all the money" are the main arguments I've seen. Meanwhile are there significant numbers of people who actually view their national identity as Californian first & foremost rather than USA? ₩€₳$€£ΘĪÐMethinks it is a Weasel 21:28, 26 December 2016 (UTC)
- Also, Texas v. White exists.--JorisEnter (talk) 21:34, 26 December 2016 (UTC)
- IT. IS. NOT. GOING. TO. HAPPEN! Levi Ackerman (talk) 21:44, 26 December 2016 (UTC)
- In the case Texas v. White, as mentioned above, the Supreme Court held that "the Constitution did not permit states to unilaterally secede from the United States". This ruling technically gives a state the right to secede but they would have to get the approval of the federal government. The process would probably look a lot like Scotland's with a referendum and since the US states have more autonomy, approval by the state's legislature. It is unlikely that the federal government would approve a process for secession because it would embolden other secessionists and hurt the overall economy if California were to leave. I would also be wary of voting in favor of secession since I believe that the techno-libertarians of the Silicon Valley would try their hardest to turn the new republic into an Ayn Randian-y "utopia".--Owlman (talk) (mail) 00:51, 27 December 2016 (UTC)
- I'd hope that if California were to succeed, that taxes would be high enough that they would all leave, but then our economy would be relying pretty much on nuts, berries, and weed.'Legionwhat do you want from me 05:14, 27 December 2016 (UTC)
- California leaving would be great if they took all $20 Trillion of the debt with them. Then we conquer California. CorruptUser (talk) 01:43, 27 December 2016 (UTC)
- If CA left, then we'd be okay until we screw up or we run out of water.-【DiamondDisc1】 (talk) 05:40, 27 December 2016 (UTC)
- I still think you are underestimating the power the Silicon Valley has; they would use their influence to craft the libertarian paradise of their dreams.--Owlman (talk) (mail) 06:28, 27 December 2016 (UTC)
- Probably true.-【DiamondDisc1】 (talk) 19:13, 27 December 2016 (UTC)
- Are Google and Apple and Amazon super-libertarian or something? I'm missing something here. Google records all of your search history and gives it to the government. Apple does the same and ensures the NSA has constant access to your webcam and microphone without you knowing. There's a case going on right now where a court is requesting Amazon release recordings from one of its "smart speakers" to help with a murder case. In that last case, the Amazon speaker is literally recording audio continuously and saving it to an Amazon server by default. Though these companies are typically socially libertarian on issues like freakin marriage and weed, they're way against laissez-faire capitalism on issues like paid family/sick leave, mandatory overtime pay, and copyright law. The notion that Silicon Valley would somehow override all the liberals in LA and San Fran to turn the place into an Ayn-Rand dystopia is a false one, and likely a planted idea by right-wingers who want to prevent Cali from seceding and becoming even more of a successful model for progressivism than it already is. Liberals shouldn't fall for this argument. PBFЯЗЭSPДCЗ (talk) 21:03, 28 December 2016 (UTC)
- Nope, not going to happen. California is a big place, but we'd have our own problems if by sheer chance we somehow became our own country. Los Angeles has some problems of its own, so to speak, so I can't bear to think of other cities like our brethren up north. Ɀexcoiler Кingbolt Noooooooo! Look! Up there! 00:36, 30 December 2016 (UTC)
- It's quite bizarre to see this "Calexit" crap doing the rounds on the interwebz, not least because it's a mirror image of the "secession" BS from certain "red" states prior to Obama's inauguration and just as (un)likely and serious. Hell, 'muricans fought a civil war over whether states could just up and leave if they didn't like the president, remember? It seems to me to be a laughable, immature and petulant reaction and I doubt it would be supported by a majority in a referendum in California anyway. Sure, plenty of Californian voters probably loathe don
TromboneTrumpone, bit I seriously doubt they despise him enough to essentially quit their country (same goes with practically all, the "I'm moving to Canada!" yammering). In the end, I'm solidly convinced, Californians are more attached to the Stars and Stripes than they are put off by Trump. ScepticWombat (talk) 08:18, 1 January 2017 (UTC)
Snowflakes[edit]
I just read the Telegraph's (pretty awful) "Snowflake Awards", & this Guardian article (which the Telegraph links to but seems to have missed the point of) about current usage of "snowflake" as an insult for people who are offended or concerned, which is increasingly used across the political spectrum.
RationalWiki defines "snowflake" (within the Manosphere Glossary) as "a female who considers herself special and different from other women", which is oddly specific & I think a long way out of step with how the phrase is used, including within manosphere circles which obviously over lap heavily with the alt-right, Gamergate, etc. where it's often used like "SJW" & similar terms.
There's also Essay:Special snowflake which says "a special snowflake is a member of a minority group who inadvertently (or in rare cases, intentionally) furthers their own societal oppression by pandering to a majority group". Again, that's not a usage I've encountered, or not commonly.
Does anyone have a clear picture of what "snowflake" is supposed to mean or why? I always thought that a "special snowflake" was supposed to mean somebody who places undue emphasis on their own views, feelings & experiences, viewing themselves as unique - like the saying about no two snowflakes being alike, and possibly originating in the line "you are not a beautiful or unique snowflake" from Fight Club. But it seems like "snowflake" is now just being used to mean somebody who is fragile & afraid of conflict or controversy, which also makes sense. Any thoughts? WëäŝëïöïďMethinks it is a Weasel 13:38, 29 December 2016 (UTC)
- According to Urban Dictionary, it pertains to the "triggered/safe space" crowd:
An overly sensitive person, incapable of dealing with any opinions that differ from their own. These people can often be seen congregating in "safe zones" on college campuses.
- Its example of use is (and I roll my eyes at this):
Those social justice warriors are just a bunch of snowflakes.
- Even as an opponent of "safe spaces" (per se), I've never used the word myself (nor found reason to even once). I rarely see the word used "in the wild", but when I do, it's generally used by assorted asshats like alt-righters, antifeminists or manospherians.
- Perhaps worth noting is that the Online Slang Dictionary defines it closer to the RW Essay meaning:
A person who thinks they are perfect and unique when in fact they are not and are like everyone else.
- My two cents is that the Urban Dictionary meaning might be the one that's really taken root these days — like The Telegraph seems to argue. The Spectator chimes in as well. Reverend Black Percy (talk) 13:58, 29 December 2016 (UTC)
- Snowflake is a word used by people criticizing SJWs. It originated among exclusevely middle-class Western people who were minorites in some fashion, who want to feel special about themselves so they would feel better. PBfreespace (talk) 20:20, 29 December 2016 (UTC)
- Growing up in the 90's, I had hippie-like teachers that insisted that each child was special and unique, like a snowflake. Now, it's used deragotarily towards anyone who is perceived as wanting to be special. CorruptUser (talk) 21:35, 29 December 2016 (UTC)
- The meaning that I've seen used most often is describing someone who is easily offended and overly sensitive, like the Urban Dictionary meaning. Ɀexcoiler Кingbolt Noooooooo! Look! Up there! 00:29, 30 December 2016 (UTC)
- I'm gonna go ahead & delete the bogus definition from our manosphere glossary page. ŴêâŝêîôîďMethinks it is a Weasel 12:57, 30 December 2016 (UTC)
- PIDOOMA, but I have a hunch that there's a direct correlation between using 'snowflake' as a insult and considering yourself more intelligent/logical than average. Vulpius (talk) 05:26, 1 January 2017 (UTC)
I was thinking of creating a page on the pseudoscience promoter David Dewitt[edit]
He is a creationist with actual qualifications in Biology and is a professor at Liberty University and is on the List of Creationist Scientists.--Rationalzombie94 (talk) 16:22, 29 December 2016 (UTC)
- Go for it! Bongolian (talk) 19:18, 29 December 2016 (UTC)
- I'd help if you do, if only because I really don't like Liberty. Also make it clear that he and this guy are different people, cause the latter dude is pretty cool. B) talk 04:51, 30 December 2016 (UTC)
- They are two totally different people, the guy I mentioned is the "Liberty" University guy with credentials in Biology and not computer science--Rationalzombie94 (talk) 13:17, 30 December 2016 (UTC)
- I made the article and to distinguish the creationist and the computer scientist I added the middle initial of his name--Rationalzombie94 (talk) 21:50, 1 January 2017 (UTC)
MuslimStatistics.Wordpress.com[edit]
It's almost cringily bad.
Headline: "Sweden: est 77% of rapes committed by 2% Muslim male population – Crime statistics"
Article text: "The foreign rape figures at 77.6% Muslim has been anonymously confirmed by Swedish police in a phone conversation."
Sigh. They then display a graphic from 2011, which doesn't classify by religion -- only "foreign" or "domestic" -- and which came far before the major influx of refugees. αδελφός ΓυζζγςατΡοτατο (talk/stalk) 17:01, 31 December 2016 (UTC)
- They can't classify by religion because Swedish law and hate crime legislation explicitly forbids it. "Foreign" and "domestic" are the only classifications the government statisticians release and journalists can use, leaving its meaning to the imagination of readers. A Swedish legislator was convicted of a hate crime for posting factual statistics in Facebook. The fact his numbers were factual was irrelevent to the case. nobs 03:03, 1 January 2017 (UTC)
- Except "foreign" includes "Finns", who are the reason Swedish women get pregnant (Finnish joke).
- I do, however, think the law is stupid. It may be irresponsible to publish the stats, but it should damn well be legal to collect the information rather than burying your head in the
sandsnow. CorruptUser (talk) 03:05, 1 January 2017 (UTC)
- Gotta love ethnic jokes and the stupidity of their premise.
- I love how people cite police statistics to justify their racist views, when the stats they cite don't even support their opinions. PBFЯЗЭSPДCЗ (talk) 03:37, 1 January 2017 (UTC)
- That reminds me of a Shaun and Jen video that covered a map migrant crime created by XY Einzelfall. TLDW: Most of their sources ddon't state that the crime was caused by a migrant or the criminal wasn't arrested.--Owlman (talk) (mail) 03:37, 1 January 2017 (UTC)
David Pakman wrecks Gad Saad on the death penalty.[edit]
Kind of an oldie, but still a goodie. Seriously, this guy (Gad Saad) is an academic? Wow! The bars to the academia of whatever his field is must be really low. Pakman absolutely thrashed him. The fun begins at the 37:08 mark.
Levi Ackerman (talk) 18:48, 1 January 2017 (UTC)
I hope the scientific community will be able to stand against Trump[edit]
Chances are that he will get "experts" for hire who follow his ideology. But we have to stand for science.--Rationalzombie94 (talk) 17:57, 26 December 2016 (UTC)
- My understanding is that US administrations have a lot of appointees in significant roles. Could he put one of his tame lunatics in charge of all the major federal scientific programmes? How many would that be? How much impact could they have?--Bob"Life is short and (insert adjective)" 18:08, 26 December 2016 (UTC)
- Trump is putting a climate change sceptic (Rick Perry) in charge of the Energy Department & talking big about ramping up the US's nuclear warfare capability. So that's the way government science funding is likely to shift. ΨΣΔξΣΓΩΙÐMethinks it is a Weasel 19:49, 26 December 2016 (UTC)
- I find it more likely that we'll see giant tax cuts and major research allocations destroyed along the way. ikanreed You probably didn't deserve that 20:33, 26 December 2016 (UTC)
- Scientists are already pulling global warming research off government servers in the fear that it will get deleted under a Trump presidency.-【DiamondDisc1】 (talk) 20:59, 26 December 2016 (UTC)
- Hopefully he'll do something about the century old stacking of American anthropology with Marxists, which started with that charlatan Boas. Drain the swamp. 94.118.167.80 (talk) 11:18, 27 December 2016 (UTC)
- Do you think that Trump knows what anthropology is?--Bob"Life is short and (insert adjective)" 12:40, 27 December 2016 (UTC)
- @Ikanreed: what makes you think a private sector boom in private research and funding isn't possible with a slash in the corporate tax rate? And it would be done much more effectively, with less waste, and more direct practical application. Why the religous belief that only government, like only Jesus, can provide the way for the betterment of humanity? nobs 13:08, 27 December 2016 (UTC)
- "lol the right r stupid we r so smart". No, you aren't. You're just liars. 94.118.24.33 (talk) 13:44, 27 December 2016 (UTC)
- And what's the lie, exactly? Reverend Black Percy (talk) 14:03, 27 December 2016 (UTC)
- Lol, "race does not exist except when we blame Whites for everything". Talk about Orwellian Jewish POV. You even named yourself "RationalWiki". How cute. 94.118.24.33 (talk) 14:10, 27 December 2016 (UTC)
- "But I thought this was supposed to be RATIONALWiki!" Drink! Reverend Black Percy (talk) 14:26, 27 December 2016 (UTC)
Note how you focus on the minor issue, and not your anti-White pro-Semite POV. And look for lame excuses to remove my comments. 94.118.24.33 (talk) 14:35, 27 December 2016 (UTC)
- Yet again, someone takes a non-racial issue and manages to turn it into a race issue. God people can be so fucking stupid. Nothing like taking a science issue and turning it into a race issue.--Rationalzombie94 (talk) 19:59, 27 December 2016 (UTC)
Going back to Nobs' point - why can't the private sector finance research? The short answer is 'profit'. The private sector is there to create profit. Full stop (or 'period' if you're colonial). As such no private sector entity would finance CERN, for example. Or the research into DNA that was way back when. Only now is that becoming profitable. Or practically any anthropology/zoology/climatology (where's the profit in them - in fact climate science is anti profit). So, yeah, some research needs to be funded in a non-profit way. Doxys Midnight Runner (talk) 13:33, 29 December 2016 (UTC)
- To remain competitive, corporations spend a huge amount of money on resesrch and development. True, some research is too expensive for a single entity and needs to funded collectively. It's not beyond the realm of possibilty for an industry trade group, say Big Pharma for instance, made up of "competitors" such as Phizer, Merck, and G.D. Searle, to issue foundation research grants. Why the automatic assumption only the US Treasury and taxpayer must fund this bullshit that ultimately always ends up in the hands of some private sector, profit making entity? nobs 14:33, 29 December 2016 (UTC)
- Private-sector research tends to favor things with near-term applications. Occasionally you get something like Bell Labs (seven Nobels in physics and one in chemistry), but for the most part, research that can't be turned into a product within a decade is the realm of public funding. --65.101.119.25 (talk) 00:19, 30 December 2016 (UTC)
- This will remain a subject of discussion.
Ifwhen the corporate tax rate is slashed from 35% to 15%, corporations certainly will have the cash to do their own R&D, and the federal government will be running massive massive deficits for a few years. But as I pointed out, people think of companies like defense contracts, pharmacueticals, technology, etc. as competitors; in Washington they are just another trade association lobbying group with common interests as concerns. I'm not saying what's likely to happen is good or bad, I'm just saying this is not the end of science & technical R&D. The arguments for it will be (a) less waste and more practical, direct application; and (b) cut out corporate cronyism.
- And of coarse the gubmint can always encourage research in a certain area with special tax considerations, which in a way, some will argue, is a direct government subsidy. nobs 01:54, 30 December 2016 (UTC)
- nobs, you are yet again pretending that a cut in the profit margin is making corporations hold back on investment. Isn't it curious that back in 1950s when effective US corporate tax rates were twice what they are today, US corporations were actually doing research?
- The thing is, as other editors have pointed out, that private sector R&D is about making gadgets or services, but basic research is hardly ever conducted by the private sector because any benefits are extremely long term and tend to be diffused over the entire society, rather than as a direct return on investment for those who conducted the research. Sure, even if a Trump administration savages public sector research we'll still get new gadgets, drugs and services, because research into applied science will continue unaffected in the private sector. Instead, the downside will be a decrease in basic research whose effects will largely be long term and thus effectively invisible, not to mention that it's difficult to predict or identify what is not being discovered or delays in scientific breakthroughs through lack of funding for basic research.
- I quite agree that corporations should indeed pay for their own R&D (and they already do, although they also receive incentives, such as the Research & Experimentation Tax Credit), but I'm simply unconvinced that current corporate tax rates are what is preventing this. The idea that being able to retain only 70% of your profits, rather than 85% (and that's based on the nominal rates), discourages corporations from investing at all is dubious. Do you really think that a CEO is looking at a proposal for R&D which will, say, be expected to generate $100 million in gross profits and then goes "Oh, well, since our company will end up keeping only $70 million I'm not going to bother. If only we'd been allowed to keep $85 million, then it would have been worth the effort"? ScepticWombat (talk) 07:32, 1 January 2017 (UTC)
- In the immediate short term what you say is abdolutely true. In the long term, if a 15% corporate tax rate were to hold for years into the future, theoretically a large trade association can pool its resources and fund outfits such as Los Alamos National Labs or give foundation grants to colleges and unnversities for basic research. Tax laws would have to be tweaked. And the US government wouldn't totally withdraw from funding research. Call it a way of diversifying risk by calling on the private sector to contribute, rather than solely be a beneficiary and exploiter of publicly funded research. nobs 13:12, 1 January 2017 (UTC)
- That sounds like rather than the government funding basic research directly, your idea is (and I'm simplifying here) that it should effectively incentivise (read: effectively pay) the private sector to do it, or rather set up a framework and then hope that private businesses will suddenly start thinking on a multi-decadal scale without any likelihood that their investment will yield a return directly to them? I admire your optimism and faith in the societal consciousness of US corporations, nobs, but that's a bet I wouldn't take. ScepticWombat (talk) 19:43, 1 January 2017 (UTC)
- I look at Trump's campaign as his approach in microcosm: Hillary spent $1 billion, Trump $300 million. Conventional wisdom says Hillary should win, and Trump couldn't raise money due to lack of popularity. But Trump took a risk here, and was making a statement, to prove conventional wisdom wrong (its similiar to the famous Central Park ice skating rink back in the 1980s which was Trump's first foray into politics). Trump considers himself more of an economic conservative, and a more successful economic conservative than Ronald Reagan. Whether that's true will be debated both in and outside the conservative movement in coming months and years. nobs 13:20, 2 January 2017 (UTC)
Predictions for 2017[edit]
For something lighthearted - What Rationalwiki orientated topics will be significant in 2017? 31.49.51.46 (talk) 11:11, 30 December 2016 (UTC)
- Donald Trump, Trade War with China and strained relations between the United States and Israel.--Rationalzombie94 (talk) 13:19, 30 December 2016 (UTC)
- Does anybody else felt whiplash at the connection "light hearted" followed by a list including Trump and Trade war? Anyway i think a lot more of "Pizzagate" and other really stupid bullshit in addition to fun elections in 2017 (Germany and France).--Benaresh (talk) 17:06, 30 December 2016 (UTC)
- Considering Trump has no experience in politics, it's a crapshoot. Considering pizzagate, yes, expect to hear more alt-right nonsense.—Hamburguesa con queso con un cara (talk • stalk) 17:15, 30 December 2016 (UTC)
- I think that RationalWiki will focus on dumb conspiracy theories, on Trump, China, Israel and unpredictable stuff. I'll probably focus on French elections, since it's a ridiculous, illogical mess, and translate pages in french since we might have a very small influence on the elections, and it can bring more people. Diacelium (talk) 22:10, 30 December 2016 (UTC)
- How about the blunders of Trump political appointees? Ɀexcoiler Кingbolt Noooooooo! Look! Up there! 02:19, 31 December 2016 (UTC)
- Since trolls and the tea party essentially jointly won the White House, I predict there will by more cyberhysteria like Pizzagate, but rather than dismiss the latest crazy unfounded rumor, the government will spend a few billion dollars investigating it. Leuders (talk) 14:04, 31 December 2016 (UTC)
- Predictions: Tillerson, Trump, and Putin conspire to raise gas prices to just under $3 a gal. 12 months from now & get fraking a US export technology globally; Japan increases its defense spending and starts fucking with the Chinese near the Spratly's, relieving the US burden; Trump renegotistes to lower the $4 billion cost of a new Air Force One with Boeing so Boeing can keep its $16 billion deal with Iran. nobs 02:00, 1 January 2017 (UTC)
- There will be a notable uptick in the suicide rates in the western world as the reality of how fucked we are really starts sinking in. Trump supporters will tie themselves in knots trying to convince themselves that they didn't fall for the most transparent con since Ponzicoin. Paul Ryan et al will age a decade having to defend the indefensible every week. Conservapedia will continue its slow, slow death. Vulpius (talk) 05:22, 1 January 2017 (UTC)
- Another prediction: Alex Jones will become one of Trump's biggest critics and the deplorable Rust Belt Democrats who voted for Obama and later Trump will never return to the Democratic party. nobs 12:50, 1 January 2017 (UTC)
- Jones turning on Trump would be hilarious to watch happen, but I reiterate that Rust Belt voters didn't go Trump, they just stayed home because of Clinton's bad messaging and terrible ground game. If a left populist with an actual vision other than "at least we're not that guy" runs, boom, they'll turn out in droves. MyNameIsMudd (talk) 17:08, 1 January 2017 (UTC)
- Listen to what Jones says about Reince Priebus and Paul Ryan. Jones loathes them. Jones predicts Priebus to be gone in 90 days. But the truth is without Priebus & Ryan, Trump will have no success. A new president has 100 days to pass his program. After the summer break, Congress is too busy running for re-election, and nothing gets done in even numbered years (election years). After 100 days, the establishment bureaucracy takes over. If Priebus is gone in 90 days as Alex Jones hopes, none of Trumps's program passes, and he's a failed president. If Trump passes these two landmark pieces of legislation - Immigration and Tax reform - the most ambitious reforms of both in 50 years, he'll owe it all to Priebus & Ryan. But Jones is too stupid to know how Washington works. nobs 12:12, 2 January 2017 (UTC)
- God I hope you're right. My ideal situation is Trump and his team of privatizers and kleptocrats completely bungle everything and there's a huge pushback from frightened, enraged leftists of all stripes. Then when Trump's popularity goes down like a lead balloon (he's already historically unpopular before he's even sworn in remember) it costs downticket Republicans big time in the midterms. Then we can run an actual progressive in 2020 and have some semblance of sanity in this country again. MyNameIsMudd (talk) 18:05, 2 January 2017 (UTC)
- Here's how he's gonna build the Wall: he's gone add 20 miles of fence to the existing wall at a cost of $200 million over 8 years; he's gonna impose a 25% surcharge on money orders and wire transfers Mexicans send home and designated for a fund to build the wall. The surcharge is gonna net about fifty bucks, and he can say he kept his promise. Meanwhile, he really only scapegoated the Mexicans to get votes, his real target being Muslims, and to re-impose idealogical tests for immigrants, which is already in the 1952 Immigration law written at the height of the Red Scare. Then he's gonna push for a $15 minimum wage and conservatives will see him as the big spending liberal panty-waist he really is, but liberals and progressives (at least those who believe in working for a living) will love him. nobs 05:23, 3 January 2017 (UTC)
- I'd love to believe you on that last part, really I would, but somehow I don't think the guy that appointed someone who doesn't think workers deserve breaks is going to push for a fifteen dollar minimum wage. MyNameIsMudd (talk) 05:34, 3 January 2017 (UTC)
- He's really not a stupid politician as many think, he's just a bad inexperienced campaigner. To get re-elected, which is his sole focus now, he must reach out to people who opposed him (to break 51%) and he must betray people who supported him. All presidents have done it, with varrying degrees of success and failure. nobs 06:00, 3 January 2017 (UTC)
- I'm high as shit off of Alprazolam right now for please forgive me if I start sounding zonked out but he's not a good or bad politician. He's not any kind of politician because he's never held any kind of governing office before. I'm of the view that since these are the twilight years of his life he's made on last big shot at having his name stamped on history forever and it, god help us all, succeeded. Reelection doesn't matter. Bringing America together doesn't matter. All that matters is his brand going down in history and his friends making out like bandits while the nation and possibly the world are brought to its knees by corruption and regressive policy on an "unpresidented" scale. MyNameIsMudd (talk) 06:23, 3 January 2017 (UTC)
- The world was going to hell before Trump, I don't know if speeding it up or slowing it down really matters when you know what the end result is. Trump says he's a negotiator. One of the intricacies of negotiation is, you are always trying to get your antagonist to act. A negotiator must be a motivator. Trump never worked for the minimum wage, so $5 an hour or $15 an hour really means nothing to him. He sees his role as motivating people to be ambitious, and think big. So he really has to sell the minimum wage to penny-pinching employers and get them to believe its beneficial, and in their own self interest. This is different from tossing poor people a bone and calling it compassion. But the country has grown quite lethargic, it may be an impossible task. nobs 07:44, 3 January 2017 (UTC)
- Some 'politicians' will do something stupid, and several will be unceremoniously dumped.
- Some poor infant of 'celebrities' will be given a stupid name.
- There will be a leak that nobody is interested in. 86.191.125.158 (talk) 22:57, 3 January 2017 (UTC)
Fun: Favorite memories of 2016[edit]
My favorite memories include- Getting a microscope, buying a carton of Newport Menthol 100's, new TV for Christmas, planning for a new ministry and going forward with it, doing odd jobs for various neighbors, getting a PS4, getting my therapy cat named (Doctor) Friskies, creating new articles on RationalWiki, getting my clergy shirt and having a nice Thanksgiving with friends and family. Post your favorite memories! :)--Rationalzombie94 (talk) 03:06, 1 January 2017 (UTC)
- My favorite memory was watching the numbers in Michigan and Wisconsin go to Trump and seeing everyone collectively lose their shit. Granted I hate Trump, but as a social phenomenon it's always fun to see people's reactions. Also, the red-baiting the Democrats did and me realizing Trump would be able to do whatever he wanted in office if the Democrats kept doing such a stupid strategy. PBfreespace (talk) 03:34, 1 January 2017 (UTC)
- My favorite memory was when the Wisconsin GOP & Reince Priebus handed Trump a 30% - 70% loss in the Wisconsin primary. We got that sonofabitch by balls now, and if he doesn't do our bidding, we're gonna squeeze 'em. nobs 03:40, 1 January 2017 (UTC)
- Pbfreespace thinks Clinton redbaited Sanders. She barely touched him in the primaries. FU22YC47P07470 (talk/stalk) 03:56, 1 January 2017 (UTC)
- Uhhhh...
- Ummmm....
- That's what's directly from the Hillary campaign, but a ton of pro-Hillary rags have used similar arguments. PBfreespace (talk) 04:15, 1 January 2017 (UTC)
- I will say this- Both the Republican and Democratic parties have become a joke. The democrats are a joke because they were claiming Trump rigged the elections when these same people stated before that Trump should accept the election results; as for the Republicans, they complain and whine when they don't get their way and snuggling up to Vladimir Putin like horny teens.--Rationalzombie94 (talk) 04:31, 1 January 2017 (UTC)
- Seeing Zootopia multiple times. Other than that, this was a thoroughly worthless year in every way. Vulpius (talk) 05:24, 1 January 2017 (UTC)
- Getting a flat and a dishwasher, seeing some of my students graduate with top marks. Unfortunately, not handing in my thesis, though, it's still on my to do list. ScepticWombat (talk) 08:21, 1 January 2017 (UTC)
- @nobs, if I did own stock in Exxon Mobile, I would be pulling out my money. I don't trust Russia in any way shape or form.--Rationalzombie94 (talk) 14:52, 1 January 2017 (UTC)
- But you said "pretty much every nation lacks responsibility" so why trust any of them? ₩€₳$€£ΘĪÐMethinks it is a Weasel 19:57, 1 January 2017 (UTC)
- @RZ, hmmm, sounds like you need investment advice. I'm available for a fee. Or are you just another indignant indigent wanking my chain who sucks the gubmint tit and your fellow citizens for your subsistance? nobs 12:57, 2 January 2017 (UTC)
- I should rephrase what I said, I meant that pretty much any nation has done something that was not responsible at one time or another.--Rationalzombie94 (talk) 21:54, 1 January 2017 (UTC)
Jack Chick finally going to hell where he belongs, watching us liberals spout conspiracy theories about Trump just like conservatives did about Obama, watching Darth Vader get the moment he's been waiting for since 1978, etc... --TeslaK20 (talk) 07:17, 3 January 2017 (UTC)
Hey Ya'll[edit]
Hey RW dwellers. I hope you're doing okay. I can't exactly say I'm doing so well myself right now, what with my anxiety flaring up and so on, but I've got my girlfriend over with me and if there's one person that can keep me hanging on it's her. As we approach 2017 I encourage you to not wear yourself down to a nub over the bad things that have happened, are happening, and will continue to happen. In all likelihood I myself do this too much. Please always, always look for the good. Look at your friends, your family, continued scientific advancement, achievements in human rights. Growth and renewal is happening, and will happen here too. The progressive movement is large, diverse, pissed off and getting organized to fight. Despite everything that's happening I have hope that we'll make it through this with a fairer, kinder, more equal America and world. Happy New Years. MyNameIsMudd (talk) 03:46, 1 January 2017 (UTC)
- Hear hear. FU22YC47P07470 (talk/stalk) 03:49, 1 January 2017 (UTC)
- Amen to that brother (or sister, well it is not like I know anybody's gender on this site)!--Rationalzombie94 (talk) 04:25, 1 January 2017 (UTC)
- Happy New Year! -【DiamondDisc1】 (talk) 04:28, 1 January 2017 (UTC)
- @RZ Haha, it's sister for me. On this site at least I want to be openly and proudly trans.
- @All have a good one you guys. MyNameIsMudd (talk) 04:36, 1 January 2017 (UTC)
- @MNiM, be loud and proud of who you are! I am proud of being a Bisexual man! Kudos to the LBGT community! :)--Rationalzombie94 (talk) 05:21, 1 January 2017 (UTC)
- [Holds zippo in support of MyNameIsMudd's words] Reverend Black Percy (talk) 07:34, 1 January 2017 (UTC)
- Welcome 2017!-【DiamondDisc1】 (talk) 08:17, 1 January 2017 (UTC)
- Don't think "zippo" is the correct word there, RBP. ;)-【DiamondDisc1】 (talk) 18:19, 2 January 2017 (UTC)
- And nobs is a right wing nut job--Rationalzombie94 (talk) 19:20, 2 January 2017 (UTC)
- @DD Well, I meant lighter — Zippo should be fine, no? You know, like at a rock concert? Reverend Black Percy (talk) 19:25, 2 January 2017 (UTC)
- @RZ Now, what in the world makes you say that?!?! Reverend Black Percy (talk) 19:25, 2 January 2017 (UTC)
- Going by nobs's homophobic and racists statements it would not be far from the truth. But it is possible he or she has been sarcastic the whole time.--Rationalzombie94 (talk) 14:09, 3 January 2017 (UTC)
About the elections in France[edit]
Who do you think should win ? Le Pen, Fillon, Valls, Mélenchon or Bayrou ? Diacelium (talk) 00:19, 2 January 2017 (UTC)
- Mélenchon, obviously, but it is unlikely that he wins. If you want change, then Le Pen would be the only other person proposing it from that pack: anti-NATO, anti-EU, anti-austerity. Also, before anyone says she is Islamaphobic, so is everyone else listed excluding Mélenchon; ironically, her anti-Islamic views are what makes her status quo.--Owlman (talk) (mail) 01:38, 2 January 2017 (UTC)
- ...What. No, no one on this list is islamophobic the way MLP is. In fact, I kinda wish the French left, after giving Catholics the middle finger, did the same with Muslims rather than suck up to them in the name of "diversity". The French left's values are diametrically opposed to those of Islam, and that's a thing they should be proud of. NewFrenchHotness (talk) 15:10, 2 January 2017 (UTC)
- There's nothing more homophobic about Le Pen that about Fillon or Valls. It's all the same bullshit about the veil, the burkini, etc... Diacelium (talk) 15:19, 2 January 2017 (UTC)
- Diacelium pointed out something important, and that is for the talk about "The French left's values are diametrically opposed to those of [religion]" and laïcité and so on, there is no discussion of real solutions or state anti-theism. There is no talk of better education to dismantle the superstitious and irrational worldviews required for strict religious adherence, no proposals for social support services for non-religious people in religious communities to make apostasy easier, no conversation about anything that would actually address the root problem. Instead, there is bullshit like banning hijab, banning minarets, deporting people, etc. Lord Aeonian (talk) 04:54, 3 January 2017 (UTC)
From one faulty walnut to another[edit]
- (PS. This all applies to you as well — yes, you!) Reverend Black Percy (talk) 04:06, 2 January 2017 (UTC)
- I think we can all relate to when our genitalia jumps up and sits on our frontal cortex :p TheGrandmother (talk) 17:35, 2 January 2017 (UTC)
- There's a "dickhead" joke in there, somewhere! :3 Reverend Black Percy (talk) 17:52, 2 January 2017 (UTC)
"US Govt Data Shows Russia Used Outdated Ukrainian PHP Malware"[edit]
Apparently I found this re-posted on infowars of all places. The website wordfence.com allegedly traces back the Russian hack to sold Ukrainian PHP malware. The website also has an FAQ on the matter now. I don't really know what to think about this at this point. —Hamburguesa con queso con un cara (talk • stalk) 18:23, 2 January 2017 (UTC)
- According to some Redditors, the headline is misleading according to the author himself. He allegedly commented:.
- Just FYI. Reverend Black Percy (talk) 18:28, 2 January 2017 (UTC)
Why am I not eligible to vote in the Moderator Election?[edit]
I want to vote in the Moderator Election, but when I tried to enter my vote for candidate(s) of my choice I was told "usted no esta eligible a votar" - que es eso? Cabrónes. Worzelpete (talk) 19:33, 3 January 2017 (UTC)
- Well whatever it is, it's not that the system is rigged to secretly prompt us when people don't put "David Gerard" in all 15 boxes. So forget that theory, that's a crazy theory. So then... Case closed, gentlemen? Reverend Black Percy (talk) 19:39, 3 January 2017 (UTC)
- Since how long have you created your account ? You need to have created it 3 month ago to be able to vote (I can't vote too, and I was prepared for the elections). Diacelium (talk) 19:42, 3 January 2017 (UTC)
- You also need atleast 75 edits. Nobody is forcing you to vote for David, either — certainly David isn't forcing anyone to do that. Certainly not. Reverend Black Percy (talk) 19:44, 3 January 2017 (UTC)
- Your account was only created on or about the end of October 2016. You're ineligible to vote this time because you need to have been a registered account holder for at least three months. Regards, Cosmikdebris (talk) 20:48, 3 January 2017 (UTC)
Bikram Choudhury (of Bikram Yoga) just lost everything.[edit]
Choudhury just lost a huge sexual-harassment lawsuit brought by a former employee. He's going to have to turn over nearly all of his assets to the plaintiff, including all of his 700 yoga studio franchises. Strangely, his fleet of 43 luxury cars disappeared the same day as the decision. Those cars were also to be turned over the the plaintiff.
- I beleive that sexual harassment and rape is wrong and that Bikram Choudhury should have been sued for his actions. I would say that roughly a million in compensatory damage is too high (the punitive damage of 7 million seems good though). If Bikram Choudhury was poor, hi Jafa-Bodden wouldn't have gotten that amount and she would never bothered suing. People should come forward all the time about rape, not just when there's a big reward.—Hamburguesa con queso con un cara (talk • stalk) 00:26, 4 January 2017 (UTC)
The United States should just cut its losses and dump Israel as an ally[edit]
When their government is spreading anti-American propaganda then we do not need to be their ally or bail them out of conflicts they started. While America is at it, take back all financial and military aide. Let them fend for themselves. Just my thought, feel free to post your thoughts--Rationalzombie94 (talk) 13:32, 30 December 2016 (UTC)
- "Dumping Israel" as you put it would in effect tell the world that the US does not give a crap about democracy. Israel is the only democracy in the Middle East that can even begin to be called stable. In Israel, the Prime Minister sends greetings to gay pride parades - in other countries in the region, gays are hung from cranes. Israel may not be perfect, but it sure beats any possible alternative - and as long as the US wants to be a global power, the goings on in the Middle East have to be of concern to the US. 77.22.253.4 (talk) 16:15, 30 December 2016 (UTC)
- If the United States wants to be a global power, it needs to not have it's economy implode on itself. I don't see that debt clock stopping anytime soon. Maybe the US should tend to that instead of going to conflicts for "justice". Wars cost money, you know. What good is one country being democratic when the United States is in the gutter?—Hamburguesa con queso con un cara (talk • stalk) 16:55, 30 December 2016 (UTC)
- Considering that the US toppled democratic Countries for going against US interests, i'd say this argument is hypocritical, in addition Israel has a badass military and Nukes so they are safe and sound. I think Israel should reconsider it current policy of pushing for new settlements and instead push for peace and maybe stop to alienate their allies. Not that Iran and Saudi Arabia is innocent in fanning the flames...--Benaresh (talk) 17:15, 30 December 2016 (UTC)
- Not trying to be an asshole but tell me this, lets saying you were in school and someone spreads rumors about you then turn around asking for help, would you want to help? Think of what I said as an analogy for U.S-Israel relations. Again, this is just constructive criticism and not meant to be rude.--Rationalzombie94 (talk) 19:01, 30 December 2016 (UTC)
- I wouldn't treat international diplomacy like a schoolyard, for starters. Vulpius (talk) 19:51, 30 December 2016 (UTC)
- @BoN The US doesn't give a flying shit about democracy. Israel iRatjonals also not the only democracy: Turkey, Kuwait, and Lebanon have elections as does Iran and Syria even if the leave much to be desired.
- In general the US won't completely abandon any of the countries it is currently aligned within the MENA because they serve its interests; the Saudis control the global oil prices, the Gulf states willingly wage proxy wars with Iran, Israel provides a buffer to the Arab states, the Kurds provide a useful proxy in Iraq, Turkey, and now Syria, and we are now pushing Turkey to challenge Russia. For a more in-depth look at the attempt to sustain US global hegemony, I recommend looking at The Next Decade written by George Friedman, the founder to Stratfor.--Owlman (talk) (mail) 21:04, 30 December 2016 (UTC)
- @RationalZombie: the US can't simply cut aid to Israel, it would have cut aid to Eygpt as well, as that is part of the agreement written into law. That would not only mean terminating the Peace Agreement between Israel and Eygpt, a state of war resuming, and the government of Eygpt would soon be broke and incapable of restraining the Eygptian jihadi movement.. You wanna risk that over what a minority of discredited and rejected American Progressives consider an insult? nobs 02:31, 1 January 2017 (UTC)
Please try to keep this discussion civil. Debate Wars: Israel and Palestine, volume 38908589 has an unfortunate preferrence for insults and ad hominems. αδελφός ΓυζζγςατΡοτατο (talk/stalk) 19:57, 30 December 2016 (UTC)
- International relations is like a school yard. Trying to be friendly here though. Think about it, kids are like countries and they trade various things on the playground much like international trade and kids will stick together like global alliances. Plus kids will fight each other like war against other nations; my analogy is accurate.--Rationalzombie94 (talk) 20:32, 30 December 2016 (UTC)
- I see your point, however, I do not see analogies as a valid argument but rather as a means to illustrate one's view on a subject. If you are going to talk politics, I suggest talking about policies and actions instead of using vague analogies.—Hamburguesa con queso con un cara (talk • stalk) 21:21, 30 December 2016 (UTC)
- I honestly wish both sides would just get their heads out of their proverbial asses and come up with some peace agreement. But I know that won't happen because there are extremists on both sides. Israel has the Jewish Home which will refuse any compromise. Palestine has Hamas which will also refuses to compromise. I honestly do believe that there is a middle ground here on this issue. S.H. DeLong (talk) 21:39, 30 December 2016 (UTC)
- I am just used to using analogies is all and I was using a schoolyard scenario as international relations is a lot like a schoolyard.--Rationalzombie94 (talk) 02:16, 31 December 2016 (UTC)
- The counterargument is that it actually isn't. WěǎšěǐǒǐďMethinks it is a Weasel 03:20, 31 December 2016 (UTC)
- I think Owlman and DeLong comments sum up the complexity and problems as short as possible, so no need to add anything to it. The schoolyard simile is flawed in that it implies a certain lack of responsibility and childishness that doesn't reflect the reality of global politics.--Benaresh (talk) 08:36, 31 December 2016 (UTC)
- I disagree respectfully, pretty much every nation lacks responsibility--Rationalzombie94 (talk) 18:23, 31 December 2016 (UTC)
What US should do:
- Urge Israel to halt settlement construction and occupation
- When they don't do this, threaten/implement sanctions, trade embargo, travel ban, weapons shipments ban, etc.
- Vote for and actively support Palestinian statehood
- While we're at it, cut aid to Egypt unless they stop the authoritarianism and blockage of Gaza
This should do loads to help the current situation in that part of the middle East. PBfreespace (talk) 03:42, 1 January 2017 (UTC)
- <sarcasm>Egypt should stop blocking Gaza? But they need to keep blocking it, lest more IDF sharks get into the Suez!</sarcasm> TheMyon (talk) 09:50, 1 January 2017 (UTC)
- @PB, you forgot to add the US should let the Muslim Brotherhood take over Eygpt. Oh, wait a minute, we already tried that with Morsi and it only led to to sending Hillary Clinton, Barack Obama, and the Progressive movement packing. nobs 12:42, 1 January 2017 (UTC)
Is Israel an "ally" of the US? If you mean "allies" in the sense of states that help each other mutually then I'm not sure Israel is an ally of the US. It's clear what Israel gets out of the situation. It's also clear that some US politicians can make political capital out of being helpful to Israel.
But I wonder how helpful the relationship really is to the US as a nation.--Bob"Life is short and (insert adjective)" 16:33, 1 January 2017 (UTC)
- White Americans should stay out of Semitic squabbles whether they're "democracies" or not. Why the hell should we care about any of those hook nosed primitive parasitic bastards? Let them kill each other with rocks and if we need the oil just go in and take it by force. 94.118.148.248 (talk) 16:46, 1 January 2017 (UTC)
". "
Lol wut? Has it occurred to you that the so called "Islamic conquest" is a bunch of retards with nothing more than a shirt walking across the border because for some crazy reason the European governments have decided not to machine gun them, as any other country would. Hopefully that changes very soon. 94.118.157.230 (talk) 16:55, 1 January 2017 (UTC)
- The German birth rate is 13 per 200 breeding pairs; the Muslim birth rate, depending on country of origin varies between 35 and 60 per 200 breeding age adults. 2.5 million Muslims have migrated to Germany in the past 3 years, about half of them children. Germany's standing military is only 400,000. Translation: in 20 years German soldiers primary alligiance will be to the Caliphate, not Germany or Nato. nobs 12:39, 2 January 2017 (UTC)
- Right, so they all have to be sent back or killed. 94.118.156.23 (talk) 13:49, 2 January 2017 (UTC)
- It's too late. The Atlantic Ocean is now the border between Western Civilization and Islam. Ask Gen. Michael Flynn, he'll explain. nobs 13:40, 3 January 2017 (UTC)
- Nobs, your argument is based on several ridiculous assumptions.
- First, you say that the birth rate in Muslim countries is going to be the same as the birth rate of Muslim refugees living in Germany. This is crazy: those countries are poorer, undeveloped, and have no birth control or contraceptives to speak of. This is like saying the high birth rate in Catholic countries means Americans will all inevitably be pledging their allegiance to the Pope. The Muslim birth rate won't be nearly as high in Germany.
- Second, even if I grant you your first argument, that doesn't mean Germany will become an Islamic state. You're assuming most of the refugees coming over are devout Muslims that also have an agenda to implement political Islam. That's not the case. Most of them are moderately religious, with some extremely and some not very much. That's not a recipe for a caliphate in 20 or even 2000 years.
- Third, you think that even the really religious ones are going to hold onto their religion after enormous cultural pressure not to do so. Most of these folks are going to meld into the culture after a long while. You act like cultural assimilation isn't a thing. Take the Somalis in Minnesota for example. They came there decades ago, war refugees from one of the most religious countries on Earth, with a birth rate of 7 children per woman. That's higher than all Muslim countries. Do you see Minneapolis/St Paul becoming a caliphate? No. In Ohio they drive taxis. Big deal.
- I really am genuinely surprised your reasoning is this stupid. Normally appeal to fear and appeal to disgust is enough, but now you people are just resorting to factually false arguments. PBFЯЗЭSPДCЗ (talk) 00:16, 5 January 2017 (UTC)
- And this is why I think nobs is a right wing nutjob. Using fear and paranoia to get his point across--Rationalzombie94 (talk) 20:34, 5 January 2017 (UTC)
This will never happen[edit]
There are two kinds of American foreign policy:
- Overly dramatic calls to arms that destroy nations to protect them, a la Vietnam and Iraq
- Hideously Machiavellian manipulations to create and maintain puppet state and proxy powers with little consideration for what's right, a la Saudi Arabia, Iran, or Cuba.
Actual non-interventionism is not seriously represented anywhere in the American political spectrum, when it comes to the real political structure of the United States. Ditching an "Ally" like Israel would be unthinkable to the middle-managers of the state department and intelligence branches, and top down instructions for reform will go about as far as Obama's have: nowhere. ikanreed You probably didn't deserve that 22:06, 5 January 2017 (UTC)
Why the alt-right is bad for the acceptance of science[edit]
One of my worries about the alt-right is their Darwin-thumping scientific racism will result in many Americans rejecting evolution and embracing creationism due to the former's association with the alt-right. I say this as a fervent supporter of evolution and the works of Darwin, which, just like the Bible, have been twisted to support a reactionary worldview. Just like the liberal religious community had to distance themselves from the fundamentalists, so too will the rationalist community have to distance itself from the scientific racists. That is why RationalWiki should devote itself to refuting the psuedo-intellectual arguments of the alt-right. Gutza1 (talk) 15:13, 3 January 2017 (UTC)
- Well that and they also got the most anti-science president in the history of the country elected. One who seems poised to dismantle scientific establishment in order to shield himself from dissent.
- The sad truth to your own claim is that "rationalism", as an ideology, went off the rails, and probably can't be recalled safely for at least a generation. And honestly, it's just as well; the biggest problem has never really been people valuing rationality in the abstract in the same way people value liberty or kindness in the abstract without ever giving a second thought to how to pursue them. The biggest problem is the unwillingness to apply a critical lens to their own ideas while proving perfectly able to apply one to others'. ikanreed You probably didn't deserve that 15:42, 3 January 2017 (UTC)
- First of all, the Alt-right can't and won't ever represent science. Far too many of them subscribe to antiquated bullshit notions like racialism, and far too few — if any of them — trust the scientific consensus on climate change, etc. Keep in mind, also, that the Alt-right actually plays on quite overtly Christian themes. See, for example, Theodore Beale's "Alt-right constitution" here — notice #4:
The Alt Right believes Western civilization is the pinnacle of human achievement and supports its three foundational pillars: Christianity, the European nations, and the Graeco-Roman legacy.
- There's also some ideological overlap between the (Christian) KKK and the Alt-right, etc — just to name two examples from off the top of my head. Don't allow yourself to be derailed from the simple fact that most popular fascist movements in history have been overtly aligned with the Catholic church. Reverend Black Percy (talk) 16:27, 3 January 2017 (UTC)
- True, but on the other hand many alt-righters are calling belief in racial equality the left-wing version of creationism, and many prominent scientific antitheists like Thunderf00t and TheAmazingAtheist have been leaning towards alt-right ideas. Then there's also neoreactionary beliefs about "the Cathedral" and how Protestant Christianity created Progressivism. Mencius Moldbug even said that "the belief in that all men are created equal" is a "theological proposition." I suspect that the alt-right is "Christian" in the same way that Richard Dawkins calls himself a cultural Christian. Gutza1 (talk) 12:43, 4 January 2017 (UTC)
- I expect there to be increasing tension between the alt-right & traditional conservativism, but I don't think much of it will be directly about science or religion. ŴêâŝêîôîďMethinks it is a Weasel 18:34, 3 January 2017 (UTC)
- Indeed; probably not in the friction between the Alt-right and their conservative elders. The Alt-right will continue their crusade against science, however — just note #8 on Beale's "Alt-right constitution":.
- Don't expect that a movement which right off the bat tries to
redefinegut science as carelessly as the ICR will ever be able to recruit anyone on the basis of said movement having any particularly coherent "science-mindedness". On the other hand, expect that they will recruit pseudoscientists with pillars like the above — "Finally, a political movement that recognizes the plight of the free vacuum energy cranksrace realists!". I mean, even if you were as rich as Markus Persson and donated a billion dollars for actual Alt-righters to do science with, it would all devolve into Lysenkoism pretty quickly. And yes, analogies to the pseudoscientific misadventures of the nativist, cultural purist, nationalist far left are actually more apt than one might think. Reverend Black Percy (talk) 18:49, 3 January 2017 (UTC)
- "Scientodific"? "Scientody"? "Scientistry"? The mind boggles. Nowhere Man (talk) 20:13, 3 January 2017 (UTC)
- Not content with just committing the odd, unintentional equivocation, Mr. Beale has instead taken said fallacy under his wing as full-time tripartite calling card, speech writer, and soulmate. Or has he? See, now — that's the genius of it. Reverend Black Percy (talk) 20:35, 3 January 2017 (UTC)
- "And yes, analogies to the pseudoscientific misadventures of the nativist, cultural purist, nationalist far left are actually more apt than one might think."
- Occam's razor would suggest it's just you Marxists pushing out the Lysenkoesque genes-don't-exist/race-doesn't-exist crank pseudoscience. "Horseshoe theory" doesn't mean you get to blame your crap on your opponents. Look at your race articles: what transparent dishonesty. John 82 (talk) 22:17, 3 January 2017 (UTC)
- Are you sure you know what Occam's razor is? B) talk 23:02, 3 January 2017 (UTC)
- Lol yes. It means one doesn't posit a complex convoluted theory when a simple one will do. In this case there's no need for "horseshoe theory" when "no it's just you theory" fits the data just fine. John 82 (talk) 06:51, 4 January 2017 (UTC)
- Another razor comes to mind when looking at your posts. Reverend Black Percy (talk) 09:09, 4 January 2017 (UTC)
- The alt-right would probably run a study like this and solve the issue. Much better than your "we're all equal because race does not exist" contrived Marxist nonsense. John 82 (talk) 22:52, 3 January 2017 (UTC)
- Reverend Black Percy (talk) 00:44, 4 January 2017 (UTC)
- Ah, appeal to ridicule. Seems like a common theme of "Rational" Wiki. Why didn't you call yourselves Pravda? John 82 (talk) 06:54, 4 January 2017 (UTC)
- "But I thought this was supposed to be RATIONALWiki!" Drink! Reverend Black Percy (talk) 09:09, 4 January 2017 (UTC)
- I can understand why you would need a drink to take away the pain of writing for an Orwellian-named Communist pseudoscience website, while constantly showing how "science" you are by fitting your entire vocabulary into each sentence, casting vague aspertions on your opponents logic while not identifying any errors, and being unironically "wacky" and irreverent while just coming across as a sophomore. And all to push a Jew/Communist agenda. John 82 (talk) 10:25, 4 January 2017 (UTC)
Laid it on too thick there. Pretty amateurish trolling. 94.5.225.114 (talk) 12:18, 4 January 2017 (UTC)
- Oh I'm "trolling". Of course. That means all of the things I'm saying aren't really true? John 82 (talk) 12:33, 4 January 2017 (UTC)
- Sorry, you're incorrect -- RationalWiki switched from pushing the Jew-Commie agenda to pushing the NWO-lizard agenda years:26, 4 January 2017 (UTC)
- It's kind of had to take anything you say seriously when you drop phrases like "Jew/Communist" agenda. Also, being so obsessed with race is a little unhealthy, no? People who spend their lives obsessing over perceived racial differences usually don't have the most objective views on the subject. Since racism almost always serves as a cover for scapegoating others for your own personal failures, objective reasoning isn't usually a priority. Making yourself feel better by diminishing others seems to be the priority. Petey Plane (talk) 16:02, 4 January 2017 (UTC)
- Lol wut? Please explain why this site is eager to fallaciously sweep the race concept under that carpet and why it was constantly brought up in this very thread? You Jew/Communists are obsessed with denying the race concept to weaken your competitors. Thanks for the Freudian/Adornonian "you think that because you're a loser" psychoanalysis. Let's all pretend the races are equal and given up White nations to the third world or you personally are a loser. Talk about kindergarten psychology.
- Do you kikes ever get tired of lying? John 82 (talk) 19:02, 4 January 2017 (UTC)
- Petey Plane (talk) 19:15, 4 January 2017 (UTC)
- There's a "proud to be ethnic Englisc (Anglo-Saxon)" user-box and similar proud to be ethnic/culture user-boxes; Rationalwiki has never denied ethnicity or culture, nor does it have a problem with people identifying with them. Ethnicity and culture however is not race. Furthermore, few people today identity with race, but ethnicity/culture. I've also found that denying race is in the best interest of ethno-cultural nationalism; for example lumping all ethnic groups and cultures from Europe together into a silly "white race" blurs their separate ethnic identities and promotes mixing between them does it not? Its seems to me that denying racialism is in the best interest of ethno-tribalists or ethno-nationalists.86.14.2.77 (talk) 19:51, 4 January 2017 (UTC)
And what about us Mexicans, then? I heard someone say that we're technically 'white." >.> Ɀexcoiler Кingbolt Noooooooo! Look! Up there! 22:59, 4 January 2017 (UTC)
- I think most Hispanics are. Lord Aeonian (talk) 23:44, 4 January 2017 (UTC)
- "White" is scientific in regards to skin colour, i.e. skin colour classification in dermatology (still in use). However having white skin doesn't match the pseudo-science of a "white race". For example, Southern European populations on average are not white, but light brown (and they are scored differently in skin colour classifications to Northern Europeans). So "White" can only accurately describe Northern Europeans in a strict pigmentation sense. This is at odds with white nationalism/"alt right" politics that considers Southern and Northern Europeans part of the same race.86.14.2.77 (talk)
- Not to mention Koreans would win this whole "white" thing. Lord Aeonian (talk) 04:04, 5 January 2017 (UTC)
- Oh my god, I'm white. Gotta tell the Sith Lord about it then. Wait a minute... Ɀexcoiler Кingbolt Noooooooo! Look! Up there! 06:38, 5 January 2017 (UTC)
A Confederacy Of Dunces[edit]
Anyone ever read the book? Wondering mostly out of curiousity. Also cause some of the characters are pretty interesting in light of recent politics, especially given that it was probably written sometime in the 60's. Regardless, highly recommend it. B) talk 17:57, 3 January 2017 (UTC)
- Yeah, I read it a few years ago. Pretty funny as I remember. It's mentioned in our article on the neoreactionary movement. WēāŝēīōīďMethinks it is a Weasel 18:24, 3 January 2017 (UTC)
- Anyone who's suffered neoreactionary blogs will cackle with glee as they read it. All the section header quotes in the neoreactionary article are from it - David Gerard (talk) 22:11, 6 January 2017 (UTC)
- Yes, it's a fun read. I might crack it open again. Bongolian (talk) 19:53, 3 January 2017 (UTC)
Uncle Joe did it again![edit]
Joe Biden forgets what year it is as he swears in new Senators. If you think this can go into the WIGO page, please move it. I'm not sure so I put it here. Nerd271 (talk) 22:54, 3 January 2017 (UTC)
- What, you mean he said 2016 instead of 2017? Awww, come on! Give the guy a break. Millions of people make mistakes like that in the first few weeks of the new year every year. I had to write the date ten times yesterday (that includes when I had to write 106, the year according to the Taiwanese calendar which starts with the founding of the Republic of China in 1911, when I paid some money into my bank account) and I'm very proud of myself for getting it right every time. Spud (talk) 04:02, 4 January 2017 (UTC)
- If it were Trump he would've said "Do you swear solemnly, and I mean solemnly, that you will preserve, protect, and defend the Declaration of Independence of the United States? You do? Tremendous. Welcome to our 45th Congress." Applesauce (talk) 17:02, 4 January 2017 (UTC)
Oops! I forgot to include the link. He said 2007 instead of 2017. Sorry guys! Nerd271 (talk) 03:25, 5 January 2017 (UTC)
New level of stupidity[edit]
- This discussion was moved to Talk:Flat earth.
Moved. Fuzzy "Cat" Potato, Jr. (talk/stalk) 02:25, 5 January 2017 (UTC)
RationalWiki in 2016[edit]
- Only the ca. 600 pages with at least 40 edits in 2016 are on display, and not all of the more than 14,000 edited pages.
- It's an svg file, so you should visit directly: only then, you get the additional information via mouse-over....
Happy New Year, --larron (talk) 12:49, 4 January 2017 (UTC)
- I don't know who IPs and Others are but they're incredibly active. Happy New Year ! Diacelium (talk) 14:09, 4 January 2017 (UTC)
Pages with more than 250 edits in 2016, grouped by namespace. Pies shows the top 10 editors. --larron (talk) 00:00, 5 January 2017 (UTC)
- I'm part of the top 10? I was only here for half a year!-【DiamondDisc1】 (talk) 00:34, 5 January 2017 (UTC)
- ♫ "I've been everywheere, maan! I've been everywheere..." ♫
- Thanks for these, LArron! Also, am I crazy — or is a Donald Trump pie chart visible both right in the center and to the lower left? Reverend Black Percy (talk) 01:08, 5 January 2017 (UTC)
- One is for the talk page, the other is for the main article.-【DiamondDisc1】 (talk) 01:13, 5 January 2017 (UTC)
- Thanks! Reverend Black Percy (talk) 01:26, 5 January 2017 (UTC)
This seriously takes stupidity to the next level.[edit]
I was browsing around on youtube looking for clips of Carrie fisher being awesome... and then this gem popped up. Seriously...
TL;DW A young Carrie fisher was CGI`ed into Rouge one ==> CGI can make people look younger ==> Stuffs about images and Antichrist in the bible ==> The Antichrist will use CGI to do stuff ==> Somehow this will affect the ability for Christians to by and sell stuff because the Antichrist doesn't want Christians to be able to engage in free trade.
I had no idea that Christian trade was a thing.
Epic quote: "If you see a CGI of somebody, don't necessarily believe it."
- Pastor Steve Cioccolanti
The comment section is a gold mine as usual. TheGrandmother (talk) 17:06, 4 January 2017 (UTC)
- "because the Antichrist doesn't want Christians to be able to engage in free trade." Do I detect a hint of a piece of classic red-baiting prosperity gospel nuttery? ScepticWombat (talk) 19:25, 4 January 2017 (UTC)
Increasing CGI usage is all part of laying the groundwork for a digitally simulated second coming. Don't you see? Reverend Black Percy (talk) 12:27, 6 January 2017 (UTC)
Fuck me[edit]
My math teacher is showing a Spirit Science video about "sacred geometry in class.'Legionwhat do you want from me 17:39, 4 January 2017 (UTC)
- "Math teacher". Are you still in high school? You can always raise a stink about it. Not saying get the person fired, but that kind of stuff doesn't belong in the classroom, and there are certainly avenues you can take to keep it out. Petey Plane (talk) 17:57, 4 January 2017 (UTC)
- Agreed. That shit should not fly unless it is followed by a critical debate about the topic. TheGrandmother (talk) 18:08, 4 January 2017 (UTC)
-
- I'm afraid to ask where you live, because I'm worried it'll be the US.
- You will want to watch this playlist (excuse the Swedish accent), and/or alert all of your classmates about it + about this article. Reverend Black Percy (talk) 18:13, 4 January 2017 (UTC)
@Petey yes I'm still in high school, and @RBP you worried right because it is the U.S specifically in a region very susceptible to that kind of woo.'Legionwhat do you want from me 18:35, 4 January 2017 (UTC)
- Well, you're never too young to start practicing your skills at scientific skepticism (I wish I knew about that stuff when I was in high school — or middle school, for that matter). Secondly — you do realize that the Spirit Science has overt religious themes, and it is perhaps not impossible that your high school teacher showing it to students in class violates your constitutional right to separation of church and state? Anyways, seriously link people to this playlist. You might even save a few minds from the jaws of woo. Reverend Black Percy (talk) 18:30, 4 January 2017 (UTC)
- So, California? Does this teacher have a history of promoting New-Agey stuff? If not, this could just be a innocent mistake, as in your teacher needed a time-waster for a hole in the lesson plan, and found something with "geometry" in the title on Youtube without knowing the content. You can always complain to the school administration that the teacher is using class time to proselytize a religion. Petey Plane (talk) 18:37, 4 January 2017 (UTC)
- Complain to the school administration? Hell, film the Spirit Science being shown in class and go straight to the ACLU — you might end up on TV. Reverend Black Percy (talk) 18:39, 4 January 2017 (UTC)
- True, but N7 may not want to get the teacher in trouble if it was an honest mistake. If not, by all means, contact the ACLU, Freedom from Religion Foundation or Americans United for Separation of Church and State. Usually, all it takes is a Cease and Desist letter with a threat of legal action from one of those three to resolve the problem. Petey Plane (talk) 18:46, 4 January 2017 (UTC)
- Or we could get you an official endorsement letter from David Icke to your teacher (for showing the Spirit Science in class) — then you just give it to the PTA instead. Launch a new satanic panic. Reverend Black Percy (talk) 18:56, 4 January 2017 (UTC)
As mentioned in our Spirit Science article, YouTuber Martymer81 has a long playlist dealing with Spirit Science's shitloads of woo, crap and bullshit. See under external links. ScepticWombat (talk) 19:39, 4 January 2017 (UTC)
- The very same playlist I link to above! (Also, his actual profession isn't being a YouTuber, but to teach at a university in Sweden — just saying). Reverend Black Percy (talk) 20:01, 4 January 2017 (UTC)
- Oh, I didn't realise that you linked to it too, Rev., because I never thought he had much of a Swedish accent, though I seemed to recall that he is some sort of scientist, physics(?) ScepticWombat (talk) 21:10, 4 January 2017 (UTC)
- No problemo Yeah, he teaches physics at a Swedish university! Reverend Black Percy (talk) 23:53, 4 January 2017 (UTC)
- Now if it was shown in a religious studies class for a lesson on comparative religion that would be one thing but considering it was a Geometry class then it had no place there.--Rationalzombie94 (talk) 17:40, 5 January 2017 (UTC)
Inaccurate creationist lies in Israeli history curriculum[edit]
Today, I was sitting in the library reading. I happened to overhear a group of high schoolers studying together, and I froze when I heard them say that Darwin was a racist, that evolution says that the white race is the supreme race that rightfully rules all others, that Darwin created Social Darwinism, and that evolution caused Nazism. I could not stand this travesty, and insisted on correcting them. They claimed that "Darwin must have been racist because he was a German". At this point my head was exploding from the levels of stupidity I was experiencing. I informed them that Darwin was an Englishman, and had nothing to do with racism or Social Darwinism. The fact that this complete and utter lie is a part of the Israeli History Curriculum is horrifying, and is undoubtedly caused by the increasingly powerful Israeli religious lobby, which significantly affects politics here. --TeslaK20 (talk) 20:36, 4 January 2017 (UTC)
- Wow. I don't know anything about Israel's education system, but could those kids have been from a religious private school, or a public school specifically for Ultra-Orthodox? The US has similar issues, but they are currently mostly confined to private schools. Petey Plane (talk) 20:52, 4 January 2017 (UTC)
- Not the old "Hitler and evolution" trope! One must never fail to acknowledge the rampant nuttery of the truly orthodox... And forget Darwin — if anything, it's the Old Testament that goes on and on about a "chosen people". Reverend Black Percy (talk) 20:58, 4 January 2017 (UTC)
- Like Petey, I wonder if they "learned" this crap from the Israeli public educational system or (and this sounds more plausible to me) it stems from some fringe pseudoeducational echo chamber. ScepticWombat (talk) 21:04, 4 January 2017 (UTC)
- I asked, and they came from a public school. And judging by their clothes and lack of Kippas, they were almost certainly not Orthodox. My guess is that they have a bad teacher who tells them these lies. It needn't be the curriculum itself. --TeslaK20 (talk) 09:53, 5 January 2017 (UTC)
- Sounds like Darwinism is evolving. nobs 10:14, 5 January 2017 (UTC)
- Haa! You said the word! Reverend Black Percy (talk) 12:28, 6 January 2017 (UTC)
Climate Change[edit]
If the world gets hotter or colder or the climate zones shift, people should know it would still mean disaster for life on Earth. This is why people need science education so people know what is happening in the world (I mean other than politics).--Rationalzombie94 (talk) 17:14, 5 January 2017 (UTC)
- Yes; yes indeed. Reverend Black Percy (talk) 18:05, 5 January 2017 (UTC)
- It's not a disaster for life. Monera will do just fine. Simpler members of plantae, like moss, will easily displace old-growth forests that can't migrate as fast as conditions change beyond their tolerances. Many phyla of animals outside vertebrates are doing great: mollesca, and gnideria in the oceans, arthropoda on land. It's only a disaster to the kind of life humans like having around. ikanreed You probably didn't deserve that 22:11, 5 January 2017 (UTC)
- Indeed. (My above reply was directed at RZ's 2nd sentence, out of the two.) Reverend Black Percy (talk) 22:23, 5 January 2017 (UTC)
- Okay, I should have not said it like that. I meant for much bigger organisms who need a specific climate (Giraffes, Hippo's, many animals in the Rain Forest, snakes, desert animals, arctic animals, many species of fish and so on). Pardon my mistake, it has been a while since I was in high school Biology and I mostly read things on human and micro Biology.--Rationalzombie94 (talk) 23:05, 5 January 2017 (UTC)
Claim YOUR $25,000 survival bunker TODAY![edit]
Started out here. Decided to go on to here.
As fringe as survivial bunkers are, I saw no reason to suspect it wasn't atleast a serious company, although working a very niche market.
I noticed that, at the very bottom of the page, there were some colorful icons — mousing over them revealed that each signified a potential calamity.
And suddenly, I had to rethink my position on the company itself, because clicking one of them led here.
Runner-ups to taking the cake include this and this. Reverend Black Percy (talk) 19:08, 5 January 2017 (UTC)
- We have an article on it: Vivos. ŴêâŝêîôîďMethinks it is a Weasel 19:14, 5 January 2017 (UTC)
- ¡Ay, caramba! Thanks, old timer. Reverend Black Percy (talk) 19:21, 5 January 2017 (UTC)
- I admit, I have a huge interest in survivalism, I wouldn't mind having my own doomsday bunker but sadly I live in an apartment and I would not be allowed to do thank kind of construction nor do I have the money for it--Rationalzombie94 (talk) 20:40, 5 January 2017 (UTC)
- @RZ Survivalist vaults/bunkers are fascinating in a way — I always loved the Fallout series of games. And, I mean, if I had a billionaire friend who owned a survival shelter and asked if I wanted to get a free ride in case nuclear war was imminent, I'd say "Sure!". Outside of that, though... Nah. I know I'd get claustrophobic immediately. Besides, there's not much to be afraid of in the real world (for me atleast). Reverend Black Percy (talk) 21:06, 5 January 2017 (UTC)
Turns out that not only have they bought a truly huge former Soviet complex in Europe, they've also gotten into life extension woo. And the founder/owner seems to be a "former" doomsday/apocalypse crank who thinks he's on a mission from God. Reverend Black Percy (talk) 21:06, 5 January 2017 (UTC)
- Our article should be updated with this info. Those repurposed bunker sites are a new development. Previously I thought Vivos were just offering empty promises to their customers, as per most survivalist pipe-dreams (the Citadel springs to mind). I'll try & look at updating the article in the next few days if I have time. ωεαşεζøίɗMethinks it is a Weasel 00:39, 6 January 2017 (UTC)
- Good thinkin', Weasel! I don't know what else they might be up to — clicking around the site on the lookout for still more gems (like I did) is prolly a good idea before you start writing. Best of luck. Reverend Black Percy (talk) 12:20, 6 January 2017 (UTC)
Trump sides with Assange and Russia over U.S. intelligence[edit]
My question is simple: Is this really such a wise thing to do? Reverend Black Percy (talk) 19:39, 5 January 2017 (UTC)
- Are you implying that his first trip as the president will be to Dallas? Vulpius (talk) 20:35, 5 January 2017 (UTC)
- The key to understanding Trump is his all-consuming ego. That's really what drives his behavior. In this case, it's simply "I didn't need help from Russia. I won the election because I'm great". Leuders (talk) 20:38, 5 January 2017 (UTC)
- The Russian hacking controversy isn't making anyone look good, but Trump's & Putin's responses are extremely suspicious. + It's grossly unprofessional & unpresidential for Trump to be publicly shitting on the US's intelligence agency while exonerating Wikileaks. WėąṣėḷőįďMethinks it is a Weasel 20:53, 5 January 2017 (UTC)
- His ego can be divided into two parts, "greedy, greedy, greedy"[1] and revenge. His plan for his reign will be massive looting of government under his direction with the necessary crushing of any opposition, past or present. His appointment of Ben Carson to head HUD can even be seen as revenge against the housing discrimination suit against him in the early 1970s. Sounds bizarre, right? Well, Carson has said he's against desegregation.[2] Nonetheless, Trump's attack on US spy agencies (which can also be seen as revenge for their delegitimizing his election) may be his undoing because they likely have compromising information on him as likely does the Russian spy agency. John Schindler, an ex-NSA agent, indicated that there might be a meeting between an agent and a journalist in parking garage at some point, harking back to Deep Throat (Mark Felt) and Watergate.[3] Bongolian (talk) 21:23, 5 January 2017 (UTC)
- TRUMPGATE *INCEPTION WHAM* —Hamburguesa con queso con un cara (talk • stalk) 21:43, 5 January 2017 (UTC)
- @Bongolian, I dunno. I always feel the need to clarify that this is with respect to his public persona, but it seems like every choice he makes almost precisely matches the behavior described in extreme cases of narcissistic personality disorder. As such "greed" is much better understood by status-seeking than pure wealth accumulation. And revenge tends to be centered on personal offense rather than in proportion to actual harm.
- I know it's both reductionist and a little insulting to people suffering from mental disorders to boil someone down to purely the expression of that mental disorder's symptoms, but god damn is not not a great heuristic for his behavior. ikanreed You probably didn't deserve that 21:57, 5 January 2017 (UTC)
- He built a multi-million dollar empire, had his own TV show, constantly tweets on twitter, and said on OZ that he feels 30 years old, you have to have narcissism given these examples.—Hamburguesa con queso con un cara (talk • stalk) 22:04, 5 January 2017 (UTC)
- The list NPD traits seems right on the money. That's our Prez. Leuders (talk) 22:32, 5 January 2017 (UTC)
- (EC)Narcissistic Personality Disorder is pretty radically different from the more general personality dimension we call narcissism. Having a self-aggrandizing point of view about things in the sense we colloquially call narcissism is actually pretty radically different from NPD, which the DSM-6 defines as "A pervasive pattern of grandiosity (in fantasy or behavior), need for admiration, and lack of empathy, beginning by early adulthood and present in a variety of contexts".
- Specifically they give 9 criteria:
- expectation.
- Is interpersonally exploitative, i.e., takes advantage of others to achieve his or her own ends.
- Lacks empathy: is unwilling to recognize or identify with the feelings and needs of other
- Is often envious of others or believes that others are envious of him or her.
- Shows arrogant, haughty behaviors or attitudes.
- Now, if you think the public persona of every famous or rich person, or even compulsive tweeter(which does have a modest correlation the personality dimension also called narcissism), you're off your rocker. Half of these are traits that Donald Trump is particularly noteworthy for exhibiting with some frequency. I'm more than a tad narcissistic, I often think quite highly of myself, and exhibit a degree of vanity. I'm in no way, shape, or form diagnosable as having NPD. ikanreed You probably didn't deserve that 22:44, 5 January 2017 (UTC)
- Fair enough.—Hamburguesa con queso con un cara (talk • stalk) 23:03, 5 January 2017 (UTC)
Assange started out 10 years ago to dethrone Bush and thd neocon conspiracy. Obama and Hillary were supposed to complete the job, but flipped and used big gubmint and the NWO apparatus to persecute Assange. Trump now, commie lib that he is, sides with Assange. In 10 years, everyone has changed except Assange, who's been kept cryonically alive in the Ecuador embassey. The US government has slowly moved to Assange's position, except the CIA, which still wants to drone him. nobs 22:55, 5 January 2017 (UTC)
- Uh, cryonically alive? B) talk 00:37, 6 January 2017 (UTC)
- RobS comes across as my favorite type of
conspiracytheorist; he hates the likes of Alex Jones with a commanding passion, yet if teleported into the InfoWars bunker a minute before the Alex Jones radio show goes live on air, nobs could likely take the man's place without half of us noticing. Never change, nobs. Reverend Black Percy (talk) 01:57, 6 January 2017 (UTC)
Trump may have been normal once, but the decades of being reward for acting abnormal have become his real persona. To further the Nixon (our heretofore most paranoid president) parallel, take a look at this post-presidential statement by Nixon on why it pays to be crazy:[4]Bongolian (talk) 01:45, 6 January 2017 (UTC)
- It comes from the company he keeps(scroll through all the photos). nobs 04:10, 6 January 2017 (UTC)
- That quote is eerily relevant to Trump. Thanks, Bongo. Reverend Black Percy (talk) 12:22, 6 January 2017 (UTC)
The assault of a disabled man in Chicago[edit]
How could they not figure out if it was a hate crime? They kidnapped the victim and violently assaulted for hours on end with anti-white racial slurs being yelled at him during the abuse. The reason it was a hate crime is the fact that it was a hate fueled attack against another race and someone with a disability. The attackers were black and they assaulted a man of another race out of hate, if the shoe were on the other foot it would be deemed a hate crime in a heart beat. I am not saying one race is better, I am saying that double standards don't help with the issue of racism.--Rationalzombie94 (talk) 02:22, 6 January 2017 (UTC)
- When you make these type of posts, please don't forget to add a link to your source — you know, so we can all be sure what you're talking about in the first place. Thanks! Reverend Black Percy (talk) 02:25, 6 January 2017 (UTC)
Sorry, here is a link- --Rationalzombie94 (talk) 02:55, 6 January 2017 (UTC)
- The question remains on Brittany Herring's relation to Black Lives Matter or was this a lone wolf attack. nobs 04:00, 6 January 2017 (UTC)
- There is no connection between them and Black Lives Matter. They just assume there was. And we all know what happens when you assume thing.--Bonesquad11 (talk) 07:22, 6 January 2017 (UTC)
- Are you assuming we all know? =0 Narky Sawtooth (BoN is paranoid!) 07:56, 6 January 2017 (UTC)
- According to the commander, they were teenagers trying to get on the news. It may seem ridiculous that anybody would make something look like a hate crime just for attention, but there was a serial killer in Canada who kept sending news agencies increasingly disturbing videos of him killing people because he couldn't make national headlines. Of course, police officers are reluctant to label anything a hate crime, regardless of the evidence. It's not good to jump the gun on those things. Narky Sawtooth (BoN is paranoid!) 07:56, 6 January 2017 (UTC)
- There, now you see how I very subtly stuck in the idea of a Black Lives Matter lone wolf attack, impugning BLM as a terrorist network with no objection from any of you. Now, when is Barack Obama gonna be called upon to disavow BLM in the same manner Trump is called upon to disavow David Duke or the KKK? nobs 08:09, 6 January 2017 (UTC)
- "no objection from any of you?" What about Bonesquad? Lord Aeonian (talk) 08:17, 6 January 2017 (UTC)
- He didn't refute the implication BLM may inspire terror attacks or hate crimes, which us the unstated thinking in many proples mind, including the Chicago Police, evidentally. nobs 08:24, 6 January 2017 (UTC)
- The word is "evidently". Are you college educated, nobs? If you are, what college did you attend, and does it give refunds? This isn't your first grammatical atrocity. You also can't tell the difference between "secede" and "succeed". This is why people are often right when they presume many of you on the Right are uneducated. They may do so for different, and often poor reasons, (e.g. arrogance), but they aren't wrong in their presumption. Many of you are indeed barely literate. Now that I've got that off my chest, please proceed. Levi Ackerman (talk) 14:19, 6 January 2017 (UTC)
- The nuns taught me spelling wrong. I wish I could blame my spelling and grammatical errors on Big Pharma which has America doped up, but attribute it to being overworked, which is becoming increasingly rare in America. nobs 14:50, 6 January 2017 (UTC)
- nobs, what are you smoking? Going by various things you said in the past and this, you must be high 24/7. Considering this nonsensical statement you must be doped on some strong stuff!--Rationalzombie94 (talk) 18:34, 6 January 2017 (UTC)
Does every thread need to be derailed to a discussion of Rob's bullshit talking points? Time to bring back the Robrail page? WëäŝëïöïďMethinks it is a Weasel 19:09, 6 January 2017 (UTC)
- Yeah uh, it's a little concerning that every discussion is starting to follow the pattern of X starting topic, nobs adding his nonsensical two cents, Y calling bullshit, prompting another even more confusing reply...ya'll might have to do something about that. MyNameIsMudd (talk) 00:35, 7 January 2017 (UTC)
- Do something about it? We already have — by which I mean, we provide a field guide to help you determine when to engage and when to look the other way (to the benefit of all involved). But "do something about" it — as in; limiting Nobs' ability to peacefully participate (if you can call it that) in discussions here? Nah, that's not us. After all, we're a place centered around the interested study of nonsensical opinions, not around their hasty supression. Nobs is just as welcome as all the other children to use the slide (though, he is under specific recommendation not to subject others to his actual personality whenever possible). That being said, however — you and Weasel should do what I do instead. Document things for posterior. Reverend Black Percy (talk) 01:57, 7 January 2017 (UTC)
- Back on the main subject, all four suspects are being held without bail and this is from multiple sources. Now off the main subject, I know arguing with nobs is like playing checkers with a Pigeon but sometimes you need to get your point across--Rationalzombie94 (talk) 16:27, 7 January 2017 (UTC)
What if Trump was mature[edit]
Here's a troll twitter account that transforms all of Trump's tweets into mature ones. I-it's ... beautiful...—Hamburguesa con queso con un cara (talk • stalk) 07:39, 6 January 2017 (UTC)
- A twitter account dedicated to fact checking Trump.—Hamburguesa con queso con un cara (talk • stalk) 07:49, 6 January 2017 (UTC)
- Yah, every othet tweet says "appoint a task force", a sure fire way to flood the swamp. nobs 08:20, 6 January 2017 (UTC)
- Nobs, I know you're not one normally inclined to change your mind in the face of evidence, but haven't you noticed how many long-term pretty-damn-corrupt assholes Trump is appointing and how openly he's selling access to monnied interests? Congrats on achieving the opposite of your stated goals, I guess. ikanreed You probably didn't deserve that 15:52, 6 January 2017 (UTC)
Washington Post makes Ken Ham look smarter than he actually is[edit]
Ken Ham corrected the Washington Post when they wrote an article claiming he believed that the dinosaurs were wiped out in Noah's flood. --Bonesquad11 (talk) 08:05, 6 January 2017 (UTC)
- Thry couldn't have been, the dinosaurs built the Pyramids, as I was informed of just yesterday. nobs 08:13, 6 January 2017 (UTC)
- D-Do you actually believe that? Reverend Black Percy (talk) 12:12, 6 January 2017 (UTC)
- Bullshit, they stored the grain. Aside from that, I read that article when it was just published and it was no better. They called Ham's opinions "controversial" as if to take him seriously. Ɀexcoiler Кingbolt Noooooooo! Look! Up there! 21:44, 6 January 2017 (UTC)
Some weird things[edit]
The page on FairTax considers it as a bad thing, yet the Mike Gravel page includes the FairTax as the good things he proposes. Also, this site seems to be neutral on communism, yet the New Deal page says banning private gold possession was stupid. It looks contradictory to me. Diacelium (talk) 11:24, 6 January 2017 (UTC)
- Neutral on communism? Certainly not. Are we neutral on Fascism? Reverend Black Percy (talk) 12:13, 6 January 2017 (UTC)
- The page on communism doesn't really criticize it. There' s even a section about places where Communism worked fine (with some places where it isn't Communism, and some where it didn't last long enough to know if it really worked). And what about the FairTax and Mike Gravel ?
- "Fascist ideology centres on national unity behind a single revered dictator and for the idea that citizens must serve the state" I don't like communism, but I don't see how this applies to communist ideology. Diacelium (talk) 12:29, 6 January 2017 (UTC)
- None of our larger articles covering particular ideologies are even of silver quality, afaik. Many were written in an older generation of RW. Quality, consistency and comprehensiveness are as follows. Now, I'm a leftist myself — but as a social democrat worth the name (never mind a humanist above any political label), I'm very, very critical of the excesses of Communism. I'm not saying it's particularly bad compared to all others (quite the opposite actually), but it certainly is worthy of criticism. Besides, discussing the relative closeness of Fascism to Communism can be highly instructive to those lacking nuance on the topic. For examples of articles on Communist themes that aren't just unreflective pandering, see — for example — Anti-Fascist Protective Wall, Command economy or False consciousness. All the best, Reverend Black Percy (talk) 13:20, 6 January 2017 (UTC)
- There are articles on very bad ideas of Communism, but these ideas have been abandonned by many communists (marxists or not) and we don't criticize the idea of abolishing private property. Ideas like communism, Communalism, and mostly life salary all look very attractive, but I don't believe they can work. Diacelium (talk) 13:42, 6 January 2017 (UTC)
- Don't forget Rent control, capping one segment of capitalist investors income while the value of their property deteriorates to the detriment of the whole society and community. nobs 13:56, 6 January 2017 (UTC)–
- @Diacelum
- Disregard nobs on everything related to Communism — that word triggers him.
- Abolition of private property is indeed a nutty pipe
nightmaredream.
- I advise against conflating Communalism with Communism (per se).
- More like: those who have abandoned those concepts are no longer "Communists" in the orthodox sense; instead making up the spectrum of "softer" leftist variants.
- Reverend Black Percy (talk) 20:01, 6 January 2017 (UTC)
- Everything is communism for nobs. I didn't conflate communism with Communalism, but they are very similar. All the things I have mentioned are utopian.
- Also, many people close to communism have abandoned the idea of communal ownership for ownership by use (which Rojava has implemented, but I don't think it'll work for very long. There's also this idea in the idea of life salary and in some version of anarchism). It's just as utopian. Those who have abandoned command economy and other concepts are still communists, they can want a less agressive planning (or even decentralized planning), or just have abandoned this idea but still believe in abolishing private property.
- The only thing there is to remember about Marx is his contributions to sociology. Diacelium (talk) 10:25, 7 January 2017 (UTC)
They censor the word "nigger" in their screenshot of the offending tweet. Why would they do that? Everyone knows what word they are talking about! Why would they censor it. Whom are they trying not to offend? Do they think reproducing the original tweet will be deemed offensive? Talk about unnecessary censorship. Political correctness gone made. Note: "political correctness" is different from "political correctness gone mad"Levi Ackerman (talk) 11:44, 7 January 2017 (UTC)
- Unfortunately, given his views on "genetic superiority", I do not believe that Trump would support a "nigger" navy. Sigh. Let the alt-right rejoice. FuzzyCatPotato!™ (talk/stalk) 12:35, 7 January 2017 (UTC)
- (EC) Same reason tabloids write "f**k" when quoting somebody saying "fuck" I guess. I find it weird how many people also do this themselves on social media. WèàšèìòìďMethinks it is a Weasel 12:37, 7 January 2017 (UTC)
- @FCP, Trump believes in "genetic superiority"? That is news to me. When did he express that opinion? I always suspected he was of the casual racist variety, but supremacist?I didn't think so.Levi Ackerman (talk) 12:55, 7 January 2017 (UTC)
- He believes in his own personal genetic superiority (based on an uncle, no less), other than that what he actually "believes" is anyone's guess. Bongolian (talk) 20:55, 7 January 2017 (UTC)
- Well, he did get sued for discriminating against blacks, and he said blacks were inferior by being genetically lazy, so there's that. Nothing big. PBFЯЗЭSPДCЗ (talk) 00:24, 8 January 2017 (UTC)
Related. Reverend Black Percy (talk) 11:06, 8 January 2017 (UTC)
The Institute for Creation Research Graduate School[edit]
Honestly it could have been a decent school as there are religious schools with research doctorates in natural sciences but because it is solely creationist they dropped the ball. Why not have it where they do present both sides and let students choose for themselves like other religious schools (Examples- Loma Linda University, Andrews University, Brimingham Young Univeristy, Baylor University and so on)? That would have been fine and dandy because if they wanted students to learn about what they think then a Statement of Faith would not be needed. Here is a link to the ICRGS Catalogue from 2008-2009 and you can make you own opinions (And for the love of God nobs, please try to have a civil discussion and not have it devolve into paranoid racist conspiracy theories!); link- --Rationalzombie94 (talk) 16:37, 7 January 2017 (UTC)
I think itsnobody.blogspot.com should get a page here[edit]
It's one of the most super fundie sites I've ever seen, lol 2.216.243.206 (talk) 19:24, 7 January 2017 (UTC)
- Looks like it was last active in 2008. Sir ℱ℧ℤℤϒℂᗩℑᑭƠℑᗩℑƠ (talk/stalk) 19:36, 7 January 2017 (UTC)
- Actually it looks like it was only active in 2008. Five short posts. BoN is likely either connected to it or just trolling. Bongolian (talk) 20:59, 7 January 2017 (UTC)
- Oops sorry, wrong link, I mean amoung other things they consider atheists subhuman and think they want humanity to go back to the Stone Age 2.216.243.206 (talk) 23:42, 7 January 2017 (UTC)
- Reading its "About" section, I'm getting strong Poe's Law vibes. Just saying. ScepticWombat (talk) 15:39, 8 January 2017 (UTC)
- My poemeter does not go through the chart after reading the about page. I feel that the about page reads a lot like it was written by someone in a manic state (maybe from type I bipolar disorder or schizophrenia). None of the statements made seem like anything particularly absurd from someone who has been sitting at home and realized that they posses great knowledge. There exists a lot of people with these kind of delusions, they are especially common for people who suffer from type I bipolar disorder. TheGrandmother (talk) 17:06, 9 January 2017 (UTC)
- The website hasn't been active since 2011 and i believe that it is not of large enough impact to warranties own page, Although it should definetly appear on the Webshites page, since it is an amusing read TheGrandmother (talk) 17:18, 9 January 2017 (UTC)
Community question: WIGOW vs WIGOB[edit]
There has been recent dispute about whether blogs (and blog-like sources) and social media (and social-media-like sources) should go in WIGOB (the blogs view), WIGOW (the news view), or wherever the original poster puts it (the idgaf view). I'd like to get community consensus. Let's first discuss, then vote. Cømяade FυzzчCαтPøтαтø (talk/stalk) 19:46, 7 January 2017 (UTC)
Discussion[edit]
I firmly support the idgaf view. RationalWiki isn't about the WIGOs -- it's about the articles those WIGOs touch on. Nobody will care how your precious source is categorized in a week, including:46, 7 January 2017 (UTC)
- It should be the contributor's choice. There's a grey area here. For example, blog posts concerning a current newsworthy event might warrant going in WIGOW. Also, it's not a sin to include several links in a single entry for amplification or different takes on the same story, etc. Let the mob decide if something looks entirely out of place. That being said, the recent edit warring over a particular post seems completely meaningless to me. --Cosmikdebris (talk) 20:32, 7 January 2017 (UTC)
- "the recent edit warring over a particular post seems completely meaningless to me". That didn't stop you from reverting my edits. That's like walking into a bar in the midst of a brawl, and then saying, "you know, I really don't care about your dispute", after having just smashed a bottle against the skull of a combatant. Levi Ackerman (talk) 21:32, 7 January 2017 (UTC)
- Everyone: Try to discuss ideas, not people. Fallacious ad hominems and all that. Herr FuzzyKatzenPotato (talk/stalk) 22:27, 7 January 2017 (UTC)
- Twitter is a microblog, thus it goes into the blogosphere. It's not blog-like; it is a blog. —Hamburguesa con queso con un cara (talk • stalk) 21:46, 7 January 2017 (UTC)
- Let's say you're right. Should anyone regulate these pages to ensure that X article goes here and Y article there? Cømяade FυzzчCαтPøтαтø (talk/stalk) 22:28, 7 January 2017 (UTC)
- Not really, it seems like a waste of time. Sure, someone can move an out of place tidbit to the correct place if they spot it, but constantly regulating it seems unproductive. Focus on article quality.—Hamburguesa con queso con un cara (talk • stalk) 22:35, 7 January 2017 (UTC)
- @CheeseburgerFace, why did you delete my response and whose post did I undo on this talk page? I checked the fossil record and there is no suggestion that I deleted anyone's post. You, sir/madam, are a pathetic liar. Levi Ackerman (talk) 07:59, 8 January 2017 (UTC)
- @Levi Ackerman You're full of shit.—Hamburguesa con queso con un cara (talk • stalk) 06:32, 9 January 2017 (UTC)
- @CheeseburgerFace Am I now? Let's take a look at the fossil record. Let's take a look at edits within those times slots, 22:34 - 22:50. Please explain to me, where during that time slot I was supposed to have undone your post/edit and why it isn't shown on the fossil record? According to the Fossil record, between 22:34 and 22:50, 7 January 2017, the only person who deleted/undid anything in the Saloon was you! Also, why isn't the entire text in your link above in emboldened red? Did you manipulate the fossil record comparison?
- For the record, here is the post the liar CheeseburgerFace deleted:
"Twitter is a Microblog, thus it goes into the blogosphere", would be a point worth making IF I HAD A POSTED A LINK TO TWITTER IN WIGO: World or we were even discussing such a post. As it happens, I didn't and we aren't - as far as I can tell. I posted a news article reporting events which occurred on Twitter. Therefore, "Twitter is a Microblog, thus it goes into the blogosphere" is NOT a point worth making; at least not as far as I am concerned. Levi Ackerman (talk) 22:40, 7 January 2017 (UTC)
- It's one thing to delete people's edits on an article or in WIGO, but to delete what they've written on a talk page, that's just Stalinist.Levi Ackerman (talk) 08:06, 8 January 2017 (UTC)
Generally I'd put tweets in WIGOB, but it's not an issue worth going in guns blazing over. Twitter is typically used as commentary, not news. If it concerns something on Twitter that is newsworthy, then perhaps it could go in WIGOW, but in the concrete example, it's a HuffPo story about a tweet rebuking a twat (going Godwin over US (non)actions in the recent UN Israel resolution spat) — that's a blog story in my book. ScepticWombat (talk) 11:05, 8 January 2017 (UTC)
- It's never been poster option - even op-ed pieces from newspapers have gone in BLOGS in the past. From the above discussion, it looks very like a problem contributor, and that's not something to be solved by adding a gratuitous new rule, 'cos they'll just find something else to be a fuckhead about.
- More generally, trying to use WIGO as a soapbox has in the past year been a pretty reliable indicator of someone who will end up editing once every thirty minutes in the very near future - David Gerard (talk) 10:55, 8 January 2017 (UTC)
- Reverend Black Percy (talk) 11:02, 8 January 2017 (UTC)
- For the umpteenth time, I did not put a tweet in WIGOW. I feel like I need to keep pointing this out, as many of you just do not seem to be getting it! Furthermore, the article was not an op-ed. It was simply a report saying, "X did this on Twitter and Y responded like so...". That's very different from posting a link to Twitter or an article in which X opines on Y's Twitter antics. Levi Ackerman (talk) 11:59, 8 January 2017 (UTC)
- In my response above I have already pointed out why I don't think a tweet becomes news just because HuffPo reports on it. It's still a story about a spat in the blogosphere and thus I think it should go in WIGOB. ScepticWombat (talk) 12:04, 8 January 2017 (UTC)
- First, when you say "a spat in the blogosphere", you totally misrepresent the story. This was the Auschwitz Memorial - the Auschwitz Memorial! - responding to a conservative pundit comparing support for the UN resolution to helpers during the Holocaust. It wasn't a "spat". A spat is what we're having vis-a-vis the Maajid Nawaz page. This was someone, of relative note, saying something profoundly stupid and insulting and the appropriate authority responding. Secondly, you say "I don't think a tweet becomes news just because HuffPo reports on it"; well looking through WIGOW archives, I can see several postings of news articles centred around things happening on Twitter. To give one example, posted as recently as October 2016:
And then they came for the Jews: In 2016, people have read anti-Semitic tweets 10 billion times, many from Trump
- — Unsigned, by: Levi Ackerman / talk / contribs 12:30, 8 January 2017
- So entries have sometimes been posted in the wrong WIGO page & left there. It happens, & there's no point in moving old entries. That's not an argument against moving new entries when they're posted in the wrong page, as I did, as many other users also do, & as I've seen you do as well. You've been edit warring for over a week to try to keep that Auschwitz entry in both WIGO pages, which is moronic & a waste of everyone's time. WěǎšěǐǒǐďMethinks it is a Weasel 12:48, 8 January 2017 (UTC)
- Weaseloid says, "...there's no point in moving old entries", yet, for over a week now Weaseloid has been trying to move an old entry. Methinks it's a contradiction. Also, it's clearly not a waste of YOUR time seeing, as you keeping trying to move my entry. I have advised you to move on, haven't I? Why are you spending so much time on something you deem "moronic" and "a waste of time"? Methinks Weaseloid does contradict himself too much. Levi Ackerman (talk) 14:10, 8 January 2017 (UTC)
- You've been edit warring against something like 7 unrelated sysops, across two different mainspace articles, since about December 20th. A mod was forced to lock a page to stop you alone. You were also warned by a mod; instantly rebuking him (and reverting him) instead. You're done. Reverend Black Percy (talk) 14:34, 8 January 2017 (UTC)
- "I'm done"? Lol. Says who?Levi Ackerman (talk) 14:42, 8 January 2017 (UTC)
- And for the record, I neither rebuked a mod, nor was I warned by a mod. I really don't know why RBP is so butthurt? Levi Ackerman (talk) 14:45, 8 January 2017 (UTC)
- Though, you kinda were, and you kinda did. Reverend Black Percy (talk) 14:54, 8 January 2017 (UTC)
- So, in your view, 'disagreeing with a mod' = 'rebuking a mod', and 'a mod disagreeing with me' = 'a mod warning me'? Okay. Talk about extrapolating conclusions to suit one's bias. Levi Ackerman (talk) 15:13, 8 January 2017 (UTC)
- "...They said I was crazy... THEY'RE the ones that are CRAZY!!" Reverend Black Percy (talk) 15:22, 8 January 2017 (UTC)
Levi, I did spot that it was the Auschwitz Memorial's twitter account, but that's still a microblog criticising some pundit twat for going Godwin on Twitter, and the entire HuffPo story is about the Twittersphere (quite correctly) criticising the pundit who then doubles down on his Twitter twattery. This is a blogosphere story, hence it goes into WIGOB. ScepticWombat (talk) 15:20, 8 January 2017 (UTC)
- No amount of reasoned discussion or mobocratic consensus will be sufficient, as having sysop allows him to put up the fight ad infinitum. Also, speaking of Levi reverting mods... Reverend Black Percy (talk) 15:39, 8 January 2017 (UTC)
- Rev. try to stick to the topic and don't let Levi derail this into a row about this or that editor. ScepticWombat (talk) 15:47, 8 January 2017 (UTC)
- Will do. (I'm beating a dead horse at this point, I know.) Reverend Black Percy (talk) 15:49, 8 January 2017 (UTC)
- Hey, Sceptic, here's a tip: if you do not want me to detail this thread, maybe don't make backhanded comments about me, like the one above. Just my two cents. You did something similar in the Maajid Nawaz talk page; moaning about how my cries of "edit wars", was becoming tedious or something like that. Stop with the backhanded comments or don't try to take the moral high ground when I respond in kind.Levi Ackerman (talk) 16:02, 8 January 2017 (UTC)
Levi Ackerman is now blocked for 24 hours (but can edit his user talk page) & sysoprevoked to make the block stick. He's persisted in edit warring over this issue against numerous editors, including moderators, ignored repeated warnings to stop & ignored the fact that literally nobody has agreed with his arguments. If he resumes warring over this after the block expires, I suggest he be vandal binned. ŴêâŝêîôîďMethinks it is a Weasel 16:38, 8 January 2017 (UTC)
- Ah, I missed the chance to engage in the drama which has seen the insufferable little scum brought low. I suppose I'll have to settle for post-hoc celebration. Lord Aeonian (talk) 21:17, 8 January 2017 (UTC)
- Ah, LA, it pleases me to know that little tete-a-tete (in which I savaged you and your massa, Aneris) left you quite so butthurt. It pleases me greatly. How is your massa, Aneris? Levi Ackerman (talk) 06:14, 9 January 2017 (UTC)
- ????? Lord Aeonian (talk) 20:24, 9 January 2017 (UTC)
Before I put in my observation, I would like to note that I have not thoroughly read everything above, so I might hit upon something already mentioned. While I don't believe there should be a really strict formula people should adhere to while posting to the various What Is Going On categories, I fear the pages becoming partisan. What one person considers a Blog, others consider a Clog. I've seen a few instances where one website or public personality is put in the Blog section because they are being held as a voice of reason, while another contributor will put something very similar by them in the Clog section a little while later. I'm excluding Stopped Clock and its opposite. One time that comes to mind is, if I remember correctly, something about the regressive left or of that nature was put in both Blogosphere and Clogosphere simultaneously, probably by two very different people. Currently, this seems to be mostly happening with the debate about Russian interference in the election. As for What Is Going On In The World (news), I've seen multiple articles posted in quick succession about one subject, usually Israel. It might be a good idea to discuss things to keep What Is Going On from becoming an ideological battleground.Teurastaja (talk) 20:01, 9 January 2017 (UTC)
A school I unintentionally came across that could make a good article[edit]
The American University of Health Sciences, it is a nursing and pharmacy school that is fundamentalist Christian and Homophobic to boot! Here is the link- --Rationalzombie94 (talk) 01:40, 8 January 2017 (UTC)
- It doesn't even have a wiki page. Is that even possible anymore? I'd be amazed if they have more than 50 students. That being said, it's very likely legit, in that state certifications (and therefor employment) for nursing (LPN level at least) and pharmacy can be surprisingly easy to obtain, depending on the state. And to be fair, outside of women's healthcare, there isn't any reason a fundy school couldn't adequately teach those professions. They are both rather engineering-like in their instruction and practice, and seem have very little overlap with the political or metaphysical, at least in my experience working in the health care industry (I work in hospice care). Petey Plane (talk) 01:56, 8 January 2017 (UTC)
- I was not stating they could not teach nursing or Pharmacy, because the Fundie school Loma Linda University which is creationist has very good medical education programs--Rationalzombie94 (talk) 02:52, 8 January 2017 (UTC)
- It's not a good sign when either the faculty are not listed or are difficult to determine on the website. Also, their address appears to be residential from Google maps.[5] Bongolian (talk) 06:06, 8 January 2017 (UTC)
- I don't think your link points to the right address, Bongolian. I could easily find the office building depicted on their website (look for the intersection between E Hill Street and N Walnut Avenue), nor had I any problems finding the faculty list on their website (under About and then Faculty List), although it contains far too much alphabet soup and far too few info blurbs or links (read: none) to anything beyond email addresses for it to be of much use.
- A big red flag is that it's accredited by Accrediting Council for Independent Colleges and Schools although the rest of the accreditations seem legit (California Bureau for Private Postsecondary Education Accreditation Council for Pharmacy Education Western Association of Schools and Colleges Commission on Collegiate Nursing Education) ScepticWombat (talk) 11:46, 8 January 2017 (UTC)
The Accrediting Council for Independent Colleges and Schools is said to be legit as it is recognized by the USDE--Rationalzombie94 (talk) 14:55, 8 January 2017 (UTC)
- Okay, I looked into it again and it is still recognized by the Council on Higher Education Accreditation but not by the Secretary of Education--Rationalzombie94 (talk) 14:59, 8 January 2017 (UTC)
- I think AUHS might merit an article here — if we can actually source it and point out its particular relevance (e.g. due to notoriety or the AUHS being haunt or alma mater of some crank we already have an article on). If it's "only" a fundie school, then I don't we need an article on it, simply add it to the fundie school list. ScepticWombat (talk) 15:30, 8 January 2017 (UTC)
@ MTV[edit]
- Dear MTV: When you base your view of your fellow man on the exact same bigoted racialist sorting heuristics that racists use — guess what that makes you too? Reverend Black Percy (talk) 12:31, 8 January 2017 (UTC)
- Dear RBP, take your nose out of h3h3's ass!Levi Ackerman (talk) 14:41, 8 January 2017 (UTC)
- ...But it's such a juicy ass? Reverend Black Percy (talk) 14:52, 8 January 2017 (UTC)
- "As a white guy, I am very offended."
- "Why am I talking about white people as a group, its insane. I have never done that before."
- I enjoy h3h3 in general but their political things tend to be a fucking cringe fest. This is the same shit as one hears all the time, someone criticizes a privileged group and then everyone goes "Omfg!! You are just as bad as the racist/sexists/misogynist/whatever, derp derp derp, you have to be nice to me."
- So sorry RBP, I must agree with Levi.
-
- Ps: Man-spreading is a real thing.
- Rant over. TheGrandmother (talk) 16:07, 8 January 2017 (UTC)
- Disagreement is healthy, so please don't apologize! That being said, though — where he said "as a white guy", he was clearly joking (imo). I assume you didn't miss the part where he ranted against the Alt-right and the racist social experiments of Joey Salads? Regarding the other quote, however — I really question the idea of directing policies and opinions towards pseudoscientifically defined "racial" groups. Because again, the whole problem with a biological race concept is that no such races actually exist. What does exist (and is terrifyingly widespread) is a cultural race concept, i.e. racism — and racism inherently pretends to biology, as racist classification by necessity categorizes from primarily physical features. But again, there is no biological race for these concepts to actually base themselves on. So, who is white? You can't answer this question without having to measure noses and compare eye colours — the travesty that is physical anthropology, in other words. And even if satisfactory criteria were drawn up, there's no way to get past the Sorites paradox and actually find any "definite step" between "races" — because again, these don't exist. Positive application of color sorting is nothing but an arbitrary system of othering based on the fallacy that physical characteristics are indicative of qualitative difference between human beings, and the fallacy that other individual people are somehow fundamentally different from yourself. Both of these claims are demonstratively false, and culturally corrosive at that. Finally... I find the whole idea of actively sorting people a priori, never mind based on appearance, to be both factually wrong and deeply unsettling. That being said, I certainly don't have a problem with critiquing priviliege or inequality; I just worry enormously when societal problems are framed in terms of: "It's all [people of skin color X]'s fault, and they're all the same too!". In my view, no "sort" of human is ever the problem, partially because there are no such "sorts" to begin with. We're all part of the same big family, and we all come from Africa. I'm on my phone so I'm cutting this short here, but ultimately I see common progressive ground between our angles here. All the best, Reverend Black Percy (talk) 18:49, 8 January 2017 (UTC)
- MTV is CBS dressed up to look cool. nobs 21:10, 8 January 2017 (UTC)
- I agree Percy, disagreement is healthy. I found the best quote related to this researching for a project:
- But back to the topic, I don't think he was joking about the "as a white guy" thing considering that it is very in line with the rest of his rant.
- Regarding the whole "I hate the alt-right, so you cant be angry at me" is a token example of Whataboutism. The proposition: "The enemy of my enemy is my friend" ⇒ ("I am the enemy of everybody" ⇒ "I am the friend of everybody") is obviously not necessarily true.
- And yes, the whole concept of biological race is silly, but, race clearly exists as a social construction. When people attack the behaviour of white men, they dont mean the behaviour of aryan men they mean the men belonging to the group of people of predominantly pale skin complexion who hold privelge and have a track record of being dicks to less priveleged groups. And yes I agree that such a grouping is undesirable, it exists and it needs to be addressed.
- Then I also agree that MTVs vido on the topic might not be MTVs greatest accomplishment. FYI, their greatest accomplishment is when Beavis and Buthead are giggling when an elevator says "going down".
- TheGrandmother (talk) 12:58, 9 January 2017 (UTC)
- I agree (good quote btw!), though I will still insist that Ethan is a comedian, and that h3h3 is a comedy channel first and foremost (unfunny or not is to each his own). Indeed, the principle of charity demands that we give him the benefit of the doubt if we suspect disagreement. As Donald Davidson puts it:
- Let me also be clear that I fully acknowledge that people on all sides (read: because we're all really siblings) tend to commit a very comfortable fallacy, that of confusing a controversial view with the person expressing it. We love to conflate problems with people. Problems are abstract, elusive, they can't always be confronted easily, and for all the hurt they cause, they can't be given what's coming to them and made to feel bad. Problems don't have feelings — they're not even aware of the fact that anyone's upset at them (which makes us feel even worse). The one thing you can do with problems — like with Gods and ghosts and other abstractions — is invest emotionally in them (heavily, if need be). People, on the other hand... You can pin them down, you can confront them (which makes them suffer — "FUCK YOU, PROBLEM! >:D"), you can joust them... and even "better", sometimes people will (seem to) step in to defend the problem. At this point, it's almost impossible to resist the fallacy that the people are the problem. "You're working for the problem, you like the problem, and — unlike the elusive problem — you're standing here right in front of me, just begging to get screamed at/punched/attacked". But it's a dangerous and blind fallacy, because in the end — like with God, contra religious people — the faithful don't actually speak for the bigger issue (God). They can't, even if both you and they'd like to think so. In the end, the problems we face may be caused by people, but you'd have literally gone full Godwin the day that getting rid of the people equates to getting rid of the problem. And besides, for all the "Dear [skin color] [gender], stop ruining society", keep in mind that Hanlon's razor still applies, even to your worst opponents. I think that very few out of the total amount (including all the unreported ones) of everyday instances of friction between intersectionally different individuals in society is actually motivated by personal malign or a desire to harm. Lack of information resulting in an understandable failure of empathy? Sure. But not actual malign between strangers. We're all victims of intersectionality; it's not actually a thing that exists in and of itself, but a heuristic intended to help us perspectivize interpersonal misunderstandings, and indeed to root out all attempts to devise a split ingroup/outgroup perception — especially one overtly framed in terms of ethnodivisionary pseudoscience (i.e., "black", "white"). Grouping problems (and uniting against them) is most useful, necessary even. We need to openly denounce problems without mercy. Grouping people (and uniting against them) is both terrifying and nonsensical. Openly denouncing people without mercy is the most wickedly immoral tripe imaginable. We need to think twice about all this. We don't understand ourselves (from the inside no less); it'd be a bit rich to assume that we could somehow understand others (from the outside no less). Golden Rule, people — stay humble. Reverend Black Percy (talk) 15:05, 9 January 2017 (UTC)
- I used to like h3h3 until he started cynically pandering to the anti-SJ crowd for clicks. I'll agree the MTV vid isn't the most intelligent thing ever made, but I also think that tone policing women and minorities is bullshit. Why should we require the utmost politeness and diplomacy from the marginalized when we don't expect the same from the social majority? It boggles my mind how utterly unable to take criticism - regardless of tone - some straight white guys are. Blitz (Complaints Box) 00:21, 9 January 2017 (UTC)
- "Why can't we just all get along".—Hamburguesa con queso con un cara (talk • stalk) 03:12, 9 January 2017 (UTC)
- Bring up white privilege to most white men and most of them will get defensive.—Hamburguesa con queso con un cara (talk • stalk) 03:14, 9 January 2017 (UTC)
- Depends on how it's brought up. Much of the time I agree, albeit changing "men" to "people" would be even more accurate. When my black coworkers say "We need to unite under Farrakhan" and insist I (as someone with both gay and Jewish family) have no right to speak because "white privilege" (yes, that was the rationale 'in toto), then yeah I have a problem. Even if the expression "playing the race card" is a grossly abused and overused, there is a reason it exists. And also, it's too bad MTV doesn't actually have music videos on anymore; they should change their name to "The Dreck Channel" or something else a little more candid about their programming. The Blade of the Northern Lights (話して下さい) 06:30, 9 January 2017 (UTC)
- I totally agree Blitz. The privileged constantly wine on and on about minorities being offended and triggered by everything. But there are few people who freaks out more the slightest fucking critisism than those who are already privileged.
Pentagon chief is wrong[edit]
I was watching Meet the Press this morning, when I saw this atrocity of a statement by Ash Carter: “They came in, they said they were going to fight ISIL, and they said they were going to help in the civil war in Syria. They haven’t done either of those things.”
This is absolutely insane. Just yesterday Russia bombed ISIS over a dozen times in one city! You also may not know that there's a large tactical engagement going on at the T4 airbase in Syria, where ISIS has been attacking the Syrian Army for 3 weeks to take one airbase. Russia has bombed ISIS at this place for weeks, and has done so just yesterday as well. They've bombed ISIS in July, August, September, December, and January. It's a ridiculous nationalistic falsehood statement that comes from a deep-seated irrational hatred of Russia, one that is endemic among top US military officials. PB (talk) 02:29, 9 January 2017 (UTC)
- Russia spent more time bombing "moderate" rebels than bombing ISIS. If it hadn't been for Russian support, Assad would've fallen and the Syrian civil war would've ended years ago and Europe wouldn't be in the immigration crisis. Likewise, if it hadn't been for American support, Assad would've crushed the rebels already and the Syrian civil war would've ended years ago and Europe wouldn't be in the immigration crisis. Russia supports Assad because Assad offered them a swanky naval base, while the US opposes Assad because they keep causing trouble with Turkey or something, and also NATO doesn't want said naval base. Welcome to geopolitics. CorruptUser (talk) 04:36, 9 January 2017 (UTC)
- "Russia spent more time bombing "moderate" rebels than bombing ISIS. If it hadn't been for Russian support, Assad would've fallen" I agree with this, although Iranian and Hezbollah support are also critical.
- "and the Syrian civil war would've ended years ago and Europe wouldn't be in the immigration crisis." Whoa whoa whoa hold it right there. No immigration crisis? Libya's dictator fell in 9 months, and there's still a civil war going on there to this day between rebel factions! A great deal of the refugees are from Libya. Syria would still be in civil war if the government fell early on. You'd have moderates fighting Islamists, and those fighting the Alawites and Kurds. The Druze and Christians might get involved. With the Islamist Sunnis in power, you'd have the perfect recipe for mass Shi'a and Christian migration to Europe, numbering in the millions. Hell, with the bigger haven for ISIS the Iraqi crisis might've been even worse, with ISIS taking over all Sunni areas then marching on Baghdad. This is ridiculous!
- "Russia supports Assad because Assad offered them a swanky naval base" Do you really think that's the main reason? You don't think economic ties and a bulwark against America-Israel-Turkey have anything to do with it? Plus fighting terrorism, which is kind of a good thing.
- Your analysis isn't far off, but you have some seriously distorted notions of how things would've went if Assad fell early. PBFЯЗЭSPДCЗ (talk) 05:32, 9 January 2017 (UTC)
- You really think for 5 seconds that Russia is actually "fighting terrorism"? Seriously? CorruptUser (talk) 06:37, 9 January 2017 (UTC)
- they said they were going to help . Carter's being a bit disengenuous. Because of the sanctions, US forces are prohibited by law from coordinating with Russian forces. It's not that they don't want to "help", it's the US has refused their help. 'Help' is a bad word, they have dominated, while the US sat on its hands waiting to turn this mess over to a new commander in chief. We re rapidly getting to point where the US is the party offering help, cause we're no longer in the drivers seat . nobs 13:14, 9 January 2017 (UTC)
For the Fundie School page (I know matters on specific articles should go on the talk page but there are very few people who use them anyway)[edit]
I was thinking of having the Fundie school list be divided into the categories of "Good", "Moderate", "Awful" and "Should not exist". I do not mean separate pages but the list being divided into categories. For example-
Good
Moderate
--Rationalzombie94 (talk) 23:25, 10 January 2017 (UTC)
Workplace democracy[edit]
What do you guys think about workplace democracy ? Is it wrong or a good idea ? Diacelium (talk) 12:39, 9 January 2017 (UTC)
- what do you mean by workplace democracy? AMassiveGay (talk) 13:01, 9 January 2017 (UTC)
- I think that, in general, the strive for consensus is desirable. But, regarding technical issues, all peoples oppinions are not worth the same. The marketing department should have no say in a discussion regarding architecture changes to the backend architecture in order to improve horizontal scalability.
- But I am also slightly biased in this issue. Nothing drives me more insane than prolonged, needlessly verbose discussion about details that are, in the end, completely irrelevant. TheGrandmother (talk) 13:09, 9 January 2017 (UTC)
- So while on the boss's dime, workers conspire to liberate the owners of their property rights. There's a word for this, I just can't of it at the moment. nobs 13:07, 10 January 2017 (UTC)
- No, they can't take away the worker's property. But since they are the reason the company is running, they should have a say in decisions of the company. Diacelium (talk) 13:11, 10 January 2017 (UTC)
- do they not get paid for their time? AMassiveGay (talk) 13:24, 10 January 2017 (UTC)
- Yes, they do, but I still think they should have a say in some company decisions. Diacelium (talk) 13:31, 10 January 2017 (UTC)
- wby exactly? You take someones money to do one thing, but you'd rather do something else? Dont take their money. Its nice and all to get asked your opinion if you think you can improve the business, but you know, its their money. AMassiveGay (talk) 13:36, 10 January 2017 (UTC)
- The workers don't work becaused they choosed to, they work to avoid homelessness, hunger and death. Diacelium (talk) 13:39, 10 January 2017 (UTC)
- doesnt really answer my question though does it AMassiveGay (talk) 13:42, 10 January 2017 (UTC)
- @Diacelium: there's a difference between outright expropriation of property, and impingement on property rights. The owner of a capital has rights over that capital, how it is to be employed. A friend told me he made a suggestion once to a boss how to improve production, and the boss responded, "There's probably a million ways to do this, but since this is my factory we're gonna do it my way". Also, a worker who feels "forced" to work out of fear, rather than choice, has a spiritual problem only Jesus can fix. Working to avoid homelessness is not a universal axiom. nobs 14:03, 10 January 2017 (UTC)
- We have democracy in the Rationalwiki workspace, no? 82.44.143.26 (talk) 17:12, 10 January 2017 (UTC)
- I feel a middle ground can be reached, let employees have some kind of say but the CEO and or President or whatever makes the primary choices on how the business is ran. You would not want to feel like you don't matter at a workplace but the employees should not make the final choice on company policy. It would be like a department store manager how to run things in turn making the employees the bosses and the CEO powerless. But concerns an employee has should not be instantly tossed out the window.--Rationalzombie94 (talk) 04:28, 11 January 2017 (UTC)
- Having owned and operated a manufacturing concern at one point in my career, I'll be brief. The investor works out a formula based on unit cost (production tools + materials + labor) that sells for a variable market price. Selling price - cost = margin, or profit. Time is a huge factor, every moment production is down costs money in lost sales. People constantly pressure you with new ideas to improve production, 99% of which ALWAYS entail more capital investment, more capital investment which either (a) you don't have, (b) would require going into debt and delaying further the day you will ever see a return on the investment you've already made, and (c) a delaying tactic either by workers to stall for more time and run up the labor cost, or (d) outside competitors trying to confuse and fuck you up. In the end you nod, smile, say thanks, and tell them you already know what you're doing. But this isn't to say 1% of helpful suggestions that come your way cannot be very profitable, indeed. nobs 17:19, 11 January 2017 (UTC)
- I seem to recall learning in school that the owner gets to call the shots at the company because they're bearing the risks of the venture. On the other hand, it seems to me that the workers are the ones losing their livelihood when those risks look like they might be realized, so I can see why the workers might want a say in the matters. Hertzy (talk) 19:54, 11 January 2017 (UTC)
[edit]
Bernie is considered to be a Welfare capitalist by some. At what point do you go from capitalism to socialism ? When is an economy socialist ? Is it at a tax level, do you need maximum wage, worker ownership of means of productions, abolition of all private property ? Diacelium (talk) 08:51, 11 January 2017 (UTC)
- there are paleoconservatives, neoconservatives, collectivist anarchist, anarcho-communists, social democrats, democratic socialists, marxist, trotskyists, etc, etc, etc. Seem we spend more time debating the labels rather than issues. Its not helpful. AMassiveGay (talk) 11:25, 11 January 2017 (UTC)
- The classic definition of socialist, long lost to the discussions of American politics involves a national government seizing and running 1 or more industries. Distinct from communism by virtue of not necessarily being a classless society and distinct from a state-run economy in that not necessarily all parts of the economy are under state control. Saudi Arabia is socialist, in that the same royal family that runs the state runs the oil industry. The "socialist" democracies of Europe rarely are actually socialist, and are instead often social democracies(state should be for the benefit of society as determined by popular vote of that society)
- So... a social democrat, like Sanders, who wants to apply low-grade wealth redistribution for the sake of an improved society, still believes in the virtue of free market capitalism, but isn't actually a socialist.
- He's only called a socialist because he gave a speech where he said "And if that makes me a socialist, then I'm a socialist". It's a completely inapt label, and as the very large homosexual person noted, debating the nuances of the label is not at all helpful. ikanreed You probably didn't deserve that 18:16, 11 January 2017 (UTC)
Is there direct worker control over the means of production and community control over social institutions? If not, then it's not socialism. Simple. PBfreespace (talk) 21:08, 11 January 2017 (UTC)
- Socialism isn't about the State. It started as the idea that riches own too much and should give to the poor, this doesn't necessarly means state owned industries. But yes, Ricardian socialism is about direct worker ownership. Joseph Charlier was an utopian socialist and didn't propose nationalizations. Many of the utopian socialists wanted industries and businesses to become worker cooperatives. Diacelium (talk) 22:29, 11 January 2017 (UTC)
- hmm, Marx said From each as he is able, to each according to his need. So the labor of the worker (which is a "means of production") is not the property of the worker, and the produce of that labor is taken from him and redistributed by government to "each according to his need". nobs 00:11, 12 January 2017 (UTC)
There's a moderator election on[edit]
- This discussion was moved to Forum:RationalWiki election process.
Unweildy, probably un-archivable discussion about election policy moved to forum. Please participate! FuzzyCatPotato of the Communist Losers (talk/stalk) 01:15, 14 January 2017 (UTC)
About that RW mod election?[edit]
During the last hectic days of the US elections, the question of our own RW mod elections was raised. However, while those who chipped in all seemed in favour of starting the process fairly soon (as the current Mods were elected a year ago), it was not entirely clear that any concrete steps were decided, nor that any clear schedule was agreed on. So, I'd like to reopen the topic as I am both among the current mods and one of those in favour of holding elections fairly soon. ScepticWombat (talk) 05:38, 1 December 2016 (UTC)
- I am in favor of a moderator election ASAP. Applesauce (talk) 15:28, 1 December 2016 (UTC)
- Yes, we need a mod election, in the spirit of mobocracy. Ɀexcoiler Кingbolt Noooooooo! Look! Up there! 18:16, 1 December 2016 (UTC)
- Please have one, I'm finally eligible to vote.-【DiamondDisc1】 (talk) 04:21, 2 December 2016 (UTC)
Before people get riled up in favor of democracy, my question: would people like to pair up the mod and board elecitons & get both over at the same time, or separate? Mʀ. Wʜɪsᴋᴇʀs, Esϙᴜɪʀᴇ (talk/stalk) 23:15, 1 December 2016 (UTC)
- I very much think these should be separated. The roles of moderators and board members are different, and the motivations both for voting and running are completely different. I think it's a mistake to figure "Hey, people have short attention spans, let's make it a huge cluster****"! It's literally better to space it all out, methinks. Reverend Black Percy (talk) 23:32, 2 December 2016 (UTC)
- I'm not sure that it's a good idea to roll both election into one either, unless we have a reason to suspect some kind of election fatigue or very low interest in one of the elections. However, we need to get a schedule ready as well as nuts and bolts, especially with regards to ballot return officers. Someone has to do the adding up, after all. ScepticWombat (talk) 08:13, 4 December 2016 (UTC)
- Fair points. Last time, I and DG basically did the grunt work and ran it by Trent. Not good -- both of us were elected. Mʀ. Wʜɪsᴋᴇʀs, Esϙᴜɪʀᴇ (talk/stalk) 09:28, 4 December 2016 (UTC)
Information[edit]
Enjoy. Sir ℱ℧ℤℤϒℂᗩℑᑭƠℑᗩℑƠ (talk/stalk) 09:28, 4 December 2016 (UTC)
Proposed schedule[edit]
Proposed schedule: (propose by FCP as a user, pending mod feedback)
- Nominations: December 19-January 01 (two weeks)
- Voting: January 02-January 07 (one week)
- Results: January 09 (one day for ballot processing)
Thoughts? αδελφός ΓυζζγςατΡοτατο (talk/stalk) 09:28, 4 December 2016 (UTC)
- Cough cough. 32℉uzzy; 0℃atPotato (talk/stalk) 21:30, 10 December 2016 (UTC)
- Cough cough. Fuzzy. Cat. Potato! (talk/stalk) 18:47, 11 December 2016 (UTC)
- You should get that cough checked by a doctor, Fuzzy, it sounds nasty.
- Anyhow, I think your schedule sounds reasonable. While it does run into Christmas and New Year's that might actually be a good thing for those who are otherwise tied up by work and need time off from all that icky socialising with family and friends. ScepticWombat (talk) 15:00, 13 December 2016 (UTC)
Tech rights and mod count question[edit]
In addition to moderators, there are several techs. During 2015's flood of spam and after discussion here, I gave CorruptUser and JorisEnter and Owlman and Queex "tech" rights. CU, JE, and Owl are all still active. This "tech" position essentially gives all the rights of a moderator, minus the ability to add/remove moderator rights.
The flood of spam is now over. Should the tech rights of these users be removed? If so, should we elect additional moderators with the goal of speedy Special:AbuseFilter adjustment -- or stick with the current count of 6 mods? Sir ℱ℧ℤℤϒℂᗩℑᑭƠℑᗩℑƠ (talk/stalk) 09:28, 4 December 2016 (UTC)
- I was also given tech rights for the purposes of monitoring and maintaining the edit filter(I've made all of 2 changes to help out a new user getting falsely flagged). If tech rights are up for review, mine should probably be commented on as well. ikanreed You probably didn't deserve that 16:01, 13 December 2016 (UTC)
- I'd actually like to request tech rights — if that's how this works — as it might be time for me to start learning how to add to the edit filter? Joris has used his tech powers responsibly and has made numerous additions to the edit filter. Unless he wants them removed, I highly advise that he gets to keep them. Also, could someone please bestow Krej with Ninja? His (lovely) 4 symbol edits have the side effect of filling up the RC feed. Oh, and before anyone asks — I will not be running for moderator. Reverend Black Percy (talk) 16:22, 13 December 2016 (UTC)
STV operators[edit]
RW uses the (no-longer-free) OpenSTV software to tally STV votes. It's pretty simple; I, DG, and Trent have experience & can troubleshoot. Are there any people interested in tabulating results after the election? I (and DG) can provide copies of OpenSTV to those interested. More people presumably means less chance of a rigged election. The FCP Foundation (talk/stalk) 09:33, 4 December 2016 (UTC)
- FWIW, the last open source version of OpenSTV is in Debian and Ubuntu. sudo apt-get install openstv and you're good to go - David Gerard (talk) 11:22, 4 December 2016 (UTC)
By the way, was there a discussion/holy war in the distant past that resulted in choosing STV that I can read? I've been reading a lot about voting systems lately, and learning that STV's single-winner cousin IRV is moderately shitty, and that score voting is a better choice for single-winner elections, but I have no opinion yet on which systems are good for multi-winner elections.
I do know that I voted in one of the mod elections, and trying to find a single rank order for 20 or so candidates was pretty daunting. I ended up just categorizing them in groups like "good" "bad" "kind of good", etc. and roughly ordering them accordingly, which sounds a lot like score voting. (But I don't know if score voting produces good multi-winner results.) Hmmph (talk) 00:14, 18 December 2016 (UTC)
Let's get on with it[edit]
It's 2-3 days past the given start date. I'll make an announcement. αδελφός ΓυζζγςατΡοτατο (talk/stalk) 00:42, 22 December 2016 (UTC)
Voting end[edit]
- What time does voting close & shouldn't there be another announcement to remind about this? WéáśéĺóíďMethinks it is a Weasel 12:26, 7 January 2017 (UTC)
- Voting closes when David Gerard makes it happen. The announcement went up when I got up. :) Sir ℱ℧ℤℤϒℂᗩℑᑭƠℑᗩℑƠ (talk/stalk) 12:39, 7 January 2017 (UTC)
Can someone please post the results?[edit]
-【DiamondDisc1】 (talk) 04:16, 10 January 2017 (UTC)
- I do agree, we want results. We wouldn't want the vote tampered with, right? Applesauce (talk) 04:28, 10 January 2017 (UTC)
RESULTS![edit]
Results are posted! Check RationalWiki:Moderator elections/Results!
Apologies for the delay -- there have been some shenanigans. Please read up and vote. FuzzyCatPotato!™ (talk/stalk) 20:17, 10 January 2017 (UTC)
|
https://rationalwiki.org/wiki/RationalWiki:Saloon_bar/Archive268
|
CC-MAIN-2022-21
|
refinedweb
| 38,169
| 59.84
|
Stroop effect experiment design jobs
Saya memerlukan design antenna 2.4ghz microstrip antenna bersama metamaterial see the peak in an as low sample as possible (avg# means the number/time
.. controls to treat the
An engineering report for an experiment. And modeling it in Abaqus CAE. the experiment is about an object (PC-9) wing, all dimensions, results and loads are known. but need to be modeled using Abaqus CAE and written in a report.
..]
New experiment set: Calcium [login to view URL] 200 [login to view URL] 42 [login to view URL] 193 [login to view URL] 79 [login to view URL] 84 [login to view URL] 11 [login to view URL] 179 [login to view URL] 47 Calci
New experiment box: Calcium [login to view URL] 200 [login to view URL] 42 [login to view URL] 193 [login to view URL] 79 [login to view URL] 84 [login to view URL] 11 [login to view URL] 179 [login to view URL] 47 Calci
I have dataset in Arabic language divided into 3 categories each category is considered as different dialects. I Need to make the experiment same as the research paper that attached
...premium features. 2. Growth Strategies to Explore: a. Improve Play Store listing with localized app title; description; screen shot and graphics. You can work with Lina to experiment with various options. a. Contact influencers on social media/bloggers. b. Direct marketing on social media (pages directed for Indonesian market) c. Market research to.
Hi Everyone, Looking to get a logo designed for a website/blog/online course. The course/website will be called Longevity Enhancer. The purpose of the company is ...but use your creativity and we may look at using your colours. Green, Silver, Grey, White are some guidelines but if you feel another colour would fit, don't be afraid to experiment.
.. Bold the most important sentence requires researches for availability, complex
Salve, vorrei trasformare una presentazione PDF Vettoriale (11 slides) in un mini video fatto con After Effect da usare come sponsor su Facebook (Max 30 secondi). Grazie!
...curve with the function youobtain theoretically. They should be similar if everything works out, in terms of Θ [login to view URL] there is a discrepancy between the theory and experiment, try to explain what might becausing it....
I need someone to make a photo HDR
marketing video for a project
If you need this project file, please comment. I will give a project file.
...the Shell”. The ideal candidate: - Is Excited about a project like this and inspired to create something different and beautiful together - Has a good taste, willing to experiment and can even come up with ideas to further enhance the film - Experience in post production is a plus If you are interested please respond with a link to your portfolio
We are developing a website at this current stage but in the meantime I have a set of videos I need to promo...current stage but in the meantime I have a set of videos I need to promote to start showing proof of concept that my videos will be able to provide a return (consider this an experiment). The videos are of Art nature, sensual some say erotic.
...chat with support companies. What kind of server / coding platform / security /
Looking for someone able to convert an idea in.. first launch
Hello We want to start developing step of a web app with <<ASP.net and SQL>> . This App is for business connections and need messenge...preferred technology and programming language for use in messenger section . * Time is very important factor for us . Delivery time should be less than 45 days . * Having experiment in similar projects is necessary .
...its not percieved as a letter or a zero. I also want the "d" to have the lines below it like in the sketch, but i want the lines to be less regular and a little flatter, experiment with longer and shorter. I want the lines below the d to be in the same style as the circle before the c. I want the text to be in the same style or similair to the circle
i need an javascript effect for a log of mine
As part of a research
There are two parts One: I have ...should be able to rate different parts of this investigation form using 1 to 5 stars, just like we do online on facebook, etc, by page 1, 2 & 3 and overall. PLEASE don't experiment with this if you are not an expert who has done this multiple times before, not not waste my time if you don't know what you're doing.
|
https://www.my.freelancer.com/job-search/stroop-effect-experiment-design/
|
CC-MAIN-2018-39
|
refinedweb
| 780
| 61.46
|
Subject: Re: [boost] [algorithm][hex] function hex_char_to_int in unnamed namespace in header file
From: Marshall Clow (mclow.lists_at_[hidden])
Date: 2012-12-03 14:58:54
On Dec 3, 2012, at 9:43 AM, Felipe Magno de Almeida <felipe.m.almeida_at_[hidden]> wrote:
> On Mon, Dec 3, 2012 at 3:24 PM, Marshall Clow <mclow.lists_at_[hidden]> wrote:
>> On Nov 27, 2012, at 11:53 AM, Felipe Magno de Almeida <felipe.m.almeida_at_[hidden]> wrote:
>>
>>> On Tue, Nov 27, 2012 at 5:41 PM, Marshall Clow <mclow.lists_at_[hidden]> wrote:
>>>>-line.
>>>
>>> I didn't meant I want the function to be inlined by the compiler. What I mean
>>> is that putting it in a unnamed namespace causes undefined behavior(AFAIK).
>>
>> I don't believe that's true, but I'm willing to be convinced.
>
>
>
> AFAIK, an unnamed namespace creates different entities for each
> translation on which it is defined (by #inclusion,
> for example).
Yes.
> If any entity defined in a unnamed namespace is used in
> an external linkage definition, such as a
> inline function or a template definition and this definition is used
> in multiple TUs it causes ODR violations, because
> it is defined differently (uses different entities) in each TU.
And No. Because the call to it (in each TU) will call the entity in the specific unnamed namespace that was part of that translation unit.
My mental model for unnamed namespaces is "a namespace with a unique compiler-generated
|
https://lists.boost.org/Archives/boost/2012/12/198786.php
|
CC-MAIN-2021-25
|
refinedweb
| 241
| 63.19
|
I discovered what was happening! I've mixed the XMLs files I was using to
test my application and the one I was using hadn't any attributes in the
element. That's the reason why getLength() returned 0.
I notice that I was making a mistake when I saw that the attributes that the
Attributes object had where attributes from other elements and not from the
element I thought Digester was processing. Perhaps Digester use always the
same Attributes object...
I'm sorry for making you lose your time answering my mail :(. Thank you
anyway ;)
Carlos
On 4/21/06, Rahul Akolkar <rahul.akolkar@gmail.com> wrote:
>
> On 4/21/06, Carlos Ruano Sánchez <ruanonline@gmail.com> wrote:
> > Thank you for your response!
> >
> > I'm not using any VariableSubstitutor so I think that's not the reason
> of my
> > problem.
> >
> > I've tried again my code and I've got the same result: when I debug my
> > program, I can see all the attributes with their values inside the
> > Attributes object but when I try to get them, I get only nulls or empty
> > strings.
> >
> > How do you get the attribute names and values? Maybe I'm not using the
> > methods properly.
> >
> <snip/>
>
> <pseudo>
> public CustomRule extends Rule {
>
> public final void begin(final String namespace, final String name,
> final Attributes attributes) throws
> Exception {
> String foo = attributes.getValue("foo");
> // do something interesting with foo
> }
>
> // and so on ...
> }
> </pseudo>
>
> Maybe try to write a simplest test case that doesn't work for you?
>
> -Rahul
>
>
> > Thanks!
> >
> > Carlos
> >
> <snap/>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
> For additional commands, e-mail: commons-user-help@jakarta.apache.org
>
>
|
http://mail-archives.apache.org/mod_mbox/commons-user/200604.mbox/%3C96d00e340604211000j4ec330fck474be772bb25efb7@mail.gmail.com%3E
|
CC-MAIN-2016-18
|
refinedweb
| 277
| 66.23
|
Here is the problem as it is written in the book:
Write a function that accepts a C- string as an argument and returns the length of the C- string as a result. The function should count the number of characters in the string and return that number. Demonstrate the function in a simple program that asks the user to input a string, passes it to the function, and then displays the function’s return value.
I have written a program that does what is specified, except for the part where the USER inputs a string. I can get the program to work when I have a pre-defined string written in the code, but how would I change my code so that it accepts a user input and calculates the number of characters there? I have tried using cin, but I think I am doing it wrong...
Here is my code so far:
#include <iostream> using namespace std; // Create function prototypes. int Count_characters(char str[]); // Create main function. int main() { char string[]="Starting out with C++"; // THIS IS WHAT I WANT TO CHANGE TO ACCEPT A USER INPUT. int count; // Holds number of characters // Call the function. count=Count_characters(string); // Display the returned value. cout<< "The number of characters in the string is: "; cout<< count; cin.ignore(); cin.get(); } int Count_characters(char str[]) { // Declare variables. int count=0; // Count variable int i=0; // Loop variable // Loop to count characters while(str[i]!='\0') { count++; i++; } // Returning count. return count; }
|
https://www.daniweb.com/programming/software-development/threads/468587/how-do-i-change-my-program-so-that-it-accepts-a-user-input
|
CC-MAIN-2016-50
|
refinedweb
| 250
| 72.46
|
Author: Russ Cox
Last Updated: March 20, 2018
Discussion:
We propose to add awareness of package versions to the Go toolchain, especially the
go command.
The first half of the blog post Go += Package Versioning presents detailed background for this change. In short, it is long past time to add versions to the working vocabulary of both Go developers and our tools, and this proposal describes a way to do that.
Semantic versioning is the name given to an established convention for assigning version numbers to projects. In its simplest form, a version number is MAJOR.MINOR.PATCH, where MAJOR, MINOR, and PATCH are decimal numbers. The syntax used in this proposal follows the widespread convention of adding a “v” prefix: vMAJOR.MINOR.PATCH. Incrementing MAJOR indicates an expected breaking change. Otherwise, a later version is expected to be backwards compatible with earlier versions within the same MAJOR version sequence. Incrementing MINOR indicates a significant change or new features. Incrementing PATCH is meant to be reserved for very small, very safe changes, such as small bug fixes or critical security patches.
The sequence of vgo-related blog posts presents more detail about the proposal.
I propose to add versioning to Go using the following approach.
Introduce the concept of a Go module, which is a group of packages that share a common prefix, the module path, and are versioned together as a single unit. Most projects will adopt a workflow in which a version-control repository corresponds exactly to a single module. Larger projects may wish to adopt a workflow in which a version-control repository can hold multiple modules. Both workflows will be supported.
Assign version numbers to modules by tagging specific commits with semantic versions such as
v1.2.0. (See the Defining Go Modules post for details, including how to tag multi-module repositories.)
Adopt semantic import versioning, in which each major version has a distinct import path. Specifically, an import path contains a module path, a version number, and the the path to a specific package inside the module. If the major version is v0 or v1, then the version number element must be omitted; otherwise it must be included.
The packages imported as
my/thing/sub/pkg,
my/thing/v2/sub/pkg, and
my/thing/v3/sub/pkg come from major versions v1, v2, and v3 of the module
my/thing, but the build treats them simply as three different packages. A program that imports all three will have all three linked into the final binary, just as if they were
my/red/pkg,
my/green/pkg, and
my/blue/pkg or any other set of three different import paths.
Note that only the major version appears in the import path:
my/thing/v1.2/sub/pkg is not allowed.
Explicitly adopt the “import compatibility rule”:
If an old package and a new package have the same import path,
the new package must be backwards compatible with the old package.
The Go project has encouraged this convention from the start of the project, but this proposal gives it more teeth: upgrades by package users will succeed or fail only to the extent that package authors follow the import compatibility rule.
The import compatibility rule only applies to tagged releases starting at v1.0.0. Prerelease (vX.Y.Z-anything) and v0.Y.Z versions need not follow compatibility with earlier versions, nor do they impose requirements on future versions. In contrast, tagging a commit vX.Y.Z for X ≥ 1 explicitly indicates “users can expect this module to be stable.”
In general, users should expect a module to follow the Go 1 compatibility rules once it reaches v1.0.0, unless the module's documentation clearly states exceptions.
Record each module‘s path and dependency requirements in a
go.mod file stored in the root of the module’s file tree.
To decide which module versions to use in a given build, apply minimal version selection: gather the transitive closure of all the listed requirements and then remove duplicates of a given major version of a module by keeping the maximum requested version, which is also the minimum version satisfying all listed requirements.
Minimal version selection has two critical properties. First, it is trivial to implement and understand. Second, it never chooses a module version not listed in some
go.mod file involved in the build: new versions are not incorporated simply because they have been published. The second property produces high-fidelity builds and makes sure that upgrades only happen when developers request them, never unexpectedly.
Define a specific zip file structure as the “interchange format” for Go modules. The vast majority of developers will work directly with version control and never think much about these zip files, if at all, but having a single representation enables proxies, simplifies analysis sites like godoc.org or continuous integration, and likely enables more interesting tooling not yet envisioned.
Define a URL schema for fetching Go modules from proxies, used both for installing modules using custom domain names and also when the
$GOPROXY environment variable is set. The latter allows companies and individuals to send all module download requests through a proxy for security, availability, or other reasons.
Allow running the
go command in file trees outside GOPATH, provided there is a
go.mod in the current directory or a parent directory. That
go.mod file defines the mapping from file system to import path as well as the specific module versions used in the build. See the Versioned Go Commands post for details.
Disallow use of
vendor directories, except in one limited use: a
vendor directory at the top of the file tree of the top-level module being built is still applied to the build, to continue to allow self-contained application repositories. (Ignoring other
vendor directories ensures that Go returns to builds in which each import path has the same meaning throughout the build and establishes that only one copy of a package with a given import path is used in a given build.)
The “Tour of Versioned Go” blog post demonstrates how most of this fits together to create a smooth user experience.
Go has struggled with how to incorporate package versions since
goinstall, the predecessor to
go get, was released eight years ago. This proposal is the result of eight years of experience with
goinstall and
go get, careful examination of how other languages approach the versioning problem, and lessons learned from Dep, the experimental Go package management tool released in January 2017.
A few people have asked why we should add the concept of versions to our tools at all. Packages do have versions, whether the tools understand them or not. Adding explicit support for versions lets tools and developers communicate more clearly when specifying a program to be built, run, or analyzed.
At the start of the process that led to this proposal, almost two years ago, we all believed the answer would be to follow the package versioning approach exemplified by Ruby‘s Bundler and then Rust’s Cargo: tagged semantic versions, a hand-edited dependency constraint file known as a manifest, a machine-generated transitive dependency description known as a lock file, a version solver to compute a lock file satisfying the manifest, and repositories as the unit of versioning. Dep, the community effort led by Sam Boyer, follows this plan almost exactly and was originally intended to serve as the model for
go command integration. Dep has been a significant help for Go developers and a positive step for the Go ecosystem.
Early on, we talked about Dep simply becoming
go dep, serving as the prototype of
go command integration. However, the more I examined the details of the Bundler/Cargo/Dep approach and what they would mean for Go, especially built into the
go command, a few of the details seemed less and less a good fit. This proposal adjusts those details in the hope of shipping a system that is easier for developers to understand and to use.
Semantic versions are a reasonable convention for specifying software versions, and version control tags written as semantic versions have a clear meaning, but the semver spec critically does not prescribe how to build a system using them. What tools should do with the version information? Dave Cheney‘s 2015 proposal to adopt semantic versioning was eventually closed exactly because, even though everyone agreed semantic versions seemed like a good idea, we didn’t know the answer to the question of what to do with them.
The Bundler/Cargo/Dep approach is one answer. Allow authors to specify arbitrary constraints on their dependencies. Build a given target by collecting all its dependencies recursively and finding a configuration satisfying all those constraints.
Unfortunately, the arbitrary constraints make finding a satisfying configuration very difficult. There may be many satisfying configurations, with no clear way to choose just one. For example, if the only two ways to build A are by using B 1 and C 2 or by using B 2 and C 1, which should be preferred, and how should developers remember? Or there may be no satisfying configuration. Also, it can be very difficult to tell whether there are many, one, or no satisfying configurations: allowing arbitrary constraints makes version solving problem an NP-complete problem, equivalent to solving SAT. In fact, most package managers now rely on SAT solvers to decide which packages to install. But the general problem remains: there may be many equally good configurations, with no clear way to choose between them, there may be a single best configuration, or there may be no good configurations, and it can be very expensive to determine which is the case in a given build.
This proposal's approach is a new answer, in which authors can specify only limited constraints on dependencies: only the minimum required versions. Like in Bundler/Cargo/Dep, this proposal builds a given target by collecting all dependencies recursively and then finding a configuration satisfying all constraints. However, unlike in Bundler/Cargo/Dep, the process of finding a satisfying configuration is trivial. As explained in the minimal version selection post, a satisfying configuration always exists, and the set of satisfying configurations forms a lattice with a unique minimum. That unique minimum is the configuration that uses exactly the specified version of each module, resolving multiple constraints for a given module by selecting the maximum constraint, or equivalently the minimum version that satisfies all constraints. That configuration is trivial to compute and easy for developers to understand and predict.
A module‘s dependencies must clearly be given some control over that module’s build. For example, if A uses dependency B, which uses a feature of dependency C introduced in C 1.5, B must be able to ensure that A's build uses C 1.5 or later.
At the same time, for builds to remain predictable and understandable, a build system‘s always possible to use a relatively recent version of D (D 1.98 or D 1.97, respectively). But when A uses both B and C, a SAT solver-based build silently selects the much older (and buggier) D 1.2 instead. To the extent that SAT solver-based build systems actually work, it is because dependencies don’t choose to exercise this level of control. But then why allow them that control in the first place?
Although the hypothetical about prime and even versions is clearly unlikely, real problems do arise. For example, issue kubernetes/client-go#325 was filed in November 2017, complaining that the Kubernetes Go client pinned builds to a specific version of
gopkg.in/yaml.v2 from September 2015, two years earlier.. The issue was closed after a change in February 2018 to update the specific YAML version pinned to one from July 2017. But the issue is not really “fixed”: Kubernetes still pins a specific, increasingly old version of the YAML library. The fundamental problem is that the build system allows the Kubernetes Go client to do this at all, at least when used as a dependency in a larger build.
This proposal aims to balance allowing dependencies enough control to ensure a successful build with not allowing them so much control that they break the build. Minimum requirements combine without conflict, so it is feasible (even easy) to gather them from all dependencies, and they make it impossible to pin older versions, as Kubernetes does. Minimal version selection gives the top-level module in the build additional control, allowing it to exclude specific module versions or replace others with different code, but those exclusions and replacements only apply when found in the top-level module, not when the module is a dependency in a larger build.
A module author is therefore in complete control of that module‘s build when it is the main program being built, but not in complete control of other users’ builds that depend on the module. I believe this distinction will make this proposal scale to much larger, more distributed code bases than the Bundler/Cargo/Dep approach.
Allowing all modules involved in a build to impose arbitrary constraints on the surrounding build harms not just that build but the entire language ecosystem. If the author of popular package P finds that dependency D 1.5 has introduced a change that makes P no longer work, other systems encourage the author of P to issue a new version that explicitly declares it needs D < 1.5. Suppose also that popular package Q is eager to take advantage of a new feature in D 1.5 and issues a new version that explicitly declares it needs D ≥ 1.6. Now the ecosystem is divided, and programs must choose sides: are they P-using or Q-using? They cannot be both.
In contrast, being allowed to specify only a minimum required version for a dependency makes clear that P‘s author must either (1) release a new, fixed version of P; (2) contact D’s author to issue a fixed D 1.6 and then release a new P declaring a requirement on D 1.6 or later; or else (3) start using a fork of D 1.4 with a different import path. Note the difference between a new P that requires “D before 1.5” compared to “D 1.6 or later.” Both avoid D 1.5, but “D before 1.5” explains only which builds fail, while “D 1.6 or later” explains how to make a build succeed.
The example of ecosystem fragmentation in the previous section is worse when it involves major versions. Suppose the author of popular package P has used D 1.X as a dependency, and then popular package Q decides to update to D 2.X because it is a nicer API. If we adopt Dep's semantics, now the ecosystem is again divided, and programs must again choose sides: are they P-using (D 1.X-using) or Q-using (D 2.X-using)? They cannot be both. Worse, in this case, because D 1.X and D 2.X are different major versions with different APIs, it is completely reasonable for the author of P to continue to use D 1.X, which might even continue to be updated with features and bug fixes. That continued usage only prolongs the divide. The end result is that a widely-used package like D would in practice either be practically prohibited from issue version 2 or else split the ecosystem in half by doing so. Neither outcome is desirable.
Rust‘s Cargo makes a different choice from Dep. Cargo allows each package to specify whether a reference to D means D 1.X or D 2.X. Then, if needed, Cargo links both a D 1.X and a D 2.X into the final binary. This approach works better than Dep’s, but users can still get stuck. If P exposes D 1.X in its own API and Q exposes D 2.X in its own API, then a single client package C cannot use both P and Q, because it will not be able to refer to both D 1.X (when using P) and D 2.X (when using Q). The dependency story in the semantic import versioning post presents an equivalent scenario in more detail. In that story, the base package manager starts out being like Dep, and the
-fmultiverse flag makes it more like Cargo.
If Cargo is one step away from Dep, semantic import versioning is two steps away. In addition to allowing different major versions to be used in a single build, semantic import versioning gives the different major versions different names, so that there's never any ambiguity about which is meant in a given program file. Making the import paths precise about the expected semantics of the thing being imported (is it v1 or v2?) eliminates the possibility of problems like those client C experienced in the previous example.
More generally, in semantic import versioning, an import of
my/thing asks for the semantics of v1.X of
my/thing. As long as
my/thing is following the import compatibility rule, that's a well-defined set of functionality, satisfied by the latest v1.X and possibly earlier ones (as constrained by
go.mod). Similarly, an import of
my/thing/v2 asks for the semantics of v2.X of
my/thing, satisfied by the latest v2.X and possibly earlier ones (again constrained by
go.mod). The meaning of the imports is clear, to both people and tools, from reading only the Go source code, without reference to
go.mod. If instead we followed the Cargo approach, both imports would be
my/thing, and the meaning of that import would be ambiguous from the source code alone, resolved only by reading
go.mod.
Our article “About the go command” explains:.
It is an explicit goal of this proposal's design to preserve this property, to avoid making the general semantics of a Go source file change depending on the contents of
go.mod. With semantic import versioning, if
go.mod is deleted and recreated from scratch, the effect is only to possibly update to newer versions of imported packages, but still ones that are still expected to work, thanks to import compatibility. In contrast, if we take the Cargo approach, in which the
go.mod file must disambiguate between the arbitrarily different semantics of v1 and v2 of
my/thing, then
go.mod becomes a required configuration file, violating the original goal.
More generally, the main objection to adding
/v2/ to import paths is that it‘s a bit longer, a bit ugly, and it makes explicit a semantically important detail that other systems abstract away, which in turn induces more work for authors, compared to other systems, when they change that detail. But all of these were true when we introduced
goinstall‘s URL-like import paths, and they’ve been a clear success. Before
goinstall, programmers wrote things like
import "igo/set". To make that import work, you had to know to first check out
github.com/jacobsa/igo into
$GOPATH/src/igo. The abbreviated paths had the benefit that if you preferred a different version of
igo, you could check your variant into
$GOPATH/src/igo instead, without updating any imports. But the abbreviated imports also had the very real drawbacks that a build trying to use both
igo/set variants could not, and also that the Go source code did not record anywhere exactly which
igo/set it meant. When
goinstall introduced
import "github.com/jacobsa/igo/set" instead, that made the imports a bit longer and a bit ugly, but it also made explicit a semantically important detail: exactly which
igo/set was meant. The longer paths created a little more work for authors compared to systems that stashed that information in a single configuration file. But eight years later, no one notices the longer import paths, we’ve stopped seeing them as ugly, and we now rely on the benefits of being explicit about exactly which package is meant by a given import. I expect that once
/v2/ elements in import paths are common in Go source files, the same will happen: we will no longer notice the longer paths, we will stop seeing them as ugly, and we will rely on the benefits of being explicit about exactly which semantics are meant by a given import.
In the Bundler/Cargo/Dep approach, the package manager always prefers to use the latest version of any dependency. These systems use the lock file to override that behavior, holding the updates back. But lock files only apply to whole-program builds, not to newly imported libraries. If you are working on module A, and you add a new requirement on module B, which in turn requires module C, these systems will fetch the latest of B and then also the latest of C. In contrast, this proposal still fetches the latest of B (because it is what you are adding to the project explicitly, and the default is to take the latest of explicit additions) but then prefers to use the exact version of C that B requires. Although newer versions of C should work, it is safest to use the one that B did. Of course, if the build has a different reason to use a newer version of C, it can do that. For example, if A also imports D, which requires a newer C, then the build should and will use that newer version. But in the absence of such an overriding requirement, minimal version selection will build A using the exact version of C requested by B. If, later, a new version of B is released requesting a newer version of C, then when A updates to that newer B, C will be updated only to the version that the new B requires, not farther. The minimal version selection blog post refers to this kind of build as a “high-fidelity build.”
Minimal version selection has the key property that a recently-published version of C is never used automatically. It is only used when a developer asks for it explicitly. For example, the developer of A could ask for all dependencies, including transitive dependencies, to be updated. Or, less directly, the developer of B could update C and release a new B, and then the developer of A could update B. But either way, some developer working on some package in the build must take an explicit action asking for C to be updated, and then the update does not take effect in A's build until a developer working on A updates some dependency leading to C. Waiting until an update is requested ensures that updates only happen when developers are ready to test them and deal with the possibility of breakage.
Many developers recoil at the idea that adding the latest B would not automatically also add the latest C, but if C was just released, there's no guarantee it works in this build. The more conservative position is to avoid using it until the user asks. For comparison, the Go 1.9 go command does not automatically start using Go 1.10 the day Go 1.10 is released. Instead, users are expected to update on their own schedule, so that they can control when they take on the risk of things breaking. The reasons not to update automatically to the latest Go release applies even more to individual packages: there are more of them, and most are not tested for backwards compatibility as extensively as Go releases are.
If a developer does want to update all dependencies to the latest version, that's easy:
go get -u. We may also add a
go get -p that updates all dependencies to their latest patch versions, so that C 1.2.3 might be updated to C 1.2.5 but not to C 1.3.0. If the Go community as a whole reserved patch versions only for very safe or security-critical changes, then that
-p behavior might be useful.
The work in this proposal is not constrained by the compatibility guidelines at all. Those guidelines apply to the language and standard library APIs, not tooling. Even so, compatibility more generally is a critical concern. It would be a serious mistake to deploy changes to the
go command in a way that breaks all existing Go code or splits the ecosystem into module-aware and non-module-aware packages. On the contrary, we must make the transition as smooth and seamless as possible.
Module-aware builds can import non-module-aware packages (those outside a tree with a
go.mod file) provided they are tagged with a v0 or v1 semantic version. They can also refer to any specific commit using a “pseudo-version” of the form v0.0.0-yyyymmddhhmmss-commit. The pseudo-version form allows referring to untagged commits as well as commits that are tagged with semantic versions at v2 or above but that do not follow the semantic import versioning convention.
Module-aware builds can also consume requirement information not just from
go.mod files but also from all known pre-existing version metadata files in the Go ecosystem:
GLOCKFILE,
Godeps/Godeps.json,
Gopkg.lock,
dependencies.tsv,
glide.lock,
vendor.conf,
vendor.yml,
vendor/manifest, and
vendor/vendor.json.
Existing tools like
dep should have no trouble consuming Go modules, simply ignoring the
go.mod file. It may also be helpful to add support to
dep to read
go.mod files in dependencies, so that
dep users are unaffected as their dependencies move from
dep to the new module support.
A prototype of the proposal is implemented in a fork of the
go command called
vgo, available using
go get -u golang.org/x/vgo. We will refine this implementation during the Go 1.11 cycle and merge it back into
cmd/go in the main repository.
The plan, subject to proposal approval, is to release module support in Go 1.11 as an optional feature that may still change. The Go 1.11 release will give users a chance to use modules “for real” and provide critical feedback. Even though the details may change, future releases will be able to consume Go 1.11-compatible source trees. For example, Go 1.12 will understand how to consume the Go 1.11
go.mod file syntax, even if by then the file syntax or even the file name has changed. In a later release (say, Go 1.12), we will declare the module support completed. In a later release (say, Go 1.13), we will end support for
go
get of non-modules. Support for working in GOPATH will continue indefinitely.
We have not yet converted large, complex repositories to use modules. We intend to work with the Kubernetes team and others (perhaps CoreOS, Docker) to convert their use cases. It is possible those conversions will turn up reasons for adjustments to the proposal as described here.
|
https://go.googlesource.com/proposal/+/master/design/24301-versioned-go.md
|
CC-MAIN-2019-13
|
refinedweb
| 4,545
| 53.81
|
Let’s learn how to get BitCoin price using CoinGecko api and Python?
Using bitcoin api
First thing I checked is how to use CoinGecko api. This is how I got url to api which will return my BitCoin price I need. There is also a possibility to try the link out directly in CoinGecko site.
I assigned api url as a python variable.
Next thing is to request this url using requests python library.
I’d like to load this as a json. Luckily Python offers dedicated json library. Loads function will do the job.
Last thing is to format requested string as I like the most.
import json import requests api_url = '' response = requests.get(api_url).text response = json.loads(response) response = response["bitcoin"]["usd"] print(f"Bitcoin price is currently {response} USD.")
While I was preparing this article the BitCoin price was 55083 USD. I wonder how it will change in the future. I hope it is much higher when you are reading this.
|
https://pythoneo.com/how-to-get-bitcoin-price-using-api/
|
CC-MAIN-2022-40
|
refinedweb
| 166
| 78.55
|
Diode is bad.
You can shorting it.
But then you can power this Arduino only from USB or from +5V in the same time!!!
Not both !!! This can damage your USB port.
Posts made by kimot
- RE: Killing Nanos, one after the other
Diode is bad.
- RE: Temperature serial sketch
@Olaf-Jacobs said in Temperature serial sketch:
First I had 4x DS18B20 temperature sensors hooked up to gpio4 on the pi without the resistor, this worked fine for some time till this gave some issues
Can you write what issues.
Why you connect DS18B20s to RPi without resistor ?
Is it some experiment?
- RE: 💬 Leaky - water detector
@Sixkillers
You can wake up every hour, but hold wifi modem off, increment "wake up counter" and go to deep sleep.
Running time between deep sleeps will be very short
And connect to wifi one per day for example.
And make some tweaks for wifi connection:
For inspiration from Step 6 here:
And final tweak here:
- RE: 💬 Leaky - water detector
@openhardware-io
I think this is not too useful concept.
In circuit diagram, there is no connection GPIO16 to RESET - so no deep sleep mode.
It seems, your node only connect to server when water leaks.
But what after two years, you do not know if battery are still good and your detector alive.
Better way use deep sleep, after some number deep sleep cycles ( one per day? ),
connect to wifi and send battery voltage for example.
If this message is missed, your controller can send you battery replacement message.
- RE: Hi everyone newbish question here
@fdlou147
Ethernet ( with POE ) is very very expensive way to connect your sensors.
Look for prices 24port switches with POE for example.
And 24 nodes is not enough....
- RE: Modular sketch to be configured with JSON (idea).
- RE: Trying to develope a whole house energy meter using My Sensors
@PedroHernandez
If you build sensor with ethernet connectivity, simply send your data to Domoticz via http call using Domoticz JSON API.
- RE: 💬 Temperature Sensor
Domoticz globally or only with MySensors ?
My Domoticz is the same version like yours.
Temperatures from ESPeasy are with two decimals on Temperature sensors page, but on devices page only one decimal.
Exactly the opposite like you wrote.
- RE: 2 Arduinos talk to each other over RS485
Examples are there too.
( MySensors uses this code for 485 transport layer too )
Or another very simple example:
- RE: Laundry sensors
I would simply endured.
Once clean clothes go away and they will go out of the house dirty, smelly or naked...
Then they empty basket sure.
- RE: RPi 3 with Domoticz and RF-link (RFXcom) 'TSP-fail'
@esfnl
You are completely wrong and mix different things together.
Firstly - you wrote RFXcom (with long range antena ) and then mention link to RFLink.
Both devices have got separete device in Domoticz:
Secondly - RFLink and RFXCom are for intergration most commercial sensors and transducers to 433MHz.
You do not need install MySensors gateway on RPI for use them.
Simply connect them and select in Domoticz devices with appropriate interface.
Then you will see all sensors in your surroundings.
Mostly your neighbors meteostantions, heatpumps etc.
Here is my RFLink sensors list after couple of hours - none from me, all neighbors.
And I live on village ....
No block of flats.
( It is twice as long as you see )
I do not know RFXCom, but RFLink can receive data from MySensors nodes.
According your link, I do not test it.
ONLY receive - so no AUTO ID for nodes, no answer for presentation etc.
If you want use MySensors, I suggest build separate USB gateway and connect it to Domoticz and select
"MySensors Gateway USB" in device list.
That all.
No "./configure" and all this.
- RE: WI-FI IOT modules
@mfalkvidd
Look for ESP-NOW ...
But it is limited to max 20 nodes per one network.
( Without encryption. With encryption, number of nodes is more limited - 6 or 10 )
- RE: PIR Sensor Gives False High in 55 Minutes (Can't find a way to solve)
Simplify your code maximally.
Remove PIR and UNO and connect D3 and D7 to correct levels.
Remove SoftwareSerial and all SMS function.
Only check serial debug messages for 4-5 hours run.
If it will work, then little by little add other functions.
My tip is problem with combination HW serial and SoftwareSerial.
- RE: is mesh n/w possible using RFM69 without using gateway?
:
- RE: Sonoff gateway: sketch uploads fine but doesn't run
....
- RE: Multisensor with DSB18B20 and relay
@kvn298
Each sensor must have unique child ID.
Your presentation:
DS18B20 ID=0 to max number of DS18B20
Relay ID=1
So second DS have got the same ID like relay.
- RE: My experiences with MySensors
@boozz
I am not user "roadman", but I am using MySensors and ESP8266 ( Wemos) so hopefully I can answer some of your questions.
I am using only one wifi access point (AP or router) in my home without problems.
But you can use one AP for your computers and TV and etc. and other for your sensors.
AP hw is cheap....
My house is 8x12 meters and wifi AP is in 2nd floor about in center of house.
It covers the entire house and very close ( 3m )out of house.
Near this wifi AP is RFM69 MySensors gateway, which covers up to the edge of my property 60 meters away.
( may further )
MySensors is goot for nodes a far away in my garden and for nodes with low energy consumption and fast reaction when wake up.
When MySensors node is sleeping and then wake up, it immediately continues in program flow immediately from the place of "sleep" command.
Wemos, when sleeping an wake ups, reboots and must connect to AP, which takes 8s to 2s when we do some tweakings.
But Wemos is very user friendly.
You can use some "ready use" solutions like ESPeasy or Tasmota and configure your node trough its web page.
Configure means select which sensor connect to which pin, send value to which contrtoller etc.
Write some programs or scripts:
All without the need to compile a new program.
And you can send to your controller what you want, not just what is implemented in MySensors.
( Using JSON API in my case with Domoticz )
And your controller can send anything to your node.
And for "MESH" topology.
Arduino "painlessMesh" library for ESPs exists.
But I think it is more easier to use more AP units - they are cheap ....
- RE: Graphing of time measured events - Solved
Domoticz has a nice dummy counter or dummy incremental counter, where you can enter the unit quantity.
MySensors unfortunately is unable to send data to these counters.
I am using them with ESP8266 to send energy consumption of my floor heating or number of actions of my relays.
So I recommend to use DzVents scripts in Domoticz instead of node-red.
I see two ways.
1.
Send from node for example in watts or m3 or litters.
With DzVents translate this value to time in minutes in Domoticz created dummy counter.
Write DzVents script for your switch, which saves time for ON action and when OFF action occurs, calculate time interval and adds minutes to dummy counter.
Then you can see the beautiful statistics for each day of the entire year back and the actual total value too.
For example here for my relay actions:
( "zapnuti" = "relay on" )
- RE: HM-TRP Gateway
It is 6 bytes sliding window which is filled from end and compared for correct byte order.
Here is _header loaded with data:
_header[5] = inch
Maybe this helps:
- RE: Door sensor with wifi
@jurimetrics
Yes, good battery life time, but not good response time.
You open the door and receive message about it after couple of seconds.
With Arduino and rfm69 or NRF24 it is much better.
- RE: HM-TRP Gateway
@chanky said in HM-TRP Gateway:
HM-TRP transceiver
Look at "MyTransportRS485.cpp and try adapt for your module which has serial communication too.
Initialize your module in "bool transportInit(void)" ?
And etc.
A lot of work .....
- RE: Door sensor with wifi
With battery powered sleeping wifi device will be always delay after door switch sensor action and message sending.
Find AP, connect to it etc.
Couple od seconds.
Maybe good for alarm, but not for switch light.
-
- RE: SerialGateway problem with install.
- RE: SerialGateway problem with install.
- RE: Node not working after adding some wires and a capacitor
Your NRF is 2.4GHz. Your Wemos and home WiFi network is 2.4GHz too.
Maybe your WiFi router randomly switch wifi channels to the chanel of your NRF network.
Try set fixed channel on your router.
- RE: ENC28J60 Ethernet gateway
ENC28J60 for a stable gateway is not a good idea.
Buy some Wiznet...
- RE: 💬 RS485 Ethernet Gateway.
- RE: How can I monitor the humidity of a wall (house)
@pierrot10
And what about using normal soil moisture sensor and replace its pcb electrodes with something tougher.
Stainless steel nail knocked into wall or drill hole and put carbon rod from disassembled AA battery into it.
And experiment with electrode distance.
- RE: Mysensor usb gateway serial problem
?
- RE: ESP8266 Gateway with AP mode instead of hardcoded ssid etc
But if you move ( or sold ) your gateway to different network, what seems as reason for selecting SSID and password,
you still need recompile your code due to different IP of your controller.
-
- RE: best solution to monitor and log power usage
Some Sonoff switching devices has got power metering.
Upload ESPeasy or Tasmota firmware and connect with HA....
- RE: Encryption with RFM69 [solved]
#define MY_RFM69_ENABLE_ENCRYPTION
All nodes and gateway must have this enabled, and all must be personalized with the same AES key.
You need a helper-sketch specifically for this purpose
- SecurityPersonalizer.ino
- RE: Getting started with Wemos d1 mini & RFM69HW
Why you are using Wemos like normal node with RFM radio?
I assume you are building ethernet gateway with Wemos and RFM69.
Simply use my sketch fot gateway and your uno like node and try.
- RE: Getting started with Wemos d1 mini & RFM69HW
For your setup:
( change frequency and HW version)
#define MY_RADIO_RFM69 )
With this setup and GW sketch from MySensors examples I am running this GW almost year without problem.
On Wemos D1
// }```
- RE: Water meter : grey scale sensor
And why you do not remove a half of plastic cover above rotating sensor wheel to put sensor closer?
- RE: Reset values measured by Power Meter Pulse? posted in Domoticz
- RE: Newbie RFM69 MQTT Gateway !TSM:INIT:TSP FAIL posted in Troubleshooting
- RE: What did you build today (Pictures) ?
@zboblamont said in What did you build today (Pictures) ?:
umbillicals
It is rubber hoses with metal braiding.
But rubber degrades and this equipment is the most common cause of water leakage.
- RE: What did you build today (Pictures) ? .....
-
- RE: 💬 Battery Powered Sensors
@tiana
Forever sleeping door sensor with low battery?
"when last massage is send the node will never power the radio module"
Why door sensor, if it never sends message?
- RE: 💬 Battery Powered Sensors posted in Announcements
- RE: 💬 Battery Powered Sensors
.
- RE: Pls Help: Sensor value shows in Domoticz Hardware TAB, but wont show on Switches
@eme
I am not sure if Domoticz can know, what you want.
I am not MySensors expert, but there are some weird things in your code:
#define CHILD_ID 0 MyMessage msgNEPA(0, V_STATUS); MyMessage msg(CHILD_ID, V_STATUS);
msg and msgNEPA are identical, but you use it in different ways ....
MyMessage msgTank1(1, V_VOLUME);
For CHILD ID 1 type of message V_VOLUME, but in loop:
for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) { // Register all sensors to gw (they will be created as child devices) present(sensor, S_BINARY); pinMode(pin, OUTPUT); // Then set relay pins in output mode savedState = loadState(pin); // Set relay to last known state (using eeprom storage) digitalWrite(pin, savedState?RELAY_ON:RELAY_OFF); DEBUG_PRINT(F("Presented Relay st : ")); DEBUG_PRINTLN(F(pin)); send(msg.set(savedState? 0 : 1)); }
You present CHILID ID 1 like S_BINARY
And then you set to this binary sensor volume value:
send(msgTank1.set(tank_level("liters")));
And in the same presentation loop you send value only to child id 0, because msg.set send to ID 0
- RE: What would you use this board for?! posted in Hardware
- RE: No working window appaers after start.
mosquitto -v #start in verbose mode
If your mosquito is already running, you cannot start it again.
First stop it:
sudo service mosquitto stop sudo systemctl stop mosquitto.service
And then try your:
mosquitto -v
- RE: No working window appaers after start.
@mslv129jdg said in No working window appaers after start.:
Error: Address already in use
I do not use Mosquito, but maybe it is already running automatically after RPI starts?
- RE: ds18b20 on 2xAAA battery
@pihome
said in ds18b20 on 2xAAA battery:
i wanted to ask what others are doing and how they are managing voltage for voltage hungry sensors
One useful "switch" you have got on your PRO MINI.
My from ebay has got LDO marked LG33, which is MIC5219 LDO with shutdown pin capability.
So remove one from arduino hacked for ultra low consumption and use it for switch power hungry sensors.
Or only unsolder and bend up from pcb output and shutdown pin of LDO.
Then you can use 3AAA to power directly VCC ( 4.5V ). Connect this to RAW pin ( input LDO ) too.
Your sensors connect to unsoldered LDO output pin and shutdown pin connect with some output IO to drive your sensors ON/OFF.
Problem can be, that sensors run on 3.3V and your Arduino runs on 4.5V.
So you can put some diodes in series between battery and Vcc pin. Each diode ( not LED ) drops about 0.6V ( try different diodes ).
Another interesting idea with this LDO can be seen here:
- RE: Problems with the neighbours
@stevanov
It seems, that both of you use MySensors in "outofbox" state.
You do not write which radio module are using.
If RFM69 - change netwotk ID, with NRF24 change channel or network ID
Somewhere in config files.
MyConfig.h
#define MY_RF24_CHANNEL (76) /** * @def MY_RF24_BASE_RADIO_ID * @brief RF24 radio network identifier. * * This acts as base value for sensor nodeId addresses. Change this (or channel) if you have more * than one sensor network. */ #ifndef MY_RF24_BASE_RADIO_ID #define MY_RF24_BASE_RADIO_ID 0x00,0xFC,0xE1,0xA8,0xA8 #endif /** * @def MY_RFM69_NETWORKID * @brief RFM69 Network ID. Use the same for all nodes that will talk to each other. */ #ifndef MY_RFM69_NETWORKID #define MY_RFM69_NETWORKID (100) #endif
Of course you must reprogram all nodes and gateway :o(
Or talk with your neighbours and ask them using different network ID if they only starting building their network and have got smaller number of sensors.
- RE: ds18b20 on 2xAAA battery
@pihome
very power hungry (Quiescent current 13uA) ?
And do you know, that with AAA (1000 mAh) it is 8 years in standby?
Maybe self discharge is greater.
Alternetively use 3xAAA with low quiescent current 3.3V LDO.
- RE: Want Wired Ethernet For All Sensor Nodes / Gateway
Sorry, but if you have got ethernet on each node, why using MS gateway? Simple use pure MQTT and publish to the broker. You only need MQTT library, not all MySensors in this case.
- RE: Battery Tank level node and Openhab
I do not know openhab, but in Domoticz this info ( battery and radio level ) I can see only in all devices list tab. Not like special sensor.
- RE: Lux sensor (BH1750) sending battery level (V)
@bgunnarb
But readVcc returns long; }```
- RE: Monitoring 2 x 18650 batteries
My way for monitoring battery.
Usually I have not got precise resistor with tolerance +-0.5% etc. for correct calculation, so I build resistor divider with what I approximately found.
Load my device with simple sketch, which reads data from ADC and write this raw ADC data to serial port.
I make notice, that for example 1009 corresponds to 6041mV with fresh battery measured with multimeter.
In my final sketch then using "magic" map Arduino function:
int raw_volt = analogRead(A1); int volt = map(raw_volt, 0, 1009, 0, 6041);
Not very useful for "mass production", but for my prototyping it is ok.
- RE: Nano minimum voltage
@bjacobse said in Nano minimum voltage:
Datasheet: The device operates between 1.8-5.5 volts.
and this means to bypass/remove the voltage regulator on the Nano board
But it do NOT means with 16Mhz crystal on Arduino Nano ...
- RE: Nano minimum voltage
Why "plus" 7805.
Nano has got voltage regulator on board.
Original Arduinos 7805 I think, clones LM1117 usually.
- RE: Never been able to get MySensors to work
Sorry, but you select most difficult way for build your sensor network.
You spare one arduino like serial gateway or one Wemos like ethernet wifi gateway and two years hacking RPI gateway with no result.
And you choose bad radio module too, I think. Instead of NRF24 use RFM69 and no more problems with distance in your home and mesh network function no needed.
For all beginners I recommended step by step solution of problems, if something do not works.
For example, first try simple communication between two modules using basic examples from RFM69 library for example.
If it works, you have got certainty, that your hardware is OK ( radio properly connected to arduino ).
Then you can load sketches for gateway and normal node to both modules and I bet, it will work.
- RE: 2 Arduinos using the one radio. Possible?
I think it is not very difficult sharing radio between two Arduinos.
But only for sending ...
Simply hold CS signal off for both Arduinos.
And connect both of them by signal, which tell each other if it is sending.
Other Arduino must wait for indication, that radio is free.
And radio initialisation only from one of them too.
- RE: I have an idea for a sensor
- RE: Atmega328P + RFM69HW(868) not working
Try my 100% working testing setup:
Wemos D1 any of the MY_DEFAULT_xx_LED_PINs in your sketch, only the LEDs that is defined is used. * - }
Node - motion sensor:
/** * // RFM69 #define MY_RADIO_RFM69 #define MY_IS_RFM69HW //#define MY_RFM69_NEW_DRIVER // ATC on RFM69 works only with the new driver (not compatible with old=default driver) // #define MY_NODE_ID 20 #include <MySensors.h> uint32_t() { pinMode(DIGITAL_INPUT_SENSOR, INPUT_PULLUP); // sets the motion sensor digital pin as input } void presentation() { // Send the sketch version information to the gateway and Controller sendSketchInfo("Motion Sensor 2", "1.0"); // Register all sensors to gw (they will be created as child devices) present(CHILD_ID, S_MOTION); } void loop() { // Read digital motion value bool); }
Antena - piece of wire on both sides.
Receiving distance - min 60m ( gateway at home, sensor in garden )
- RE: Can we increase the number of nodes from 254 to 1024 or more?
Do not forgot, that some radios ( RFM69 ) allow only 255 address in one network.
No way connect more nodes to all receiving all messages ...
- RE: Water leak sensor
IoT ESP8266 WiFi Tutorial - Water Leak/Flood/Rain Detector! Push Notification from trigBoard! – 06:43
— Kevin Darrah
IoT ESP8266 WiFi Tutorial - Water Leak/Flood/Rain Detector! Push Notification from trigBoard! – 06:43
— Kevin Darrah
- RE: Solar powered node, that should only send occasionally ...
- RE: WakeOnLan over nrf24 radio posted in Development
- RE: Ideal Sensor read interval
It depends on type of your radio module too. With 868Mhz modules you can transmit for example only 1 percent of time per hour. ( In our country )
So if you send every minute, your transmit time can be max 0.6 sec.
- RE: help with serial gateway on raspberry pi
@fernando-alvarez-buylla
I think you only need define your gateway in Domoticz.
That Is all.
- RE: Failed to make encryption work on a barebone ATMEGA328P
@encrypt
I am not sure, if we speak about the same AES key.
I mean encryption key for RFM69 chip, because you select using encryption by this radio in your network.
But I am on my mobile only, so it is dificult study source codes Now.
- RE: Failed to make encryption work on a barebone ATMEGA328P posted in Troubleshooting
- RE: Pan Tilt stepper motors
When you switch off power for servos, they will stay in last position. And they have got a gear so not too easy self moving like single steppers.
And pan tilt kits are very cheap.
- RE: RF Nano = Nano + NRF24, for just $3,50 on Aliexpress
@alowhum
For me top user friendly is ESPeasy.
Through web interface selecting which sensors on which pins connected and to which controller send data.
When user become more experienced, he can use rules to write some "programs".
No recompilation needed.
But not useful for battery powered nodes which needs receive some data.
- RE: Pan Tilt stepper motors
And what kit with stepper motors? Or you mean servo motors ?
- RE: Female-female header connectors?
You realy think, that it Is useful fór connecting two male connectors together, what way asked?
- RE: DHT and DOOR sensor
@terence-faul
comment step by step blocks of code for DOOR switch and try when it start to work.
- RE: Using an 802.11g wifi transport
If you plan using ESP chips or Raspberry as your sensors node, I think better way is ESPeasy or similar sw for ESPs.
- RE: 💬 MyThermostat.
-
- RE: How to protect rain sensor from oxidation?
Piezo detector exists for detecting the impact of the drop.
- RE: 💬 RS485 MCU Module
It is a very interesting board for RS485 applications (modbus etc.).
But not quite right for Mysensors serial bus. RS485 is not designed for multimaster bus.
CAN bus drivers are most preferable.
- RE: Combined electricity, gas and water use sensor
You are probably the exception that you have electricity, gas and water gauges side by side and you can read them with one device.
- RE: WAF in jeopardy today
@dbemowsk
Yes, sometimes it got USB1 instead of USB0.
You can create fix symlink for your USBtoSerial adapter and then write for example ttySonoff and allways will be right.
- RE: Thanks to all
@fernando-alvarez-buylla
ESP with Tasmota or ESPeasy is good solution for sensors where power is available. But if you must use battery, you must find something different. And then MySensors with RFM69 radio (not your 2.4GHz NRF24L01 ) can be good choice. It has a lot of better distance on 848 or 433MHz.
- RE: Problem with sensors on arduino and domoticz
@hyperflemme
Use gateway sketch and add sensor presentation and sensor data sending like in node sketch.
example from this forum:
void presentation() { // Present locally attached sensors here // Send the sketch version information to the gateway and Controller sendSketchInfo("AWI_ESP 120", "1.0"); // Register all sensors to gw (they will be created as child devices) present(CHILD_ID, S_DIMMER, "AWI_ESP 120" " dimmer"); present(CHILD_ID2, S_INFO, "AWI_ESP 120" " text"); } void loop() { // Send locally attached sensors data here send(msg.set(messageCounter)); // Send message to gw messageCounter = ++messageCounter % 100 ; // wrap send(msg2.set("Hallo")); // Send message to gw // Send update every SLEEP_TIME wait(SLEEP_TIME) ; } void receive(const MyMessage &message) { // messages from node or controller //char printBuf[40] ; //Serial.print(message.getInt()); //sprintf(printBuf, "Message node: %d %d OK\n", message.sender, message.getInt()); } //Serial.print(printBuf) ; //sprintf(printBuf, "Messages: %d Errors: %d\n", messageCounter, messageErrorCounter); //Serial.print(printBuf) ;
- RE: WAF in jeopardy today
You must install esptool:
or
Attention, there are some dependencies...
Then normally go to folder where .bin file is placed and run command:
esptool.py --port /dev/ttyUSB0 --baud 115200 write_flash 0x00000 ESP_Easy_v2.0-20180322_normal_ESP8285_1024.bin
or
python esptool.py .........................
not ./esptool.py
But I suggest first try :
esptool.py --port /dev/ttyUSB0 flash_id
To check if every is OK ( port, etc )
- RE: Problem with sensors on arduino and domoticz
I think we still do not know the topology of your network and we use different terms.
For most of us a "sensor" is - temperature sensor, humidity sensor, pressure sensor, etc. These sensors are connected to Arduino, which we call the "node".
These node are connected through radio or RS485 to Arduino which works like gateway and send received messages from nodes to controller ( Rpi with Domoticz ).
Usually gateway have got no sensors and you can use pure gateway sketch from examples.
But you can connect sensors directly to gateway, but you must modify gateway sketch then.
- setup your sensors
- present your sensors
- send values form your sensors.
And of course NO SLEEP FUNCTION in sensor send code.
Places, where put it is marked by comments in gateway sketch:
void setup() { // Setup locally attached sensors } void presentation() { // Present locally attached sensors } void loop() { // Send locally attached sensor data here }
Usual topology:
I think your topology:
- RE: WAF in jeopardy today
@dbemowsk
It is from here:
I connect it like you wrote.
- RE: RS485 & SoftwareSerial
@paweld
And must you really use SoftwareSerial and not AltSoftSerial, which is default for MySensors RS485 link layer?
You do not need include SoftwareSerial in your sketch then.
- RE: WAF in jeopardy today
@dbemowsk
I have 12 of these new and working without any problems.
There is a missing gpio14 pin, where I connected the DS18B20, but I used the RX pin instead.
PCB design is more solid to me - you can even see the power fuse.
ESPeasy flashing without problem using esptool.
My way to program new Sonoffs:
To check comunication:
esptool.py --port /dev/ttyUSB0 flash_id
Erase flash:
esptool.py --port /dev/ttyUSB0 erase_flash
Program ESPeasy bin:
esptool.py --port /dev/ttyUSB0 --baud 115200 write_flash 0x00000 ESP_Easy_v2.0-20180322_normal_ESP8285_1024.bin
Look here:
- RE: RS485 & SoftwareSerial.
- RE: WAF in jeopardy today
Can you connect to Sonoffs web pages?
Or can you see its SSID if they are in AP mode?
My Sonoffs Basic is switched off four times per every day and works like charm.
No DHCP, fixed IP, Domoticz. It is the most stable part of my sensors network.
It Is not probable, that all of yours are bad.
It must je different problem.
- RE: Problem with sensors on arduino and domoticz
@hyperflemme
Than in your second sketch ( with sensors )
define MY_GATEWAY_SERIAL
is missing.
This sketch works like normal node without this, not as gateway with sensors connected.
- RE: 433mhz chinese burglar alarm and openHAB
I am not using OpenHAB but Domoticz.
But I think, that RFLink or RFXCom will help you with OpenHAB top.
- RE: Determine if pin interupt or awakens from sleep
Create a global variable and set to 0.
In the interrupt handler subroutine, set it to 1.
Check its status in the main program to determine if an interruption has occurred.
if (my_global_variable == 1) my_global_variable = 0; {do this} / Action if an interrupt has occurred if (awkens from sleep) {do that}```
- RE: Need some help with this sensor setup for RF remote
RFLink to your controller plus 4 button RF senders from ebay.
- RE: Problem with sensors on arduino and domoticz
Do you connect your sensor to the same mega2560 which works like serial gateway or are you using different mega2560 connected through radio to serial gateway mega2560?
- RE: [SOLVED] Puzzle over water meter .sensor
.
- RE: [SOLVED] Puzzle over water meter .sensor
Arduino 3V at 16MHz is out of specification. You cannot be surprised by no standart behavior.
- RE: 2 dallas temp + 4 relays
For low number of DS18B20 and if you have got enough free pins,
I suggest use separate Arduino pin for each DS18B20.
Then your code is absolute universal and you always know, which pin what measure.
Do not matter, which DS18B20 you use.
With your method, you must read each DS18B20 signature - hardcoded it, compile and flash.
When sensor needs replacement due to malfunction - whole process again.
- RE: Sensor required to detect PVC insulated COPPER wire
@hard-shovel
But mesh is on other direction too - parallel with movement and sure not still at the same position and pure parallel.
So digital signal can be generated longer time than you expected.
|
https://forum.mysensors.org/user/kimot/posts
|
CC-MAIN-2022-05
|
refinedweb
| 4,629
| 65.22
|
To begin with, let's start building an extremely simplistic bandit algorithm. The actual bandit class will have two methods:
choose_treatment and
log_payout. The first method will recommend the best treatment to choose, and
log_payout will be used to report back on how effective the recommended treatment was.
The simplest way to approach this algorithm from a test-driven perspective is to start with a single treatment so that the algorithm only has one thing to recommend. The code for this test looks like the following:
from nose.tools import assert_equal import simple_bandit def given_a_single_treatment_test(): bandit = simple_bandit.SimpleBandit(['A']) chosen_treatment = bandit.choose_treatment() assert_equal(chosen_treatment, ...
No credit card required
|
https://www.oreilly.com/library/view/test-driven-machine-learning/9781784399085/ch03s03.html
|
CC-MAIN-2019-26
|
refinedweb
| 108
| 50.23
|
In the future, I hope to update this post to also include a complete list of steps for getting setup with python’s webpy over lighttpd.
1. Install web.py
1.1. Install webpy with apt-get
sudo apt-get install python-webpy
1.2. Install webpy using easy_install using python setuptools
1.2.1. Install python setuptools (easy_install)
# 1.2.1.1. Using apt-get:
sudo apt-get install python-setuptools
# 1.2.1.2. Manually retrieving easy_install from the web using wget
wget
sudo python ez_setup.py
# 1.2.2. Now get the web.py egg using python’s easy_install
# This will put the python ‘web’ module in your python environment path
sudo easy_install web.py
1.3. Install webpy straight from git
# Or, get webpy straight from git
git clone git://github.com/webpy/webpy.git ln -s `pwd`/webpy/web .
2. Write Your Web.py App
Choose a directory where you would like your web.py python application to live. If my username is ‘mek’ and I want to name my project ‘project’, I might make a directory /home/sajee/project.
2.1. Make a directory for your web.py app to live
# Replace the word project in the path below with your desired project name
mkdir ~/project
cd ~/project # move into the project directory you have created
2.2. Create your application file using web.py
# this will create our application file ~/project/main.py
touch main.py
2.3. Open your application with your favourite editor
# Substitute “emacs -nw” with an editor of your choice: vim, nano, etc
emacs -nw main.py
2.4. Paste the following in your app file and save
import web
app_path = os.path.dirname(__file__)
sys.path.append(app_path)
if app_path: # Apache
os.chdir(app_path)
else: # CherryPy
app_path = os.getcwd()
urls = (
‘/(.*)’, ‘hello’
)
# WARNING
# web.debug = True and autoreload = True
# can mess up your session: I’ve personally experienced it
web.debug = False # You may wish to place this in a config file
app = web.application(urls, globals(), autoreload=False)
application = app.wsgifunc() # needed for running with apache as wsgi
class hello:
def GET(self, name):
if not name:
name = ‘World’
return ‘Hello, ‘ + name + ‘!’
if __name__ == “__main__”:
app.run()
2.4. (Optional) Setup static directory for imgs, css, js, etc
# Having a static directory allows you to serve static content without
# your webpy application trying to steal focus and parse the request
# This is especially important using the default CherryPy server.
# We’ll also handle this case in our apache config within:
# /etc/apache2/sites-available
mkdir ~/project/static
3. Install Apache2
3.1. Install apache and wsgi dependencies
sudo aptitude install apache2 apache2.2-common apache2-mpm-prefork apache2-utils libexpat1 ssl-cer
# I like to also install python-dev (optional) to make sure I have
# python’s latest support files
sudo apt-get install python-dev
3.2. Install apache mod_wsgi and enable mod_wsgi + mod_rewrite
sudo aptitude install libapache2-mod-wsgi
sudo a2enmod mod-wsgi;sudo a2enmod rewrite
Need help troubleshooting your apache/mod_wsgi installation?
4. Configure Apache2 With Your App
In the following steps, replace ‘project’ with the name of your project
4.1. Make Apache Directories for your project
sudo mkdir /var/www/project
sudo mkdir /var/www/project/production
sudo mkdir /var/www/project/logs
sudo mkdir /var/www/project/public_html
4.2. Create Symlinks
Creating symlinks to your project files is an important covention as, if there is a problem with one of your code bases, you can simply change your symlink to a stable codebase without having to modify your apache configuration.
ln -s ~/project/ production
ln -s ~/project/static public_html # If you created the static directory in step 2.4.
4.3. Replace you /etc/apache2/sites-available/default with:
ServerAdmin admin@project.com
DocumentRoot /var/www/project.com/public_html/
ErrorLog /var/www/project.com/logs/error.log
CustomLog /var/www/project.com/logs/access.log combined
WSGIScriptAlias / /var/www/project.com/production/main.py
Alias /static /var/www/project.com/public_html
AddType text/html .py
WSGIDaemonProcess www-data threads=15
WSGIProcessGroup www-data
Order deny,allow
Allow from all
Options +FollowSymLinks
Options -Indexes
4.4. Change the group and owner of files requiring write access to apache’s www-data
Careful in this step to only change the group and owner of directories or files that will require write access.
sudo chgrp -R www-data
sudo chown -R www-data
5.Try to run!
sudo /etc/init.d/apache2 restart # Open your browser and visit the url: or 127.0.01
You will see Hello World on the browser.
One thought on “Complete Tutorial: Webpy + Apache + mod_wsgi on Ubuntu”
Thank you for sharing. However, some additional clarifications are essential.
1) What is the exact name of the file to be replaced in /etc/apache2/sites-available/default? (under /etc/apache2/sites-available/ , there are two files: 000-default.conf and default-ssl.conf)
2) How ‘project’ directory (folder) would become ‘project.com’ stated in the replacement file?
3) Where is www-data? When I do your commands, the error says: missing operand after ‘www-data’
You must log in to post a comment.
|
https://sajeetharan.com/2016/11/29/complete-tutorial-webpy-apache-mod_wsgi-on-ubuntu/
|
CC-MAIN-2021-04
|
refinedweb
| 862
| 51.44
|
Hello World — React native
What is React Native?.
Let’s Start
I have Node v8 installed and I assume you have already installed Node.js
In this blog I am going to use Expo to create new React Native project
Expo is a free and open source toolchain built around React Native to help you to build native iOS and Android projects using JavaScript and React.
Since you have already installed Node.js, use npm command to install Expo CLI
npm install -g expo-cli
Now you can use
expo init to create new React Native Project
expo init helloWorld
Then you can choose a template
If you want a project with screen navigation, chose tabs option. Since we are creating simple hello world app in this blog, I am going to use blank option.
To start development server, move to project folder and execute npm start.
cd helloWorld
npm start
Then the server starts and you can see QR code in both browser and terminal
How to Run on Actual Device
To run this application on actual device, First you have to download the Expo app from Google Play Store or App Store (depends on your device)
Next important thing is to make sure your mobile is connected to the same Network as your computer.
Then, open Expo app and scan QR code in your terminal or browser. Now, you can see your app running on the device.
Hello world App
Now, Let’s look at the code.
You can see in the project, you have app.json file. You can find all the configurations related to app in there, such as app name, sdk version, icon etc..
And there is package.json file with list of dependencies for the app.
Then you have App.js. It is the starting point of your app. You can see render method there, it has
View component which is used to wrap the
Text component.
In the bottom of App.js file you can see styles object, which defines the styles for your UI components. In react native, moving styles from render method improve the code readability. You can define different styles to different UI components.
Let’s remove the existing code in App.js and write following code to change the Hello World! text to Hello John! on a button click.
Remember to import Button from ‘react-native’
export default class App extends React.Component { constructor(props){ super(props); this.state = { name: 'World!', } } onClick = () => { this.setState({ name: 'John!', }) }; render() { return ( <View style={styles.container}> <Text>Hello {this.state.name}</Text> <Button
onPress={() => {this.onClick()}}
</Button> </View> ); }}const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, nameText: { fontSize: 50, padding: 15, }});
In the above code,
Text component will display the name in state. Initial value of
name in the state is World! and pressing Click me button will call onClick function which change the value of
name to John!.
In this code I added style nameText to
Text Component, which sets fontSize and add padding to the Text.
When it comes to
Button, React Native provides very limited options for that component. Button component renders the native button on the platform. Because of this, it does not have
style prop. It has its own set of props. So in order to change the button color I passed #4169E1 to color prop.
If you want more control on appearance, use TouchableOpacity instead of button.
I think you got basic idea about how to work with React Native. So, now you can try your first react native app.
You can find the code here:
References
What is the difference between React.js and React Native?
React is ideal for building dynamic, high performing, responsive UI for your web interfaces, while React Native is…
|
https://aihalapathirana.medium.com/hello-world-react-native-df14662a22c6
|
CC-MAIN-2021-39
|
refinedweb
| 633
| 75.81
|
SVN::Web - Subversion repository web frontend
If you are upgrading an existing SVN::Web installation then please see UPDATING.pod. Installing new SVN::Web versions without making sure the configuration file, templates, and localisations are properly updated and merged will likely break your current installation.
To get started with SVN::Web.
mkdir svnweb
svnweb-installin this directory to configure the environment.
cd svnweb svnweb-install
repos: test: '' should be the URL for an existing Subversion repository.
svnweb-serverto start a simple web server for testing.
svnweb-server
Note:
svnweb-server requires HTTP::Server::Simple to run, which is not a requirement of SVN::Web. You may have to install HTTP::Server::Simple first.
svnweb-serverthen this is.
See for the SVN::Web source code, browsed using SVN::Web.
SVN::Web provides a web interface to subversion repositories. It's features include:) or that are remotely accessible using the
svn://schemes.
Reported in: t#1234
then SVN::Web can turn
t#1234 in to a link to that ticket. SVN::Web can also be configured to recognise e-mail addresses, URLs, and anything else you wish to make clickable.
Additional actions can easily be added to the base set supported by the core of SVN::Web.
Various aspects of SVN::Web's behaviour can be controlled through the configuration file config.yaml. See the
YAML documentation for information about writing YAML format files.
SVN::Web's configuration file must contain a version number. If this number is missing, or does not match the version number of the version of SVN::Web that is being used then a fatal error will occur.
version: 0.53
SVN::Web can show information from one or more Subversion repositories. These repositories do not have to be located on the same server.
Repositories are specified as a hash items under the
repos key. Each key is the repository name (defined by you), the value is the repository's URL.
The three types of repository are specified like so.
repos: my_local_repo: '' my_http_repo: '' my_svn_repo: 'svn://hostname/path'
You may list as many repositories as you need.
For backwards compatibility, if a repository URL is specified without a scheme, and starts with a
/ then the scheme is assumed. So
repos: my_local_repo: /path/to/local/repo
is also valid.
If you have multiple repositories that are all under a single parent directory then use
reposparent.
reposparent: '/path/to/parent/directory'
If you set
reposparent then you can selectively block certain repositories from being browseable by specifying the
block setting.
block: - 'first_subdir_to_block' - 'second_subdir_to_block'
repos and
reposparent are mutually exclusive.
SVN::Web's output is entirely template driven. SVN::Web ships with a number of different template styles, installed in to the templates/ subdirectory of wherever you ran
svnweb-install.
The default templates are installed in templates/trac. These implement a look and feel similar to the Trac () output.
To change to another set, use the
templatedirs configuration directive.
For example, to use a set of templates that implement a much plainer look and feel:
templatedirs: - 'template/plain'
Alternatively, if you have your own templates elsewhere you can specify a full path to the templates.
templatedirs: - '/full/path/to/template/directory'
You can specify more than one directory in this list, and templates will be searched for in each directory in turn. This makes it possible for actions that are not part of the core SVN::Web to ship their own templates, and for you to override specific templates of your choice.
For example, if an action is using a template called
view, and
templatedirs is configured like so:
templatedirs: - '/my/local/templates' - '/templates/that/ship/with/svn-web'
then /my/local/templates/view will first by checked. If it exists the search terminates and it's used. If it does not exist then the search continues in /templates/that/ship/with/svn-web.
For more information about writing your own templates see "ACTIONS, SUBCLASSES, AND URLS".
SVN::Web's interface is fully localised and ships with a number of translations. The default web interface allows the user to choose from the available localisations at will, and the user's choice is saved in a cookie.
SVN::Web's localisation information is stored in files with names that take the form
language.po. SVN::Web ships with a number of localisations that are automatically installed with SVN::Web.
You can configure SVN::Web to search in additional directories for localisation files. There are typically three reasons for this.
Use the
language_dirs configuration to specify all the additional directories that SVN::Web should search. For example:
language_dirs: - /path/to/my/local/translation - /path/to/third/party/action/localisation
If files in more than one directory contain the same localisation key for the same language then the file in the directory that is listed last in this directive will be used.
languages specifies the localisations that are considered available. This is a hash. The keys are the basenames of available localisation files, the values are the language name as it should appear in the interface.
svnweb-install will have set this to a default value.
To find the available localisation files look in the po/ directory that was created in the directory in which you ran
svnweb-install, and in the directories listed in the
language_dirs directive (if any).
For example, the default (as of SVN::Web 0.48) is:
languages: en: English fr: Français zh_cn: Chinese (Simplified) zh_tw: Chinese (Traditional)
default_language, specifies the language to use if the user has not selected one. The value for this option should be one of the keys defined in
languages. For example;
default_language: fr
SVN::Web can use any module implementing the Cache::Cache interface to cache the data it retrieves from the repository. Since this data does not normally change this reduces the time it takes SVN::Web to generate results.
This cache is not enabled by default.
To enable the cache you must specify a class that implements a Cache::Cache interface. Cache::SizeAwareFileCache is a good choice.
cache: class: Cache::SizeAwareFileCache
The class' constructor may take various options. Specify those under the
opts key.
For example, Cache::SizeAwareFileCache supports (among others) options called
max_size,
cache_root, and
directory_umask. These could be configured like so:
# Use the SizeAwareFileCache. Place it under /var/tmp instead of # the default (/tmp), use a custom umask, and limit the cache size to # 1MB cache: class: Cache::SizeAwareFileCache opts: max_size: 1000000 cache_root: /var/tmp/svn-web-cache directory_umask: 077
Note: The
namespace option, if specified, is ignored, and is always set to the name of the repository being accessed.
Template Toolkit can cache the results of template processing to make future processing faster.
By default the cache is not enabled. Use
tt_compile_dir to enable it. Set this directive to the name of a directory where the UID that SVN::Web is being run as can create files.
For example:
tt_compile_dir: /var/tmp/tt-cache
A literal
. and the UID of the process running SVN::Web will be appended to this string to generate the final directory name. For example, if SVN::Web is being run under UID 80 then the final directory name is /var/tmp/tt-cache.80. Since the cached templates are always created with mode 0600 this ensures that different users running SVN::Web can not overwrite one another's cached templates.
This directive has no default value. If it is not defined then no caching will take place.
Many of the templates shipped with SVN::Web include log messages from the repository. It's likely that these log messages contain e-mail addresses, links to other web sites, and other rich information.
The Template::Toolkit makes it possible to filter these messages through one or more plugins and/or filters that can recognise these and insert additional markup to make them active.
In SVN::Web this is accomplished using a Template::Toolkit MACRO called
log_msg. The trac templates define this in a template called _log_msg, which is included in the relevant templates by this line:
[% PROCESS _log_msg %]
You may redefine this macro yourself to filter log messages through additional plugins depending on your requirements. As a MACRO this also has access to the template's variables, allowing you to easily specify different filters depending on the values of different variables (perhaps per-repository, or per-author filtering). See the _log_msg template included with this distribution for more details.
There are a number of places in the web interface where SVN::Web will display a timestamp from Subversion.
Internally, Subversion stores times in UTC. You may wish to show them in your local timezone (or some other timezone). You may also wish to change the formatting of the timestamp.
To do this use the
timezone and
timedate_format configuration options.
timezone takes one of three settings.
localthen SVN::Web will adjust all timestamps to the web server's local timezone (which may not be the same timezone as the server that hosts the repository).
BSTor
EST, then SVN::Web will adjust all timestamps to that timezone.
When displaying timestamps SVN::Web uses the POSIX
strftime() function. You can change the format string that is provided, thereby changing how the timestamp is formatted. Use the
timedate_format configuration directive for this.
The default value is:
timedate_format: '%Y/%m/%d %H:%M:%S'
Using this format, a quarter past one in the afternoon on the 15th of May 2006 would appear as:
2006/05/15 13:15:00
If instead that was:
timedate_format: '%a. %b %d, %l:%M%p'
then the same timestamp would appear as:
Mon. May 15, 1:15pm
Note that strftime(3) on different operating systems supports different format specifiers, so consult your system's strftime(3) manual page to see which specifiers are available.
Each action that SVN::Web can carry out is implemented as a class (see "ACTIONS, SUBCLASSES, AND URLS" for more). You can specify your own class for a particular action. This lets you implement your own actions, or override the behaviour of existing actions.
The complete list of actions is listed in the
actions configuration directive.
If you delete items from this list then the corresponding action becomes unavailable. For example, if you would like to prevent people from retrieving an RSS feed of changes, just delete the
- rss entry from the list.
To provide your own behaviour for standard actions just specify a different value for the
class key. For example, to specify your own class that implements the
view action;
actions: ... view: class: My::View::Class ...
If you wish to implement your own action, give the action a name, add it to the
actions list, and then specify the class that carries out the action.
For example, SVN::Web currently provides no action that generates ATOM feeds. If you implement this, you would write:
actions: ... atom: class: My::Class::That::Implements::Atom ...
Please feel free to submit any classes that implement additional functionality back to the maintainers, so that they can be included in the distribution.
Actions may have configurable options specified in config.yaml under the
opts key. Continuing the
annotate example, the action may be written to provide basic output by default, but feature a
verbose flag that you can enable globally. That would be configured like so:
actions: ... annotate: class: My::Class::That::Implements::Annotate opts: verbose: 1 ...
The documentation for each action should explain in more detail how it should be configured. See SVN::Web::action for more information about writing actions.
If an action is listed in
actions and there is no corresponding
class directive then SVN::Web takes the action name, converts the first character to uppercase, and then looks for an
SVN::Web::<Action> package.
In the user interface the
action menu is a list of actions that are valid in the current context. This menu is built up programmatically from additional metadata about each action included in the config file.
The metadata is written as a hash, with each key corresponding to a particular piece of metadata. The hash is rooted at the
action_menu key.
A worked example may prove instructive. Here is the default entry for SVN::Web::RSS. This shows all the valid keys under
action_menu.
rss: class: SVN::Web::RSS action_menu: show: - file - directory link_text: (rss) head_only: 1 icon: /css/trac/feed-icon-16x16.png
The keys, and their meanings, are:
The contexts in which this action should appear in the action menu. Each SVN::Web action produces a result in a particular context. The valid contexts are:
The action is acting on a single file. E.g., SVN::Web::View or SVN::Web::Blame.
The action is acting on a single directory. E.g., SVN::Web::Browse.
The action is acting on a single revision. E.g., SVN::Web::Revision.
Valid values are any of the three items above, plus the special value
global, indicating that the action should always appear in the action menu.
In this example, the
rss action is available when browsing directories and viewing files. It makes no sense to make the RSS action available when browsing an individual revision, so that is not listed as a valid context.
The text that should appear in the action menu for this item. This text is passed through the localisation system.
A boolean that indicates whether the action is always available in the listed contexts, or whether it should only appear when viewing the HEAD revision in a particular context.
In this example it makes no sense to clamp the RSS feed to a particular revision, so it is flagged as only being available when looking at the HEAD of a file or directory.
The (relative) path to the icon to use for this menu item (if any).
For comparison, this is the recommended setting for SVN::Web::Checkout.
This action is only valid when viewing files -- checking out a directory does not make sense. A file can be checked out at any revision, so
head_only can be omitted (
head_only: 0 would have the same effect). And there is no icon for this action.
For details of how this information is used see the template/trac/_action_menu template.
The
action_menu metadata is optional. Some actions might not merit a menu option (e.g.,
diff or
revision), so those actions should not have
action_menu metadata.
SVN::Web can use a custom CGI class. By default SVN::Web will use CGI::Fast if it is installed, and fallback to using CGI otherwise.
Of course, if you have your own class that implements the CGI interface you may specify it here too.
cgi_class: 'My::CGI::Subclass'
SVN::Web URLs are broken down in to four components.
.../index.cgi/<repo>/<action>/<path>?<arguments>
or
.../apache-handler/<repo>/<action>/<path>?<arguments>
The repository the action will be performed on. SVN::Web can be configured to operate on multiple Subversion repositories.
The action that will be run.
The path within the <repository> that the action is performed on.
Any arguments that control the behaviour of the action.
Each action is implemented as a Perl module. By convention, each module carries out whatever processing is required by the action, and returns a reference to a hash of data that is used to fill out a
Template::Toolkit template that displays the action's results.
The standard actions, and the Perl modules that implement them, are:
Shows the blame (also called annotation) information for a file. On a per line basis it shows the revision in which that line was last changed and the user that committed the change.
Shows the files and directories in a given repository path. This is the default command if no path is specified in the URL.
Returns the raw data for the file at a given repository path and revision.
Shows the difference between two revisions of the same file.
Lists the available Subversion repositories. This is the default command if no repository is specified in the URL.
Shows log information (commit messages) for a given repository path.
Shows information about a specific repository revision.
Generates an RSS feed of changes to the repository path.
Shows the commit message and file contents for a specific repository path and revision.
See the documentation for each of these modules for more information about the data that they provide to each template, and for information about customising the templates used for each module.
This section explains how to configure some common webservers to run SVN::Web. In all cases,
/path/to/svnweb in the examples is the directory you ran
svnweb-install in, and contains config.yaml.
If you've configured a web server that isn't listed here for SVN::Web, please send in the instructions so they can be included in a future release.
svnweb-server is a simple web server that runs SVN::Web, and is included and installed by this module. It may be all you need to productively use SVN::Web without needing to install a larger server. To use it, run:
svnweb-server --root /path/to/svnweb
See
perldoc svnweb-server for details about additional options you can use.
Apache must be configured to support CGI scripts in the directory in which you ran
svnweb-install
<Directory /path/to/svnweb> Options All ExecCGI <:
You can use mod_perl or mod_perl2 with SVN::Web. You must install Apache::Request (for mod_perl) or Apache2::Request (for mod_perl2) to enable this support.
The following Apache configuration is suitable.
<Directory /path/to/svnweb> AllowOverride None Options None SetHandler perl-script PerlHandler SVN::Web </Directory> <Directory /path/to/svnweb/css> SetHandler default-handler <:
SVN::Web works with Apache and FastCGI. The following Apache configuration is suitable.
FastCgiServer /path/to/svnweb/index.cgi ScriptAlias /svnweb /path/to/svnweb/index.cgi Alias /svnweb/css /path/to/svnweb/css <Directory /path/to/svnweb/css> SetHandler default-handler </Directory>
SVN::Web works as a CGI script with IIS and Subversion on Windows servers.
After following the instructions in "SYNOPSIS", ensure that IIS makes the new svnweb directory available either as a directory or a virtual host.
Using IIS Manager:
There is a mailing list for SVN::Web users and developers. The address is svnweb@ngo.org.uk. To subscribe please visit.
SVN::Web::action, svnweb-install(1), svnweb-server(1)
Please report any bugs or feature requests to
bug-svn-web@rt.cpan.org, or through the web interface at. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
Chia-liang Kao
<clkao@clkao.org>
Nik Clayton
<nik@FreeBSD.org>
<clkao@clkao.org>.
<nik@FreeBSD.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/~nikc/SVN-Web/lib/SVN/Web.pm
|
crawl-002
|
refinedweb
| 3,122
| 56.96
|
-----
The graph above is generated by sending data from the PI to the sen.se API. Sen.se is one cool place. Their goal is to assist in internet connectivity of personal devices; "the internet of things". They have widgets, tools, applications, channels and a few other things that I barely understand. Play around with sen.se some and you will get the idea . In my application, I have sen.se graphing the core temperature of two Raspberry PIs; a data point every 60 seconds. Just for fun, I also keep track of the number of reading, calculate an average temperature, and display the temperature change since the last reading. Sen.se allows you to keep this information private or display it to the public.
----
So.... from the graph we see one PI is running about ~12F hotter than the other. Why?
Probably due to a few reasons:
RasPI_1 is always running the "motion" webcam software and functioning as an OpenVPN server. RasPI_1 is also in a fully enclosed case. (Maybe I should take it out of that case....)
RasPI_2 is not in a case on is only running my Hand of PI project. Hand of PI is a robot hand that you can control by sending twitter commands to it. Click for build page.
Of course, both PIs are running the temperature logging script.
-----
If you are still with me, the python source code is below. It has been running flawlessly for a while, so it should be solid. Occasionally Sen.se will go down briefly for maintenance, but that is why I put in the error traps. Good luck and tweet the Hand of PI to let us know you were here!!!
------
# whiskeytangohotel.com
# May 2013
# Python script to read RaspberryPI
# internal core temp, covert from C to F
# and log to sen.se for graphing.
# If you get errros on the import
# make certain you have the 'apts' installed
import httplib
import json as simplejson
from random import randint
import time
# init some vars
run_number = 0
tempC = 0
tempF = 0
# Enter your private sen.se API KEY in quotes. Enter the Feed ID# without quotes
SENSE_API_KEY = "x1xxxxxy2yyyyyyz3zzzz"
FEED_ID1 = 12345
# Function to format for sen.se
# The try/expect are there to trap errors if sen.se goes down
# or is slow. This keeps the script running.
def send_to_opensense()
conn.close()
except:
pass
while(True):
# The try/expect are there to trap errors if sen.se goes down
# or is slow. This keeps the script running
try:
# read the PI core temperture and store in tempC
# then convert from C to F and send the data to sen,se
tempC = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
tempF = (tempC * 1.8) + 32
run_number = run_number + 1
print "Run:", run_number, " tempC:", tempC, " tempF:",tempF
data = { 'F' : tempF}
send_to_opensense(data)
time.sleep(60)
except:
pass
-----
|
http://www.whiskeytangohotel.com/2013/05/
|
CC-MAIN-2019-47
|
refinedweb
| 476
| 76.11
|
Both projects require Boost 1.48 and the first one additionally requires the Google Testing Framework 1.6 to be installed. The first one
is more like a unit test where you naturally can see most features in action, while the second one is rather a simple test project which might be easier to understand!
This articles solves the Reflection issue for C++ enumerations, and especially the "enum class"es that come with C++11.
The Reflection issue describes the ability to do things like "Enumerate all values", "Enumerate member strings",
"Convert to/from string", "Safe casts from integer", and "Flags or so called Enum-Sets". Of course one could always
do that manually, but this comes at the cost of writing a lot of useless boilerplate and code that is hard to maintain. The framework I present
here is used in a large software project (mine), and will be updated regularly in case of bugs or whatever, if you or I report something...
There are already a lot of articles about this topic out there, but they all, without exception (at least not known to me),
don't fulfill the most important requirement for any large scale project. That is they require you to type enumeration members twice.
Some do even worse and require you using additional files for your enumerations or even utilize generators (that's about the worst it could get).
If we don't take that into consideration, additionally most of them suffer from at least one or more of the following:
So now let's take a look at how you can define a fully reflectable enum class with the framework described here:
PP_MACRO_ENUM_CLASS_EX(
(DemoEnum)(SubNamespace), // put in namespace "DemoEnum::SubNamespace"
EType_B, // typename
(e_0, 2),
(f_1, 8),
(g_2, 1),
(all, e_0 | f_1 | g_2),
(alias, f_1)
);
That's it. No additional code is required on your side and this is all the framework needs of you. I won't go into the details of the strange syntactical notion
that is required here. In the section "Behind the scenes", you will find some pointers on how to go on if you want to understand the foundation of this framework.
Note that there is also a less verbose shortcut, I will introduce below.
When only considering the generated type, using a C++11 compiler (otherwise it will look different), the above macro expands (among a lot of other stuff) to:
namespace DemoEnum {
namespace SubNamespace
{
enum class EType_B
{
e_0 = 2,
f_1 = 8,
g_2 = 1,
all = e_0 | f_1 | g_2,
alias = f_1,
};
}
}
Some may be worried about the "enum class". Yes, this is C++11 and not supported by Visual Studio 2010, but it will be in VS2011.
Additionally, if support for enum classes is not available, the framework will automatically pick a fallback (described later) which is more or less
compatible to enum classes and a good temporary workaround (the code you write does not need to be aware of the difference when you stick to some basic rules).
There is also a shortcut, which looks like this:
PP_MACRO_ENUM_CLASS(
(DemoEnum)(SubEx),
EType_A,
a_0, b_1, c_2, d_3
);
It does pretty much the same, except that it automatically assigns enumeration values, from zero to infinity, to your enumeration members.
This is exactly the same as C++ does it, where "a_0" would be set to zero, "b_1" to one, and so on. If you don't need custom values,
which is often the case, this shortcut will come in handy.
a_0
b_1
So what does this give us? Well, now you can use this fresh new type with a set of predefined enumeration support routines that come along with
the framework (TEnum denotes a template parameter which is on demand replaced by a proper enumeration type):
TEnum
// is the given integer value a valid enumeration member?
bool Enum::IsValid(int inProbableEnum);
// returns a string list with all member values for a specific enumeration
vector<TEnum> Enum::GetValues();
// returns a string list with all member identifiers for a specific enumeration
vector<string> Enum::GetNames();
// looks for the enum member identifier that maps
// to the given value and returns it string representation
string Enum::ToString(TEnum inEnum);
// Safely converts the given string to an enumeration
// value by member identifier lookup (case-insensitive).
// Throws "PP_MACRO_ENUM_ARG_EXCEPTION" if conversion fails.
TEnum Enum::FromString(string inString);
bool Enum::TryParse(string inProbableEnum, TEnum* outValue);
bool Enum::TryParse(int inProbableEnum, TEnum* outValue);
// Safely converts the given int to an enumeration value by member value lookup.
// Throws "PP_MACRO_ENUM_ARG_EXCEPTION" if conversion fails.
TEnum Enum::FromInt(int inProbableEnum);
And for flags:
// is the given integer value a valid flags value?
bool AreValid(int inProbableEnum);
// is the given flag "inFlagToCheck" set in "inFlags"?
bool IsSet(TEnum inFlags, TEnum inFlagToCheck);
// is any of the given flags "inFlagToCheck" set in "inFlags"?
bool IsAnySet(TEnum inFlags, TEnum inFlagsToCheck);
// are all the given flags "inFlagToCheck" set in "inFlags"?
bool AreAllSet(TEnum inFlags, TEnum inFlagsToCheck);
// returns a list of enumeration members that are set
// in "inFlags"? Useful for ToString() implementations...
vector<TEnum> Decompose(TEnum inFlags);
// returns a list of all valid flag values. Useful for FromString() implementations...
vector<TEnum> GetValues();
bool TryParse(int inProbableEnum, TEnum* outValue);
// Safely converts the given int to a flags value by member value lookup.
// Throws "PP_MACRO_ENUM_ARG_EXCEPTION" if conversion fails.
TEnum FromInt(int inProbableEnum);
Since enumerations are of fixed size, naturally the time complexity of all methods is O(1). But even if we want to be honest,
the practical constant is quite low, heavily depending on compiler optimizations. If not properly supported, especially the enumerative
routines could suffer considerable performance hit, which you still won't notice in most applications. If this is still a problem for you, either cache
the results or replace the enumerative containers with std::array. For the latter, you have to understand what's going on in the sources, though.
Maybe I will do that myself at some other time and post an update.
std::array
First let's look at how to include this framework in your code. I will assume a clean Visual Studio 2010 SP1 installation and a fresh new C++ console application project.
Now add the root directory of your boost 1.48 (lower versions might work as well) installation as an additional include path. Of course you will also
need access to the framework files that come with this project. These are:
#include "EnumFramework_Config.h"
#include "EnumFramework_Magic.h"
#include "EnumFramework_Custom.h"
The first one provides some general configuration (see section "Customization"). The second is the scary internal stuff you should not
manipulate unless you know what you are doing. The third one contains usual C++ code implementing the support routines. This is probably the most
interesting one if you want to customize this thing (see section "Modifying the Source Code"). You need to include some other dependencies,
before including the framework headers! If you setup the boost include directory properly, everything shall be alright and will look similar to this:
#include <stdio.h>
#include "include/gtest/gtest.h"
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <assert.h>
#include <boost/foreach.hpp>
#include <boost/unordered_map.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/../libs/unordered/examples/case_insensitive.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/tuple/to_list.hpp>
#include <boost/preprocessor/list/for_each.hpp>
#include <boost/preprocessor/facilities/empty.hpp>
#include <boost/preprocessor/facilities/expand.hpp>
#include <boost/preprocessor/selection/max.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/control/expr_if.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/logical/or.hpp>
#include "EnumFramework_Config.h"
#include "EnumFramework_Magic.h"
#include "EnumFramework_Custom.h"
Now you can start defining enums as you please.
Attention: One rule to keep in mind is that you shall always place the macros in the root namespace! Otherwise it won't work. For example:
namespace MyNamespace
{
PP_MACRO_ENUM_CLASS(
(DemoEnum)(SubEx),
EType_A,
a_0, b_1, c_2, d_3
);
}
won't place "EType_A" in the namespace "MyNamespace::DemoEnum::SubEx". Instead it will smash a pile of errors at you!
EType_A
MyNamespace::DemoEnum::SubEx
I am confident that this is a restriction imposed by my limited meta-programming skills. After all I am in serious C++ development for only a few weeks (C#, Java,
and "C like C++" previously)... A more experienced metaprogrammer should be able to remove this restriction, at least if the language specification
allows it (I am not sure about that). The main issue I have here is that I need to define namespaces relative to the global namespace and this seems to be forbidden
inside of a subnamespace. To solve this, one would probably require a lot more sophisticated design I would not be willing to afford.
Also note that if you plan on later supporting C++11, you should regularly compile your code with a C++11 compiler and the CFLAGS_ENABLE_ENUM_CLASS_WORKAROUND
macro set to 0, preferably as a compiler option. This will cause the EnumFramework to generate enum classes instead of enum hacks .
While both are compatible to some extend, you will still have to fix certain compiler errors in either case to get them both to work smoothly for
the same code (they each require additional casts or template parameters here and there).
CFLAGS_ENABLE_ENUM_CLASS_WORKAROUND
0
Now that everything is setup, you may be interested in some actual code samples of the support routines. I will just guide you through with small snippets, since
they shall be rather self explaining. For a full demonstration, look at the sample project which uses most of the functionality for the sake of testing it.
First, we declare a small enumeration:
PP_MACRO_ENUM_CLASS_EX(
(System)(Drawing), // put in namespace "System::Drawing"
EColor, // typename
(Black, 2),
(White, 8),
(Red, 1),
(All, Black | Red | White),
(SimilarWhite, White)
);
From now on, consider all code (for the rest of this section) to be contained in the following "main" function:
main
int main(int argc, char* argv[])
{
using namespace std;
using namespace System::Drawing;
using namespace System::Compiler;
using namespace MetaEnumerations;
return 0;
}
Now we can loop through names like:
BOOST_FOREACH(string colorName, Enum::GetNames<EColor>())
{
cout << colorName << " = "
<< (int)Enum::FromString<EColor>(colorName) << endl;
}
/* Output of loop:
Black = 2
White = 8
Red = 1
All = 11
SimilarWhite = 8
*/
and similarly through all values:
BOOST_FOREACH(EColor colorValue, Enum::GetValues<EColor>())
{
cout << Enum::ToString(colorValue) << " = "
<< (int)colorValue << endl;
}
/* Output of loop:
Black = 2
SimilarWhite = 8
Red = 1
All = 11
SimilarWhite = 8
*/
Notice the use of "SimilarWhite" instead of the expected "White". This is because there is no way to distinguish between them,
as they have the same numeric value.
You may also read values from string input (case-insensitive in default configuration):
string colorName;
EColor colorValue;
do{
cout << endl << "Enter a valid color: ";
cin >> colorName;
}
while(!Enum::TryParse(colorName, &colorValue));
cout << endl << "You have entered \"" << Enum::ToString(colorValue) << "\"!" << endl;
As you may know, numeric values can be casted to enumerations (even with enum classes) and so the expression (EColor)443 is correct C++ code,
but inherently wrong! With the following, you can now (easily) validate such values:
(EColor)443
cout << Enum::IsValid<EColor>(1); // true
cout << Enum::IsValid<EColor>(2); // true
cout << Enum::IsValid<EColor>(3); // false
cout << Enum::IsValid<EColor>(4); // false
cout << Enum::IsValid<EColor>(5); // false
cout << Enum::IsValid<EColor>(6); // false
cout << Enum::IsValid<EColor>(7); // false
cout << Enum::IsValid<EColor>(8); // true
cout << Enum::IsValid<EColor>(11); // true
Be aware of that all conversion functions which take either an int or an enum and are not prefixed with "Is" or "Try" will throw
an exception if you pass an invalid enumeration value!
int
enum
There is not much more to know about enums right now.
Instead we will take a look at flags, or enumsets. In contrast to enum sets, flags are intended to hold more than one enumeration member at a time
while still fitting into the same space. This is done by assigning every enumeration member a power of two. There is a special macro included for this purpose:
PP_MACRO_ENUM_CLASS_FLAGS(
(System)(Compiler), // put in namespace "System::Compiler"
EOpMode, // typename
Preprocess,
Compile,
Link,
Optimize,
Execute
);
This will define an enumeration EOpMode where every member has precisely one bit set and thus they can all be combined as you please.
Of course, you could thread any enumeration as flags, but only the ones with one bit per member usually make sense, unless you want to specify masks.
If you don't want to interoperate with native code, putting masks into the enum is usually a bad idea and this why there is no special construct included.
If you want to use masks, you will have to specify your enum using the more verbose PP_MACRO_ENUM_CLASS_EX.
EOpMode
PP_MACRO_ENUM_CLASS_EX
You can now easily decompose such flags, which is useful for validation, specific tasks that need to be invoked for specific flags set,
converting flags to string or whatever:
EOpMode opMode = Flags::Of(EOpMode::Compile, EOpMode::Link, EOpMode::Execute);
BOOST_FOREACH(EOpMode step, Flags::Decompose(opMode))
{
cout << Enum::ToString(step) << " = " << (int)step << endl;
}
/* Output of loop:
Compile = 2
Link = 4
Execute = 16
*/
Flags::Of is simply a shortcut for ORing enum values; especially since enum classes do not support this (for good reason,
since it usually only makes sense on flags) without casting to int, this method comes in handy.
Flags::Of
OR
Additionally, you may get all flag values from an enum value. Only enum members which have precisely one bit set will be included in this enumeration:
BOOST_FOREACH(EColor color, Flags::GetValues<EColor>())
{
cout << Enum::ToString(color) << " = " << (int)color<< endl;
}
/* Output of loop:
Red = 1
Black = 2
SimilarWhite = 8
*/
As you can see, EColor::All is not included, since it is composed of more than one bit.
EColor::All
Flags suffer from the same problem as enumerations, which is (EOpMode)-456 is a valid expression but just makes no sense at all.
For flags, you need a special function for validation, since their value does usually not map to a member:
Flags::AreValid<EColor>(1); // true
Flags::AreValid<EColor>(2); // true
Flags::AreValid<EColor>(8); // true
Flags::AreValid<EColor>(3); // true
Flags::AreValid<EColor>(11); // true
Flags::AreValid<EColor>(10); // true
Flags::AreValid<EColor>(9); // true
// false for everything else...
There are some masking methods available like AreAllSet, IsAnySet, IsSet:
AreAllSet
IsAnySet
IsSet
opMode = Flags::Of(EOpMode::Link, EOpMode::Execute);
Flags::AreAllSet<EOpMode>(opMode, EOpMode::Preprocess); // false
Flags::AreAllSet<EOpMode>(opMode, EOpMode::Execute); // false
Flags::AreAllSet<EOpMode>(opMode, opMode); // true
Flags::AreAllSet<EOpMode>(opMode, Flags::Of(EOpMode::Link, EOpMode::Execute, EOpMode::Preprocess)); // true
Well, there are more methods available but they are kinda self-explaining. Of course, there are plenty of more methods to think of, like validating flags based
on conditional masks which really check if a flag is valid based on sophisticated rules. Feel free to add this functionality!
I am not sure if this is required at all, since support is only there for enum classes anyway and there shouldn't be too much code around already using them.
Unfortunately, usual C++ enums can not be supported. You can easily integrate existing enum classes, but you will have to retype the members in that case:
#if !CFLAGS_ENABLE_ENUM_CLASS_WORKAROUND
// consider the following to be your existing enum
namespace Some { namespace Nested { namespace Namespace {
enum class ESomeEnum
{
a_0 = 1, b_1 = 4, c_2 = 8, d_3 = 3,
};
}}}
// now it is simple to import it:
PP_MACRO_ENUM_CLASS_IMP((Some)(Nested)(Namespace), ESomeEnum, a_0, b_1, c_2, d_3)
#endif
The values will automatically be retrieved from your original enum class and you do not need to type them again (it is also not supported).
The above macro does not introduce any new type to work with. Instead it just skips the type generation and only dumps out the supporting code
for making your enumeration work with the Reflection provided here! The CFLAGS_ENABLE_ENUM_CLASS_WORKAROUND switch is important,
since the above definition only makes sense when enum classes are used and supported (C++11 standard).
The framework allows for some configuration and comes with macro-placeholders for most of the used datatypes and namespaces (I chose macros over typedefs,
since they may cause trouble with templates especially since I can not rely on the template aliases introduced in C++11 due to lack of support). So it shouldn't
be too hard for you to adjust all important properties to suite your needs. You can either change the macro in the header file "EnumFramework_Config.h"
or define them before including this header, in which case it will take your macro instead of redefining it.
typedef
In the following text, I will give a short explanation of what you can configure. First, look at all the macros that are used in configuration:
#define PP_MACRO_STD_VECTOR std::vector
#define PP_MACRO_STD_STRING std::string
#define PP_MACRO_STD_UNORDERED_MAP boost::unordered_map
#define PP_MACRO_STD_IEQUAL_TO hash_examples::iequal_to
#define PP_MACRO_STD_IHASH hash_examples::ihash
#define PP_MACRO_ENUM_ARG_EXCEPTION std::exception
#define PP_MACRO_STD_MAKE_PAIR std::make_pair
#define PP_MACRO_METAENUM_NAMESPACE (MetaEnumerations)
#define PP_MACRO_METAENUM_ENUM_NAMESPACE (MetaEnumerations)(Enum)
#define PP_MACRO_METAENUM_FLAGS_NAMESPACE (MetaEnumerations)(Flags)
The first six macros denote the respective types that will be used in the framework. This is usually helpful, since not everyone is using STD types or BOOST, respectively.
So they provide a convenient way of making the framework compatible with your own types.
The last three macros denote the namespaces where the EnumFramework will put its internal stuff as well as the names for Enum support routines
and Flags support routines. If you change the latter two, all the above code examples will probably not compile anymore . For example, if you do:
Enum
Flags
#define PP_MACRO_METAENUM_ENUM_NAMESPACE (System)(Enumeration)
You will no longer find methods like Enum::ToString() in the MetaEnumerations namespace but rather in the System namespace
and have to use Enumeration::ToString() instead, provided that you've inlined System previously.
Enum::ToString()
MetaEnumerations
System
Enumeration::ToString()
Additionally, there is a CFLAGS_ENABLE_ENUM_CLASS_WORKAROUND macro. It currently evaluates to one, because the standard detection
for C++11 doesn't seem to work these days but maybe in a few years . So for now, if you want to enable C++11 support, that is enum classes, you have to manually
set this flag to zero before including any of the framework specific header files.
one
zero
If you still want to dig deeper, continue in section "Modifying the source code".
Make sure you are using the correct syntax. If you type in something wrong when declaring your enumeration, you will most likely get a massive amount of unrelated
errors which reveal as much about the real cause as you staring at a can of meat... So be careful. Another thing that might cause trouble is when your enum members
are macro names. While this also won't work in most cases when using the raw C++ type, the difference is again that you won't get useful error information, but just a pile of scary junk.
In case of Linux, there is one unsolved problem, the Linker! It seems to take its job a little bit too seriously and does not permit static template data members to be redefined
in multiple compilation units. This is a serious problem and the only way I found to solve this is to create just one CPP file and include all your other CPP files in it.
Then it will work, provided that your code supports that kind of compilation (especially if you didn't plan on doing this, it might actually cause some trouble).
If anyone has a fix for this, I would really appreciate it, since I also need Linux support myself... Currently, I can't think of something other than using static
template data members to do the job (at least not without typing enum members twice and this is an absolute no go for me; then I'd rather go not using enums at all).
Well, to be honest, I have something in mind that could work, but since I am not in desperate need of a Linux fix, I won't look into it right now as there are bigger
fish to fry. It is based on introducing another macro that just receives the namespace and enumeration name (this is something I could agree on, since you don't have
to synchronize members, and enum names are unlikely to change over time, since it would cause a massive need for refactoring). This macro would now be declared only
in one compilation unit per enumeration and will act as a well named proxy for providing the Reflection data.
If you are not to be scared easily, take a look at the source code (which is really ugly, but there is not much you can do about it; in the end, it provides the means
for getting your code cleaner at least), instead of just working with the macros. I will give you a few pointers on where to start and what you can change without
the need of understanding how this framework is working .
The most important and trivial change is adding new methods. For this, you have to add a new public
static method for the classtemplate<class TEnum> struct EnumSupport
located in the file "EnumFramework_Custom.h".
Additionally, you should create an alias either in the Enum or Flags namespace located below the EnumSupport class definition.
There you just create an alias like the others located in there. I think it is pretty obvious if you look closer. Just let you guide by the existing methods.
template<class TEnum> struct EnumSupport
EnumSupport
Another thing that you may want to change is the compatibility workaround that is used when no enum classes are available. It is located at the bottom of the file
and starts with struct TEnum. I can't tell you what to do here, you will know what you want to change to make it suit your needs.
struct TEnum
The example application uses the Google Testing Framework and comes with a bunch of essential tests, validating the whole concept of reflective enumeration.
If you change something, you shall always make sure that the test cases run through properly and the code does compile with MSVC 2010 and CLang 3 (supported by Apple).
These are the most important compilers in my opinion (they couldn't be more disjoint), and if you support them both, especially thanks to the high degree of standard
conformance of CLang, your code will most likely also compile with any other major compiler, at most with slight modifications. Also note that CLang
is an amazing technology. Even though it is not really ready for productive development, due to lack of good tools and debuggers, it is the way to go
for any future effort on C++. It provides outstanding error reporting mechanisms, without whcih this project would not have been possible! For example,
in Visual Studio, you get something along the lines of "Unexpected ',' at the end of identifier". And if you double click, it shows you the macro
from which this error originated. Also, the command line output shows no more information even. Yeah, nice. Depending on the macro, this may actually mean hours
of trial and error code-changes until you find out the real reason. Time enough to install the CLang compiler and let it give you more insights. It will generate
a full macro-expansion and template instantiation trace for the specific error and underline in each trace step which expression was replaced with what
and at which source code line this trace step takes place (even with source code dump of the current line). And it shows useful error messages
that pinpoint the actual problem instead of some random weird garbage. CLang really is something evolved and the people have learned a lot from
the failures of GCC (at least when it comes to C++).
If you wan't to know more, just read some of the good docs about "Preprocessor Metaprogramming" and also C++ templates. What's done here is simply
abusing the preprocessor and template instantiation for code generation or let's say some sort of domain specific language; in that case, a language to define reflective enums.
My time is somewhat up right now, and also I think it wouldn't make much sense to add this kind of information to this article, since the stuff discussed
before was really straightforward and now it would get really nasty , but also a lot more interesting I have to admit. But this article was about how to use
this framework, not how to re-implement.
|
http://www.codeproject.com/Articles/318690/C-11-Non-intrusive-enum-class-with-reflection-supp?fid=1680704&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None
|
CC-MAIN-2016-26
|
refinedweb
| 4,073
| 50.57
|
# Machine Learning in Static Analysis of Program Source Code

Machine learning has firmly entrenched in a variety of human fields, from speech recognition to medical diagnosing. The popularity of this approach is so great that people try to use it wherever they can. Some attempts to replace classical approaches with neural networks turn up unsuccessful. This time we'll consider machine learning in terms of creating effective static code analyzers for finding bugs and potential vulnerabilities.
The PVS-Studio team is often asked if we want to start using machine learning to find bugs in the software source code. The short answer is yes, but to a limited extent. We believe that with machine learning, there are many pitfalls lurking in code analysis tasks. In the second part of the article, we will tell about them. Let's start with a review of new solutions and ideas.
New Approaches
--------------
Nowadays there are many static analyzers based on or using machine learning, including deep learning and NLP for error detection. Not only did enthusiasts double down on machine learning potential, but also large companies, for example, Facebook, Amazon, or Mozilla. Some projects aren't full-fledged static analyzers, as they only find some certain errors in commits.
Interestingly, almost all of them are positioned as game changer products that will make a breakthrough in the development process due to artificial intelligence.

Let's look at some of the well-known examples:
1. DeepCode
2. Infer, Sapienz, SapFix
3. Embold
4. Source{d}
5. Clever-Commit, Commit Assistant
6. CodeGuru
### DeepCode
Deep Code is a vulnerability-searching tool for Java, JavaScript, TypeScript, and Python software code that features machine learning as a component. According to Boris Paskalev, more than 250,000 rules are already in place. This tool learns from changes, made by developers in the source code of open source projects (a million of repositories). The company itself says that their project is some kind of Grammarly for developers.

In fact, this analyzer compares your solution with its project base and offers you the intended best solution from the experience of other developers.
In May 2018, developers said that the support of C++ is on its way, but so far, this language is not supported. Although, as stated on the site, the new language support can be added in a matter of weeks due to the fact that the language depends only on one stage, which is parsing.


A series of posts about basic methods of the analyzer is also available on the site.
### Infer
Facebook is quite zealous in its attempts to introduce new comprehensive approaches in its products. Machine learning didn't stay on the sidelines either. In 2013, they bought a startup that developed a static analyzer based on machine learning. And in 2015, the source code of the project [became open](https://github.com/facebook/infer).
Infer is a static analyzer for projects in Java, C, C++, and Objective-C, developed by Facebook. According to the site, it's also used in Amazon Web Services, Oculus, Uber, and other popular projects.
Currently, Infer is able to find errors related to null pointer dereference and memory leaks. Infer is based on Hoare's logic, separation logic and bi-abduction, as well as abstract interpretation theory. Usage of these approaches allows the analyzer to break the program into chunks and analyze them independently.
You can try using Infer on your projects, but developers warn that while with Facebook projects it generates about 80% of useful warnings, a low number of false positives isn't guaranteed on other projects. Here are some errors that Infer can't detect so far, but developers are working on implementing these warnings:
* array index out of bounds;
* type casting exceptions;
* unverified data leaks;
* race condition.
### SapFix
SapFix is an automated editing tool. It receives information from Sapienz, a testing automation tool, and the Infer static analyzer. Based on recent changes and messages, Infer selects one of several strategies to fix bugs.

In some cases, SapFix rolls back all changes or parts of them. In other cases, it tries to solve the problem by generating a patch from its set of fixing patterns. This set is formed from patterns of fixes collected by programmers themselves from a set of fixes that were already made. If such a pattern doesn't fix an error, SapFix tries to adjust it to the situation by making small modifications in an abstract syntax tree until the potential solution is found.
But one potential solution is not enough, so SapFix collects several solutions' on the grounds of a couple of points: whether there are compilation errors, whether it crashes, whether it introduces new crashes. Once the edits are fully tested, patches are reviewed by a programmer, who will decide which of the edits best solves the problem.
### Embold
Embold is a start-up platform for static analysis of software source code that was called Gamma before the renaming. Static analyzer works based on the tool's own diagnostics, as well as using built-in analyzers, such as Cppcheck, SpotBugs, SQL Check and others.

In addition to diagnostics themselves, the platform focuses on vivid infographics on the load of codebase and convenient viewing of found errors, as well as searching for possible refactoring. Besides, this analyzer has a set of anti-patterns that allows you to detect problems in the code structure at the class and method level, and various metrics to calculate the quality of a system.

One of the main advantages is the intelligent system of offering solutions and edits, which, in addition to conventional diagnostics, checks edits based on information about previous changes.

With NLP, Embold breaks the code apart and searches for interconnections and dependencies between functions and methods, saving refactoring time.

In this way, Embold basically offers convenient visualization of your source code analysis results by various analyzers, as well as by its own diagnostics, some of which are based on machine learning.
### Source{d}
Source{d} is the most open tool in terms of the ways of its implementation compared to the analyzers we've reviewed. It is also an [open source code solution](https://github.com/src-d/sourced-ce). On their website, in exchange for your mail address, you can get a product leaflet describing the technologies they use. Besides, the website gives a [link](https://github.com/src-d/awesome-machine-learning-on-source-code#program-repair-and-bug-detection) to the database of publications related to machine learning usage for code analysis, as well as the [repository](https://github.com/src-d/datasets/tree/master/PublicGitArchive) with dataset for code-based learning. The product itself is a whole platform for analyzing the source code and the software product, and is focused not on developers, but rather on managers. Among its capabilities is calculation of technical debt size, bottlenecks in the development process and other global statistics on the project.

Their approach to code analysis through machine learning is based on Natural Hypothesis, as outlined in the article "[On the Naturalness of Software](https://people.inf.ethz.ch/suz/publications/natural.pdf)".
*«Programming languages, in theory, are complex, flexible and powerful, but the programs that real people actually write are mostly simple and rather repetitive, and thus they have usefully predictable statistical properties that can be captured in statistical language models and leveraged for software engineering tasks.»*
Based on this hypothesis, the larger the code base is, the greater the statistical properties are, and the more accurate the metrics, achieved through learning, will be.
To analyze the code in source{d}, the Babelfish service is used, which can parse the code file in any of the available languages, get an abstract syntax tree and convert it into a universal syntax tree.

However, source{d} doesn't search for errors in code. Based on the tree using ML on the entire project, source{d} detects code formatting, style applied in the project and in a commit. If the new code doesn't correspond to the project code style, it makes some edits.


Learning focuses on several basic elements: spaces, tabulation, line breaks, etc.

Read more about this in their publication: "[STYLE-ANALYZER: fixing code style inconsistencies with interpretable unsupervised algorithms](https://arxiv.org/abs/1904.00935)".
All in all, source{d} is a wide platform for collecting diverse statistics on the source code and the project development process: from efficiency calculations of developers to time costs for code review.
### Clever-Commit
Clever-Commit is an analyzer created by Mozilla in collaboration with Ubisoft. It's based on a [CLEVER](https://static-wordpress.akamaized.net/montreal.ubisoft.com/wp-content/uploads/2018/03/03172129/clever-commit-msr18.pdf) (Combining Levels of Bug Prevention and Resolution Techniques) study by Ubisoft and its child product Commit Assistant, which detects suspicious commits that are likely to contain an error. Since CLEVER is based on code comparison, it can both point at dangerous code and make suggestions for possible edits. According to the description, in 60-70% of cases Clever-Commit finds problem places and offers correct edits with the same probability. In general, there is little information about this project and about the errors it is able to find.
### CodeGuru
Recently CodeGuru, which is a product from Amazon, has fallen into line with analyzers using machine learning. It is a machine learning service that allows you to find errors in the code, as well as identify costly areas in it. The analysis is available only for Java code so far, but authors promise to support other languages in future. Although it was announced quite recently, Andy Jassy, CEO AWS (Amazon Web Services) says it has been used in Amazon for a long time.
The website says that CodeGuru was learning on the Amazon code base, as well as on more than 10 000 open source projects.
Basically, the service is divided into two parts: CodeGuru Reviewer, taught using the search for associative rules and looking for errors in code, and CodeGuru Profiler, monitoring performance of applications.

In general, there is not much available information about this project. As the website states, the Reviewer analyzes Amazon code bases and searches for pull requests, containing API AWS calls in order to learn how to catch deviations from «best practices». Next, it looks at the changes made and compares them to data from the documentation, which is analyzed at the same time. The result is a «best practices» model.
It is also said that recommendations for user's code tend to improve after receiving feedback on them.
The list of errors that Reviewer responds to is fairly blurred, as no specific error documentation has been published:
* «Best Practices» AWS
* Concurrency
* Resource leaks
* Leak of confidential information
* General «best practices» of coding
Our Skepticism
--------------
Now let's consider error searching from the point of view of our team, which has been developing static analyzers for many years. We see a number of high-level problems of learning method application, which we'd like to cover. To begin with, we'll divide all ML approaches into two types:
1. Those which manually teach a static analyzer to search for various problems, using synthetic and real code examples;
2. Those which teach algorithms on a large number of open source code and revision history (GitHub), after which the analyzer will begin to detect bugs and even offer edits.
We will talk about each direction separately, as they have different drawbacks. After that, I think, readers will get why we don't deny the possibilities of machine learning, but still don't share the enthusiasm.
**Note.** We look from the perspective of developing a universal static general purpose analyzer. We are focused on developing the analyzer, which any team will be able to use, not the one focused on a specific code base.
### Manual Teaching of a Static Analyzer
Let's say we want to use ML to start looking for the following kinds of flaws in the code:
```
if (A == A)
```
It is strange to compare a variable with itself. We can write many examples of correct and incorrect code and teach the analyzer to search for such errors. Additionally, you can add real examples of already found bugs to the tests. Well, the question is where to find such examples. Ok, let's assume it's possible. For example, we have a number of examples of such errors: [V501](https://www.viva64.com/en/examples/v501/), [V3001](https://www.viva64.com/en/examples/v3001/), [V6001](https://www.viva64.com/en/examples/v6001/).
So is it possible to identify such defects in code by using the ML algorithms? Yes, it is. The thing is — why do we need it?
See, to teach the analyzer we'll need to spend a lot of efforts on preparing the examples for teaching. Another option is to mark the code of real applications, indicating the fragments where the analyzer has to issue a warning. In any case, a lot of work will need to be done, as there should be thousands of examples for learning. Or tens of thousands.
After all, we want to detect not only (A == A) cases, but also:
* if (X && A == A)
* if (A + 1 == A + 1)
* if (A[i] == A[i])
* if ((A) == (A))
* and so on.

Let's look at the potential implementation of such a simple diagnostic in PVS-Studio:
```
void RulePrototype_V501(VivaWalker &walker,
const Ptree *left, const Ptree *right, const Ptree *operation)
{
if (SafeEq(operation, "==") && SafeEqual(left, right))
{
walker.AddError("Oh boy! Holy cow!", left, 501, Level_1, "CWE-571");
}
}
```
And that's it! You don't need any base of examples for ML!
In the future, the diagnostic has to learn to take into account a number of exceptions and issue warnings for (A[0] == A[1-1]). As we know, it can be easily programmed. On the contrary, in this case, things are going to be bad with the base of examples.
Note that in both cases we'll need a system of testing, documentation and so on. As for labor contribution on creating a new diagnostic, the classic approach, where the rule is rigidly programmed in the code, takes the lead.
Ok, it's time for another rule. For example, the one where the result of some functions must be used. There is no point in calling them and not using their result. Here are some of such functions:
* malloc
* memcmp
* string::empty
This is what the PVS-Studio [V530](https://www.viva64.com/en/w/v530/) diagnostic does.
So what we want is to detect calls to such functions, whose result isn't used. To do this, you can generate a lot of tests. And we think everything will work well. But again it is not clear why it is needed.
The V530 diagnostic implementation with all exceptions took 258 lines of code in the PVS-Studio analyzer, 64 of which are comments. There is also a table with functions annotations, where it's noted that their result must be used. It is much easier to top up this table than to create synthetic examples.
Things will get even worse with diagnostics that use data flow analysis. For example, the PVS-Studio analyzer can track the value of pointers, which allows you to find such a memory leak:
```
uint32_t* BnNew() {
uint32_t* result = new uint32_t[kBigIntSize];
memset(result, 0, kBigIntSize * sizeof(uint32_t));
return result;
}
std::string AndroidRSAPublicKey(crypto::RSAPrivateKey* key) {
....
uint32_t* n = BnNew();
....
RSAPublicKey pkey;
pkey.len = kRSANumWords;
pkey.exponent = 65537; // Fixed public exponent
pkey.n0inv = 0 - ModInverse(n0, 0x100000000LL);
if (pkey.n0inv == 0)
return kDummyRSAPublicKey; // <=
....
}
```
The example is taken from the article "[Chromium: Memory Leaks](https://www.viva64.com/en/b/0555/)". If the condition *(pkey.n0inv == 0)* is true, the function exits without freeing the buffer, the pointer to which is stored in the *n* variable.
From the PVS-Studio's point of view, there is nothing complicated here. The analyzer has studied the *BnNew* function and remembered that it returned a pointer to the allocated memory block. In another function, it noticed that the buffer might not free and the pointer to it gets lost at the moment of exiting the function.
It's a common algorithm of tracking values working. It doesn't matter how the code is written. It doesn't matter what else is in the function that doesn't relate to the pointer work. The algorithm is universal and the V773 diagnostic finds a lot of errors in various projects. See how different the [code fragments](https://www.viva64.com/en/examples/v773/) with detected errors are!
We aren't experts in ML, but we have a feeling that big problems are right around the corner here. There is an incredible number of ways you can write code with memory leaks. Even if the machine learned well how to track values of variables, it would need to understand that there are calls to functions as well.
We suspect it would require so many examples for learning that the task becomes ungraspable. We're not saying it's unrealistic. We doubt that the cost of creating the analyzer will pay off.
**Analogy.** What comes to my mind is the analogy with a calculator, where instead of diagnostics, one has to program arithmetic actions. We are sure, that you can teach an ML based calculator to sum up numbers well by feeding it the results of operations 1+1=2, 1+2=3, 2+1=3, 100+200=300 and so on. As you understand, the feasibility of developing such a calculator is a big question (unless it is allocated a grant :). A much simpler, faster, more accurate and reliable calculator can be written using the simple operation "+" in the code.
**Conclusion** Well, this way will work out. But using it, in our opinion, doesn't make practical sense. Development will be more time-consuming, but the result — less reliable and accurate, especially when it comes to implementing complex diagnostics based on data flow analysis.
### Learning on Large Amount of Open Source Code
Okay, we've sorted out with manual synthetic examples, but there's also GitHub. You can track commit history and deduce code changing/fixing patterns. Then you can point not only at fragments of suspicious code, but even suggest a way to fix the code.
If you stop at this detail level, everything looks good. The devil, as always, is in the details. So let's talk right about these details.
**The first nuance. Data source.**
GitHub edits are quite random and diverse. People are often lazy to make atomic commits and make several edits in the code at the same time. You know how it happens: you would fix the bug, and at the same time refactor it a bit («And here I will add handling of such a case ...»). Even a person may then be incomprehensible, whether these fixed are related to each other, or not.
The challenge is how to distinguish actual errors from adding new functionality or something else. You can, of course, get 1000 people who will manually mark the commits. People will have to point out: here an error was fixed, here is refactoring, here is some new functionality, here the requirements have changed and so on.
Is such a markup possible? Yep! But notice how quickly the spoofing happens. Instead of «the algorithm learns itself on the basis of GitHub» we are already discussing how to puzzle hundreds of people for a long time. The work and cost of creating the tool is increasing dramatically.
You can try to identify automatically where the bugs were fixed. To do this, you should analyze the comments to the commits, pay attention to small local edits, which most likely are those very bug fixes. It's hard to tell how well you can automatically search for error fixes. In any case, this is a big task that requires separate research and programming.
So, we haven't even got to learning yet, and there are already nuances :).
**The second nuance. A lag in development.**
Analyzers that will learn based on such platforms, as GitHub will always be subject to such a syndrome, as «mental retardation delay». This is because programming languages change over time.
Since C# 8.0 there [have](https://www.viva64.com/en/b/0631/) been Nullable Reference types, helping to fight against Null Reference Exceptions (NRE). In JDK 12, a new switch operator ([JEP 325](https://openjdk.java.net/jeps/325)) appeared. In C++17, there is a possibility to perform compile-time conditional constructs ([constexpr if](https://www.bfilipek.com/2018/03/ifconstexpr.html)). And so on.
Programming languages are evolving. Moreover, the ones, like C++, develop very fast. New constructions appear, new standard functions are added and so on. Along with the new features, there are new error patterns that we would also like to identify with static code analysis.
At this point, the ML method faces a problem: the error pattern is already clear, we would like to detect it, but there no code base for learning.
Let's look at this problem using a particular example. Range-based for loop appeared in C++11. You can write the following code, traversing all elements in the container:
```
std::vector numbers;
....
for (int num : numbers)
foo(num);
```
The new loop has brought the new error pattern with it. If we change the container inside the loop, this will lead to invalidation of «shadow» iterators.
Let's take a look at the following incorrect code:
```
for (int num : numbers)
{
numbers.push_back(num * 2);
}
```
The compiler will turn it into something like this:
```
for (auto __begin = begin(numbers), __end = end(numbers);
__begin != __end; ++__begin) {
int num = *__begin;
numbers.push_back(num * 2);
}
```
During *push\_back* , *\_\_begin* and *\_\_end* iterators can be invalidated, if the memory is relocated inside the vector. The result will be the undefined behavior of the program.
Therefore, the error pattern has long been known and described in literature. The PVS-Studio analyzer diagnoses it with the [V789](https://www.viva64.com/en/w/v789/) diagnostic and has already found [real errors](https://www.viva64.com/en/examples/v789/) in open source projects.
How soon will GitHub get enough new code to notice this pattern? Good question… It's important to bear in mind that if there is a range-based for loop, it doesn't mean that all programmers will immediately begin to use it at once. It may be years before there is a lot of code using the new loop. Moreover, many errors must be made, and then they must be fixed so that the algorithm can notice the pattern in the edits.
How many years will it take? Five? Ten?
Ten is too many, or is it a pessimistic prediction? Far from it. By the time the article was written, it had been eight years since a range-based for loop appeared in C++11. But so far in our database there are only [three cases](https://www.viva64.com/en/examples/v789/) of such an error. Three errors is not much and not few. One should not draw any conclusion from this number. The main thing is to confirm that such an error pattern is real and it makes sense to detect it.
Now compare this number, for example, with this error pattern: [pointer gets dereferenced before the check](https://www.viva64.com/en/examples/v595/). In total, we have already identified 1,716 such cases when checking open-source projects.
Perhaps we shouldn't look for errors in range-based for loops at all? No. It's just that programmers are inertial, and this operator is becoming popular very slowly. Gradually, there will be both more code with it and errors, respectively.
This is likely to happen only 10-15 years after the C++11 appeared. This leads to a philosophical question. Suppose we already know the error pattern, we'll just wait for many years until we have many errors in open source projects. Will it be so?
If «yes», it is safe to diagnose «mental development delay» for all ML based analyzers.
If «no», what should we do? There are no examples. Write them manually? But in this way, we get back to the previous chapter, where we've given a detailed description of the option when people would write a whole pack of examples for learning.
This can be done, but the question of expediency arises again. The implementation of the V789 diagnostic with all exceptions in the PVS-Studio analyzer takes only 118 lines of code, of which 13 lines are comments. That is, it is a very simple diagnostic, which can be easily programmed in a classic way.
The situation will be similar to any other innovations that appear in any other languages. As they say, there is something to think about.
**The third nuance. Documentation.**
An important component of any static analyzer is the documentation describing each diagnostic. Without it, it will be extremely difficult or impossible to use the analyzer. In PVS-Studio [documentation](https://www.viva64.com/en/w/), we have a description of each diagnostic, which gives an example of erroneous code and how to fix it. We also give the link to [CWE](https://cwe.mitre.org/), where one can read an alternative problem description. And still, sometimes users don't understand something, and they ask us clarifying questions.
In the case of ML based static analyzers, the documentation issue is somehow hushed up. It is assumed that the analyzer will simply point to a place that seems suspicious to it and may even suggest how to fix it. The decision to make an edit or not is up to the person. That's where the trouble begins… It is not easy to make a decision without being able to read, which makes the analyzer seem suspicious of a particular place in the code.
Of course, in some cases, everything will be obvious. Suppose the analyzer points to this code:
```
char *p = (char *)malloc(strlen(src + 1));
strcpy(p, src);
```
And suggest that we replace it with:
```
char *p = (char *)malloc(strlen(src) + 1);
strcpy(p, src);
```
It is immediately clear that the programmer made a typo and added 1 in the wrong place. As a result, less memory will be allocated than necessary.
Here it's all clear even without documentation. However, this will not always be the case.
Imagine that the analyzer «silently» points to this code:
```
char check(const uint8 *hash_stage2) {
....
return memcmp(hash_stage2, hash_stage2_reassured, SHA1_HASH_SIZE);
}
```
And suggests that we change the char type of the return value for int:
```
int check(const uint8 *hash_stage2) {
....
return memcmp(hash_stage2, hash_stage2_reassured, SHA1_HASH_SIZE);
}
```
There is no documentation for the warning. Apparently, there won't be any text in the warning's message either, if we're talking about a completely independent analyzer.
What shall we do? What's the difference? Is it worth making such a replacement?
Actually, I could take a chance and agree to fix the code. Although agreeing to fixes without understanding them is a cruddy practice… :) You can look into the description of the [*memcmp*](http://www.cplusplus.com/reference/cstring/memcmp/) function and find out that the function really returns values like *int*: 0, more than zero and less than zero. But it may still be unclear why make edits, if the code is already working well.
Now, if you don't know what the edit is, check out the description of the [V642](https://www.viva64.com/en/w/v642/) diagnostic. It immediately becomes clear that this is a real bug. Moreover, it can cause a vulnerability.
Perhaps, the example seemed unconvincing. After all, the analyzer suggested a code that is likely to be better. Ok. Let's look at another example of pseudocode, this time, for a change, in Java.
```
ObjectOutputStream out = new ObjectOutputStream(....);
SerializedObject obj = new SerializedObject();
obj.state = 100;
out.writeObject(obj);
obj.state = 200;
out.writeObject(obj);
out.close();
```
There's an object. It's serializing. Then the state of the object changes, and it re-serializes. It looks fine. Now imagine that, all of a sudden, the analyzer doesn't like the code and it wants to replace it with the following:
```
ObjectOutputStream out = new ObjectOutputStream(....);
SerializedObject obj = new SerializedObject();
obj.state = 100;
out.writeObject(obj);
obj = new SerializedObject(); // The line is added
obj.state = 200;
out.writeObject(obj);
out.close();
```
Instead of changing the object and rewriting it, a new object is created and it will be serialized.
There is no description of the problem. No documentation. The code has become longer. For some reason, a new object is created. Are you ready to make such an edit in your code?
You'll say it's not clear. Indeed, it is incomprehensible. And it will be so all the time. Working with such a «silent» analyzer will be an endless study in an attempt to understand why the analyzer doesn't like anything.
If there is documentation, everything becomes transparent. The class *java.io.ObjectOuputStream* that is used for serialization, caches the written objects. This means that the same object will not be serialized twice. The class serializes the object once, and the second time just writes in the stream a reference to the same first object. Read more: [V6076](https://www.viva64.com/en/w/v6076/) — Recurrent serialization will use cached object state from first serialization.
We hope we managed to explain the importance of documentation. Here comes the question. How will the documentation for the ML based analyzer appear?
When a classic code analyzer is developed, everything is simple and clear. There is a pattern of errors. We describe it in the documentation and implement the diagnostic.
In the case of ML, the process is reverse. Yes, the analyzer can notice an anomaly in the code and point to it. But it knows nothing about the essence of the defect. It doesn't understand and won't tell you why you can't write code like that. These are too high-level abstractions. This way, the analyzer should also learn to read and **understand** documentation for functions.
As I said, since the documentation issue is avoided in articles on machine learning, we are not ready to dwell on it further. Just another big nuance that we've spoken out.
**Note.** You could argue that documentation is optional. The analyzer can refer to many examples of fixes on GitHub and the person, looking through the commits and comments to them, will understand what is what. Yes, it is so. But the idea doesn't look attractive. Here the analyzer is the bad dude, which will rather puzzle a programmer than help him.
**Fourth nuance. Highly specialized languages.**
The approach described is not applicable to highly specialized languages, for which static analysis can also be extremely useful. The reason is that GitHub and other sources simply don't have a large enough source code base to provide effective learning.
Let's look at this using a concrete example. First, let's go to GitHub and search for repositories for the popular Java language.
Result: language:«Java»: **3,128,884** available repository results
Now take the specialized language «1C Enterprise» used in accounting applications produced by the Russian company [1C](https://ru.wikipedia.org/wiki/1%D0%A1).
Result: language:«1C Enterprise»: **551** available repository results
Maybe analyzers are not needed for this language? No, they are. There is a practical need to analyze such programs and there are already appropriate analyzers. For example, there is SonarQube 1C (BSL) Plugin, produced by the company "[Silver Bullet](https://silverbulleters.org/)".
I think no specific explanations are needed as to why ML approach will be difficult for specialized languages.
**The fifth nuance. C, C++, #include**.
Articles on ML-based static code analysis are mostly about such languages such as Java, JavaScript, and Python. This is explained by their extreme popularity. As for C and C++, they are kind of ignored, even though you can't call them unpopular.
We suggest that it's not about their popularity/promising outlook, but it's about the problems with C and C++ languages. And now we're going to bring one uncomfortable problem out to the light.
An abstract c/cpp file can be very difficult to compile. At least you can't load a project from GitHub, choose a random cpp file and just compile it. Now we will explain what all this has to do with ML.
So we want to teach the analyzer. We downloaded a project from GitHub. We know the patch and assume it fixes the bug. We want this edit to be one example for learning. In other words, we have a .cpp file before and after editing.
That's where the problem begins. It's not enough just to study the fixes. Full context is also required. You need to know the declaration of the classes used, you need to know the prototypes of the functions used, you need to know how macros expand and so on. And to do this, you need to perform full file [preprocessing](https://en.wikipedia.org/wiki/C_preprocessor).
Let's look at the example. At first, the code looked like this:
```
bool Class::IsMagicWord()
{
return m_name == "ML";
}
```
It was fixed in this way:
```
bool Class::IsMagicWord()
{
return strcmp(m_name, "ML") == 0;
}
```
Should the analyzer start learning in order to suggest *(x == «y»)* replacement forstrcmp(x, «y»)?
You can't answer that question without knowing how the *m\_name* member is declared in the class. There might be, for example, such options:
```
class Class {
....
char *m_name;
};
class Class {
....
std::string m_name;
};
```
Edits will be made in case if we're talking about an ordinary pointer. If we don't take into account the variable type, the analyzer might learn to issue both good and bad warnings (for the case with *std::string*).
Class declarations are usually located in header files. Here were face the need to perform preprocessing to have all necessary information. It's extremely important for C and C++.
If someone says that it is possible to do without preprocessing, he is either a fraud, or is just unfamiliar with C or C++ languages.
To gather all the necessary information, you need correct preprocessing. To do this, you need to know where and what header files are located, which macros are set during the build process. You also need to know how a particular cpp file is compiled.
That's the problem. One doesn't simply compile the file (or, rather, specify the key to the compiler so that it generates a preprocess file). We need to figure out how this file is compiled. This information is in the build scripts, but the question is how to get it from there. In general, the task is complicated.

Moreover, many projects on GitHub are a mess. If you take an abstract project from there, you often have to tinker to compile it. One day you lack a library and you need to find and download it manually. Another day some kind of a self-written build system is used, which has to be dealt with. It could be anything. Sometimes the downloaded project simply refuses to build and it needs to be somehow tweaked. You can't just take and automatically get preprocessed (.i) representation for .cpp files. It can be tricky even when doing it manually.
We can say, well, the problem with non-building projects is understandable, but not crucial. Let's only work with projects that can be built. There is still the task of preprocessing a particular file. Not to mention the cases when we deal with some specialized compilers, for example, for embedded systems.
After all, the problem described is not insurmountable. However, all this is very difficult and labor-intensive. In case of C and C++, source code located on GitHub does nothing. There's a lot of work to be done to learn how to automatically run compilers.
**Note.** If the reader still doesn't get the depth of the problem, we invite you to take part in the following experiment. Take ten mid-sized random projects from GitHub and try to compile them and then get their preprocessed version for .cpp files. After that, the question about the laboriousness of this task will disappear :).
There may be similar problems with other languages, but they are particularly obvious in C and C++.
**Sixth nuance. The price of eliminating false positives.**
Static analyzers are prone to generating false positives and we have to constantly refine diagnostics to reduce the number of false warnings.
Now we'll get back to the previously considered [V789](https://www.viva64.com/en/w/v789/) diagnostic, detecting container changes inside the range-based for loop. Let's say we weren't careful enough when writing it, and the client reports a false positive. He writes that the analyzer doesn't take into account the scenario when the loop ends after the container is changed, and therefore there is no problem. Then he gives the following example of code where the analyzer gives a false positive:
```
std::vector numbers;
....
for (int num : numbers)
{
if (num < 5)
{
numbers.push\_back(0);
break; // or, for example, return
}
}
```
Yes, it's a flaw. In a classic analyzer, its elimination is extremely fast and cheap. In PVS-Studio, the implementation of this exception consists of 26 lines of code.
This flaw can also be corrected when the analyzer is built on learning algorithms. For sure, it can be taught by collecting dozens or hundreds of examples of code that should be considered correct.
Again, the question is not in feasibility, but in practical approach. We suspect that fighting against specific false positives, which bother clients, is far more costly in case of ML. That is, customer support in terms of eliminating false positives will cost more money.
**Seventh nuance. Rarely used features and long tail.**
Previously, we've grappled with the problem of highly specialized languages, for which may not be enough source code for learning. A similar problem takes place with rarely used functions (system ones, WinAPI, from popular libraries, etc.).
If we're talking about such functions from the C language, as *strcmp*, then there is actually a base for learning. GitHub, available code results:
* strcmp — 40,462,158
* stricmp — 1,256,053
Yes, there are many examples of usage. Perhaps the analyzer will learn to notice, for example, the following patterns:
* It is strange if the string is compared with itself. It gets fixed.
* It's strange if one of the pointers is NULL. It gets fixed.
* It is strange that the result of this function is not used. It gets fixed.
* And so on.
Isn't it cool? No. Here we face the «long tail» problem. Very briefly the point of the «long tail» in the following. It is impractical to sell only the Top50 of the most popular and now-read books in a bookstore. Yes, each such book will be purchased, say, 100 times more often than books not from this list. However, most of the proceeds will be made up of other books that, as they say, find their reader. For example, an online store Amazon.com receives more than half of the profits from what is outside of 130,000 «most popular items».
There are popular functions and there are few of them. There are unpopular, but there are many of them. For example, there are the following variations of the string comparison function:
* g\_ascii\_strncasecmp — 35,695
* lstrcmpiA — 27,512
* \_wcsicmp\_l — 5,737
* \_strnicmp\_l — 5,848
* \_mbscmp\_l — 2,458
* and others.
As you can see, they are used much less frequently, but when you use them, you can make the same mistakes. There are too few examples to identify patterns. However, these functions can't be ignored. Individually, they are rarely used, but a lot of code is written with their use, which is better be checked. That's where the «long tail» shows itself.
At PVS-Studio, we manually annotate features. For example, by the moment about 7,200 functions had been annotated for C and C++. This is what we mark:
* WinAPI
* Standard C Library ,
* Standard Template Library (STL),
* glibc (GNU C Library)
* Qt
* MFC
* zlib
* libpng
* OpenSSL
* and others.
On the one hand, it seems like a dead-end way. You can't annotate everything. On the other hand, it works.
Now here is the question. What benefits can ML have? Significant advantages aren't that obvious, but you can see the complexity.
You could argue that algorithms built on ML themselves will find patterns with frequently used functions and they don't have to be annotated. Yes, it's true. However, there is no problem to independently annotate such popular functions as *strcmp* or *malloc*.
Nonetheless, the long tail causes problems. You can teach by making synthetic examples. However, here we go back to the article part, where we were saying that it was easier and faster to write classic diagnostics, rather than generate many examples.
Take for example a function, such as [*\_fread\_nolock*](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fread-nolock) . Of course, it is used less frequently than *fread*. But when you use it, you can make the same mistakes. For example, the buffer should be large enough. This size should be no less than the result of multiplying the second and third argument. That is, you want to find such incorrect code:
```
int buffer[10];
size_t n = _fread_nolock(buffer, size_of(int), 100, stream);
```
Here's what the annotation of this function looks like in PVS-Studio:
```
C_"size_t _fread_nolock"
"(void * _DstBuf, size_t _ElementSize, size_t _Count, FILE * _File);"
ADD(HAVE_STATE | RET_SKIP | F_MODIFY_PTR_1,
nullptr, nullptr, "_fread_nolock", POINTER_1, BYTE_COUNT, COUNT,
POINTER_2).
Add_Read(from_2_3, to_return, buf_1).
Add_DataSafetyStatusRelations(0, 3);
```
At first glance, such annotation may look difficult, but in fact, when you start writing them, it becomes simple. Plus, it's write-only code. Wrote and forgot. Annotations change rarely.
Now let's talk about this function from the point of view of ML. GitHub won't help us. There are about 15,000 mentions of this function. There's even less good code. A significant part of the search results takes up the following:
```
#define fread_unlocked _fread_nolock
```
What are the options?1. Don't do anything. It's a way to nowhere.
2. Just imagine, teach the analyzer by writing hundreds of examples just for one function so that the analyzer understands the interconnection between the buffer and oher arguments. Yes, you can do that, but it's economically irrational. It's a dead-end street.
3. You can come up with a way similar to ours when the annotations to functions will be set manually. It's a good, sensible way. That's just ML, which has nothing to do with it :). This is a throwback to the classic way of writing static analyzers.
As you can see, ML and the long tail of the rarely used features don't go together.
At this point, there were people related to ML who objected and said that we hadn't taken into account the option when the analyzer would learn all functions and make conclusions of what they were doing. Here, apparently, either we don't understand the experts, or they don't get our point.
Bodies of functions may be unknown. For example, it could be a WinAPI-related function. If this is a rarely used function, how will the analyzer understand what it is doing? We can fantasize that the analyzer will use Google itself, find a description of the function, read and **understand it**. Moreover, it would have to draw high-level conclusions from the documentation. The [*\_fread\_nolock*](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fread-nolock) description tells nothing about the interconnection between the buffer, the second and the third argument. This comparison should be deduced by artificial intelligence on its own, based on an understanding of the general principles of programming and how the C++ language works. I think we should think about all this seriously in 20 years.
Bodies of functions may be available, but there may be no use from this. Let's look at a function, such as *memmove*. It is often implemented in something like this:
```
void *memmove (void *dest, const void *src, size_t len) {
return __builtin___memmove_chk(dest, src, len, __builtin_object_size(dest, 0));
}
```
What is *\_\_builtin\_\_\_memmove\_chk*? This is an intrinsic function that the compiler itself is already implementing. This function doesn't have the source code.
Or *memmove* might look something like this: [the first assembly version](https://github.com/esialb/yocto-3.10-edison/blob/624014e385e6ab4a62f74e60573502b647cf3330/arch/mn10300/lib/memmove.S). You can teach the analyzer to understand different assembly options, but such approach seems wrong.
Ok, sometimes bodies of functions are really known. Moreover, we know bodies of functions in user's code as well. It would seem that in this case ML gets enormous advantages by reading and understanding what all these functions do.
However, even in this case we are full of pessimism. This task is too complex. It's complicated even for a human. Think of how hard it is for you to understand the code you didn't write. If it is difficult for a person, why should this task be easy for an AI? Actually, AI has a big problem in understanding high-level concepts. If we are talking about understanding the code, we can't do without the ability to abstract from the details of implementation and consider the algorithm at a high level. It seems that this discussion can be postponed for 20 years as well.
**Other nuances**
There are other points that should also be taken into account, but we haven't gone deep into them. By the way, the article turns out to be quite long. Therefore, we will briefly list some other nuances, leaving them for reader's reflection.
* **Outdated recommendations.** As mentioned, languages change, and recommendations for their use change, respectively. If the analyzer learns on old source code, it might start issuing outdated recommendations at some point. Example. Formerly, C++ programmers have been recommended using [*auto\_ptr*](http://www.cplusplus.com/reference/memory/auto_ptr/) instead of half-done pointers. This smart pointer is now considered obsolete and it is recommended that you use *unique\_ptr*.
* **Data models.** At the very least, C and C++ languages have such a thing as a [data model](https://www.viva64.com/en/t/0012/). This means that data types have different number of bits across platforms. If you don't take this into account, you can incorrectly teach the analyzer. For example, in Windows 32/64 the *long* type always has 32 bits. But in Linux, its size will vary and take 32/64 bits depending on the platform's number of bits. Without taking all this into account, the analyzer can learn to miscalculate the size of the types and structures it forms. But the types also align in different ways. All this, of course, can be taken into account. You can teach the analyzer to know about the size of the types, their alignment and mark the projects (indicate how they are building). However, all this is an additional complexity, which is not mentioned in the research articles.
* **Behavioral unambiguousness.** Since we're talking about ML, the analysis result is more likely to have probabilistic nature. That is, sometimes the erroneous pattern will be recognized, and sometimes not, depending on how the code is written. From our experience, we know that the user is extremely irritated by the ambiguity of the analyzer's behavior. He wants to know exactly which pattern will be considered erroneous and which will not, and why. In the case of the classical analyzer developing approach, this problem is poorly expressed. Only sometimes we need to explain our clients why there is a/there is no analyzer warning and how the algorithm works, what exceptions are handled in it. Algorithms are clear and everything can always be easily explained. An example of this kind of communication: "[False Positives in PVS-Studio: How Deep the Rabbit Hole Goes](https://www.viva64.com/en/b/0612/)". It's not clear how the described problem will be solved in the analyzers built on ML.
Conclusions
-----------
We don't deny the prospects of the ML direction, including its application in terms of static code analysis. ML can be potentially used in typos finding tasks, when filtering false positives, when searching for new (not yet described) error patterns and so on. However, we don't share the optimism that permeates the articles devoted to ML in terms of code analysis.
In this article, we've outlined a few issues that one will have to work on if he's going to use ML. The described nuances largely negate the benefits of the new approach. In addition, the old classical approaches of analyzers implementation are more profitable and more economically feasible.
Interestingly, the adherents' articles of the ML methodology don't mention these pitfalls. Well, nothing new. ML is provokes certain hype and probably we shouldn't expect balanced assessment from its apologists concerning ML applicability in static code analysis tasks.
From our point of view, machine learning will fill a niche in technologies, used in static analyzers along with control flow analysis, symbolic executions and others.
The methodology of static analysis may benefit from the introduction of ML, but don't exaggerate the possibilities of this technology.
P.S.
----
Since the article is generally critical, some might think that we fear the new and as [Luddites](https://en.wikipedia.org/wiki/Luddite) turned against ML for fear of losing the market for static analysis tools.

No, we're not afraid. We just don't see the point in spending money on inefficient approaches in the development of the PVS-Studio code analyzer. In one form or another, we will adopt ML. Moreover, some diagnostics already contain elements of self-learning algorithms. However, we will definitely be very conservative and take only what will clearly have a greater effect than the classic approaches, built on loops and ifs :). After all, we need to create an effective tool, not work off a grant :).
The article is written for the reason that more and more questions are asked on the topic and we wanted to have an expository article that puts everything in its place.
Thank you for your attention. We invite you to read the article "[Why You Should Choose the PVS-Studio Static Analyzer to Integrate into Your Development Process](https://www.viva64.com/en/b/0687/)".
|
https://habr.com/ru/post/484202/
| null | null | 8,758
| 57.27
|
This document lays out the feature and API set for the eighth annual release of the Eclipse Object Constraint Language (Eclipse OCL) Project, version 4.1.0.
The plan for 4.1 was to complete the prototyping of models and solutions to the UML alignment and many other issues in the OMG OCL 2.3.1 specification.
Considerable progress was made, but not enough to permit the examples prototypes to be promoted as replacements for the legacy functionality.
The OCL to Java code generator was rewritten twice so that it now has a sound underlying model making the code simpler and more efficient and permitting optimizations to be realized easily.
The support for UML was improved so that the new functionality is now exploited within Papyrus for profiles and validation.
The project should now be in good shape to complete UML alignment and then support accurate auto-generation of Java for the many new and changed OCL constraints in the UML 2.5 specification.
Note that, since the OMG OCL 2.3.1 standard suffers from significant ambiguities and conflicts making a compliant implementation impossible, Eclipse (MDT) OCL 4.1.
Eclipse OCL 4.1 will use GIT for source control.
Eclipse OCL 4.1 will primarily target Eclipse 4.3 rather than Eclipse 3.9.
Eclipse OCL 4.1.0 source code will be available as versions tagged "Kepler" in the project's GIT repository.
In order to remain current, each Eclipse release targets reasonably current versions of the underlying operating environments. The Eclipse Object Constraint Language (OCL). Eclipse OCL will target the same Java version as EMF and UML2, which currently require Java 5. Eclipse Platform SDK 4.3 will be tested and validated on a number of reference platforms. Eclipse OCL will be tested and validated against a subset of those listed for the platform.
Indirect dependence on version 6 of the JRE has arisen through use of the third party components such as Google Guava. This may justify raising the lower bound explicitly for Luna.
A direct dependence on version 6 of the JRE exists on ly when dynamic compilation of auto-generated Java is exploited.
As described above, the Eclipse OCL 4.1.0 release should address usability of the editors. The main OCL plugins should be unaffected, but the associated examples plugins may be revised significantly.
Again as described above, the Eclipse OCL 4.1.0 release for Kepler will introduce significant new APIs in a new namespace that replaces the old. The old namespace will be deprecated once all Simultaneous Release projects have migrated to the new namespace.
|
http://www.eclipse.org/modeling/mdt/ocl/project-info/plan_kepler.xml
|
CC-MAIN-2015-40
|
refinedweb
| 434
| 57.98
|
I looked this up on Google and watched a video, but this doesn't work for me.
When I try to link a symbol in the library with an AS Linkage, then attach it to a BitmapData variable, this error code shows:
Scene 1, Layer 'Layer 1', Frame 1, Line 4 1067: Implicit coercion of a value of type Gun to an unrelated type flash.display:BitmapData.
I don't use bitmap or bitmapdata much, and I don't use classes much, so I have no idea what is wrong. This is my code:
import flash.display.BitmapData;
var gun:BitmapData = new Gun;
You can't declare it as BitmapData - BitmapData is just raw bitmap data :)
Since you have declared MovieClip as Base Class, this should become a MovieClip:
var gun:MovieClip = new Gun();
If your gun has no timeline (so it's a graphics with just one frame), set the Base Class to Sprite and handle it as sprite - this is better for memory and performance:
var gun:Sprite = new Gun();
|
https://codedump.io/share/55G8XP2iPk8K/1/bitmap-from-library
|
CC-MAIN-2016-50
|
refinedweb
| 172
| 64.38
|
On Thu, Mar 31, 2005 at 05:36:11PM +0200, Miguel Mendez wrote: > On Thu, 31 Mar 2005 16:11:17 +0100 > Jonathon McKitrick <jcm@xxxxxxxxxxxxxxxxx> wrote: > > > > Sorry this is such a lame question, but I never quite figured out what > > 'static' does to a function declaration. Obviously for a variable, it > > allocates memory for the lifetime of the process rather than on the stack just > > for one function call. Only for function scope variables. > > But what about 'static' for all the kernel functions > > that have no return value? > > static foo(blah blah) restricts the scope of the function to that > module, i.e. it's not visible outside that .c file. You usually do that > to keep private functions from being called from somewhere else. That > way other parts of the program will only talk to the published API. That's right. It's also what happens with file scope variables. Beside keeping the namespace cleans, it allows the compiler to choose a different ABI for internal functions. It also allows the compiler to warn about unused local functions and variables. Joerg
|
http://leaf.dragonflybsd.org/mailarchive/kernel/2005-03/msg00140.html
|
CC-MAIN-2014-15
|
refinedweb
| 183
| 72.46
|
Chapter 4
Making Predictions
Correlation
In the last chapter, we began developing a method that would allow us to estimate the birth weight of babies based on the number of gestational days. In this chapter, we develop a more general approach to measuring the relation between two variables and estimating the value of one variable given the value of another.
Our proposed estimate in the example of birth weights was simple:
- Find the ratio of the birth weight to gestational days for each baby in the sample.
- Find the median of the ratios.
- For a new baby, multiply the number of gestational days by that median. This is our estimate of the baby's birth weight.
Here are the data; the column
r_bwt_gd contains the ratio of birth weight to gestational days.
baby = Table.read_table('baby.csv') baby['r_bwt_gd'] = baby['birthwt']/baby['gest_days'] baby
... (1164 rows omitted)
The median of the ratios is just about 0.429 ounces per day:
np.median(baby['r_bwt_gd'])
0.42907801418439717
So we can construct our proposed estimate by multiplying the number of gestational days of each baby by 0.429. The column
est_wt contains these estimates.
baby['est_bwt'] = 0.429*baby['gest_days'] baby.drop('r_bwt_gd')
... (1164 rows omitted)
Because of the way they are constructed – by multiplying the gestational days by a constant – The estimates all lie on a straight line.
bb0 = baby.select(['gest_days', 'est_bwt']) bb0.scatter('gest_days') plots.ylim(40,200) plots.xlabel('gestational days') plots.ylabel('estimated birth weight')
A natural question to ask is, "How good are these estimates?" To get a sense of the answer, let us visualize the data by drawing a scatter plot of birth weight versus gestational days. The scatter plot consists of one point for each of the 1,174 babies in the sample. The horizontal axis represents the number of gestational days and the vertical axis represents the birth weight.
The plot is generated by using a
Table method called
scatter. The argument is the label of the column that contains the values to be plotted on the horizontal axis. For each of the other columns in the table, a scatter diagram is produced with the corresponding variable on the vertical axis. To generate just one scatter plot, therefore, we start by selecting only the variables that we need.
gd_bwt = baby.select(['gest_days', 'birthwt']) gd_bwt.scatter('gest_days') plots.xlabel('gestational days') plots.ylabel('birth weight')
How good are the estimates that we calculated? To get a sense of this, we will re-draw the scatter plot and overlay the line of estimates. This can be done by using the argument
overlay=True when we call
scatter.
gd_bwt_est = baby.select(['gest_days', 'birthwt', 'est_bwt']) gd_bwt_est.scatter('gest_days', overlay=True) plots.xlabel('gestational days')
The line appears to be roughly in the center of the scatter diagram; if we use the line for estimation, the amount of over-estimation will be comparable to the amount of under-estimation, roughly speaking. This is a natural criterion for determining a "good" straight line of estimates.
Let us see if we can formalize this idea and create a "best" straight line of estimates.
To see roughly where such a line must lie, we will start by attempting to estimate maternal pregnancy weight based on the mother's height. The heights have been measured to the nearest inch, resulting in the vertical stripes in the scatter plot.
ht_pw = baby.select(['mat_ht', 'mat_pw'])
plots.scatter(ht_pw['mat_ht'], ht_pw['mat_pw'], s=5, color='gold') plots.xlabel('height (inches)') plots.ylabel('pregnancy weight (pounds)')
Suppose we know that one of the women is 65 inches tall. What would be our estimate for her pregnancy weight?
We know that the point corresponding to this woman must be on the vertical strip at 65 inches. A natural estimate of her pregnancy weight is the average of the weights in that strip; the rough size of the error in this estimate will be the SD of the weights in the strip.
For a woman who is 60 inches tall, our estimate of pregnancy weight would be the average of the weights in the vertical strip at 60 inches. And so on.
Here are the average pregnancy weights for all the values of the heights.
v_means = ht_pw.group('mat_ht', np.mean) v_means
... (9 rows omitted)
In the figure below, these averages are overlaid on the scatter plot of pregnancy weight versus height, and appear as green dots at the averages of the vertical strips. The graph of green dots is called the graph of averages. A graph of averages shows the average of the variable on the vertical axis, for each value of the variable on the horizontal axis. It can be used for estimating the variable on the vertical axis, given the variable on the horizontal.
plots.scatter(baby['mat_ht'], baby['mat_pw'], s=5, color='gold') plots.scatter(v_means['mat_ht'], v_means['mat_pw mean'], color='g') plots.xlabel('height (inches)') plots.ylabel('pregnancy weight (pounds)') plots.title('Graph of Averages')
For these two variables, the graph of averages looks roughly linear: the green dots are fairly close to a straight line for much of the scatter. That straight line is the "best" straight line for estimating pregnancy weight based on height.
To identify the line more precisely, let us examine the oval or football shaped scatter plot.
First, we note that the position of the line is a property of the shape of the scatter, and is not affected by the units in which the heights and weights were measured. Therefore, we will measure both variables in standard units.
x_demo = np.random.normal(0, 1, 10000) z_demo = np.random.normal(0, 1, 10000) y_demo = 0.5*x_demo + np.sqrt(.75)*z_demo plots.scatter(x_demo, y_demo, s=10) plots.xlim(-4, 4) plots.ylim(-4, 4) plots.axes().set_aspect('equal') plots.plot([-4, 4], [-4*0.6,4*0.6], color='g', lw=1) plots.plot([-4,4],[-4,4], lw=1, color='r') plots.plot([1.5,1.5], [-4,4], lw=1, color='k') plots.xlabel('x in standard units') plots.ylabel('y in standard units')
Here is a football shaped scatter plot. We will follow the usual convention of calling the variable along the horizontal axis $x$ and the variable on the vertical axis $y$. Both variables are in standard units. This implies that the center of the football, corresponding to the point where both variables are at their average, is the origin (0, 0).
Because of the symmetry of the figure, resulting from both variables being measured in standard units, it is natural to see whether the 45 degree line is the best line for estimation. The 45 degree line has been drawn in red. For points on the red line, the value of $x$ in standard units is equal to the value of $y$ in standard units.
Suppose the given value of $x$ is at the average, in other words at 0 on the standard units scale. The points corresponding to that value of $x$ are on the vertical strip at $x$ equal to 0 standard units. The average of the values of $y$ in that strip can be seen to be at 0, by symmetry. So the straight line of estimates should pass through (0, 0).
A careful look at the vertical strips shows that the red line does not work for estimating $y$ based on other values of $x$. For example, suppose the value of $x$ is 1.5 standard units. The black vertical line corresponds to this value of $x$. The points on the scatter whose value of $x$ is 1.5 standard units are the blue dots on the black line; their values on the vertical scale range from about 2 to about 3. It is clear from the figure that the red line does not pass through the average of these points; the red line is too steep.
To get to the average of the vertical strip at $x$ equal to 1.5 standard units, we have to come down from the red line to the center of the strip. The green line is at that point; it has been drawn by connecting the center of the strip to the point (0, 0) and then extending the line on both sides.
The scatter plot is linear, so the green line picks off the centers of the vertical strips. It is the line that should be used to estimate $y$ based on $x$ when both variables are in standard units.
The slope of the red line is equal to 1. The green line is less steep, and so its slope is less than 1. Because it is sloping upwards in the figure, we have established that its slope is between 0 and 1.
Summary. When both variables are measured in standard units, the best line for estimating $y$ based on $x$ is less steep than the 45 degree line and thus has slope less than one. The discussion above was based on a scatter plot sloping upwards, and so the slope of the best line is a number between 0 and 1. For scatter diagrams sloping downwards, the slope would be a number between 0 and -1. For the slope to be close to -1 or 1, the red and green lines must be close, or in other words, the scatter diagram must be tightly clustered around a straight line.
The Correlation Coefficient¶
This number between -1 and 1 is called the correlation coefficient and is said to measure the correlation between the two variables.
- The correlation coefficient $r$ is a number between $-1$ and 1.
- When both the variables are measured in standard units, $r$ is the slope of the "best straight line" for estimating $y$ based on $x$.
- $r$ measures the extent to which the scatter plot clusters around a straight line of positive or negative slope.
The function
football takes a value of $r$ as its argument and generates a football shaped scatter plot with correlation roughly $r$. The red line is the 45 degree line $y=x$, corresponding to points that are the same number of standard units in both variables. The green line, $y = rx$, is a smoothed version of the graph of averages. Points on the green line correspond to our estimates of the variable on the vertical axis, given values on the horizontal.
Call
football a few times, with different values of $r$ as the argument, and see how the football changes. Positive $r$ corresponds to positive association: above-average values of one variable are associated with above-average values of the other, and the scatter plot slopes upwards.
Notice also that the bigger the absolute value of $r$, the more clustered the points are around the green line of averages, and the closer the green line is to the red line of equal standard units.
When $r=1$ the scatter plot is perfectly linear and slopes upward. When $r=-1$, the scatter plot is perfectly linear and slopes downward. When $r=0$, the scatter plot is a formless cloud around the horizontal axis, and the variables are said to be uncorrelated.
# Football shaped scatter, both axes in standard units # Argument of function: correlation coefficient r # red line: slope = 1 (or -1) # green line: smoothed graph of averages, slope = r # Use the green line for estimating y based on x football(0.6)
football(0.2)
football(0)
football(-0.7)
Calculating $r$¶
The formula for $r$ is not apparent from our observations so far; it has a mathematical basis that is outside the scope of this class. However, the calculation is straightforward and helps us understand several of the properties of $r$.
Formula for $r$:
- $r$ is the average of the products of the two variables, when both variables are measured in standard units.
Here are the steps in the calculation. We will apply the steps to a simple table of values of $x$ and $y$.
t = Table([np.arange(1,7,1), [2, 3, 1, 5, 2, 7]], ['x','y']) t
Based on the scatter plot, we expect that $r$ will be positive but not equal to 1.
plots.scatter(t['x'], t['y'], s=30, color='r') plots.xlim(0, 8) plots.ylim(0, 8) plots.xlabel('x') plots.ylabel('y', rotation=0)
Step 1. Convert each variable to standard units.
t['x_su'] = (t['x'] - np.mean(t['x']))/np.std(t['x']) t['y_su'] = (t['y'] - np.mean(t['y']))/np.std(t['y']) t
Step 2. Multiply each pair of standard units.
t['su_product'] = t['x_su']*t['y_su'] t
Step 3. $r$ is the average of the products computed in Step 2.
# r is the average of the products of standard units r = np.mean(t['su_product']) r
0.61741639718977093
As expected, $r$ is positive but not equal to 1.
The calculation shows that:
- $r$ is a pure number; it has no units. This is because $r$ is based on standard units.
- $r$ is unaffected by changing the units on either axis. This too is because $r$ is based on standard units.
- $r$ is unaffected by switching the axes. Algebraically, this is because the product of standard units does not depend on which variable is called $x$ and which $y$. Geometrically, switching axes reflects the scatter plot about the line $y=x$, but does not change the amount of clustering nor the sign of the association.
plots.scatter(t['y'], t['x'], s=30, color='r') plots.xlim(0, 8) plots.ylim(0, 8) plots.xlabel('y') plots.ylabel('x', rotation=0)
The NumPy method
corrcoef can be used to calculate $r$. The arguments are an array containing the values of $x$ and another containing the corresponding values of $y$. The program evaluates to a correlation matrix, which is this case is a 2x2 table indexed by $x$ and $y$. The top left element is the correlation between $x$ and $x$, and hence is 1. The top right element is the correlation between $x$ and $y$, which is equal to the correlation between $y$ and $x$ displayed on the bottom left. The bottom right element is 1, the correlation between $y$ and $y$.
np.corrcoef(t['x'], t['y'])
array([[ 1. , 0.6174164], [ 0.6174164, 1. ]])
For the purposes of this class, correlation matrices are unnecessary. We will define our own function
corr to compute $r$, based on the formula that we used above. The arguments are the name of the table and the labels of the columns containing the two variables. The function returns the mean of the products of standard units, which is $r$.
def corr(table, column_A, column_B): x = table[column_A] y = table[column_B] return np.mean(((x-np.mean(x))/np.std(x))*((y-np.mean(y))/np.std(y)))
Here are examples of calling the function. Notice that it gives the same answer to the correlation between $x$ and $y$ as we got by using
np.corrcoef and earlier by direct application of the formula for $r$. Notice also that the correlation between maternal age and birth weight is very low, confirming the lack of any upward or downward trend in the scatter diagram.
corr(t, 'x', 'y')
0.61741639718977093
corr(baby, 'birthwt', 'gest_days')
0.40754279338885108
corr(baby, 'birthwt', 'mat_age')
0.026982911002929499
plots.scatter(baby['mat_age'], baby['birthwt']) plots.xlabel("mother's age") plots.ylabel('birth weight')
Properties of Correlation¶
Correlation is a simple and powerful concept, but it is sometimes misused. Before using $r$, it is important to be aware of the following points.
Correlation only measures association. Correlation does not imply causation. Though the correlation between the weight and the math ability of children in a school district may be positive, that does not mean that doing math makes children heavier or that putting on weight improves the children's math skills. Age is a confounding variable: older children are both heavier and better at math than younger children, on average.
Correlation measures linear association. Variables that have strong non-linear association might have very low correlation. Here is an example of variables that have a perfect quadratic relation $y = x^2$ but have correlation equal to 0.
tsq = Table([np.arange(-4, 4.1, 0.5), np.arange(-4, 4.1, 0.5)**2], ['x','y']) plots.scatter(tsq['x'], tsq['y']) plots.xlabel('x') plots.ylabel('y', rotation=0)
corr(tsq, 'x', 'y')
0.0
- Outliers can have a big effect on correlation. Here is an example where a scatter plot for which $r$ is equal to 1 is turned into a plot for which $r$ is equal to 0, by the addition of just one outlying point.
t = Table([[1,2,3,4],[1,2,3,4]], ['x','y']) plots.scatter(t['x'], t['y'], s=30, color='r') plots.xlim(0, 6) plots.ylim(-0.5,6)
corr(t, 'x', 'y')
1.0
t_outlier = Table([[1,2,3,4,5],[1,2,3,4,0]], ['x','y']) plots.scatter(t_outlier['x'], t_outlier['y'], s=30, color='r') plots.xlim(0, 6) plots.ylim(-0.5,6)
corr(t_outlier, 'x', 'y')
0.0
- Correlations based on aggregated data can be misleading. As an example, here are data on the Critical Reading and Math SAT scores in 2014. There is one point for each of the 50 states and one for Washington, D.C. The column
Participation Ratecontains the percent of high school seniors who took the test. The next three columns show the average score in the state on each portion of the test, and the final column is the average of the total scores on the test.
sat2014 = Table.read_table('sat2014.csv').sort('State') sat2014
... (41 rows omitted)
The scatter diagram of Math scores versus Critical Reading scores is very tightly clustered around a straight line; the correlation is close to 0.985.
plots.scatter(sat2014['Critical Reading'], sat2014['Math']) plots.xlabel('Critical Reading') plots.ylabel('Math')
corr(sat2014, 'Critical Reading', 'Math')
0.98475584110674341
It is important to note that this does not reflect the strength of the relation between the Math and Critical Reading scores of students. States don't take tests – students do. The data in the table have been created by lumping all the students in each state into a single point at the average values of the two variables in that state. But not all students in the state will be at that point, as students vary in their performance. If you plot a point for each student instead of just one for each state, there will be a cloud of points around each point in the figure above. The overall picture will be more fuzzy. The correlation between the Math and Critical Reading scores of the students will be lower than the value calculated based on state averages.
Correlations based on aggregates and averages are called ecological correlations and are frequently reported. As we have just seen, they must be interpreted with care.
Serious or tongue-in-cheek?¶
In 2012, a paper in the respected New England Journal of Medicine examined the relation between chocolate consumption and Nobel Prizes in a group of countries. The Scientific American responded seriously; others were more relaxed. The paper included the following graph:
See what you think about the analysis and also about the Reuters report that said, "The p-value Messerli calculated was 0.0001. 'This means that the odds of this being due to chance are less than 1 in 10,000," he said."
Regression
The regression line¶
The concepts of correlation and the "best" straight line through a scatter plot were developed in the late 1800's and early 1900's. The pioneers in the field were Sir Francis Galton, who was a cousin of Charles Darwin, and Galton's protégé Karl Pearson. Galton was interested in eugenics, and was a meticulous observer of the physical traits of parents and their offspring. Pearson, who had greater expertise than Galton in mathematics, helped turn those observations into the foundations of mathematical statistics.
The scatter plot below is of a famous dataset collected by Pearson and his colleagues in the early 1900's. It consists of the heights, in inches, of 1,078 pairs of fathers and sons.
The data are contained in the table
heights, in the columns
father and
son respectively. In the previous section, we saw how to use the table method
scatter to draw scatter plots. Here, the method
scatter in the
pyplot module of
matplotlib (imported as
plots) is used for the same purpose. The first argument of
scatter is a array containing the variable on the horizontal axis. The second argument contains the variable on the vertical axis. The optional argument
s=10 sets the size of the points; the default value is
s=20.
# Scatter plot using matplotlib method heights = Table.read_table('heights.csv') plots.scatter(heights['father'], heights['son'], s=10) plots.xlabel("father's height") plots.ylabel("son's height")
Notice the familiar football shape. This is characteristic of variable pairs that follow a bivariate normal distribution: the scatter plot is oval, the distribution of each variable is roughly normal, and the distribution of the variable in each vertical and horizontal strip is roughly normal as well.
The correlation between the heights of the fathers and sons is about 0.5.
r = corr(heights, 'father', 'son') r
0.50116268080759108
The regression effect¶
The figure below shows the scatter plot of the data when both variables are measured in standard units. As we saw earlier, the red line of equal standard units is too steep to serve well as the line of estimates of $y$ based on $x$. Rather, the estimates are on the green line, which is flatter and picks off the centers of the vertical strips.
This flattening was noticed by Galton, who had been hoping that exceptionally tall fathers would have sons who were just as exceptionally tall. However, the data were clear, and Galton realized that the tall fathers have sons who are not quite as exceptionally tall, on average. Frustrated, Galton called this phenomenon "regression to mediocrity." Because of this, the line of best fit through a scatter plot is called the regression line.
Galton also noticed that exceptionally short fathers had sons who were somewhat taller relative to their generation, on average. In general, individuals who are away from average on one variable are expected to be not quite as far away from average on the other. This is called the regression effect.
# The regression effect f_su = (heights['father']-np.mean(heights['father']))/np.std(heights['father']) s_su = (heights['son']-np.mean(heights['son']))/np.std(heights['son']) plots.scatter(f_su, s_su, s=10) plots.plot([-4, 4], [-4, 4], color='r', lw=1) plots.plot([-4, 4], [-4*r, 4*r], color='g', lw=1) plots.axes().set_aspect('equal')
The
Table method
scatter can be used with the option
fit_line=True to draw the regression line through a scatter plot.
# Plotting the regression line, using Table heights.scatter('father', fit_line=True) plots.xlabel("father's height") plots.ylabel("son's height")
Karl Pearson used the observation of the regression effect in the data above, as well as in other data provided by Galton, to develop the formal calculation of the correlation coefficient $r$. That is why $r$ is sometimes called Pearson's correlation.
The equation of the regression line¶
As we saw in the last section for football shaped scatter plots, when the variables $x$ and $y$ are measured in standard units, the best straight line for estimating $y$ based on $x$ has slope $r$ and passes through the origin. Thus the equation of the regression line can be written as:
$~~~~~~~~~~$ estimate of $y$, in $y$-standard units $~=~$ $r ~ \times$ (the given $x$, in $x$-standard units)
That is, $$ \frac{\mbox{estimate of}~y ~-~\mbox{average of}~y}{\mbox{SD of}~y} ~=~ r \times \frac{\mbox{the given}~x ~-~\mbox{average of}~x}{\mbox{SD of}~x} $$
The equation can be converted into the original units of the data, either by rearranging this equation algebraically, or by labeling some important features of the line both in standard units and in the original units.
It is a remarkable fact of mathematics that what we have observed to be true for football shaped scatter plots turns out to be true for all scatter plots, no matter what they look like.
Regardless of the shape of the scatter plot:$$ \mbox{slope of the regression line} ~=~ \frac{r \cdot \mbox{SD of}~y}{\mbox{SD of}~x} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $$$$ \mbox{intercept of the regression line} ~=~ \mbox{average of}~y ~-~ \mbox{slope} \cdot \mbox{(average of}~x\mbox{)} $$
Calculation of the slope and intercept¶
The NumPy method
np.polyfit takes as its first argument an array consisiting of the values of the given variable; its second argument an array consisting of the variable to be estimated; its third argument
deg=1 specifies that we are fitting a straight line, that is, a polynomial of degree 1. It evaluates to an array consisting of the slope and the intercept of the regression line.
# Slope and intercept by NumPy method np.polyfit(heights['father'], heights['son'], deg=1)
array([ 0.51400591, 33.89280054])
It is worth noting that the intercept of approximately 33.89 inches is not intended as an estimate of the height of a son whose father is 0 inches tall. There is no such son and no such father. The intercept is merely a geometric or algebraic quantity that helps define the line. In general, it is not a good idea to extrapolate, that is, to make estimates outside the range of the available data. It is certainly not a good idea to extrapolate as far away as 0 is from the heights of the fathers in the study.
The calculations of the slope and intercept of the regression line are straightforward, so we will set
np.polyfit aside and write our own function to compute the two quantities. The function
regress takes as its arguments the name of the table, the column label of the given variable, and the column label of the variable to be estimated; it evaluates to an array containing the slope and the intercept of the regression line.
#])
A call to
regress yields the same results as the call to
np.polyfit made above.
slope_int_h = regress(heights, 'father', 'son') slope_int_h
array([ 0.51400591, 33.89280054])
Fitted values¶
We can use the regression line to get an estimate of the height of every son in the data. The estimated values of $y$ are called the fitted values. They all lie on a straight line. To calculate them, take a son's height, multiply it by the slope of the regression line, and add the intercept. In other words, calculate the height of the regression line at the given value of $x$.
# Estimates of sons' heights are on the regression line heights['fitted value'] = slope_int_h[0]*heights['father'] + slope_int_h[1] heights
... (1068 rows omitted)
The amount of error in each of these regression estimates is the difference between the son's height and its estimate. These errors are called residuals. Some residuals are positive. These correspond to points that are above the regression line – points for which the regression line under-estimates $y$. Negative residuals correspond to the line over-estimating values of $y$.
# Error in the regression estimate: Distance between observed value and fitted value # "Residual" heights['residual'] = heights['son'] - heights['fitted value'] heights
... (1068 rows omitted)
As with deviations from average, the positive and negative residuals exactly cancel each other out. So the average (and sum) of the residuals is 0.
Error in the regression estimate¶
Though the average residual is 0, each individual residual is not. Some residuals might be quite far from 0. To get a sense of the amount of error in the regression estimate, we will start with a graphical description of the sense in which the regression line is the "best".
Our example is a dataset that has one point for every chapter of the novel "Little Women." The goal is to estimate the number of characters (that is, letters, punctuation marks, and so on) based on the number of periods. Recall that we attempted to do this in the very first lecture of this course.
lw = Table.read_table('little_women.csv')
# One point for each chapter # Horizontal axis: number of periods # Vertical axis: number of characters (as in a, b, ", ?, etc; not people in the book) plots.scatter(lw['Periods'], lw['Characters']) plots.xlabel('Periods') plots.ylabel('Characters')
corr(lw, 'Periods', 'Characters')
0.92295768958548163
The scatter plot is remarkably close to linear, and the correlation is more than 0.92.
a = [131, 14431] b = [231, 20558] c = [392, 40935] d = [157, 23524] def lw_errors(slope, intercept): xlims = np.array([50, 450]) plots.scatter(lw['Periods'], lw['Characters']) plots.plot(xlims, slope*xlims + intercept, lw=2) plots.plot([a[0],a[0]], [a[1], slope*a[0] + intercept], color='r', lw=2) plots.plot([b[0],b[0]], [b[1], slope*b[0] + intercept], color='r', lw=2) plots.plot([c[0],c[0]], [c[1], slope*c[0] + intercept], color='r', lw=2) plots.plot([d[0],d[0]], [d[1], slope*d[0] + intercept], color='r', lw=2) plots.xlabel('Periods') plots.ylabel('Characters')
The figure below shows the scatter plot and regression line, with four of the errors marked in red.
# Residuals: Deviations from the regression line slope_int_lw = regress(lw, 'Periods', 'Characters') lw_errors(slope_int_lw[0], slope_int_lw[1])
Had we used a different line to create our estimates, the errors would have been different. The picture below shows how big the errors would be if we were to use a particularly silly line for estimation.
# Errors: Deviations from a different line lw_errors(-100, 50000)
Below is a line that we have used before without saying that we were using a line to create estimates. It is the horizontal line at the value "average of $y$." Suppose you were asked to estimate $y$ and were not told the value of $x$; then you would use the average of $y$ as your estimate, regardless of the chapter. In other words, you would use the flat line below.
Each error that you would make would then be a deviation from average. The rough size of these deviations is the SD of $y$.
In summary, if we use the flat line at the average of $y$ to make our estimates, the estimates will be off by the SD of $y$.
# Errors: Deviations from the flat line at the average of y lw_errors(0, np.mean(lw['Characters']))
The Method of Least Squares¶
If you use any arbitrary line as your line of estimates, then some of your errors are likely to be positive and others negative. To avoid cancellation when measuring the rough size of the errors, we take the mean of the sqaured errors rather than the mean of the errors themselves. This is exactly analogous to our reason for looking at squared deviations from average, when we were learning how to calculate the SD.
The mean squared error of estimation using a straight line is a measure of roughly how big the squared errors are; taking the square root yields the root mean square error, which is in the same units as $y$.
Here is the second remarkable fact of mathematics in this section: the regression line minimizes the mean squared error of estimation (and hence also the root mean squared error) among all straight lines. That is why the regression line is sometimes called the "least squares line."
Computing the "best" line.
- To get estimates of $y$ based on $x$, you can use any line you want.
- Every line has a mean squared error of estimation.
- "Better" lines have smaller errors.
- The regression line is the unique straight line that minimizes the mean squared error of estimation among all straight lines.
Regression Functions¶
Regression is one of the most commonly used methods in statistics, and we will be using it frequently in the next few sections. It will be helpful to be able to call functions to compute the various quantities connected with regression. The first two of the functions below have already been defined; the rest are defined below.
corr: the correlation coefficient
regress: the slope and intercept of the regression line
fit: the fitted value at one given value of $x$
fitted_values: the fitted values at all the values of $x$ in the data
residuals: the residuals
scatter_fit: scatter plot and regression line
residual_plot: plot of residuals versus $x$
# Correlation coefficient def corr(table, column_A, column_B): x = table[column_A] y = table[column_B] x_su = (x-np.mean(x))/np.std(x) y_su = (y-np.mean(y))/np.std(y) return np.mean(x_su*y_su)
#])
# Fitted value; the regression estimate at x=new_x def fit(table, column_x, column_y, new_x): slope_int = regress(table, column_x, column_y) return slope_int[0]*new_x + slope_int[1]
# Fitted values; the regression estimates lie on a straight line def fitted_values(table, column_x, column_y): slope_int = regress(table, column_x, column_y) return slope_int[0]*table[column_x] + slope_int[1]
# Residuals: Deviations from the regression line def residuals(table, column_x, column_y): fitted = fitted_values(table, column_x, column_y) return table[column_y] - fitted
# Scatter plot with fitted (regression) line def scatter_fit(table, column_x, column_y): plots.scatter(table[column_x], table[column_y], s=10) plots.plot(table[column_x], fitted_values(table, column_x, column_y), lw=1, color='green') plots.xlabel(column_x) plots.ylabel(column_y)
# A residual plot def residual_plot(table, column_x, column_y): plots.scatter(table[column_x], residuals(table, column_x, column_y), s=10) xm = np.min(table[column_x]) xM = np.max(table[column_x]) plots.plot([xm, xM], [0, 0], color='k', lw=1) plots.xlabel(column_x) plots.ylabel('residual')
Suppose you have carried out the regression of sons' heights on fathers' heights.
scatter_fit(heights, 'father', 'son')
It is a good idea to then draw a residual plot. This is a scatter plot of the residuals versus the values of $x$. The residual plot of a good regression looks like the one below: a formless cloud with no pattern, centered around the horizontal axis. It shows that there is no discernible non-linear pattern in the original scatter plot.
residual_plot(heights, 'father','son')
Residual plots can be useful for spotting non-linearity in the data, or other features that weaken the regression analysis. For example, consider the SAT data of the previous section, and suppose you try to estimate the
Combined score based on
Participation Rate.
sat2014 = Table.read_table('sat2014.csv') sat2014
... (41 rows omitted)
plots.scatter(sat2014['Participation Rate'], sat2014['Combined'], s=10) plots.xlabel('Participation Rate') plots.ylabel('Combined')
The relation between the variables is clearly non-linear, but you might be tempted to fit a straight line anyway, especially if you did not first draw the scatter diagram of the data.
scatter_fit(sat2014, 'Participation Rate', 'Combined') plots.title("A bad idea")
The points in the scatter plot start out above the regression line, then are consistently below the line, then above, then below. This pattern of non-linearity is more clearly visible in the residual plot.
residual_plot(sat2014, 'Participation Rate', 'Combined') plots.title('Residual plot of the bad regression')
This residual plot shows a non-linear pattern, and is a signal that linear regression should not have been used for these data.
The rough size of the residuals¶
Let us return to the heights of the fathers and sons, and compare the estimates based on using the regression line and the flat line (in yellow) at the average height of the sons. As noted above, the rough size of the errors made using the flat line is the SD of $y$. Clearly, the regression line does a better job of estimating sons' heights than the flat line does; indeed, it minimizes the mean squared error among all lines. Thus, the rough size of the errors made using the regression line must be smaller that that using the flat line. In other words, the SD of the residuals must be smaller than the overall SD of $y$.
ave_y = np.mean(heights['son']) scatter_fit(heights, 'father', 'son') plots.plot([np.min(heights['father']), np.max(heights['father'])], [ave_y, ave_y], lw=2, color='gold')
Here, once again, are the residuals in the estimation of sons' heights based on fathers' heights. Each residual is the difference between the height of a son and his estimated (or "fitted") height.
heights
... (1068 rows omitted)
The average of the residuals is 0. All the negative errors exactly cancel out all the positive errors.
The SD of the residuals is about 2.4 inches, while the overall SD of the sons' heights is about 2.7 inches. As expected, the SD of the residuals is smaller than the overall SD of $y$.
np.std(heights['residual'])
2.4358716091393409
np.std(heights['father'])
2.744553207672785
Smaller by what factor? Another remarkable fact of mathematics is that no matter what the data look like, the SD of the residuals is $\sqrt{1-r^2}$ times the SD of $y$.
np.std(heights['residual'])/np.std(heights['son'])
0.86535308826267487
np.sqrt(1 - r**2)
0.86535308826267476
The residuals are equal to the values of $y$ minus the fitted values. Since the average of the residuals is 0, the average of the fitted values must be equal to the average of $y$.
In the figure below, the fitted values are all on the green line segment. The center of that segment is at the point of averages, consistent with our calculation of the average of the fitted values.
scatter_fit(heights, 'father', 'son')
The SD of the fitted values is visibly smaller than the overall SD of $y$. The fitted values range from about 64 to about 73, whereas the values of $y$ range from about 58 to 77.
So if we take the ratio of the SD of the fitted values to the SD of $y$, we expect to get a number between 0 and 1. And indeed we do: a very special number between 0 and 1.
np.std(heights['fitted value'])/np.std(heights['son'])
0.50116268080759108
r
0.50116268080759108
Here is the final remarkable fact of mathematics in this section:
Notice the absolute value of $r$ in the formula above. For the heights of fathers and sons, the correlation is positive and so there is no difference between using $r$ and using its absolute value. However, the result is true for variables that have negative correlation as well, provided we are careful to use the absolute value of $r$ instead of $r$.
Bootstrap for Regression
Assumptions of randomness: a "regression model"¶
In the last section, we developed the concepts of correlation and regression as ways to describe data. We will now see how these concepts can become powerful tools for inference, when used appropriately.
Questions of inference may arise if we believe that a scatter plot reflects the underlying relation between the two variables being plotted but does not specify the relation completely. For example, a scatter plot of the heights of fathers and sons shows us the precise relation between the two variables in one particular sample of men; but we might wonder whether that relation holds true, or almost true, among all fathers and sons in the population from which the sample was drawn, or indeed among fathers and sons in general.
As always, inferential thinking begins with a careful examination of the assumptions about the data. Sets of assumptions are known as models. Sets of assumptions about randomness in roughly linear scatter plots are called regression models.
In brief, such models say that the underlying relation between the two variables is perfectly linear; this straight line is the signal that we would like to identify. However, we are not able to see the line clearly. What we see are points that are scattered around the line. In each of the points, the signal has been contaminated by random noise. Our inferential goal, therefore, is to separate the signal from the noise.
In greater detail, the regression model specifies that the points in the scatter plot are generated at random as follows.
- The relation between $x$ and $y$ is perfectly linear. We cannot see this "true line" but Tyche can. She is the Goddess of Chance.
- Tyche creates the scatter plot by taking points on the line and pushing them off the line vertically, either above or below, as follows:
- For each $x$, Tyche finds the corresponding point on the true line, and then adds an error.
- The errors are drawn at random with replacement from a population of errors that has a normal distribution with mean 0.
- Tyche creates a point whose horizontal coordinate is $x$ and whose vertical coordinate is "the height of the true line at $x$, plus the error".
- Finally, Tyche erases the true line from the scatter, and shows us just the scatter plot of her points.
Based on this scatter plot, how should we estimate the true line? The best line that we can put through a scatter plot is the regression line. So the regression line is a natural estimate of the true line.
The simulation below shows how close the regression line is to the true line. The first panel shows how Tyche generates the scatter plot from the true line; the second show the scatter plot that we see; the third shows the regression line through the plot; and the fourth shows both the regression line and the true line.
Run the simulation a few times, with different values for the slope and intercept of the true line, and varying sample sizes. You will see that the regression line is a good estimate of the true line if the sample size is moderately large.
def draw_and_compare(true_slope, true_int, sample_size): x = np.random.normal(50, 5, sample_size) xlims = np.array([np.min(x), np.max(x)]) eps = np.random.normal(0, 6, sample_size) y = (true_slope*x + true_int) + eps tyche = Table([x,y],['x','y']) plots.figure(figsize=(6, 16)) plots.subplot(4, 1, 1) plots.scatter(tyche['x'], tyche['y'], s=10) plots.plot(xlims, true_slope*xlims + true_int, lw=1, color='gold') plots.title('What Tyche draws') plots.subplot(4, 1, 2) plots.scatter(tyche['x'],tyche['y'], s=10) plots.title('What we get to see') plots.subplot(4, 1, 3) scatter_fit(tyche, 'x', 'y') plots.xlabel("") plots.ylabel("") plots.title('Regression line: our estimate of true line') plots.subplot(4, 1, 4) scatter_fit(tyche, 'x', 'y') xlims = np.array([np.min(tyche['x']), np.max(tyche['x'])]) plots.plot(xlims, true_slope*xlims + true_int, lw=1, color='gold') plots.title("Regression line and true line")
# Tyche's true line, # the points she creates, # and our estimate of the true line. # Arguments: true slope, true intercept, number of points draw_and_compare(3, -5, 20)
|
http://data8.org/fa15/text/4_prediction.html
|
CC-MAIN-2019-13
|
refinedweb
| 7,140
| 64.81
|
By chance does anyone have a working configuration of some example of this working? I am not so interested in a SNMP trap. But if I could have it email/page me, now that would rock. Craig -----Original Message----- From: dm-devel-bounces redhat com [mailto:dm-devel-bounces redhat com] On Behalf Of Mike Anderson Sent: Friday, May 16, 2008 8:27 AM To: device-mapper development Subject: Re: [dm-devel] simple question... to tough to answer? Hannes Reinecke <hare suse de> wrote: > Hi Wim, > > Wim Colgate wrote: >> Hi, >> >> I???m not quite sure why no one in the community hasn???t been able to >> answer my questions. >> >> Simply (re)stated: >> >> 1) Are there hooks for dm/multipath events to notify software? >> > Yes. There is the general dm_event mechanism (which I wouldn't recommend) > or with newer kernels you'll get netlink events from multipath for any > path-related events. > You can look at the documentation in recent kernels trees to get an example of the event attributes provided with each event using the uevent interface: Documentation/device-mapper/dm-uevent.txt >> 2) does path down/up fire up udev rules? >> > Not as such. As stated above we should be sending out netlink events for > path up/down events, but to my knowledge no-one is taking advantage > of them. Certainly not udev in its default setting nor multipath. One should note that if using the the current git version of the multipath tools and one wants to experiment with additional events one would need to add a udev rule "(i.e., RUN+="socket:...") You can reference this previous email for context. On some what related note. With all the work around making sure we can run in low memory situations we should make a choice to use raw netlink interface or the udev abstract namespace socket. -andmike -- Michael Anderson andmike linux vnet ibm com -- dm-devel mailing list dm-devel redhat com
|
http://www.redhat.com/archives/dm-devel/2008-June/msg00030.html
|
CC-MAIN-2014-42
|
refinedweb
| 324
| 64.91
|
April Fools' Day Application
I'm tend to go a bit crazy when it comes to pranks. April Fool's day is almost like Christmas to me. So bombarding someone with 1,000 super bouncy balls seemed like the proper thing to do come the first possible moment.
But that someone was a bit harder than I thought. I needed a victim however but with how SpringCM's executive offices are designed, I quickly found him. My victim for this task is my CTO, Dave Dahl. I wasn't alone in this prank, I had my friend / co-worker, Andy Konkol, help out with the final assembly and testing of the application.
Here is the video of the final outcome over at YouTube.
You need a laptop, a rigging system, a WiFi network, a ton of bouncy balls, a drill, a spare ceiling tile, some string and a relay board. Here is the picture of the system finally done. The ceiling tile was modified with the sides shaved and gluing a piece of wood to the back to apply anchors into. To figure out how to wire up relay boards, I suggest reading Brian Peek's holiday lighting article. Brian provides diagrams and wiring safety information.
And we mustn't forget the balls. How does one buy super bouncy balls? It was surprisingly simple with Google and searching for "Super Bouncy balls". I got mine from Gumball Machine Warehouse for about $70 if memory serves. Each bag weights about 5 pounds I'd guess and is about a foot by a foot. Apply them gingerly onto the shaven tile since it isn't supported by the orginal 1/4" lip anymore.
Andy Konkol admiring the release rig. You can see we've mounted the drill to the fire system. You'll also notice the drill's trigger is tied down so all we need to do is hit the relay and the drill will be on.
So as every good programmer knows is to test often, and as this picture shows, it is well earned. Cleaning up the mess took about five minutes. A video of this test can be found over on YouTube. Since we didn't know how much it would hurt or cause damage, a human test subject was needed. I stepped up to plate and had the crap freaked out of myself even knowing the balls were going to be deployed.
The application is fairly simple and uses a Control Anything USB relay board and has a laptop placed on a ceiling tile. The laptop was left on and with Remote Desktop Connection, the application will be triggered.
I'm using the relay board for another project so currently it is a fairly simple codebase. This application was the test bed for the next project. How the relay board works is by sending a sequence of commands. 254 will prepare for a command, 29 then will turn all the relays off, 30 on. The Control Anything relay board has a host of other features I haven't had time yet to implement but will soon so you can check back for a richer API for the relay board. The company does provide Visual Basic 6 code examples and uses the chr$ command instead of a byte array.
C#
public bool AllRelaysOff() { ComPort.WriteBuffer(new byte[] { 254, 29 }); return relaySuccess(); } public bool AllRelaysOn() { ComPort.WriteBuffer(new byte[] { 254, 30 }); return relaySuccess(); } private bool relaySuccess() { return (ComPort.ReadBufferChar() == 85); }
VB
Public Function AllRelaysOff() As Boolean ComPort.WriteBuffer(New Byte() {254, 29}) Return relaySuccess() End Function Public Function AllRelaysOn() As Boolean ComPort.WriteBuffer(New Byte() {254, 30}) Return relaySuccess() End Function Private Function relaySuccess() As Boolean Return (ComPort.ReadBufferChar = 85) End Function
The comport code is actually a slightly refractored version from my dance floor application. The class itself is a wrapper for the .Net SerialPort object which can be found in System.IO.Ports. Furthermore, it now inherits off IDisposable to help auto close the serial port and is designed aimed to help ease use for multiple applications.
C#
public class ComPortIO : IDisposable { #region varibles public SerialPort ComPort { get { return _comPort; } set { _comPort = value; } } private SerialPort _comPort; public bool DoneWriting { get { return _doneWriting; } set { _doneWriting = value; } } private bool _doneWriting; public bool DisableWriting { get { return _disableWriting; } set { _disableWriting = value; } } private bool _disableWriting; #endregion public void Dispose() { if (ComPort.IsOpen) ComPort.Close(); } #region constructors public ComPortIO(string ComPortName, int BaudRate, bool DisableComWriting) { DisableWriting = DisableComWriting; if (!DisableWriting) { if (!doesPortExist(ComPortName)) throw new ArgumentException("The serial port used is not valid", ComPortName); ComPort = new SerialPort(ComPortName, BaudRate, Parity.None, 8, StopBits.One); if (!ComPort.IsOpen) ComPort.Open(); ComPort.ReadTimeout = 100; } } #endregion #region public functions public void WriteBuffer(char[] Buffer) { if (!DisableWriting) ComPort.Write(Buffer, 0, Buffer.Length); } public void WriteBuffer(byte[] Buffer) { if (!DisableWriting) ComPort.Write(Buffer, 0, Buffer.Length); } public void WriteBuffer(string Buffer) { if (!DisableWriting) ComPort.Write(Buffer); } public string ReadBuffer() { try { if (!DisableWriting && ComPort.IsOpen) { return ComPort.ReadLine(); } } catch (Exception) { } return null; } public int ReadBufferChar() { try { if (!DisableWriting && ComPort.IsOpen) { return ComPort.ReadChar(); } } catch (Exception) { } return -1; } public int ReadBufferByte() { try { if (!DisableWriting && ComPort.IsOpen) { return ComPort.ReadByte(); } } catch (Exception) { } return -1; } #endregion #region private functions private static bool doesPortExist(string ComPortName) { string[] serialPortNames = SerialPort.GetPortNames(); for (int i = 0; i < serialPortNames.Length; i++) { if (string.Compare(serialPortNames[i], ComPortName, true) == 0) return true; } return false; } #endregion }
VB
Public Class ComPortIO Implements IDisposable Private _comPort As SerialPort Private _doneWriting As Boolean Private _disableWriting As Boolean Public Sub New(ByVal ComPortName As String, ByVal BaudRate As Integer, ByVal DisableComWriting As Boolean) MyBase.New() DisableWriting = DisableComWriting If Not DisableWriting Then If Not doesPortExist(ComPortName) Then Throw New ArgumentException("The serial port used is not valid", ComPortName) End If ComPort = New SerialPort(ComPortName, BaudRate, Parity.None, 8, StopBits.One) If Not ComPort.IsOpen Then ComPort.Open() End If ComPort.ReadTimeout = 100 End If End Sub Public Property ComPort() As SerialPort Get Return _comPort End Get Set(ByVal value As SerialPort) _comPort = value End Set End Property Public Property DoneWriting() As Boolean Get Return _doneWriting End Get Set(ByVal value As Boolean) _doneWriting = value End Set End Property Public Property DisableWriting() As Boolean Get Return _disableWriting End Get Set(ByVal value As Boolean) _disableWriting = value End Set End Property Public Overloads Sub Dispose() Implements IDisposable.Dispose If ComPort.IsOpen Then ComPort.Close() End If End Sub Public Overloads Sub WriteBuffer(ByVal Buffer() As Char) If Not DisableWriting Then ComPort.Write(Buffer, 0, Buffer.Length) End If End Sub Public Overloads Sub WriteBuffer(ByVal Buffer() As Byte) If Not DisableWriting Then ComPort.Write(Buffer, 0, Buffer.Length) End If End Sub Public Overloads Sub WriteBuffer(ByVal Buffer As String) If Not DisableWriting Then ComPort.Write(Buffer) End If End Sub Public Function ReadBuffer() As String Try If (Not DisableWriting _ AndAlso ComPort.IsOpen) Then Return ComPort.ReadLine End If Catch End Try Return Nothing End Function Public Function ReadBufferChar() As Integer Try If (Not DisableWriting _ AndAlso ComPort.IsOpen) Then Return ComPort.ReadChar End If Catch End Try Return -1 End Function Public Function ReadBufferByte() As Integer Try If (Not DisableWriting _ AndAlso ComPort.IsOpen) Then Return ComPort.ReadByte End If Catch End Try Return -1 End Function Private Shared Function doesPortExist(ByVal ComPortName As String) As Boolean Dim serialPortNames() As String = SerialPort.GetPortNames Dim i As Integer = 0 Do While (i < serialPortNames.Length) If (String.Compare(serialPortNames(i), ComPortName, True) = 0) Then Return True End If i = (i + 1) Loop Return False End Function End Class
As soon as Dave Dahl sat down, I clicked the drop button and the everything worked like clock work. If you want to see the video, once again it is over at YouTube for your April Fools Day pleasure.
Before you do such a prank, please be sure you your victim will be cool with it so you won't get fired. Thankfully, I wasn't and Dave is cool ... I hope. I wasn't happy totally with our deployment solution since it was partially visible due to the string. I'd also like to have had the entire system automated with maybe an IR sensor or a force sensor hidden in the seat. Given a few more weekends and actually planning this prank out a bit more, I think Andy and myself could have come up with a more robust system.
A special thanks to Dave Dahl for being such a good sport and Andy Konkol for helping out.
Clint is an application developer for SpringCM, an on-demand, web-based document and content management system. His two primary development languages are C# and JavaScript. Prior to the ball drop.
this is a kick * trick. too much work for dropping some bouncy balls though...
I like the trick. We play pranks on each other in our office all the time but they usually pretty low-tech. This year at Christmas we wrapped a guys entire cubicle in wrapping paper. Computer, chair, pencils...everything
I'll have to get my tech guys to help me out with some better high-tech pranks now.
Charles
That is soooooo AWESOME!!!! I have to try that on my friends!!! Great prank!!!
Clint, this is AWESOME! I'm going to have to try this next year, or something like it.
Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.
|
https://channel9.msdn.com/coding4fun/articles/April-Fools-Day-with-Bouncy-Balls
|
CC-MAIN-2017-09
|
refinedweb
| 1,587
| 57.77
|
- Start Date: 2018-06-19
- RFC PR:
- Ember Issue: (leave this empty)
Deprecate Ember.merge in favor of Ember.assign
Summary
The goal of this RFC is to remove
Ember.merge in favor of using
Ember.assign.
Motivation
Ember.assign has been around quite awhile, and has the same functionality as
Ember.merge.
With that in mind, we should remove the old
Ember.merge, in favor of just having a single function.
Detailed design
Ember will start logging deprecation messages that tell you to use
Ember.assign instead of
Ember.merge.
The exact deprecation message will be decided later, but something along the lines of:
Using `Ember.merge` is deprecated. Please use `Ember.assign` instead. If you are using a version of Ember <= 2.4 you can use [ember-assign-polyfill]() to make `Ember.assign` available to you.
How we teach this
This should be a simple 1 to 1 conversion, and the deprecation message should be clear enough for all to
understand what they need to do, and convert all usages of
Ember.merge to
Ember.assign.
Deprecation Guide
An entry to the Deprecation Guides will be added outlining the conversion from
Ember.merge to
Ember.assign.
Ember.merge predates
Ember.assign, but since
Ember.assign has been released,
Ember.merge has been mostly unnecessary.
To cut down on duplication, we are now recommending using
Ember.assign instead of
Ember.merge. If you are using a version of
Ember <= 2.4 you can use ember-assign-polyfill to make
Ember.assign
available to you.
Before:
import { merge } from '@ember/polyfills'; var a = { first: 'Yehuda' }; var b = { last: 'Katz' }; merge(a, b); // a == { first: 'Yehuda', last: 'Katz' }, b == { last: 'Katz' }
After:
import { assign } from '@ember/polyfills'; var a = { first: 'Yehuda' }; var b = { last: 'Katz' }; assign(a, b); // a == { first: 'Yehuda', last: 'Katz' }, b == { last: 'Katz' }
Codemod
A codemod will be provided to allow automatic conversion of
Ember.merge to
Ember.assign.
Drawbacks
The only drawback, that I can think of, is people would need to convert
Ember.merge to
Ember.assign, but this would be a very easy change and could easily be done via codemod.
Alternatives
The impact of not doing this, is we continue to have two functions that do basically the same thing, which we need to maintain.
Another alternative, could be to remove both
Ember.merge and
Ember.assign, in favor of
Object.assign
or something similar.
Unresolved questions
None, that I can think of.
|
https://emberjs.github.io/rfcs/0340-deprecate-ember-merge.html
|
CC-MAIN-2019-43
|
refinedweb
| 409
| 61.93
|
Dec 10, 2018 06:17 PM|kstMan|LINK
Hello, I have an ASP application.I performed the tutorial on code first migrations. When I executed the commands, the following code was generated for the user table:
CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), ApplicationId = c.Guid(nullable: false), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: true), UserName = c.String(nullable: false, maxLength: 256), Discriminator = c.String(), LegacyPasswordHash = c.String(), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex");
My problem is that I don't need some columns. So, I removed the code from those columns and updated my DB. But, when I try to authenticate a user, I get this error:
Invalid column name 'EmailConfirmed'. Invalid column name 'PhoneNumberConfirmed'. Invalid column name 'TwoFactorEnabled'. Invalid column name 'LockoutEndDateUtc'. Invalid column name 'LockoutEnabled'. Invalid column name 'AccessFailedCount'.
But these columns no longer exist because I deleted them. Or, is it possible to put it back and assign them default values for example:
to avoid making an insertion when creating a user. I use EF 6.2.0
Need help please.
Dec 10, 2018 07:18 PM|mgebhard|LINK
kstMan
Please Mgebhard, what do yo mean by "the model properties that generated the script". Does that mean that after I execute the command that generates the script, I have to modify the script before continuing?
Migration scripts are generated from Entity Models. The script was updated but not the model.
Again, simply start over and ignore the columns you do not plan to use.
Dec 10, 2018 08:22 PM|yogyogi|LINK
If you don't need a database table's column to be created for a property then give [NotMapped] attribute to that property. See this tutorial- Configurations in Entity Framework Core
All-Star
45489 Points
Microsoft
Dec 11, 2018 02:14 AM|Zhi Lv - MSFT|LINK
Hi kstMan,
kstManMy problem is that I don't need some columns. So, I removed the code from those columns and updated my DB. But, when I try to authenticate a user, I get this error:
As yogyogi said, you can apply the [NotMapped] attribute on one or more properties for which you do NOT want to create a corresponding column in a database table. This attribute applies to EF 6 and EF core.
Code as below:
using System.ComponentModel.DataAnnotations.Schema; public class Student { public int StudentId { get; set; } public string StudentName { get; set; } [NotMapped] public int Age { get; set; } }
More details about the [NotMapped] attribute, please check this article.
Best regards,
Dillion
All-Star
47180 Points
Dec 11, 2018 08:33 AM|PatriceSc|LINK
Hi, covers custom storage but is also interesting to understand the overall architecture. Rather than using the default implementation that covers all features you could also implement just those features you need.
It could be a bit cleaner than using the full implementation and trying to ignore/delete some columns...
Dec 11, 2018 06:04 PM|kstMan|LINK
Thank you for the replies. As suggested, I have tried :
public class ApplicationUser : IdentityUser{ [NotMapped] bool PhoneNumberConfirmed { get; set; } [NotMapped] public bool TwoFactorEnabled { get; set; } [NotMapped] public Nullable<DateTime> LockoutEndDateUtc { get; set; } [NotMapped] public bool LockoutEnabled { get; set; } [NotMapped] public int AccessFailedCount { get; set; } [NotMapped] public bool EmailConfirmed { get; set; } }
And also:
public class ApplicationUser: IdentityUser{ [NotMapped] public override bool PhoneNumberConfirmed { get; set; } [NotMapped] public override bool TwoFactorEnabled { get; set; } [NotMapped] public override Nullable<DateTime> LockoutEndDateUtc { get; set; } [NotMapped] public override bool LockoutEnabled { get; set; } [NotMapped] public override int AccessFailedCount { get; set; } [NotMapped] public override bool EmailConfirmed { get; set; } }
because the columns are inherited from identityUser, but it doesn't work.
Dec 11, 2018 06:19 PM|mgebhard|LINK
And the expected results.
Either ignore the ASP Identity feature you are not interested in used or customize Identity. Keep in mind fields you are trying exclude are used in other parts of the Identity API. These are features like two-factor authentication, Phone number store, and user lockout. So simply excluding a few properties does not really remove the features.
I recommend customizing Identity to suite your needs and only implement the stores that you need.
Dec 11, 2018 06:35 PM|mgebhard|LINK
kstMan
Ok I will try to customize
It's far easier to take advantage of the features you are interested in implementing and simply do not use or configure the features that you are not interested in. In the end it is up to you but crafting a custom Identity implementation has a steep learning curve depending on your programming experience.
10 replies
Last post Dec 11, 2018 06:35 PM by mgebhard
|
https://forums.asp.net/p/2150249/6241702.aspx?Re+Invalid+column+name+in+entity+framework
|
CC-MAIN-2020-29
|
refinedweb
| 809
| 58.08
|
BBC micro:bit
Encoding Ciphers
Introduction
If you have written a Python program and flashed it to the micro:bit, you can use the REPL window to interact with it. This project turns the micro:bit into a cipher toolkit for encoding and decoding ciphers.
This page will start you off. There are algorithms for several ciphers in another section of this web site.
This page shows you that you can use the micro:bit as a platform for running Python programs for you to interact with via REPL.
Caesar Shift
We'll start with one of the simplest ciphers, the Caesar Shift Cipher. Read more about it on this page.
from microbit import * def Caesar(plain, shift): cipher = "" p = plain.upper() for s in p: if ord(s)==32: cipher += " " elif ord(s)>=65 and ord(s)<=90: c = ord(s) c += shift if c<65: c += 26 elif c>90: c -= 26 cipher += chr(c) return cipher
The program is just a function. You will need to use an REPL terminal to interact with the program. Here is an example of it in action using Mu.
Vignère
This is a slightly more complex cipher. Read about it on this page.
The cipher uses a keyword and more than one alphabet.
from microbit import * def Vignere(plain, keyword): p = plain.upper() k = keyword.upper() cipher = "" x = 0 y = 0 clean = "" for l in p: if ord(l)>=65 and ord(l)<=90: clean += l cnt = 0 for i,c in enumerate(clean, start=0): y = ord(c)-65 x = ord(k[i % len(k)]) - 65 cipher += chr(65 + ((x+y)%26)) return cipher
In action,
Challenges
Have a look at some of the algorithms in the Ciphers section of the site. Just add more functions to your program and call them from the REPL window.
Keep going with this idea. You can make a whole host of functions and run them directly from the REPL window.
|
http://www.multiwingspan.co.uk/micro.php?page=cipher
|
CC-MAIN-2019-09
|
refinedweb
| 327
| 73.58
|
SQL injection has been around since the begging of time. It has consistently been on the OWASP top 10 list and shows no signs of slowing down. Almost every application interacts with a back end database in some way so it’s no surprise that its one of the most popular vulnerabilities out there. When doing a black box engagement you might place a ‘ or “ mark every where to see if the page errors out, if it does you most likely got SQL injection. If you have access to the source code you will go about finding this a little differently.
String Concatenation
So many vulnerabilities are caused by string concatenation. Buffer overflows, XSS, SQL Injection, and a lot of other vulnerabilities can arise when you improperly combine strings together.
buffer_Overflow = string1 + user_supplied_string XSS = string1 + user_supplied_string + string2 SQL_Injection = string1 + user_supplied_string + string2
If you ever see user supplied input being combined with a string you should always take a second and check for known vulnerabilities.
SQL Injection Basics
SQL injection occurs when user supplied input is improperly passed to the back end database. If you’r looking for SQL injection in source code one of the first things I look for is common SQL strings as shown below:
SELECT column_name from table_name where username = user_input UPDATE column_name set column_name = "s" where username = user_input
I often find myself grepping for the word “SELECT” which will normally show you the majority of the database calls. It really doesn’t matter what programming language the application uses SQL injection can be found in anything that communicates with a database.
Another technique is to search for common function names. Every program language has specific functions which are used to communicate with the backend database. Instead of searching for common database strings you can search for common functions which are used to communicate with a database. For example PHP uses the “mysql_query” function to make database calls. So if your dealing with an PHP application you can search for that specific function which should point you in the right direction. There are several other functions as well and SQL injection isn’t limited to just MYSQL.
As I mentioned earlier string concatenation can lead to all kinds of problems. If you see user supplied input being concatenated with a database query you most likely got SQL injection as shown below:
def search(): code = request.args.get('code') conn = sqlite3.connect("data.db") c = conn.cursor() try: statement = "select * from data where data='" + code + "'" c.execute(statement) found = c.fetchall() if found == []: return f"Invalid Code<br>{statement}" else: return f"Wifi Connection Established<br>{statement}" except sqlite3.Error as e: return str(e) + f"<br>{statement}
The above code is written in python. One of the first things you want to do is identify user supplied input. As you can see we can pass a GET parameter called “code” which will be saved to a variable.
code = request.args.get('code')
The next step is to identify if this variable is being improperly passed to a database query string which it is as shown below:
statement = "select * from data where data='" + code + "'"
You can clearly see the variable “code” is being combined with the query string. There is no sanitization checks or anything like that. This is a strong indicated of SQL injection.
Example
For this example i’m going to be using PHP code from:
<html> <head> <title>PHP Test</title> </head> <body> <?php echo '<p>SQL injection demo 1</p>'; ?> <?php $con = mysql_connect("localhost","sqli","sqli"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("sqliexample", $con); $id = $_GET['id']; // No input validation!! $result = mysql_query("SELECT name FROM user WHERE id=$id", $con); mysql_close($con); $num = mysql_num_rows($result); $i=0; while ($i < $num) { $name = mysql_result($result, $i, "name"); echo "Hello " . $name; echo "<br/>"; $i++; } ?> </body> </html>
Now that you know what to look for this vulnerability to jump out at you. You can clearly see that user supplied input is being passed to a database string as shown below:
$id = $_GET['id']; // No input validation!! $result = mysql_query("SELECT name FROM user WHERE id=$id"
This may be a PHP application but it looks identically to the python example we previously worked through. We have user supplied input being passed directly to a database query string with out validation. This application is clearly vulnerable to sql injection.
Conclusion
SQL injection is one of the oldest and most popular vulnerabilities out there. If you have access to the applications source code finding this vulnerability can be very easy. If you see user supplied input being combined with a database query string you most likely got SQL injection.
|
http://ghostlulz.com/source-code-analysis-sql-injection/
|
CC-MAIN-2022-05
|
refinedweb
| 780
| 54.93
|
All the JavaScript you need to know before starting with React
React developers love the modern features in JavaScript and use them extensively in their projects. In this guide, I’ll go over the most popular features that are usually used with React. Most of these features are modern to JavaScript but I’ll also talk about some older ones that are related and important for React.
This will NOT be a complete list of everything offered by the JavaScript language but rather the subset that I think will help you write better code for React.
Block scopes and the var/let/const keywords
A block scope is created with a pair of curly brackets. This happens every time you create an if-statement, for-statement, while-statement, etc. The only exception is the curly brackets you use with functions. These create a function scope, not a block scope.
Block and function scopes
{
// Block Scope
}if (true) {
// Block Scope
}for (var i = 1; i <= 10; i++) {
// Block Scope
}function doSomething() {
// Function Scope
} a standard for-loop statement, if the loop variable is defined with
var you can access that variable after the loop is done.
This is why the more recommended way to declare variables in modern JavaScript is by using the
let keyword instead of the
var keyword. When defining variables with
let, we won’t have this weird out-of-scope access problem.
However, you should use the
let keyword only when the variable’s value needs to be changed. This should not be a common thing in your code. For most other cases you should use the
const keyword instead, so let me tell you about it.
In JavaScript, a variable is basically a label we put on a certain space in the computer’s memory.
let V = { id: 42 }; // create a memory unit and label it as V
When you change the value of the variable
V you are not really changing the content of the memory space that was initially associated with
V. Instead, you’re creating a new memory space and changing the
V label to be associated with that new space.
// Discard current memory unit (and its current label)
// Create new memory unit and label it as VV = []; // No errors
When you use
const to define a variable, you are instructing the computer to not only label a space in memory but to also never change that label. The label will be forever associated with its same space in memory.
// Create a memory unit and label it as V
// This label cannot be discarded or reused
const V = { id: 42 };// Later in the program
V = []; // TypeError: Assignment to constant variable.
Note that the constant part here is just the label. The value of what’s in the memory space can still change (if it’s mutable). For example, objects in JavaScript are mutable, so for the
V above:
// You can do:
V.id = 37; // No errorsconsole.log(V.id); // 37// But you still can't do:
V = { that you need to increment in your program you would need to use
let:
// Can't use const for this case:
let counter = 0;counter = counter + 1; // Discard and re-label
Always use the
const keyword to define variables. Only use the
let keyword when you absolutely need it. Never use the
var keyword.
Arrow functions and closures
Arrow functions are probably the most used feature in Modern JavaScript.
Here’s what they look like:
const doSomething = () => {
// Function Scope
};
This new “shorter” syntax to define functions is popular not only because it’s shorter but also because it behaves more predictably with closures. Arrow functions give access to their defining environment while regular functions give access to their calling environment. This access is possible through the special
this keyword in a function’s scope:
- The value of the
thiskeyword inside a regular function depends on how the function was called.
- The value of the
thiskeyword inside an arrow function depends on where the function was defined.
Here is a code example to expand on the explanation. Try to figure out what will be printed in Output #1 through #4 (last 4 lines):
// jsdrops.com/arrow-functionsthis.whoIsThis = 'TOP'; // Identify this scope// 1) Defining
const fancyObj {
whoIsThis: 'FANCY', // Identify this object
regularF: function () {
console.log('regularF', this.whoIsThis);
},
arrowF: () => {
console.log('arrowF', this.whoIsThis);
},
};// 2) Calling
console.log('TOP-LEVEL', this.whoIsThis); // It's "TOP" herefancyObj.regularF(); // Output #1 (Fancy)
fancyObj.arrowF(); // Output #2 (Top)fancyObj.regularF.call({whoIsThis: 'FAKE'}); // Output #3 (Fake)
fancyObj.arrowF.call({whoIsThis: 'FAKE'}); // Output #4 (Top)
This example has a regular function (
regularF) and an arrow function (
arrowF) defined in the same environment and called by the same caller. Here’s the explanation of the outputs in the last 4 lines:
- The regular function will always use its
thisto represent who called it. In the example above, the caller of both functions was the
fancyObjitself. That’s why Output #1 was "FANCY".
- The arrow function will always print the
thisscope that was available at the time it was defined. That’s why Output #2 was "TOP".
- The functions
.call,
.apply, and
.bindcan be used to change the calling environment. Their first argument becomes the new "caller". That’s why Output #3 was "FAKE".
- The arrow function does not care about the
.callcaller change. That’s why Output #4 was "TOP" and not the new "FAKE" caller.
One other cool thing about arrow functions is that if the function only has a single return line:
const square = (a) => {
return a * a;
};
You can make it even more concise by removing the curly brackets and the return keyword altogether.
const square = (a) => a * a;
You can also remove the parentheses around the argument if the function receives a single argument:
const square = a => a * a;
This much shorter syntax is usually popular for functions that get passed to array methods like
map,
reduce,
filter, and other functional programming methods:
console.log([1, 2, 3, 4].map(a => a * a));
Note that if you want to use the arrow-function one-liner version to make a function that returns an object you’ll have to enclose the object in parenthesis because otherwise the curly brackets will actually be for the scope of the function.
// Wrong
const objMaker = () => { answer: 42 };// Right
const objMaker = () => ({ answer: 42 };
The above is actually one of the most common mistakes beginners do when working with libraries like React.
Arrow functions are short and more readable. They give access to their defining environments making them ideal for cases when you need the function to be executed in a different environment than the one where it was defined (think timers or click events handlers).
The literal notations
You can create a JavaScript object in a few different ways but the most common way is with an object literal (using curly brackets):
The object literal
const obj = {
// key: value
};
This literal notation (AKA initializer notation) is very common. We use it for objects, arrays, strings, numbers, and even things like regular expressions!
For arrays, the literal syntax is to use a set of square brackets
[]:
The array literal
const arr = [item0, item1, item2, ...];
For strings, you can use either single quotes or double quotes:
const greeting = "Hello World";
const answer = 'Forty Two';
These 2 ways to define string literals in JavaScript are equivalent. Modern JavaScript has a third way to define strings and that’s using the backtick character.
const html = `
<div>
${Math.random()}
</div>
`;
Paste that in your browser’s console and see how it forms a multi-line string that has a random value:
Strings defined with the backtick character are called template strings because they can be used as a template with dynamic values. They support string strings. This tagging feature is used in the popular styled-components library (for React).
Backticks look very similar to single quotes. Make sure to train your eyes to spot template strings when they are used.
Expressions for React
In React, there is a syntax similar to the template literal syntax that you can use to dynamically insert a JavaScript expression into your React components’ code. It looks like this:
// Somewhere in a React component's return value<div>
{Math.random()}
</div>
This is NOT a JavaScript template literal. These curly brackets in React are how you can insert dynamic expressions in JSX. You don’t use a
$ sign with them. Although, you can still use JavaScript template strings elsewhere in a React application (including anywhere within JSX curly brackets). This might be confusing so here’s an example that uses both JSX curly brackets and JavaScript template literals curly brackets in the same line:
JSX expression with JS template literals
<div>
{`Random value is: ${Math.random()}`}
</div>
The bolded part is the JavaScript template literal, which is an expression. We’re evaluating that expression within JSX curly brackets.
Destructuring arrays and objects
The destructuring syntax is simple but it makes use of the same curly and square brackets you use with object/array literals, which makes it confusing sometimes. You need to inspect the context to know whether a set of curly brackets (
{}) or square brackets (
[]) are used as literal initializing or destructuring assignment.
Curly brackets multi-use
const PI = Math.PI;
console.log({ PI });
const fn = ({ PI }) => {}
In Coding Listing 3.9, the first
{ PI } (in the second line) is an object literal which uses the
PI variable defined in the first line. The second
{ PI } (in the last line) is a destructuring assignment that has nothing to do with the
PI variable defined in the first line.
It can really get a lot more confusing than that, but here is a simple general rule to identify what’s what:
When brackets appear on the left-hand side (LHS) of an assignment or within the parenthesis used to define a function they are most-likely used for destructuring. There are exceptions to this rule and these exceptions are rare.
Example of destructuring:
// 1) Destructure array items
const [first, second,, forth] = [10, 20, 30, 40];// 2) Destructure object properties
const {) assuming arr is [10, 20, 30, 40]
const first = arr[0];
const second = arr[1];
// third element skipped
const forth = arr[3];// 2)
const PI = Math.PI;
const E = Math.E;
const SQRT2 = Math.SQRT2;
This is useful when you need to use a few properties out of a bigger object. For example, here’s a line to destructure the
useState and
useEffect hook functions out of the React’s API.
const { useState, useEffect } = React;
After this line, you can use these React API objects directly:
const [state, setState] = useState();useEffect(() => {
// do something
});
Note how the 2 items in the
useState function’s return value (which is an array of exactly 2 items) were also destructured into 2 local variables.
When designing a function to receive objects and arrays as arguments, you can use destructuring as well to extract named items or properties out of them and into local variables in the function’s scope. Here’s an example:
const circle = {
label: 'circleX',
radius: 2,
};const circleArea = ({ radius }, [precision = 2]) =>
(Math.PI * radius * radius).toFixed(precision);console.log(
circleArea(circle, [5]) // 12.56637
);
The
circleArea function is designed to receive an object in its first argument and an array in its second argument. These arguments are not named and not used directly in the function’s scope. Instead, their properties and items are destructured and used in the function’s.
The rest/spread syntax
Destructuring gets more interesting (and useful) when combined with the rest syntax and the spread syntax, which are both done using the 3 dots (
...) syntax. However, they do different things.
The rest syntax is what you use with destructuring. The spread syntax is what you use in object/array literals.
Here’s an example:
const :
const obj1 = {
temp1: '001',
temp2: '002',
firstName: 'John',
lastName: 'Doe',
// many other properties
};
If you need to create a new object that has all the properties of
obj1 except for
temp1 and
temp2, what would you do?
You can simply destructure
temp1 and
temp2 (and ignore them) and then use the rest syntax to capture the remaining properties into a new object:
const { temp1, temp2, ...obj2 } = obj1;
How cool is that?
The spread syntax uses the same 3-dots to shallow-copy an array or an object into a new array or an object. This is commonly used to merge partial data structures into existing ones. It replaces the need to use the
Object.assign method.
const array2 = [newItem0, ...array1, newItem1, newItem2];
const object2 = {
...object2,
newP1: 1,
newP2: 2,
};
When using the spread syntax with objects a property-name conflict will resolve to taking the value of the last property.
What is shallow-copy?? Simply put, any nested arrays or objects will be shared between the copies. This is a similar story to memory-spaces and their labels, except here labels are cloned and made to label the exact same memory spaces.
In React, the same 3-dots are used to spread an object of “props” for a component call. The JavaScript spread syntax was inspired by React (and others), but the usage of the 3-dots in React/JSX and in JavaScript is a little bit different. For example, given that a component
X has access to an object like:
const engine = { href: "", src: "google.png" };
That component can render another component
Y and spread the properties of the
engine object as props (attributes) for Y:
<Y {...engine} />
This is equivalent to doing:
<Y href={engine.href} src={engine.src} />
Note that the curly brackets above are the JSX curly brackets.
Shorthand and dynamic properties
Here are a few things you can do with object literals in modern JavaScript:
Modern features in object literals
const mystery = 'answer';
const InverseOfPI = 1 / Math.PI;const obj = {
p1: 10, // Plain old object property (don't abbreviate) f1() {}, // Define a shorthand function property InverseOfPI, // Define a shorthand regular property f2: () => {}, // Define an arrow function property [mystery]: 42, // Define a dynamic property
};
Did you notice that
[mystery] thing? That is NOT an array or a destructuring thing. It is how you define a dynamic property.
Interview Question: Given the code above, what is the value of
obj.mystery?
When you use the dynamic property syntax, JavaScript will first evaluate the expression inside
[] and whatever that expression evaluates to becomes the object’s new:
const obj = {
InverseOfPI: InverseOfPI,
};
Objects are very popular in JavaScript. They are used to manage and communicate data and using their modern literal features will make your code a bit shorter and easier to read.
Promises and.
const fetchData = () => {
fetch('').then(resp => {
resp.json().then(data => {
console.log(data);
});
});
};:
const fetchData = async () => {
const resp = await fetch('');
const data = await resp.json();
console.log(data);
};
You just
await on the async call (the one that returns a promise) and that will give you back the response object directly. Then, you can
await on the
json() method to access the parsed JSON data. To make
await calls work, you just).
For error-handling (when promises reject, for example) you can combine the async/await syntax with the plain-old try/catch statement (and you should do that all the time).
Modules import/export
Modern JavaScript introduced the import/export statements to provide a solution for “module dependency management”, which is just a fancy term to describe JavaScript files that need each other.
A file
X.js that needs to use a function from file
Y.js can use the
import statement to declare this dependency. The function in
Y.js has to be exported first in order for any other files to import it. For that, you can use the
export keyword:
// Y.jsexport const functionY() {}
Now any file can import this named
functionY export. If
X.js is on the same level as
Y.js, you can do:
// X.jsimport { functionY } from './Y';// functionY();
The
{ functionY } syntax is not destructuring! It’s importing of a named export. You can also export without names using this other syntax:
// Y.jsexport default function () {}
When you import this default
Y export, you can give it any name you want:
// X.jsimport function42 from './Y';// function42();
While default exports have their advantages, named exports play much better with intelligent IDEs that offer autocomplete/discoverability and other features. It is usually better to use named exports especially when you’re exporting many items in a module.
Map, filter, and reduce
These 3 array methods replace the need to use for/while loops in many cases. The value of using them over for/while loops is that they all return a value. They are expressions. They can be embedded right into JSX curly brackets.
All of these methods work on an original array and receive a callback function as an argument. They invoke the callback function per item in the original array and do something with that callback’s return value. The best way to understand them is through examples.
Here’s an example of
.map that squares all numbers in an array of numbers:
[4, 2, 0].map(e => e * e);// Result: [16, 4, 0]
The
map method uses the return values of its callback function to construct a new array. The return value for each callback function invocation becomes the new values in the new constructed (mapped) array.
Here’s an example of
.filter that filters an array of numbers reducing it to the set of even numbers only:
[4, 7, 2, 5, 0, 11].filter(e => e%2 === 0)// Result: [4, 2, 0]
The
filter method uses the return values of its callback function to determine if the current item should remain in the new constructed (filtered) array. If the callback function returns true, the item remains.
Here’s an example of
reduce that will compute the sum of all numbers in an array:
[16, 4, 0].reduce((acc, curr) => acc + curr, 0);// Result: 20
The
reduce method uses a slightly different callback function. This one receives 2 arguments instead of one. Besides the regular current-item element (named
e in all examples), this one also receive an accumulator value (named
acc in the example). The initial value of
acc is the second argument of reduce (
0 in the example).
The return value for each callback function invocation becomes the new value for the
acc variable.
Here’s what happens to reduce
[16, 4, 0] into
20:
Initial value of acc = 0First run: acc = 0, curr = 16
New acc = 0 + 16 = 16Second run: acc = 16, curr = 4
New acc = 16 + 4 = 20Third run: acc = 20, curr = 0
New acc = 20 + 0 = 20Final value of acc = 20
Because all of these functions are expressions that return values, we can chain them together:
[4, 7, 2, 5, 0, 11]
.filter(e => e%2 === 0)
.map(e => e * e)
.reduce((acc, curr) => acc + curr, 0);// Result: 20
This chain will take an array of numbers and compute the sum of the even numbers in that array after they are squared. You might think that doing 3 loops instead of 1 (which would manually include all the operations) is an overkill but this functional styles has many advantages.
Conditional expressions
Because you can only include expressions within the JSX curly brackets, you can’t write an if statement in them. You can, however, use a ternary expression:
<div>
{condition ? valueX : valueY}
</div>
JSX will output either
valueX or
valueY based on condition. The values can be anything, including other UI elements rendered with JSX:
<div>
{condition ? <input /> : <img />}
</div>
If the result of evaluating an expression inside JSX curly brackets is
true or
false(including
undefined and
null), React will completely ignore that expression. It will not be casted as strings: "true"/"false"/"null"/"undefined".
This div will have no content at all:
React ignores true/false in curly brackets
<div>
{3 === 3}
</div>
This is intentional. It allows using a shorter syntax to conditional put a value (or element) behind a condition by using the
&& operator:
The short-circuit evaluation
<div>
{condition && <input />}
</div>
If
condition is true, the second operand will be returned. If it’s false React will ignore it. This means it will either render an input element or nothing at all. This JavaScript trick is known as the "short-circuit evaluation".
Timeouts and intervals
Timeouts and intervals are part of a browser’s API. They’re not really part of the JavaScript language itself but they’re used with JavaScript functions like
setTimeout and
setInterval.
Both of these functions receive a “callback” function and a “delay” value.
setTimeout will invoke its callback function one time after its delay value while
setInterval will repeatedly invoke its callback function with its delay value between each invocation.
This code will print the “Hello Timeout!” message after 3 seconds:
setTimeout(() => {
console.log('Hello Timeout!');
}, 3000);
The first argument is the callback function and the second is the delay (in milliseconds). The code in the callback function (the bolded part) is the code that will be executed after 3 seconds.
This code will print the “Hello Interval!” message each 3 seconds, forever:
setInterval(() => {
console.log('Hello Interval!');
}, 3000);
A
setInterval call will usually have an "exit" condition. Both
setTimeout and
setInterval return an "id" of the timer object they create and that id value can be used to stop them. You can use a
clearTimeout(id) call to stop a timeout object and
clearInterval(id) to stop an interval object.
This code will print the “Hello Interval!” message each 3 seconds but only for 3 times:
let count = 0;
const intervalId = setInterval(() => {
count = count + 1
console.log('Hello Interval!');
if (count === 3) {
clearInterval(intervalId);
}
}, 3000);
Timers in a React application are usually introduced within a “side effect” hook function.
Originally published at on January 6, 2019.
|
https://medium.com/swlh/all-the-javascript-you-need-to-know-before-starting-with-react-abe2ebffb067
|
CC-MAIN-2019-47
|
refinedweb
| 3,642
| 62.98
|
!
OUTPOSTS AGAIN ACTIVE.
SIGNS OF A MOVE NORTH.
{Japanese, Skirmishers Reported Be
pulsed South of Moukdcn.
■ St. Petersburg. Oct. s.— Official advices from
■ the For East given out last evening describe a
merits of skirmishes on the southern front of
*Gener:xl IE si ii|ia|llß'g army, the only impor
tance of v.-hich lies la the fact that the Japan
ese are showing a disposition to press forward
.end feel out the RuwliJ positions. General
aiistchcnkos Cossacks in every case drove back
.the opposirg forces.
The activity of the Japanese outposts Is doubt
less Intended to screen movements of their
•rmles. an* therefore may be regarded as a sign
of final preparations for an advance, which
..probably will begin v.ithin a week.
A special messenger lias brought to the Em
peror General Kuropatkln's full report of the
-battle of rise Ts— 7 The messenger says that
the main Bias? Is concentrated at Tie Pass, and
that It is not likely General Kuropatkln will
jnake a determined stand at Moukden.
General Grlpper.berg. recently appointed to the
-co.Tin:ai.d of the Second M mchurian Army, will
'fee received by Emperor Nicholas at Peterhof
An the morning.
1 It is understood that the Third Division of
the Guards, stationed at Warsaw, Is under or
ders to go to the front. This, with the Second
Division of the Guards and the Rifle Brigade of
.the Guards, stationed in and around 6t. Peters
burg, xvlll make- altogether about 40.000 of this
lone who have been ordered to the Far East.
There were rumors again to-night of the fall
■•f I'ort Arthur, but they have not the slightest
foundation.
- General SakharofTe dispatch, dated October 3.
jdescribing the outpost actions, i* as follows:
-' • At dawn on October 1 a squadron of Japanese
■cavalry twice attempted to break through the
Jline of advance posts of Coesacks of the Guard
In the district between Khuar.khuandla and
Feng-Tia-Pu. Both attempts were unsuccessful.
Two sotnta* of our cavalry reinforced the ad
vance pasta and the Japanese dispersed.
, Toward noon en the fame day one battalion
•f the Japanese advance guard, with two or
"three squadrons of cavalry, renewed the offensive
movement again:-, 1 a regiment of Cossacks. The
•firing lasted until nightfall. General Mistehenko
sent iilnflm iillissjlS to the aid of the Cossacks,
*«nd toward evening the enemy was repulsed at
all points, t'.!«- whole line retreating toward
•eiallonkhetry. pursued by our cavalry. ,
. Captain Tolstoukine, commander of a sotnla,
• mbu»«hed one of the enemy's patrols at Kon
'•chutzy. One Japanese officer was killed.
: In th«" positions abandoned by the Japanese
*>ur Coesa found a number of cartridges and
'medical stores, and also a few dead horses.
$Ye had two officers and two Cossacks wounded.
' The same day a Japanese force of one bat
talion and a half and a squadron of cavalry at
tacked in three divisions our outpost between
tho Hun River and the, railway. Toward even
ing this movement was checked with the help of
another company, which reinforced the outpost.
- One Cossack was killed and one wounded.
. . One Russian patrol dispersed two Japanese
>patrols in the vicinity of Tschantan. on the right
Lank of the Hun River, taking three Japanese
■ prisoners.
Another Russian patrol. cent in an easterly
•traction, discovered Ta-Wang-Hau Pass occu
pied by two hundred Chinese bandits com
manded by Japanese officers. In the reconnols
aanoe one Cossack was killed.
* Sera* relief was shown at the War Office yes
terday by the receipt of Information which
* definitely located General Kuroki's army, ac
cording to which he has not appreciably
Chanced bis position along the line from Pen? ihu
to BeoUlapudza. General Nodzu still occupies
the Yentat Hills and General Oku Is to the
'•vest of the railroad. The Russian outposts are
•a far south as the Shakhe River, fifteen miles
.from Mockden. Field Marshal Oyama Is re-
Stoned to be with the Fourth Army, which at
eaa time was understood to have attained con
siderable proportions. It now seems to be not
touch larger than a brigade. Its mission prob
ably Is only to cause a demonstration on the
Stueslan left.
. Tbe Emperor has postponed for a few days hie
trip to RevaL where be intended to bid farewell
"to the Baltic fleet
i The police authorities make absolute denial
*f the story published In Vienna on the au
thority of Polish newspapers, that an attempt
fvza made to blow up the Emperor's train on
Ills recent visit to Southern Russia.
[S A dispatch from Meukden says the population
'Sot <\at place has been greatly Increased by
'•rrU Us from all quarters. Chinese who have
;oed from the south say the Japanese are ad
1 ministering affairs in Southern Manchuria with
Rii high hand, and many complaints of ill treat
ment of the natives are made. There is a
. *reat scarcity of provisions among the Chinese
A population.
< THE JAPANESE TKTEEHCHIHO.
;' German Correspondent Believes That Oyama
Will Await Attack.
Berlin. Oct. s.— Colonel Gaedke, the "Tag*
; Watt's" correspondent In the Par East, tele
graphs from Moukden that the Japanese appar
ently art n.i longer advancing; but are prepar-
Irq for defensive operations.
OYAMA HOLDING BACK.
tfapanrsc Armies' Positions Un
changed—Scouts in Action.
t TokJo. Oct. 4.— The following official report has
t>een issued:
The Manchurian headquarters reports by tele
- Ciaph that a bogy of scouts sent by our ad
vance detachment on October 2, consisting of
• a company of infantry and a troop of cavalry.
[Attacked end routed a detachment of the en-
I •■ray's cavalry, sixty strong, occupying Pao-Slng-
Tati, thirteen miles north of L4ao-Yang and
• SUae miles vest of the Moukden road. While fur
3 ther reconnoitring in the vicinity a force of
' Russian cavalry. 280 strong, attacked the Jap
*«c?se scouts. After fighting for some time th«
' Japanese returned- The enemy's loss was about
thirty. We sustained no casualties.
.-' The state of affairs at the front of our army
, remains unchanged.
ALL QUIET AT VLADIVOSTOK.
Vladivostok. Oct. 4— The town is quiet, and
.many families »ho flea to the Interior earlier
*tn the season are returning. It is an excellent
filing season, but there Is a scarcity of salt.
Navigation en the A moor will close this weak.
SOLD dEAL
Special Dry—
Surpassingly fine in bouquet and flavor and made by the French
process from the choicest grapes grown in our vineyards, it equal*
any of the foreign products at one-half the price. Whr nay a heavy
import duty on labels? " . .""
URBANA WINE CO.. Urban*. N. V., Sole Maker
HARVEST IN MANCIIVBIA.
Tall Corn Being Cut- -The Nights
Bitterly Cold.
Moukden, Oct. 4.— The complete I»U to
operations wm broken on October 2 by a slight
skirmish a few miles east of the bridge over
the Shakhe River, where a company ' f Jap "
anese came up. exchanged a few phots with the
Ruß*lari outposts and then retired, carrying off
tbelr killed and wour.ded.
The weather, on the whole, 1« good. The days
are fine and warm, but the nights are Mtt« rly
cold. Snow has fallen at HtnaT-Chang.
The Chinese corn, which lias been a splendid
ally of the Japanese, is being rapidly harvested.
Arrangements have been made for the Issue
of a special Illustrated -Ked Cross Magazine*
at Christmas. All the war correspondents and
artists have agreed to make contributions.
BANDITS IN ACTION.
Organized Bodies Reported Fighting
with the Japanese.
Ijonflon. Oct. s.— According to "The Morning
Post's" correspondent at Moukdsn. Chinese ban
dits, organised Into regular troops. #re flghtlr.e
dally side by side with the Japanese on their
west flank south of Hsln-Mln-Tun.
ATTACHES STILL MISSING.
Japanese Legation Denies Rumors of Their
Assassination.
Parts. Oct. 4.— The Japanese Legation has
given out a statement denying the reports In
French newspapers charging that the missing
French and German naval attaches at Port
Arthur. Lieutenant de CuverviUe and Captain
yon Gllgenbeim. were assassinated by the Jap
anese while leaving Port Arthur on a Chinese
Junk. The statement says that no such junk
ha« been captured, and that the most careful
Inquiries at Tokio and elsewhere hare frilled to
find the attaches. The Japanese officials, it Is
added, are using the utmost efforts to locate the
two officers.
JAPANESE AGITATION IN CHINA.
London. Oct. 4.— Reports have reached London
from official sources that many Japanese have
appeared recently in the big cities of Northern
China, and that they have begun an agitation
which it is feared, If the Russians gain victories
In Manchuria, may result in disorders which
might lead to the intervention of the powers.
JAPANEBE REFUGEES AT BERLIN.
Berlin. Oct. 4.— Seven hundred Japanese ref
ugees from Russia arrived In Berlin to-day. The
Japanese Minister and other members of the
legation I the Japanese Consul and a commit
tee of^ie Red Cross and missionaries gath
ered at the yard to greet the refugees, but were
not allowed to approach the train, the railroad
authorities saying that It would be contrary to
the regulations to permit them to cross the
tracks. The travellers greeted their countrymen
with prolonged cries of "Banzai!" The refugees
sail from Bremen for home on October 20.
CHINA MAY BLOCK GREAT BRITAIN.
Amban at Lhasa Unauthorized to Sigh
Expedition's Hardships.
London. Oct. Dispatches from the Lhasa
expedition Bay that the Chinese Amban signed
the Anglo-Tibetan treaty without having re
ceived the necessary mission from the Chi
nese government. The expedition, these advKca
say. Is undergoing great hardships In Its march
toward India.
CANTON-HANKOW S UNE EXTENSION.
sTo Preference To Be Shown in the Matter
of Foreign Capital.
Peking, Oct. 4.— Is announced by tho American
Legation, with reference to the Canton-Hankow
Railway, that a previous ttateraer.t to the effect
that if foreign capital should be necessary in ex
tending the railway beyond the limits of American
and Belgian direction by the construction of a line
to Chung-King, In the Province of Bse-Cbuen, 83]
miles above Hankow, American and British finan
ciers would have th« preference, In Incorrect.
What the Chinese government promises Is that
If foreign capital is sought application will first l>e
made to American ami British financiers, but that
there Is to b# no preference.
TO CHECK TUBERCULOSIS.
Congress at St. Louis Discusses Means of In
specting Schools and Tenement Houses.
Bt. Louis. Oct. 4 — Prerentatlve legislation was the
subject which opene<! the discussion at tho •■»•:.!
day's session of tbe International Congress of Tu
bercuJoelf. The speakers told of ways and means
that might be enforced through legislation for the
prevention of the Infection and ih<- spread of con
sumption. The papers presented and ensuing di*
cussiocs dealt with legislation compiling State and
rational governments to inspect closely not only
public buildings sad vehicles of transportation, but
also tenement districts and schools. It »-a alpo
advanced that beneficial results would to attained
by tli« segregation of tho tubercular insane In
asylums and hospital*.
The session was opened with an address by Clark
Bell, member of tlut New-York bar. and discussions
followed his address.
STRIKE DESERTERS SHOT.
Fired Upon from an Ambush Because They
Had Not Supported Miners' Union.
Bonweet, P»nn., Oct. 4— William Sutton and Will
lam Kemp, who are alleged to have recently de
serted th* ranks of the -union men who have been
on a strike since last December In th« Meyersdal*
coal region, were fired on from ambush early to
day while on their way to work in tho Wilmouth.
mine. Both had their legs riddled with buckshot.
The wounded men were removed to their homes,
and the armed deputies employed In the region art
Marching for the guilty parties.
Two weeks ago the tipple at the Wilmouth. mine
was fired by Incendiaries. The damage was re
paired yesterday, and to-day a force of men wont
to work In the mine.
A TON OF PUMPKINS FROM ONE HILL.
Morristown. N. J., Oct. 4 (Special;. -Nathan L
Anderson, of Spring Valley, says ho is th* cham
pion pumpkin grower of the United States From
one hill of pumpkins Mr. Anderson harvested one
ten of pumpkins. Eight of the pumpkins weighed
over eighty pounds, clx of them weighed sixty
pounds each, ten of them weighed forty pounds
each, and the rest weighed from twenty-nve pounds
down. He says this is the largest yield of pump
kins from cue hill that ha has ever heard of.
Mas the Sparkling Bead and Aroma
Possessed by No Other Wine.
America's Favorite
CHAMPAGNE
iVEW-YORK DAILY TRIBUTE. WEDNESDAY. OCTOBER 5. 1904.
PEACE CONGRESS OPENS.
A NOTABLE ASSEMBLY.
Delegates from Many Lends in
Conference in Boston.
mßoston,m Boston, Oct. 4.— A general Bflppllcation, almost a
demand for the institution of peace among the na
tions of the world was the keynote to-day of the
first deliberative session of the thirteenth Interna
tional Peace Congress. Pelt gates from tha great
countries of the globe, all prominent In their home
lands, participated in the proceedings.
A feature of the opening session was the receipt
of a report from the International Peace Bureau for
ISM. in which was reviewed what had been at
tained in tho direction of peace- by th* peace- work
ers of the world la the last year. Tha present war
conditions of the world were also set forth. Tha
suggestion was made that some collective move
might be made to Induce Russia and Japan to re
turn to peace.
Edwin V. Mead, the chairman of the organization
committee of the congress, delivered the opening
address cf tho meeting, speaking an earnest word
in favor of the reduction of great navies and a
general disarmament among nations. Robert Treat
Paine. sr., of Boston, wad elected president of the
congress, and Dr. Benjamin F. Trueblood. also of
this city, secretary. Responses were made, by on*
delegate from each of the countries represented at
the congress, including Alderman Thomas Snap©, of
Liverpool, for Great Britain. Mr. Snapo referred
particularly to Secretary Hay's appearance at yes
terday's peace meeting as the representative of
the United States, and took occasion to remark
what an astounding tiling it would be considered in
England should tho British Foreign Secretary of
ficially represent his government at a similar meet-
Ing. A general commendation of President Roose
velt's call for another Hague conference marked
the other addresses.
Among the letters and cable messages received
by the congress, and announced to-day were thoso
from Frau Solenka, of Munich; Elizabeth Stuart
Phclp« Ward. Carl Bchurs. Frederic Pasty, of
France, and Dr. Henry W. Warren, of Colorado.
A noticeably large- number of greetings were re
ceived from Baptist denominations and con
ferences" in various parts of the country. Including
Topeka, Kan.: Pltt»burg. New- Haven. Albany. Bur
falo and the District of Columbia. Memorials were
also received from the New-Orleans Board of
Trade and the Philadelphia Board of Trade.
Two mass meetings under the management of the
congress were held to-night. At one was consid
ered tho work and Influence of the Hague Tribunal.
Oecar S. Straus, formerly United States Minister to
Turkey and a member of the Hague court. pre
*!<led. Mr. Straus advocated a revision of the
Hague treaty so that It might be mad© certain that
when nations enter into a struggle some one of
them would take the initiative In referring the dif
ferences to the Hague Tribunal. Th* other mass
meeting was conducted by the Christian Endeavor
societies, with the Rev. Dr. Francis E. Clark cs
chairman.
Th« accredited (Selejntes occupied seats on the
floor of Tremont Temple, where to-day's meeting
was eld. filling that part of the auditorium, while
hundreds of spectators were In .the galleries. Mr.
Meed opened the meeting and expended welcome in
behalf of the American Peace Society. He re
marked upon 'he auspicious place of Its meeting,
reviewing the connection of Tremont Temple with
tho peaca movement, especially la 1599, when the
principal American meetings were held there tn
promote Interests in the Hague conference. Mr.
Mead continued In part:
II In th« great temptation* of our opulence ar.d
power come of us are in danger of forgetfulntes
ar.d fal'tilessness. may trn presence of so many of
you here from nations whoa* burdens and danger*
are so much greater than ours and who need lha
eupport of every Influence cf oura upon tha right
flae. and not the wron* side. \\f\x> to call us bacic
to our great national Ideals and better selves. You
have a right tj ask ;:a to check tbe building of a
Krciit navy. We must «uy to you that the r»-nl way
to hr-I;, u« Is by such organization at horn* jui
shall check the Increase of your own. Our Precl
dent has recently, proudly and properly. elaim<ti
that the HiiKue court was lmtiot«nt and the gov
ernment >■•'• th« Unltrtl States mart* it a reality. It
is not alone his word. It Is the warm word also of
Huron d'KsiearneUes da Constant.
Mr. Mead's address *..»• repented In French for
the benefit of tho foreign delegate!. In responding
as president-elect of tho congress. Mr. Paine ex
pressed the faith that peace throughout the worM
was not Jar distant, a result which, he saJJ. was
to i« largely brought about by the cessation of th«
rivalry among nations. He pointed out that the
cari*e of peac« bad made greater progress In th
last thirteen years than any other cau*e In th»
world. Th© speaker"* characterization of «se:reurj
Hay .11 "the greatest statesman In the world" was
received with vigorous applauto. In closing. Presi
dent Paine offered the «ugge?tlon. which was re
ceived with marked favor by the audience, that «U
should look forward to and plan for an Inter*
national co-grece of all nations. Nt which the pea.«
cf the world might become assured.
Upon the invitation of President Paine, several
of the foreign delegates then spoke briefly. 11
lowing these proceeding*. th« report of the Inter.
national Peace Bureau for 1301 was read by Becre.
tary Troebieod. The report, after reviewing the
efforts for Inducing Japan and Russia to have re
course to a friendly solution of the conflict, con
tinues in part as follows: .
In contrast to the gloomy pictures which the
last year gives us from the point of view of the
peace movement, we are happy to be able to put
down to the credit of the year a number of en
couraging facts. In no former period has so much
Ijetu accomplished to brln« the peoples and th«
governments of tlie world under the sway of inter'
national arbitration. As particularly important, we
may point out th". following conventions In their
chronological order: Th« Franco-Englioh arbitra
tion treaty of October, 1908; tho treaty of arbitra
tion between France and Italy, of December. 1003;
the Anglo-Italian arbitration treaty of January.
I*4: the arbitration treaty between Denmark and
Holland February, !IO4: the Franco-Bpanlsh arbi
tration treaty. March. &H; the Anglo-Spanish ar
bitration treaty. March. 190*: the new Franco-Eng
li*h agreement ii.pr.-riiinK Egypt, Morocco, New
foundland and Western Africa, an well as Slam.
th« New- Hebrides and Madagascar. April. 1904: the
:ri a lion treaty between i ranee and Holland,
Adi •••'!• th« \nglo-G*rman arbitration treaty,
July ' lW the Anglo-Scandinavian arbitration
treaty "inly 1904: the arbitration treaty between
Sr-Jiri and Portugal. To the Franco-Italian ar
bitration treaty has been added the Franco-Italian
convention concerning labor legislation, signed in
* We cannot better clo*f> this report than by re«
<&llip.'< the following words, uttered by Mr. Roose
velt on the occasion of his message to the Congress
of thn United States: "Wo have not yet arrived «t
the point where we can avoid nil wars by the aid
of arbitration, but with prudence, firmness ana
wisdom the provocations and piet«-xt» of war may
be removed, and conflicts adjusted by rational
methods."
The following appointments as vice-presidents
were announced: England. William Randall
Cremer; Franca, Professor Th. Buyssen; Germany,
Dr. Acloij.h Blebter; Belgium. M. Houzeau «ie Le.
haie; Austria. Baroness Bertha yon Suttner; Italy,
Fignor B. T. Moneta; Norway. John Lund: Monaco,
Abb« Plchot; China, Dr. Yamei Kin; Sweden. Joh»
Olsten: Armenia. Dr. John L. Mellkoff: Switser<
land, Professor Pierre Clergct; United States, Al
bert K. Smiley.
Dr. Edward Everett' Hale offered a resolution,
which was unanimously adopted, extending the
greeting of the congress to the Episcopal General
Convention and Inviting all the delegates of the lat
ter to take part in the deliberations of the peace
conferences. After the Chair had appointed several
commute*, the convention adjourned until to-mor
row morning.
STRAUS ON HAGUE TRIBUNAL
Ex-Minister Presides Over Big Public Meet
ing in Tremont Temple.
Boston, Oct. 4.— Tremont Temple was the scene
to-night of a great public meeting, under the direc
tion of the Peace Congress, to hear from distin
guished publicists of the work and Influence of tho
Hague Tribunal. A part of the main floor was re
served for foreign delegates.] Among the persons
on the platform wore Mrs. Julia Ward Howe, Rob
ert Treat Paine, president of the congress, and the
speakers of the evening. M. Gustav Hubbard. mem
ber of the French Chamber of Deputies; Professor
Quidde, of Munich: J. O. Alexander, secretary of
the International Law Association, and Dr. XV.
Evans Darby, secretary of the English Pea^e So
ciety.
Secretary Trueblood referred to the absence of
Andrew V. White. ex-Mlnlster to Germany, /ho
was to have presided at the meeting but was de
tained on account of Illness. He then introduced
Oscar 8. Straus, former United States Minister to
Turkey and member of The Hague Court, as the
presiding officer. Mr. Straus paid a high tribute
to the diplomatic and scholarly ability of ex-
a 'ia!» ttr White. After sketching the growth of the
universal desire and endeavors toward peace. Mr.
Etraus continued in part:
The work of The Hague conference, the estab
lishment of the permanent court of international
arbitration by the representatives of the tweatjr
six leading nations of the world, marks not onl>
the crowning glory of the nineteenth century. but,
with God bleesife-s. the nvofct enduring humani
tarian achievement of the ages. Although the
time was not yet ripe to enable this congress «>
succeed In lessening: the armaments of war. tne
very establishment of the permanent tribunal, wttii
us fourscore members, ever ready to re s P o , at°
the nations' call for the adjustment o''" 1 "na
tional differences, cannot fall in time «ffecti\ei>
to contribute to that Inevitable end and tend more
and more tr bring "the future of humanity under
the niujest/ of the law."
As Americans and hopeful advocates of T>»ac*
you win pardon the justified pride we feel in the
tribute paid to our country only a few days n?o
by that distinguished French peace advocate, pub
licist and statesman, a leading delegate to the
peace conference and a memoer of the permanent
tribunal. Baron d'Estournelles de. Constant. After
expressing his regret for his Inability to be present
with us. n regret which I am sure Is shared by
every one here, he said:
"I had hoped at Boston to recognize publicly the
grant and decisive services rendered to the cause
of International arbitration by the United States.
and particularly by President Roosevelt. Better
than any one, I know that the court at The Hague
stood deserted, abandoned and ridiculed until the
day when he had the courage, generosity and fore
sight to save It. That act alone has entitled him
to tho thanks of ell Europe for his pacific and
liberal spirit."
Mr. Straus said that the present Congress and
future congresses coild not. In his judgment, ad
dress themselves to a more practical and imperative
subject than that of ascertaining ami developing
the morit ac-Ttable and effective method of in
voking and applying the Initiative in bringing dis
pute* between nations to the Hague tribunal. Mr.
Strauss speech was listened to with marked at
tention and received with applause. Joseph G.
Alexander, of England, the next speaker, said that
the International Law Association, which he repre
sented, always considered international arnitration
as a great Ideal worthy of attainment He contin
ued In cart:
The Hague conference was first Intended to con
sider the subject of disarmament, but although un
successful in this, it achieved me wondenuj euc
c*bs of constituting a permanent tribunal or aroi
tration. It is tho beginning of organized lp«««. or
the substitution of a machinery of arbitrament oy
Judicial means for the cruel arbitrament <««»<»
sword. The machinery now needs motive i>o*er.
and that power is public opinion.
At the meeting heid to-ntght under the auspice*
of the Christian Endeavor Societies. In the Spark
Street Church, the Rev. Dr. Francis E. Clark pre
sided. The edifice was crowded. In taking the
chair Dr. Clark referred to the formation of the
International Christian Endeavor Brotherhood in
London last June. He added:
These representatives of many lands, speaking
different languages, with different traditions be
hind them, owing allegiance to different forms of
government, bar.de.i themselves together into an
international brotherhood to pray and labor, to
*peaK und work tor peace to the world; for arbi
tration and conciliation, and for opposition to all
unjust military aK»?iu:: sement The great thought
which will mark tho twentieth century was
regnant In the hearts of those representatives *><.
millions of erdeavorers in many lands The leaven
is working. The better days are on the way.
Dr. Clark introduced as the first speaker the
Rev. Richard Weatrope, of York. England. The
other speakers Included the Rev. Walter Walsh,
of Scotland; the Key. M. J. Elliot, of England, and
the Rev. Charles Wagner, of Paris.
LIPPES REGENCY OPEN.
Tier man Emperor Refuses to Recog
nize Count Leopold.
Berlin. Oct. The Lippe government has
published a telegram from Esaperor William to
Count Leopold, non of the late Regent. Count
Ernst, condoling with him on the death of his
father and informing him that, as the legal situ
ation la uiicertu,'D, be Uhe Emperor) la unable
to recognize Count Leopold as Regent, and that
hence tin military will not be permitted to take
the o.itn of allegiance to Count Leopold.
The government of Llnpe suggests that th«
dispute over th'- right of snrnsMlnn .shall be
submitted 10 the lii.wrial Supreme Court or
aoinv other non-partisan court. Instead of the
Federal Council.
The death of Count Ernst of LJppe-Blesterfald, at
DeUDOid, on September IS, was followed by a pro
test of ITln'ia OviT^'i 4 Behaumborg-Lippe, direct*
ed to the Federal Council, against tho suecssjsosj
cf Count Leopold, on the ground that the entire
Uppe-Blesterfeld line lost its rights of succession
because Mode; te yon Unruh. irreu,t-grandmother of
Count L«opol4. was not legitimately descanted
from the noble family. The protest adds that ths
fact* about Ifodeste were not known when tha
Llppe Diet Bsssed the law of succession In MM,
placing the right In Count Leopold. Prince Adolf
cf Bchatunburg-Llppe, who is a candidate for the
regency, is a brotlier-ln-law of the Emperor
through hi* marriage to the Pi Illness Victoria or
Prussia, and » brother of Prince George of Schauin
burg-I.ippe. It is understood that Prussia and
Meckfcnliurg-Schwerln support the protest ox
Prince George.
FILIPINOS MUST WAIT.
Salutary Advice on Independence
Given by Governor Wright.
Manila, Oct. 4. — The Federal party has given
a dinner to the delegation ot leading natives of
tho archipelago who have recently returned from
a visit to tho United States. In their speeches
tho members of the delegation spoke In high
praise of the treatment accorded them In the
United States. Each touched on the tndepend-*
» :; a movement, and made an urgent plea for a
popular assembly at once and full independence
nt an early date, except Vlctorino Mapa, asso
ciate justice of tho Supreme Court, who spoke
In a different tone. He advised his people to
have confidence la the people of the United
States and to prepare for the time v hen their
hopes would be fulfilled. r
Governor Luke E. Wright made the principal
speech at the dinner, and when he finished he
was warmly cheered. Ills address was an able
one. and he gave the guests nome important
facts bearing on the subject of independence
Ho spoke as follows:
Some seem to think that independence will
work miracles and bring about the millennium
You make th« claim, and I believe that your
claim Is just, that with the opportunity and ex
perience you are capable of better things The
aspirations of a people or an Individual for bet
ter things are praiseworthy, if they are con
sistent and sensible and reasonable in char
acter.
The South American republics, where revolu
tions are rife and where each country in torn
continually in factional strife, are fashioned on
the United State* model, but they have demon
strated that the people have mad* a failure in
self-government. Now, the Americans' arrival
here was the result of an accident, the victory
of Manila Bay. They found themselves charged
with the responsibility of government, and felt
•t their duty to take care of the country until
its people would develop a capacity to take care
of it themselves.
What the returning commissioners say about
the kindly feeling throughout America and the
purpose to assure to them the greatest degree of
liberty is the trutn to-d»y. nnd ever nince we
put our foot on these, islands It has been the
truth—the same old truth. I think if would not
be out of plat to say that the members of the
commission who arrived here in 1900 have
proved that they did not come to destroy, but
to benefit you. Is It not true that you now elect
your municipal and provincial utnctals. and that
a greater number of employes of the govern
ment are Filipinos? Have you not three repre
sentative on the commission Itself? How many
more centuries would you have remained here
under Spanish rule before you would have en
joyed what you have under cix years of Ameri
can occupation? How often do you think It
would be possible for the Federal party to give
a dinner where the guests could talk freely of
Independence? As much as we endeavor to do
for these people, you can readily understand how
any distrust or hostility would Interfere with
the good work we have just started. It seems to
me that not academic, but real, practical ques.
tlons confront us. The wild man who goes
naked is Independent, but I do not believe that
he Is a model for us.
LIGHTER RAMMED AND BEACHED.
The steam lighter Elizabeth Cockling had to he
beached about 6 o'clock last night after she had
been rammed by a Long Island Railroad float off
tbe Battery. The tug Ttmmins towing an Italian
steamship It ft her to save the. lighter by towing
her to the Jersey shore, where she beached her.
The- lighters steam pipes burst and her upp^r
works were badly trsgW No oae waa hart. -
GOVERNOR AT ST. LOUI?.
He Exhorts Young Men to Brave
Calumnies of Public Life.
St. Louis, Oct. The most successful State
Day celebration yet held at the exposition, both
in point of Interest and attendance, was that of
New-York State to-day. The New-York Build-
Ing was beautifully decorated, and was crowded
with guests.
The Garde Republlcalne Band, of France, be
gan the exercises incident to the celebration with
a concert at the State building. Edward Lyman
Bill, of Neve-York City, the State Ccmm:s?;or. r,
spoke at the exercises held in the State buill
irg. The Rev. Dr. William W. Board ©I St.
Louts, formerly a resident of New-Yerit. deliv
ered the ln\ocatlcn.
Music was rendered on the or^an by Professor
S. H. Groves, of Neiv-Tork ires'??:- weri
made by Mr. Skiff, Director of Exhibits, ;r..l
Commissioner Bill, to which Governor Odell re
sponded. Governor Odell said in part:
The diplomacy which led up to the acquisition of
the Louisiana Territory lurnishes one of th« moat
resting incidents in the world's history. 1 ne.
establishment of a republic devoted to the inter
ests of and affording liberty of conscience, and
freedom 01 action to its citizens was an experi
ment ip government which could not have suc
ceeded if any restraint had been placed upon that
liberty, or if its Constitution had not been broad
enough to me*t the demaaoa of a growiug coun
try. WMI« there was authority for the admis
sion of new States, there was no constitutional
Permission for the purchase of territory. « ben we
look over the results which have followed this ex
pansion of our country, whea we calculate, our
magnirtcent growth In population ami wealth, all
of these appear insigniacunt beside t:io result
which was accomplished in showing to the world
tnai we were living under a Constitution broad
enough In Its provisions to be so interpreted as to
taaui* success to popular government, l.vt joi
fcrson and his advisers acted wisely in so con
struing their power at that time is undoubted. If
thfre were no other achievements of that wonder
ful administration, then this alone would suffice to
make it a memorable one.
That the acquisition or this territory was ac
complished through peaceful means, rather than
by bloodshed, was another triumph tor civiliza
tion. While wars have come since ar.d may come
In the future, the plan or arbitration which has
been adopted so generally by this and otter na
tions may. perhaps, have had Us inception in this
peaceful solution of a burning and important ques
tion to this country. Our Union now Is one that
is composed of commonwealths bound together by
all that means common inter "St. the coraaion wai
and common protection of all the people. It leads
to the hope that when the rearesentative* or all
the. States have decreed by a majority for that
which Is for the best interest of the wh=>e coun
try, then these question* should no longer b* th«
subject of partisanship or party difference, but
the government should have the legal supporter
all who believe in America and her future. Th?
same law* govern us, the same protection should
bo an.i is accorded to every citizen, and there is
no Individual or isolated community that does r.ot
share In the prosperity of all others whose inter
ests are not on the same plane of equality.
THE CALUSiy OF PUBLIC LIFE.
Every man should be a part of the government.
He should '■■■: it to be aa much tvs duty to re
spond to civic responsibilities as to those living
under a monarchy, who»« early tuition Insuw
In them the belief that they owe t::- 1 best part or
their lives to the military service of their gov
ernment. As th^y arc undeterred by fear of «l^atn
(.■r disaster. »<• should our young men be undeterred
iiora entering puolic life by calumny, viltncatior.
and abuse wnich they *cc too frequently »u<l too
unjustly bestowed "upon others. «-„-.
New-York Is here to-day by Its official repre
sentative* to testify first to its loyalty to the pur
pose* for whU-h this exposition was conceived: to
Show the people of the \\\*l that in their progress
we are Interested, and that to them we look tor
such rr-turna In dividends upon the stocK or
patriotism as win «r!ve to our nation men or
energy, of right imputes. To you we owe much.
and from you we expect much Our efforts will
be to aid you la every laudable undertaking, to
»t*nd behind you In all that means the prosperity
of our common country. ...... _..„
You hay* here an exr»o9lt!on of which you may
be Justly proud. Nothing like it has erer been
known tn the annals o| the world, bkllied work
men from all parts of the earth are here to aid
In its »ucce.-is. lier-j you witness not only th»
steady progress that has been made la the sci
er.e«; the arts and agriculture, but you have be
fore you also exhibits from some of the posses
sions which have recently come under our contr^
We may study here some of the problems wn..
demand solution at the hands of tea American
"oiur^ftag has be-:-, planted In a far off land, and
we muFt face responsibilities which it would be
cowardly to shirk. To us have been intrusted
duties that have cost us the blop.l of some of th«
biavc?t men of the North and of the South, or rh«
Kast ard West. Here we may see something of
that which has been accomplished «a well as a
prekentation of taoss conditions which it la our
duty to •-■'■rr.-ct. it l» our privilege to give to
others the mioo liberty which we enjoy ourselves,
to establish some form of government such as
ours wherever these people are ready for It. and it
Is our duty to protect them In their weakness
until they 'are prepared for it. There Is no one
who haa'seen the progress which i» here repre
sented who does not believe that the wors for
■••vtllzatlon which i» ours to perform has already
»a.l mi<"h an Impetus that the time will rome when
we shall b'* 1.*!!1 .*!! tho.«e who had the courage to stand
for It airfitrnt those who demanded another solu
tion of this important question. To our credit b«
It said »ha» no true American demands the sur
render of these possessions, and that the only
question of difference between the people of our
country Is whether they shall be given their in
aependeni s now. or when they are in a condition
to enioy it.
Th's exposition stands not only as a monument
to our progress, but to our unittd and determined
*uort to take a prominent part in all tliat means
the advancement of mankind ar.«l the prosperity
of the whole world. We ow« that which we ere
at present to th..< devotion anil heroism of the
men of the p«»». and to protect ard guard the
Inherit which has come to us should V*e our
aim To be bread and conservative In our con
ception ol our duties .••.•l responsibilities should
>..• our purpose. To instil Into the minds or our
youth a determination to meet every question with
true American courage should ■■■' our object.
Every effort that makrs for th.-> goo*i of humanity
ts a "fitting tribute to that national policy which
hao taught us i^at there is no responsibility too
rreat for our eittaens to bear. and thai in the on
war*, progress of riTllhßiti«»« America recognize'l
her duty and will not fail Is Its performance.
The day closed with a reception and ball.
given by the New- York Commission In honor of
Governor and Mrs. Odeii
LIFE SAVED BY TALL HIT.
Coachman Falls on It — Uis Em
ployer Dragged by Runaway.
Harry Costell", «on of P. C Costello. of Tar
rytown. was dragged five hund»«d feet In the
depot square there yesterday afternoon, and had
a marvellous escape from death. He was being
driven M the d>rot to catch the 5:33 train for
this city.
As the coachman turned the horse Into the
square the bit broke and the horse bolted. The
runabout struck the curb and the coachman
shot up in the air fifteen or twenty feet, as If
he was shot out of a gun. and he landed square
on hie head on the brick pavement. The on
lookers thought him dead. Younr Costello was
thrown over the dashboard and hung head
down, close to the horse's heels. He was
dragged this way for five hundred feet, when he
managed to free himself and drop. lie was
dazed and badly bruised when he was picked up.
He wad helped to a livery stable, where a doctor
found that no bones were broken.
The coachman had received only a bad scalp
wound. Ills high stiff hat was the thing that
saved his life.
DOWIE CONVICTED OT lIBEL
Must Pay $2,000 as Result of an Article in
"leaves of Healing."
!»r TFLf.BAPn TO tSJi TKisrxt I
Chicago, Oct. —John Alexander Dowl<\ the
"First Apostle of the Christian Catholic Church
In Zlon." must pay Samuel G. Priddle $2,000 for
having libelled him in his publication. "Leaves
of Healing." This was the oplnloa rendered by
the Appellate Court to-day, affirming the finding
of the Circuit Court. Priddle sued Dowle for an
article published by him denouncing the plaintiff
because ITiddle Baid he dreamed that Duwie
would be assassinated in May. U*>l Dowie ad
mitted at the trial that he was the author si the
libel, and also that he Is worth several million
dollars.
AN OLD LANDMARK.
A stone has been discovered at Bellewood Park,
near Pattcuburg. N. J.. bearing the inscription.
"Munselougbaway. ISM. '
This ator.e was found at a spring, briar covered
and unused, and the name la said to be that given
to the brook which runs through Bellewood Park
by a tribe of th« t*nn! Lenape Indians, who once
Inhabited that region.
An apparent desire on the part nt rtsldont*
of that locality to aoaodoa Sndiaa regies la .US
»a the name HoppooH Broak. by Whieb thi
•nt generation knows the arse*. 09 prMh
Note.—The following article has bee» «tts\
published and is one of the most remarkable
Illustrations cf the value of careful marshalling
and analysis of facts in presenting a subject to
the public.
LEVEEE3S.
The Mission of Whiskey, Tobacco en&
Coffee.
The Creator made all things, we believe.
If so. He must have made these.
We know what He made food and water tot\
and air and sunshine, but why Whiskey. To
bacco and Coffee?
They are here sure enough and each perfbna.
ing its work.
There must be some great plan behtnd It all;
the thoughtful man seeKs to understand some
thing of that plan and thereby to Judge these
articles for their true worth.
Let us not sar 'bad" or "gooi" without tak
ing testimony.
There are times and conditions waen it cer
tainly s-err.s to the casual observer that these
stimulant narcotics are real blessings.
Right here 13 the ambush that conceal* a
"killing" enemy.
One can slip into the habit of either whiak-y.
tobacco or coffee easy enough, but .0 "untanjl* 1 "
is often a fearful struggle.
It seems plain that there are circumstances
when the narcotic effect of these poisons 13 for
th« moment beneficial, but the fearful argument
against them is that seldom ever does one find
a steady user of either whiskey, coffee or to
bacco free rcm disease of some kisd.
Certainly powerful elements in their effect on
the human race.
It is a matter of daily history testiSeti to by
literally millions of people, that Whiskey. To
bacco and Coffee are smiling, promising, beguil
ing frU-nd3 on the start, but »iw»»* false as
t.e'.l itself In the end. Once they get firm hold
enough to show their strength, they insist upon
governing and drive the victim steadily towards
11! health in some form: if permlued to continue
to rule, they will not let up until physical and
mental ruin sets in.
A man under that sDell (and "under the
epell" is correct), of any one i*4 these drug?.
frequently assures himself and his friends.
"W'h" I can Uave oft any time I want to. I did
quit for a week Just to shoT I could." It is a
sure mark vt the eiave when one gets to that
stage. He wiggled through a week fightingr
every day to break the spell, was finally
whipped, and began his slavery ail over again.
The slave (Coffee slave as well as Tobacco and
Whiskey) dally reviews his condition, sees per
fectly plain the steady encroachments of dis
ease, how the nerves get weaker day by day
and demand the drug -that seems to smile and
offer relief for a few minute? and then leave
the diseased condition plainer to view than ever
and growing wor3<». Many times the Coffee
slave realizes that he 13 between two fires. Ha
feels bad if he leaves o.T an.i a little worse If
he drinks and allows the effect to wear off. ">
So it goes on from day to cay. £.very nijlit
the struggling victim promises himself that h«»
will break the habit and next day when ha feeia
a little bad (as he is <iuite sure to) breaks, net
the habit, but his own resolution. li :3 nearly
always a tough fight, with disaster ahead fur»
ii the habit wins. *■
There have been hundreds of thousands of
people driven to their graves through riisea?-*
brought 0:1 by coffee drinkir-s alone, ar.d it i*
quite certain that mor human misery la caused
by coffee ar.d tobacco than by whiskey, for Uta
two first are more widely used, ar.d more hidden
and insidious In the effect on nerves, heart an i
other vital organs, and are thus unsuspected
until much of the dangerous work is done.
Now. Reader, what in your opinion as to Iba
real use th* Creator has for these thlr.33? Tak»
a look at the Question from this point of view.
There Is a law of Nature and of Nature's God
that things slowly evolve from lower planes t<>
higher, a sturdy, steady and dignified advance
toward more perfect things i:i both ths Physical
and Spiritual world. The ponderous tread of
evolutionary development la fixed by the In
finite and will not be Quickened out of natural
law by any of man's meti
Therefore we see many illustrations showing:
how nature checks too r-CMti advance. Illinois
raises phenomenal crops of corn for two or three
years. If she continued to do bo every year her
farmers would advance In wealth tar beyond
those of other sections or countries. So Nature
Interposes a bar every three or four years, sod
brings on a "bad year.™
Here we see the leveling influence at wort
A man is prosperous in his business for a
number of years and grows rich. Then Natnr*
sets the 'leveling Influence" at work en fcta.
Some of his investments lose. he becomes lux
urious and lazy. Perhaps it 13 whiskey, tobacco.
coffee, women, gambling, or some other form.
The Intent and purpose Is to le*«l him. K?e?
him from evolving too far ah*-- of the masses.
A nation becomes prosperous and great 12k»
ancient lioire. If no leveling influence set In
she would dominate the world perhaps for all
time- But Dame Nature sets her arm;* of "levei
ers*' *« work. Luxury, over-eating and drink
bsg?, licentiousness, waste and extravagance in
dulgences of all kind*, then comes the creek.
Sure Pur)». S'.:re.
The law of the unit is (he law of the mass.
Man goes through the san proce33. Weakness
tin childhood), gradual growth cf strength, en
ersty, thrift, probity, prosperity, wealth, com
fort, ease, relaxation, self-indulgence, luxury.
Idleness, waste, debauchery, disease, and th*
wreck fellows. The "lereleta" are In the bushes
along the pathway of every successful man aad
woman arc! they 'on? the majority.
Only row and then can a man s:and out
against there Irratarsr' and hold his fortune,
fvime and health to toe end. >
So the Creator has use for Whiskey. Tobacco
and Coffee to !e\e! down the successful ones
*n<J thosa who show fljns cf beinj successful,
and keep them tack in the race, so that the
great "field" ith? musei) may not be U!t too
far behind.
And yet we must admit that same si! wls>»
Creator has placed it to the power cf man t>
stand upright, clothed in the annex of a clean
cut. stead: mind, and say onto Mrr.self. **I de
cline to exchange my birthright for a mess of
potage."
"I wi!l not deaden v? rer.ses. weaken siy grip
en affairs and keep myself cheap; common anl
behind in fortune and me by drugging- with
whiskey, tobacco or coffee— is too short. It
is hard enough to win the good things without
any sort of handicar. *» a man is certainly a
Tool trader* when he trades strength, healt*-,.
money, and the good things that come with
power, for th> balf««s!eep condition of th>
"drugger.* with the certainty of sickness and
disease ahaad."
It Is a matter each Individual must decide tor
himself. He can be a tea&vv and semi-god !f h=*
will, or he can go along through Ufa a drugs* 1 *
clown, a cheap "hewer cf wood cr carrier ot
water."
Certain H Is that while the Orrat Father "'
v* all Joes not >«em to "mind" If some of Ml
children are foolish and stupid, hi? to se
lect others (perhaps those he intends for roes
special work) aid alfc»ws then to be thrashed
and castigated most fearfully fey these -lavel
ers."
If a man tries flirting with these tevelers a
while, end gets a few slaps as a hint, be bad
better take the hint or a good, solid bio will
fellow.
When a man tries to live upright, clear
thrifty, sober, and undrugr;oj. asajUfostlßg «'
near as he knows what the Creator Intends na
should, happiness, health and peace seem tl*t 1 *
come to him. Does it pay?
This article was writ tan to set people thinking.
to rouse the "God within," for every highly or
ganized man and woman has times when they
feel a something calling from within for them
to press to the front and "be about the Father-"
bu?!r.ess ; don't n:.st.»ie It; *. * sparls ci tin
Infinite ia tiisrc. anil it pays in every wjt.
health, happiness, peace; and even worldly pros
perity, to break off the habita an 1 strip clr".-'
for th« work cut out for us.
It has b/en the business of the write* to rr°/
vide a practical and essy way frr people to bJtG-5
away from the coffee t&bit and bo assured W v
a return to health and all of the good thlßS*
that brings, provided the abuse has not gene too
far. and. even then the crises where the boa:'
has been rebuilt on a buais oi strength ana
health run into the thousands.
It Is an easy and comfortab'e ftop to stop
coffee instantly by bavins wel'-madu Fostam
loo.i Coffee *ervt.l rich ami hot with g«*©«
cream, for the color and flavor are there, bu:
none of the caffeine or other nerve destroylos
element* of ordinary coffee. ■ •
"On the contrary, the moat powerful re>uUa;n^
Clements furrtshaii by Nature ere !a Postum.
and they »iulckly set about rcpiirlns the «-a^
age. Seldom 1* It more tb.-»n 2 days *i T -*r «•
change is made before the old stomach or bowoi
troubles, or complaints of kidneys, hearty heci
>r nerves stow unmistakable evidence oi_ get
ting better, and! ten days' time c v .ans<» thing*
wonderfully.
Literally millions of brain-working American*
io-riay us© Postuni. having four.tl the value an *
common cense in the change. ' r»nsT
C. X* . Pv'* 1
-Get tha I famous little book, Tke *** •"
VTelvtll*.* hi each pita*."
xml | txt
|
http://chroniclingamerica.loc.gov/lccn/sn83030214/1904-10-05/ed-1/seq-4/ocr/
|
CC-MAIN-2015-48
|
refinedweb
| 8,718
| 72.66
|
Demonstrates how to plot histograms with matplotlib.
import matplotlib.pyplot as plt import numpy as np from matplotlib import colors from matplotlib.ticker import PercentFormatter # Fixing random state for reproducibility np.random.seed(19680801)
To generate a 1D histogram we only need a single vector of numbers. For a 2D histogram we’ll need a second vector. We’ll generate both below, and show the histogram for each vector.
N_points = 100000 n_bins = 20 # Generate a normal distribution, center at x=0 and y=5 x = np.random.randn(N_points) y = .4 * x + np.random.randn(100000) + 5 fig, axs = plt.subplots(1, 2, sharey=True, tight_layout=True) # We can set the number of bins with the `bins` kwarg axs[0].hist(x, bins=n_bins) axs[1].hist(y, bins=n_bins)
The histogram method returns (among other things) a
patches object. This
gives us access to the properties of the objects drawn. Using this, we can
edit the histogram to our liking. Let’s change the color of each bar
based on its y value.
fig, axs = plt.subplots(1, 2, tight_layout=True) # N is the count in each bin, bins is the lower-limit of the bin N, bins, patches = axs[0].hist(x, bins=n_bins) # We'll color code by height, but you could use any scalar fracs = N.astype(float) / N.max() # we need to normalize the data to 0..1 for the full range of the colormap norm = colors.Normalize(fracs.min(), fracs.max()) # Now, we'll loop through our objects and set the color of each accordingly for thisfrac, thispatch in zip(fracs, patches): color = plt.cm.viridis(norm(thisfrac)) thispatch.set_facecolor(color) # We can also normalize our inputs by the total number of counts axs[1].hist(x, bins=n_bins, normed=True) # Now we format the y-axis to display percentage axs[1].yaxis.set_major_formatter(PercentFormatter(xmax=1))
To plot a 2D histogram, one only needs two vectors of the same length, corresponding to each axis of the histogram.
fig, ax = plt.subplots(tight_layout=True) hist = ax.hist2d(x, y)
Customizing a 2D histogram is similar to the 1D case, you can control visual components such as the bin size or color normalization.
fig, axs = plt.subplots(3, 1, figsize=(5, 15), sharex=True, sharey=True, tight_layout=True) # We can increase the number of bins on each axis axs[0].hist2d(x, y, bins=40) # As well as define normalization of the colors axs[1].hist2d(x, y, bins=40, norm=colors.LogNorm()) # We can also define custom numbers of bins for each axis axs[2].hist2d(x, y, bins=(80, 10), norm=colors.LogNorm()) plt.show()
Total running time of the script: ( 0 minutes 0.262 seconds)
Gallery generated by Sphinx-Gallery
|
http://matplotlib.org/gallery/statistics/hist.html
|
CC-MAIN-2017-43
|
refinedweb
| 458
| 60.92
|
The QListWidget class provides an item-based list widget. More...
#include <QListWidget>
Inherits QListView.
The QListWidget class provides an item-based list widget.
QListWidget is a convenience class that provides a list view similar to the one supplied by QListView, but with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list.
For a more flexible list view widget, use the QListView class with a standard model.
List widgets are constructed in the same way as other widgets:
QListWidget *listWidget = new QListWidget(this);
The selectionMode() of a list widget determines how many of the items in the list can be selected at the same time, and whether complex selections of items can be created. This can be set with the setSelectionMode() function.
There are two ways to add items to the list: they can be constructed with the list widget as their parent widget, or they can be constructed with no parent widget and added to the list later. If a list widget already exists when the items are constructed, the first method is easier to use:
new QListWidgetItem(tr("Oak"), listWidget); new QListWidgetItem(tr("Fir"), listWidget); new QListWidgetItem(tr("Pine"), listWidget);
If you need to insert a new item into the list at a particular position, it is more required to construct the item without a parent widget and use the insertItem() function to place it within the list. The list widget will take ownership of the item.
QListWidgetItem *newItem = new QListWidgetItem; newItem->setText(itemText); listWidget->insertItem(row, newItem);
For multiple items, insertItems() can be used instead. The number of items in the list is found with the count() function. To remove items from the list, use takeItem().
The current item in the list can be found with currentItem(), and changed with setCurrentItem(). The user can also change the current item by navigating with the keyboard or clicking on a different item. When the current item changes, the currentItemChanged() signal is emitted with the new current item and the item that was previously current.:
Notifier signal:.
Warning: All items will be permanently deleted.
Closes the persistent editor for the given item.
See also openPersistentEditor().
Returns the current item.
See also setCurrentItem().
This signal is emitted whenever the current item changes.
previous is the item that previously had the focus; current is the new current item.
This signal is emitted whenever the current item changes.
currentRow is the row of the current item. If there is no current item, the currentRow is -1.
This signal is emitted whenever the current item changes.
currentText is the text data in the current item. If there is no current item, the currentText is invalid.
Reimplemented from QWidget::dropEvent().
Handles data supplied by an external drag and drop operation that ended with the given action in the given index. Returns true if data and action can be handled by the model; otherwise returns false.
See also supportedDropActions().
Starts editing the item if it is editable.
Reimplemented from QObject::event()..
See also QWidget::setMouseTracking().(), QListWidgetItem::is in the same process, the list is empty.
Returns an object that contains a serialized description of the specified items. The format used to describe the items is obtained from the mimeTypes() function.
If the list of items is empty, 0 is returned instead of a serialized empty list.
Returns a list of MIME types that can be used to describe a list of.
hint specifies where the item should be located after the operation.
Returns a list of all selected items in the list widget.
Sets the current item to item.
Unless the selection mode is NoSelection, the item is.
|
http://doc.qt.digia.com/4.6/qlistwidget.html
|
CC-MAIN-2014-15
|
refinedweb
| 614
| 66.74
|
Streaming Music from SoundCloud in Ionic 2: Part 1
By
In this first part of the tutorial, we are going to focus on getting a bare bones application set up, and we will leave the interface and other finishing touches to the next part.
Before we proceed, it’s important to understand that we will be using content created by others in our application, and it’s important to understand the rules around that. Specifically, SoundCloud specifies that you must:
- Credit the uploader as the creator of the sound
- Credit SoundCloud as the source by including one of the logos found here
- Link to the SoundCloud URL containing the work
- If the sound is private link to the profile of the creator
We are not going to be displaying that information until Part 2, so if you are planning on publishing this application make sure that you do include this information before doing so.. Generate a new Ionic 2 Application
We’re going to start off by generating a new Ionic 2 application and setting up a provider.
Run the following command to generate a new application
ionic start ionic2-soundcloud blank --v2
We’ll only be using a single page in this application, so we don’t need to generate any pages. We will be using a provider to handle the integration with the SoundCloud API though, so let’s set that up now.
Run the following command to generate the SoundCloud provider
ionic g provider SoundCloud
2. Set up the SoundCloud Javascript SDK
SoundCloud offers a Javascript, Ruby, and Python SDK that developers can use to interact with their HTTP API. We will of course be making use of the Javascript SDK.
Often when installing 3rd party services into an Ionic 2 application we would install an
npm package and import it wherever we want to use it. We’re going to do this old school though and follow the instructions [here]( by just including the SDK directly in our
index.html file.
Modify your
index.htmlfile to include the following script:
<script src="build/js/app.bundle.js"></script> <script src=""></script>
This will make an object called
SC globally available that we can use to interact with the SoundCloud API.
3. Get a Client ID from SoundCloud
In order to use the SoundCloud API you will need your own Client ID. You can do this by visiting developers.soundcloud.com:
and clicking on the ‘Register a new app’ button. Follow the prompts to create your SoundCloud account and app, and you should receive a Client ID to use. Make note of this for the next step.
4. Implement the SoundCloud Provider
Now that we have the SDK available within our application, we are going to work on our provider so that we can fetch tracks from the API and play them within the application. Let’s start our with a skeleton of what we will be building and work on it from there.
Modify sound-cloud.ts to reflect the following:
import { Injectable } from '@angular/core'; import { Platform } from 'ionic-angular'; import 'rxjs/add/operator/map'; declare var SC; @Injectable() export class SoundCloud { private clientId: string = 'YOUR_CLIENT_ID'; private tracks: any[] = []; private playTrack: number = 0; public currentTrack: Track; constructor(private platform: Platform) { this.platform.ready().then(() => { SC.initialize({ client_id: this.clientId }); }); } fetchTracks(bpm: number, genre:string): void { } startStreaming(){ } }
This is a fairly basic skeleton, but there are a few things to take note of. First we add this line above the
@Injectable decorator:
declare var SC
This is because we will be using the
SC object from SoundCloud, which the TypeScript compiler doesn’t know about, so we add this line to suppress any warnings that TypeScript might throw at us.
We’ve declared a few different member variables. The
clientId which you should replace with your own Client ID, a
tracks array to hold the tracks we will fetch from SoundCloud,
playTrack which will indicate the track we are up to, and
currentTrack that will hold information about the track that is currently playing.
All of these are given
types, most of which are pretty normal – string, any, type – but we have also given
currentTrack a type of
Track. We don’t have an appropriate type to represent the structure of the object that
currentTrack will contain (one that will be returned from the SoundCloud API), so we are going to create our own with an “interface”. We will talk more about this in just a moment.
The
constructor handles initialising the SoundCloud API, and then we have two more functions. The
fetchTracks function will pull in a list of songs to stream from SoundCloud, and
startStreaming will play the list of songs that were fetched. We will implement both of these soon.
4.1 Fetch Tracks from SoundCloud
We are going to start off by implementing the
fetchTracks function. This function will take in parameters of a
bpm which will represent the desired “beats per minute” and a
genre string that will represent one or more desired genres of music.
Modify the
fetchTracksfunction to reflect the following:
fetchTracks(bpm: number, genre:string): void { SC.get('/tracks', { genres: genre, bpm: { from: bpm - 5, to: bpm + 5 }, filter: 'public' }).then((tracks) => { console.log(tracks); this.tracks = tracks; console.log("Playing " + tracks.length + " tracks"); this.startStreaming(); }); }
We make a call to the
/tracks endpoint of the SoundCloud API, and supply our options to it. We extend the range of the supplied BPM by 5 on both sides, and we are also supplying a
public filter – this will only return songs that are available to the public and allowed to be streamed.
This call will return a promise that resolves with an array of tracks – we assign those tracks to our member variable
tracks and then call the
startStreamin function, which will handle playing the tracks we just received.
4.2 Play the List of Fetched Songs
Now that we have our tracks we just need to play them. SoundCloud makes it pretty easy to play a specific track, but we don’t want to just play one track. We want to play all of them, which means when one song finishes we want to play the next. This will involve setting up some listeners for events and handling them.
Modify the
startStreamingfunction to reflect the following:
startStreaming(){ this.currentTrack = this.tracks[this.playTrack]; console.log("Playing track " + this.playTrack); console.log(this.currentTrack); SC.stream('/tracks/' + this.currentTrack.id).then((player) => { player.play(); player.on('buffering_start', () => { console.log('buffering...'); }); player.on('buffering_end', () => { console.log('party!'); }); player.on('finish', () => { if(this.playTrack < this.tracks.length - 1){ this.playTrack++; } else { this.playTrack = 0; } console.log('time to move on...'); this.startStreaming(); }); }); }
First we set the
currentTrack as the track in our
tracks array with an index that matches
playTrack – this starts at 0, so will get the first track, and will be incremented each time we finish playing a song.
We then use the
stream method from the SoundCloud SDK to stream the track from SoundCloud – we simply have to supply its
id. This will return to us a
player that we can use to play the track (which we do), but the player also allows us to listen for various events. We are using three here:
buffering_start which indicates when a track is loading,
buffering_end which indicates when a track has finished loading, and
finish which indicates when a track has finished playing. You can find a full list of available events here.
When a track does finish playing we increment the
playTrack (or reset it to 0 if there are no tracks left) and then call the
startStreaming function again so that the next track will play.
4.3 Create an Interface
As you may be aware, when building Ionic 2 applications we are using TypeScript. TypeScript likes to complain about things it doesn’t know about – and it certainly doesn’t know about the data structure returned from SoundCloud. You may have experienced this before when attempting to reference things from the global
cordova object in your code, TypeScript doesn’t know what that is so it will throw up a warning (which prevents your application from building).
One way to solve this problem is to install
typings, which defines types for whatever it is that you are using (this makes TypeScript happy). This is quite easy to do through the use of the
typings package, but not everything has typings available.
Another way to solve this problem of missing types is to define an
interface. An interface will allow you to define simple or complex type definitions – it allows you to create your own “types”. As I mentioned before, we want to use our own
Track type, and we are going to define that now.
Modify sound-cloud.ts by adding the following above the @Injectable decorator:
interface User { permalink_url: string; username: string; } interface Track { id: number; title: string; artwork_url: string; permalink_url: string; user: User; }
The format here is reasonably simple. The
Track object that will be returned to our application will look something like this:
{ id: 123, title: 'Some Song', permalink_url: '', artwork_url: '', user: { permalink_url: '', username: 'joshuamorony' } }
So we define the same properties in our
interface, and give an appropriate type to each property. The only complex part here is that the
user property is in itself an object with its own properties, so we define another
interface to create a
User type. This doesn’t cover the entire structure of the data sent back by SoundCloud, but it does cover everything we use, so TypeScript won’t throw any errors at us when we try to access them.
Since the data will take a little while to load in from SoundCloud, but we will (later) be trying to access it straight away, we are going to create a dummy track in the
constructor.
Modify the
constructorin sound-cloud.ts to reflect the following:
constructor(private platform: Platform) { this.currentTrack = { id: 0, title: 'Fetching tracks...', permalink_url: '', artwork_url: '', user: { permalink_url: '', username: '' } }; this.platform.ready().then(() => { SC.initialize({ client_id: this.clientId }); }); }
That’s it for our provider! Now let’s move on to actually making use of it.
5. Inject the SoundCloud Provider
We are going to make a single instance of the SoundCloud provider available globally, so we are going to inject it into our root component. If you want to learn more about providers, and the difference between adding it to app.ts and a normal component, take a look at this tutorial.
Modify app.ts to reflect the following:
import { Component } from '@angular/core'; import { ionicBootstrap, Platform } from 'ionic-angular'; import { StatusBar } from 'ionic-native'; import { SoundCloud } from './providers/sound-cloud/sound-cloud'; import { HomePage } from './pages/home/home'; @Component({ template: '<ion-nav [root]="rootPage"></ion-nav>' }) export class MyApp { rootPage: any = HomePage; constructor(platform: Platform, soundCloud: SoundCloud) { platform.ready().then(() => { StatusBar.styleDefault(); soundCloud.fetchTracks(120, 'electronic'); }); } } ionicBootstrap(MyApp, [SoundCloud]);
We’ve imported the provider, and added it to
ionicBootstrap here. We’ve also injected it into the
constructor and we make a call to the
fetchTracks function as soon as the
ready() method resolves. We supply a
bpm of 120 and a
genre of “electronic” but you can change this to whatever you like. Now as soon as we start the app the music will be fetched and played right away.
Party!
If you run the application now with
ionic serve you will see the normal blank starter app, but if you wait a few seconds some music should start playing! In the next part of the tutorial we will focus on creating a proper interface, that will display the track being played (along with the appropriate attribution to the creators) and allow the user to skip songs.
|
https://www.joshmorony.com/streaming-music-from-soundcloud-in-ionic-2-part-1/
|
CC-MAIN-2019-51
|
refinedweb
| 1,964
| 59.23
|
Mock v0.7.2 documentation
Here are some more examples for some slightly more advanced scenarios than in the getting started guide.
Mocking chained calls is actually straightforward with mock once you understand the Mock.Mock object at 0x...> >>>.
Here’s how we might do it in a slightly nicer way. We start by creating our initial mocks:
>>> something = Something() >>> mock_response = Mock(spec=file) >>> mock_backend = Mock() >>> get_endpoint = mock_backend.get_endpoint >>> create_call = get_endpoint.return_value.create_call >>> start_call = create_call.return_value.start_call >>> start_call.return_value = mock_response
With these we monkey patch the “mock backend” in place and can make the real call:
>>> something.backend = mock_backend >>> something.method()
Keeping references to the intermediate methods makes our assertions easier, and also makes the code less ugly.
>>> get_endpoint.assert_called_with('foobar') >>> create_call.assert_called_with('spam', 'eggs') >>> start_call.assert_called_with() >>> # make assertions on mock_response about how it is used).
So first the topic of creating a mock object that can be called, with the return value able to act as a context manager. The easiest way of doing this is to use the new MagicMock, which is preconfigured to be able to act as a context manger. As an added bonus we’ll use the spec argument to ensure that the mocked object can only be used in the same ways a real file could be used (attempting to access a method or attribute not on the file will raise an AttributeError):
>>> mock_open = Mock() >>> mock_open.return_value = MagicMock(spec=file)
In terms of configuring our mock this is all that needs to be done. In fact it could be constructed with a one liner: mock_open = Mock(return_value=MagicMock(spec=file)).
So what is the best way of patching the builtin open function? One way would be to globally patch __builtin__.open. So long as you are sure that none of the other code being called also accesses open this is perfectly reasonable. It does make some people nervous however. By default we can’t patch the open name in the module where it is used, because open doesn’t exist as an attribute in that namespace. patch refuses to patch attributes that don’t exist because that is a great way of having tests that pass but code that is horribly broken (your code can access attributes that only exist during your tests!). patch will however create (and then remove again) non-existent attributes if you tell it that you are really sure you know what you’re doing.
By passing create=True into patch we can just patch the open function in the module under test instead of patching it globally:
>>> open_name = '%s.open' % __name__ >>> with patch(open_name, create=True) as mock_open: ... mock_open.return_value = MagicMock(spec=file) ... ... with open('/some/path', 'w') as f: ... f.write('something') ... <mock.Mock object at 0x...> >>> file_handle = mock_open.return_value.__enter__.return_value >>> file_handle.write.assert_called_with('something')() >>> generator = mock_foo.iter.return_value >>> iterator = iter([1, 2, 3]) >>> generator.__iter__.return_value = iterator >>> list(mock_foo.iter()) [1, 2, 3]
The above example is done step-by-step. The shorter version is:
>>> mock_foo = MagicMock() >>> mock_foo.iter.return_value._ mocksignature', mocksignature=True) as mock_foo: ... mock_foo.>> mock_foo.assert_called_once_with(foo)
If we don’t use mocksignature=True then the unbound method is patched out with a Mock instance instead, and isn’t called with self.
A few people have asked about mocking properties, specifically tracking when properties are fetched from objects or even having side effects when properties are fetched.
You can already do this by subclassing Mock and providing your own property. Delegating to another mock is one way to record the property being accessed whilst still able to control things like return values:
>>> mock_foo = Mock(>> mock_foo.assert_called_once_with()
This approach works fine if you can replace the whole object you’re mocking. If you just want to mock the property on another object here’s an alternative approach using the support for magic methods introduced in 0.7:
>>> class Foo(object): ... @property ... def fish(self): ... return 'fish' ... >>> with patch.object(Foo, 'fish') as mock_fish: ... mock_fish.__get__ = Mock(return_value='mocked fish') ... foo = Foo() ... print foo.fish ... mocked fish >>> mock_fish.__get__.assert_called_with(mock_fish, foo, Foo)
If you’re using an earlier version of mock, a third approach is to subclass Mock and provide a __get__ method that delegates back to the mock:
>>> class PropertyMock(Mock): ... def __get__(self, instance, owner): ... return self() ... >>> prop_mock = PropertyMock() >>> with patch.object(Foo, 'fish', prop_mock): ... foo = Foo() ... prop_mock.return_value = 'mocked fish' ... print foo.fish ... mocked fish >>> prop_mock.assert_called_with()
As you’re patching on the class these techniques affect all instances of Foo., the API is not quite so nice.
All of the calls, in order, are stored in call_args_list as tuples of (positional args, keyword args).
>>> mock = Mock(return_value=None) >>> mock(1, 2, 3) >>> mock(4, 5, 6) >>> mock() >>> mock.call_args_list [((1, 2, 3), {}), ((4, 5, 6), {}), ((), {})]
Because it stores positional args and keyword args, even if they are empty, the list is overly verbose which makes for ugly tests. It turns out that I do this rarely enough that I’ve never got around to improving it. One of the new features in 0.7.0 helps with this. The tuples of (positional, keyword) arguments are now custom objects that allow for ‘soft comparisons’ (implemented by Konrad Delong). This allows you to omit empty positional or keyword arguments from tuples you compare against.
>>> mock.call_args_list [((1, 2, 3), {}), ((4, 5, 6), {}), ((), {})] >>> expected = [((1, 2, 3),), ((4, 5, 6),), ()] >>> mock.call_args_list == expected True
This is an improvement, but still not as nice as assert_called_with. Here’s a helper function that pops the last argument of the call args list and decrements the call count. This allows you to make asserts as a series of calls to assert_called_with followed by a pop_last_call.
>>> def pop_last_call(mock): ... if not mock.call_count: ... raise AssertionError("Cannot pop last call: call_count is 0") ... mock.call_args_list.pop() ... try: ... mock.call_args = mock.call_args_list[-1] ... except IndexError: ... mock.call_args = None ... mock.called = False ... mock.call_count -=1 ... >>> mock = Mock(return_value=None) >>> mock(1, foo='bar') >>> mock(2, foo='baz') >>> mock(3, foo='spam') >>> mock.assert_called_with(3, foo='spam') >>> pop_last_call(mock) >>> mock.assert_called_with(2, foo='baz') >>> pop_last_call(mock) >>> mock.assert_called_once_with(1, foo='bar')
The calls to assert_called_with are made in reverse order to the actual calls. Your final call can be a call to assert_called_once_with, that ensures there were no extra calls you weren’t expecting. You could, if you wanted, extend the function to take args and kwargs and do the assert for you. Mock Mock [(('a',), {}), (('c',), {}), (('d',), {}), (('b',), {}), (('d',), {})] >>> mock.__setitem__.call_args_list [(('b', 'fish'), {}), (('d', 'eggs'), {})] >>> my_dict {'a': 1, 'c': 3, 'b': 'fish', 'd': 'eggs'}
If you have a mock object, particularly one created for you by patch, setting up attributes and return values for methods takes one line for every aspect of configuration..Mock object at 0x...> >>> mock.foo 3 >>> print mock.bar None
return_value and side_effect can be used to set them directly on the main mock anyway as they are just attributes.
>>> mock = Mock() >>> configure_mock(mock, side_effect=KeyError) <mock.Mock object at 0x...> >>> mock() Traceback (most recent call last): ... KeyError
This is fine for directly setting attributes, but what if you want to configure the return values or side effects of child mocks? How about using standard dotted notation to specify these. Instead of normal keyword arguments you’ll need to build a dictionary of arguments and pass them in with **. The function could also create a mock for us if we pass in None:
>>>
If you have any opinions on this then please comment on the issue.
A minimal implementation of configure_mock that you can start using now is:.Mock object at 0x...> >>> patch methods: start and stop, work around this by taking a reference to sys.modules inside the test rather than at import time. (Using patch.dict as a decorator takes a reference to sys.modules at import time, it doesn’t do the patching until the test is executed though.)
The Mock class allows you to track the order of method calls on your mock objects through the Mock:
>>> manager = Mock() >>> mock_foo = manager.foo >>> mock_bar = manager.bar >>> mock_foo.something() <mock.Mock object at 0x...> >>> mock_bar.other.thing() <mock.Mock object at 0x...> >>> manager.method_calls [('foo.something', (), {}), ('bar.other.thing', (), {})]
Using the “soft comparisons” feature of mock 0.7.0 we can make the final assertion about the expected calls less verbose:
>>> expected_calls = [('foo.something',), ('bar.other.thing',)] >>> manager.method_calls == expected_calls True
To make them even less verbose I would like to add a new call object to mock 0.8.0. You can see the issues I expect to work on for 0.8.0 in the issues list.
call would look...> >>> mock.bar.baz(a=3, b=6) <mock.Mock object at 0x...> >>>...> >>> mock_bar.other.thing() <mock.Mock object at 0x...> >>> manager.method_calls == [call.foo.something(), call.bar.other.thing()] True
Sometimes you may need to make assertions about some of the arguments in a call to mock, but either not care about some of the arguments or want to pull them individually out of Mock.call_args and make more complex assertions on them.
To ignore certain arguments you can pass in objects that compare equal to everything. Calls to Mock.assert_called_with() and Mock.assert_called_once_with() will then succeed no matter what was passed in.
Here’s an example implementation:
>>> class _ANY(object): ... def __eq__(self, other): ... return True ... >>> ANY = _ANY()
And an example of using it:
>>> mock = Mock(return_value=None) >>> mock('foo', bar=object()) >>> mock.assert_called_once_with('foo', bar=ANY)
Using the same basic concept as the ANY pattern above we can implement matchers to do more complex assertions on objects used as arguments to mocks.
Suppose we expect some object to be passed to a mock that by default compares equal based on object identity (which is the Python default for user defined classes). To use Mock: ((<__main__.Foo object at 0x...>,), {}) Called with: ((<_).
|
http://www.voidspace.org.uk/python/mock/0.7/examples.html
|
CC-MAIN-2015-48
|
refinedweb
| 1,643
| 58.99
|
introduces==." type="number"><.)..
The platform throws events when the user does not respond, doesn't respond intelligibly, bargein is not specified, then the value of the bargein property is used. form item and each>vanilla|chocolate|strawberry<" type="boolean"> 17).> and <dtmf> <field> type attribute is used to specify a built <emp><value expr="lo_fat_meal"/></emp>. <, and nomatchevent is thrown to cause a reprompt.
<field name="ticket_num" type="digits"> <prompt> Read the 12 digit number from your ticket. </prompt> <help>The 12 digit number is to the lower left.</help> <filled> <if mcond="ticket_num.length != 12"> <prompt> Sorry, I didn't hear exactly 12 digits. </prompt> <assign name="ticket_num" expr="undefined"/> </if> </filled> </field>
It is important that there be input conventions for each built-in type, so that, for instance, generic prompt and help messages can be written that apply to all implementations of VoiceXML. These are locale-dependent, and a certain amount of variability is allowed. For example, the boolean type’s grammar should minimally allow “yes” and “no” responses, but each implementation is free to add other choices, such as “yeah” and “nope”. In cases where an application requires a different behavior, it should use explicit field grammars.
In addition, each built-in type has a convention for the format of the value returned. These are independent of locale and of the implementation. The return type for built-in fields is string except for the booleanfield type. To access the actual recognition result, the author can reference the shadow variablename$.utterance.
All built.gram" type="application/x-jsgf"/> </field>
Grammars can be specified inline, for example using JSGF:
<field name="flavor"> <prompt>What is your favorite flavor?</prompt> <help>Say one of vanilla, chocolate, or strawberry.</help> <grammar type="application/x-jsgf"> vanilla {van} | chocolate {choc} | strawberry {straw} </grammar> <dtmf type="application/x-jsgf"> 1 {van} | 2 {choc} | 3 {straw} </dtmf> </field> <enumerate> element is discussed in Section 7.
The attributes of <option> are:
Some built-in field types can be parameterized. This may be done by explicitly referring to built-in grammars using a special-purpose “builtin:” URI scheme and a URI-style query syntax of the form type?param=value in the src attribute of a <grammar> or <dtmf> element, or in the type attribute of a field, for example:
<grammar src="builtin:grammar/boolean"/> <dtmf src="builtin:dtmf/boolean?y=7"/> <field type="digits?minlength=3;maxlength=5">…</field>
By definition the following:
<field type="X">…</field>
is equivalent to:
<field> <grammar src="builtin:grammar/X"/> <dtmf src="builtin:dtmf/X"/> … </field>
where X is one of the built-in field types (boolean, date, etc.). The digits and boolean grammars may be parameterized as follows:
Note that more than one parameter may be specified separated by “;” as illustrated above. In <grammar> or <dtmf> elements, the src attribute URI must start with builtin:grammar/ or builtin:dtmf/ as shown above. When a <grammar> element is specified in a <field>, it overrides the default speech grammar implied by the type attribute of the field. Likewise, when a <dtmf> element is specified in a <field>, it overrides the default DTMF grammar.
This element is a form item. It contains executable content that is executed if the block’s form item variable is undefined and the block's cond attribute, if any, evaluates to true.
<block> Welcome to Flamingo.example,scope of the form.
Attributes of <block> include:
In a typical mixed initiative form, the <initial> element is visited when the user is initially being prompted for form-wide information, and has not yet entered into the directed mode where each field is solicited individually. Like field items, it has prompts, catches, and event counters. Unlike field items, <initial> has no grammars, and no <filled> action. For instance:
<form id="get_from_and_to_cities"> <grammar src=""/> =""/> <prompt>From which city are you leaving?</prompt> … etc. … </field> … etc. … </form>
While visiting an <initial> element, no field grammar is active..
Note: explicit assignment of values to field item variables does not affect the value of an <initial>’s form item variable.
Attributes of <initial> include:
A <subdialog> element invokes a “called” dialog (known as the subdialog) identified by its src attribute. The subdialog executes in a new execution context. The subdialog proceeds until the execution of a <return> element which causes the subdialog to return. When the subdialog returns, its execution context is deleted, and execution resumes in the calling dialog with any appropriate <filled> elements. An execution context includes all declarations and state information for the dialog, the dialog’s document, and the application root (if present). Subdialogs can permit the reuse of a common dialog such as this example of prompting a user for credit card information, or build libraries of reusable applications.
The attributes are: corresponding <param> value, if they don't have an expr attribute. Thus <param> elements can only initialize <var> elements without expr attributes./x-jsgf"/> ="1.0"> <form> <field name="birthday" type="date"> What is your birthday? </field> <subdialog name="result" src="/cgi-bin/getlib#getdriverslicense" namelist="birthday"> <filled> <submit next=""/> </filled> </subdialog> </form> </vxml>
<?xml version="1.0"?> <vxml version="1.0"> <form id="getdriverlicense"> <var name="birthday" expr="'1980-02-10'"/> <!-- Generated by server script --> <field name="drivelicense"> <grammar src="" type="application/x-jsgf"/> .. For example, if subdialog A transitions to dialog B, then the interpretation of B considers only active grammars in its dialog scope and the default grammars.="1.0"> <!-- Example of subdialog to collect credit card information. --> <!-- file is at --> <form id="getcredit"> <var name="status" expr="'no_result'"/> <var name="username"/> <field name="creditcardnum"> <prompt> What is your credit card number? </prompt> <help> I am trying to collect your credit card information. <reprompt/> </help> <nomatch> <return namelist="status"/> </nomatch> <grammar .../> </field> <field name="expirydate" type="date"> ="1.0"> <!-- Example main program --> <!-- --> <!-- calls subdialog ccn.vxml --> <!-- assume this gets defined by some dialog --> <var name="username"/> <form id="buysoftware"> <var name="ccn"/> <var name="exp"/> <grammar ..../> <initial name="start"> <prompt> Please tell us the software product you wish to buy and the operating system on which it must run. </prompt> <noinput> <assign name="start" expr="true"/> </noinput> </initial> <field name="product"> <prompt> Which software product would you like to buy? </prompt> </field> <field mname="/> <asssign name="exp" expr="cc_results.expirydate"/> </if> </filled> </subdialog> <block> We will now process your order. Please hold. <submit namelist="username product operatingsystem ccn exp"/> </block> </form> </vxml>
A VoiceXML implementation platform may have platform-specific functionality that an application wants to use, such as speaker verification, native components, additional telephony functionality, and so on. Such platform-specific objects are accessed using the <object> element, which is analogous to the HTML <OBJECT> element. For example, a native credit card collection object could be accessed like this:
<object name="debit" classid="method://credit_card/gather_and_debit" data=""/> <param name="amount" expr="document.amt"/> <param name="vendor" expr="vendor_num"/> </object>
In this example, the <param> element (Section 18).message.
Attributes of <object> include:
If an <object> element refers to an unknown object, the error.unsupported.object event is thrown. There is no requirement for implementations to provide platform-specific objects, although support for the <object> element is required.
The <record> element is a field item that collects a recording from the user. The recording is stored in the field item variable, which can be played back or submitted to a server, as shown in this example:
<?xml version="1.0"?> <vxml version="1.0"> <form> <record name="greeting" beep="true" maxtime="10s" finalsilence="4000ms" dtmfterm="true" type="audio/wav"> <prompt> At the tone, please say your greeting. </prompt> <noinput> I didn't hear anything, please try again. </noinput> </record> <field name="confirm" type="boolean"> <prompt> Your greeting is <value expr="greeting"/>. </prompt> <prompt> To keep it, say yes. To discard it, say no. </prompt> <filled> <if cond="confirm"> <submit next="save_greeting.pl" method="post" namelist="greeting"/> </if> <clear/> </filled> </field> </form> </vxml>
The user is prompted for a greeting and then records it. The greeting is played back, and if the user approves it, is sent on to the server for storage using the HTTP POST method. Notice that like other field items, <record> has prompts and catch elements. It may also have <filled> actions. If the platform supports simultaneous recognition and recording, form and document scoped grammars can be active while the recording is in progress.
The attributes of <record> are:
The <record> shadow variable name$ has the following ECMAScript properties after the recording has been made:
Occasionally, it is appropriate to suspend the session between the user and the interpreter and initiate a session with another entity. The most common use for this capability in current practice is to connect a user in a telephone conversation with a interpreter to a third party through the telephone network. The <transfer> element directs the interpreter to make such a third party connection. Two scenarios are supported:
The form item variable is used to store the outcome of the transfer attempt. Here are the possible values:
This example attempts to transfer the user to a customer support operator and then wait for that conversation to terminate.
<form name="transfer"> <var name="mydur" expr="0"/> <block> <audio src="chopin12.wav"> </block> <transfer name="mycall" dest="phone://18005551234" connecttimeout="30s" bridge="true"> <filled> <assign name="mydur" expr="mycall$.duration"/> <if cond="mycall == 'busy'"> <prompt> Sorry, our customer support team is busy serving other customers. Please try again later. </prompt> <elseif cond="mycall == 'noanswer'"/> <prompt> Sorry, our customer support team's normal hours are 9 am to 7 pm Monday through Saturday. </prompt> </if> </filled> </transfer> <block> <submit namelist="mycall mydur" next="/cgi-bin/report"/> </block> </form>.
Attributes include:
The <transfer> shadow variable (name$) has the following ECMAScript properties after a transfer completes:
Events thrown inside a <transfer> include:
The <filled> element specifies an action to perform when some combination of fields are filled by user input. It may occur in two places: as a child of the <form> element, or as a child of a field item.
As a child of a <form> element, the <filled> element can be used to perform actions that occur when a combination of one or more fields is filled. For example, the following <filled> element does a cross-check to ensure that a starting city field differs from the ending city field:
<form id="get_starting_and_ending_cities"> <field name="start_city"> <grammar src=""/> <prompt>What is the starting city?</prompt> </field> <field name="end_city"> <grammar src=""/> <prompt>What is the ending city?</prompt> </field> <filled mode="any" namelist="start_city end_city"> <if cond="start_city == end_city"> <prompt> You can't fly from and to the same city. </prompt> <clear/> </if> </filled> </form>
If the <filled> element appears inside a field item, it specifies an action to perform after that field is filled in by user input. This is a notational convenience for a form-level <filled> element that triggers on a single field item:
<form id="get_city"> <field name="city"> <grammar src=""/> <prompt>What is the city?</prompt> <filled> <if cond="city == 'Novosibirsk'"> <prompt> Note, Novosibirsk service ends next year. </prompt> </if> </filled> </field> </form>
After each gathering of the user’s input, all the fields mentioned in the input are set, and then the interpreter looks at each <filled> element in document order (no preference is given to ones in fields vs. ones in the form). Those whose conditions are matched by the utterance are then executed in order, until there are no more, or until one transfers control or throws an event.
Attributes include:
The <meta> element specifies meta-data, as in HTML, which is data about the document rather than the document’s content. There are two types of <meta>. The first type specifies a meta-data property of the document as a whole. For example to specify the maintainer of a VoiceXML document:
<?xml version="1.0"?> <vxml version="1.0"> <meta name="maintainer" content="jpdoe@anycompany.example"/> … </vxml>
The interpreter could use this information, for example, to compose and email an error report to the maintainer.
VoiceXML does not specify required meta-data properties, but the following are recommended:
The second type of <meta> specifies HTTP response headers. In the following example, the first <meta> element sets an expiration date that prevents caching of the document; the second <meta> element sets the Dateheader.
<?xml version="1.0"?> <vxml version="1.0"> <meta http- <meta http- … </vxml>
Attributes of <meta> are: for all the prompts in a particular form:
<form id="no_bargein_form"> <property name="bargein" value="false"/> <block> <prompt> This introductory prompt cannot be barged into. </prompt> <prompt> And neither can this prompt. </prompt> <prompt bargein="true"> But this one <emp>can</emp> be barged into. </prompt> </block> … </form>
Properties are also used to specify platform-specific data and settings. For example, to set a platform-specific property to prepend one second of silence before each recording made by a particular document:
<?xml version="1.0"?> <vxml version="1.0"> <property name="example.acme.endpointing.record_init_silence" value="1s"/> … dialogs that make recordings go here … </vxml>
The generic speech recognizer properties are taken from the Java Speech API (see):
Several generic properties pertain to DTMF grammar recognition:
These properties apply to the fundamental platform prompt and collect cycle:
These properties pertain to the fetching of new documents and resources:
This property determines which input modality to use:
Our last example shows several of these properties used at multiple levels.
<?xml version="1.0"?> <vxml version="1.0"> <!-- set default characteristics for page --> <property name="caching" value="safe"/> <property name="audiofetchhint" value="safe"/> <property name="confidence" value="0.75"/> <form> <!-- override defaults for this form only --> <property name="confidence" value="0.5"/> <property name="bargein" value="false"/> <grammar src="address_book.gram" type="application/x-jsgf"/> " type="boolean"> <!-- Use actual utterances to playback recognized words, rather than returned slot values --> <prompt> You said to call <value expr="person$.utterance"/> at <value expr="location$.utterance"/>. Is this correct? </prompt> <filled> <if cond="confirm"> <submit next="" namelist="person location" /> </if> <clear/> </filled> </field> </form> </vxml>
The <param> element is used to specify values that are passed to subdialogs or objects. It is modeled on the HTML <PARAM> element. Its attributes are:
Exactly one of expr or value must be present. MIME/x-jsgf"/> .
Executable content refers to a block of procedural logic. Such logic appears in:
The <block> form item.
The <filled> actions in forms and form items.
Event handlers (<catch>, <help>, et cetera).attribute <emp>last</emp> chance. </prompt> </nomatch> <nomatch count="3"> Entrance denied. <exit/> </nomatch>
The FIA assumes that when a catch element is executed, it has queued appropriate prompts. Therefore the FIA normally suppresses playing of prompts on the iteration of the FIA following the execution of a catch element. However, if a <reprompt> is executed in the catch, this tells the FIA that when it selects the next form item to visit, it should do the normal prompt processing (which includes selection of a prompt and incrementing the prompt counter).
For example, this noinput catch expects the next form item prompt to be selected and played:
<field name="want_ice_cream" type="boolean"> .
C: I could not hear you.
H: No
Note that if no <reprompt> is executed in a catch, then the FIA skips the prompt selection and queuing phase of the selected form item. The form item’s prompt counter is therefore not incremented.
If a <reprompt> is executed, then the FIA executes the form item’s prompt selection queuing phase. This does increment the form item’s prompt counter. A <reprompt> does not cause the prior prompt to be played, in general, but will cause prompt(s) to be played based on the current value of the prompt counter and the current values of the prompt conditions. will likewise drop the old document level variables, even if the new document is the same one that is making the transition. If you want data to persist across multiple documents, store data in the application scope.
Attributes of <goto> are:
Exactly one of next, expr, nextitem, or expritem must be specified.
The <submit> element is similar to <goto> in that it results in a new document being obtained."/>
Attributes of <submit> include:
If an ECMAScript object o is the target of a submit then all its (ECMAScript) fields f1, f2, ... are submitted using the names o.f1, o.f2, etc.:
Return ends execution of a subdialog and returns control and data to a calling dialog. The attributes are:
In returning from a subdialog, an event can be thrown at the invocation point, or data is returned as an ECMAScript object./x-jsgf"/> telephone.disconnected.hangup event, which may be caught to do cleanup processing, e.g.
<disconnect/>
A <disconnect> differs from an <exit> in that it forces the interpreter context to drop the call.
The <script> element allows the specification of a block of client-side scripting language code, and is analogous to the HTML <SCRIPT> element. For example, this document has a script that computes a factorial.
<?xml version="1.0"?> <vxml version="1.0"?> <script> <![CDATA[ function factorial(n) { return (n <= 1)? 1 : n * factorial(n-1); } ]]> </script> <form id="form"> <field name="fact" type="number"> <prompt> Tell me a number and I'll tell you its factorial. </prompt> <filled> <prompt> <value expr="fact"/> factorial is <value expr="factorial(fact)"/> </prompt> </filled> </field> </form> </vxml>
A <script> element may occur in the <vxml> element, or in executable content (in <filled>, <if>, <block>, <catch>, or the short forms of <catch>). Scripts in the <vxml> element are evaluated just after the document is loaded, along with the <var> elements, in document order. A <script> element in executable content is executed, like other executable elements, as it is encountered.
The <script> element has the following attributes:
Each <script> element is executed in the scope of its containing element; i.e., it does not have its own scope.
Here is a time-telling service with a block containing a script that initializes time variables in the dialog scope of a form:
<?xml version="1.0"?> <vxml version="1.0"> <form> <var name="hours"/> <var name="minutes"/> <var name="seconds"/> <block> <script> var d = new Date(); hours = d.getHours(); minutes = d.getMinutes(); seconds = d.getSeconds(); </script> </block> <field name="hear_another" type="boolean"> <prompt> The time is <value expr="hours"/> hours, <value expr="minutes"/> minutes, and <value expr="seconds"/> seconds. </prompt> <prompt>Do you want to hear another time?</prompt> <filled> <if cond="hear_another"> <clear/> </if> </filled> </field> </form> </vxml>
The ECMAScript scope chain (see section 10.1.4 in) is set up so that variables declared with <var> are put into the scope associated with the element in which the <var> element occurs. All variables must be declared before being assigned or referenced by ECMAScript scripts, or by VoiceXML elements.
Time designations follow those used in W3C's Cascading Style Sheet recommendation (. org/TR/REC-CSS2/syndata.html#q20). They consist of an unsigned integer followed by an optional time unit identifier. The time unit identifiers are:
ms: milliseconds (the default)
s: seconds
<!-- A DTD for Voice Extensible Markup Language --> <!-- Copyright (c) 2000 VoiceXML Forum (AT&T, IBM, Lucent Technologies, Motorola) --> <!ENTITY % audio "#PCDATA | audio | enumerate | value" > <!ENTITY % boolean "(true|false)" > <!ENTITY % content.type "CDATA"> <!ENTITY % duration "CDATA" > <!ENTITY % event.handler "catch | help | noinput | nomatch | error" > <!ENTITY % event.name "NMTOKEN" > <!ENTITY % event.names "NMTOKENS" > <!ENTITY % executable.content "%audio; | assign | clear | disconnect | exit | goto | if | prompt | reprompt | return | script | submit | throw | var " > <!ENTITY % expression "CDATA" > <!ENTITY % field.name "NMTOKEN" > <!ENTITY % field.names "NMTOKENS" > <!ENTITY % integer "CDATA" > <!ENTITY % item.attrs "name %field.name; #IMPLIED cond %expression; #IMPLIED expr %expression; #IMPLIED " > <!ENTITY % uri "CDATA" > <!ENTITY % cache.attrs "caching (safe|fast) #IMPLIED fetchhint (prefetch|safe|stream) #IMPLIED fetchtimeout %duration; #IMPLIED " > <!ENTITY % next.attrs "next %uri; #IMPLIED expr %expression; #IMPLIED " > <!ENTITY % submit.attrs "method (get|post) 'get' enctype %content.type; 'application/x-www-formurlencoded' namelist %field.names; #IMPLIED" > <!ENTITY % tts "break | div | emp | pros | sayas" > <!ENTITY % variable "block | field | var" > <!--============================== Root ============================--> <!ELEMENT vxml (%event.handler; | form | link | menu | meta | property | script | var)+ > <!ATTLIST vxml application %uri; #IMPLIED base %uri; #IMPLIED lang CDATA #IMPLIED version CDATA #REQUIRED > <!ELEMENT meta EMPTY > <!ATTLIST meta name NMTOKEN #IMPLIED content CDATA #REQUIRED http-equiv NMTOKEN #IMPLIED > <!--============================= Dialogs ==========================--> <!ENTITY % input "dtmf | grammar" > <!ENTITY % scope "(document | dialog)" > <!ELEMENT form (%input; | %event.handler; | filled | initial | object | link | property | record | subdialog | transfer | %variable;)* > <!ATTLIST form id ID #IMPLIED scope %scope; 'dialog' > <!ELEMENT menu (%audio; | choice | %event.handler; | prompt | property)*> <!ATTLIST menu id ID #IMPLIED scope %scope; 'dialog' dtmf %boolean; 'false' > <!ELEMENT choice (%audio; | grammar | %tts;)* > <!ATTLIST choice %cache.attrs; dtmf CDATA #IMPLIED event %event.name; #IMPLIED fetchaudio %uri; #IMPLIED %next.attrs; > <!--============================ Prompts ===========================--> <!ELEMENT prompt (%audio; | %tts;)* > <!ATTLIST prompt bargein %boolean; #IMPLIED cond %expression; #IMPLIED count %integer; #IMPLIED timeout %duration; #IMPLIED > <!ELEMENT enumerate (%audio; | %tts;)*> <!ELEMENT reprompt EMPTY > <!--============================ Fields ============================--> <!ELEMENT field (%audio; | %event.handler; | filled | %input; | link | option | prompt | property)* > <!ATTLIST field %item.attrs; type CDATA #IMPLIED slot NMTOKEN #IMPLIED modal %boolean; 'false' > <!ELEMENT option (#PCDATA)* > <!ATTLIST option dtmf CDATA #IMPLIED value CDATA #IMPLIED > <!ELEMENT var EMPTY > <!ATTLIST var name %field.name; #REQUIRED expr %expression; #IMPLIED > <!ELEMENT initial (%audio; | %event.handler; | link | prompt | property)* > <!ATTLIST initial %item.attrs; > <!ELEMENT block (%executable.content;)* > <!ATTLIST block %item.attrs; > <!ELEMENT assign EMPTY > <!ATTLIST assign name %field.name; #REQUIRED expr %expression; #REQUIRED > <!ELEMENT clear EMPTY > <!ATTLIST clear namelist %field.names; #IMPLIED > <!ELEMENT value EMPTY > <!ATTLIST value class CDATA #IMPLIED expr %expression; #REQUIRED mode (tts|recorded) "tts" recsrc %uri; #IMPLIED > <!--============================ Events ============================--> <!ENTITY % event.handler.attrs "count %integer; #IMPLIED cond %expression; #IMPLIED" > <!ELEMENT catch (%executable.content;)* > <!ATTLIST catch event %event.names; #REQUIRED %event.handler.attrs; > <!ELEMENT error (%executable.content;)* > <!ATTLIST error %event.handler.attrs; > <!ELEMENT help (%executable.content;)* > <!ATTLIST help %event.handler.attrs; > <!ELEMENT link (dtmf | grammar)* > <!ATTLIST link %cache.attrs; %next.attrs; fetchaudio %uri; #IMPLIED event %event.name; #IMPLIED > <!ELEMENT noinput (%executable.content;)* > <!ATTLIST noinput %event.handler.attrs; > <!ELEMENT nomatch (%executable.content;)* > <!ATTLIST nomatch %event.handler.attrs; > <!ELEMENT throw EMPTY > <!ATTLIST throw event %event.name; #REQUIRED > <!--========================== Audio Output ========================--> <!ELEMENT audio (%audio; | %tts;)* > <!ATTLIST audio src %uri; #IMPLIED %cache.attrs; > <!ELEMENT break EMPTY > <!ATTLIST break msecs %integer; #IMPLIED size (none|small|medium|large) #IMPLIED > <!ELEMENT div (%audio; | %tts;)* > <!ATTLIST div type CDATA #IMPLIED> <!ELEMENT emp (%audio; | %tts;)* > <!ATTLIST emp level (strong | moderate | none | reduced) "moderate" > <!ELEMENT pros (%audio; | %tts;)* > <!ATTLIST pros rate CDATA #IMPLIED vol CDATA #IMPLIED pitch CDATA #IMPLIED range CDATA #IMPLIED > <!ELEMENT sayas (#PCDATA)* > <!ATTLIST sayas sub CDATA #IMPLIED class CDATA #IMPLIED phon CDATA #IMPLIED > <!--=========================== Audio Input ========================--> <!ENTITY % key "CDATA" > <!ENTITY % grammar.attrs "%cache.attrs; scope %scope; #IMPLIED src %uri; #IMPLIED type CDATA #IMPLIED " > <!ELEMENT dtmf (#PCDATA)* > <!ATTLIST dtmf %grammar.attrs; > <!ELEMENT grammar (#PCDATA)* > <!ATTLIST grammar %grammar.attrs; > <; | dtmf | filled | grammar | prompt | property)* > <!ATTLIST transfer %item.attrs; dest %uri; #IMPLIED destexpr %expression; #IMPLIED bridge %boolean; 'false' connecttimeout %duration; #IMPLIED maxtime %duration; #IMPLIED > <!--========================== Control Flow ========================--> <!ENTITY % if.attrs "cond %expression; #REQUIRED" > <!ELEMENT if (%executable.content; | elseif | else)* > <!ATTLIST if %if.attrs; > <!ELEMENT elseif EMPTY > <!ATTLIST elseif %if.attrs; > <!ELEMENT else EMPTY > <!ELEMENT exit EMPTY > <!ATTLIST exit expr %expression; #IMPLIED namelist %field.names; #IMPLIED > <!ELEMENT filled (%executable.content;)* > <!ATTLIST filled mode (any|all) "all" namelist %field.names; #IMPLIED > <!ELEMENT goto EMPTY > <!ATTLIST goto %cache.attrs; %next.attrs; fetchaudio %uri; #IMPLIED expritem %expression; #IMPLIED nextitem %field.name; #IMPLIED > <!ELEMENT param EMPTY > <!ATTLIST param name NMTOKEN #REQUIRED expr %expression; #IMPLIED value CDATA #IMPLIED valuetype (data|ref) 'data' type CDATA #IMPLIED > <!ELEMENT return EMPTY > <!ATTLIST return namelist %field.names; #IMPLIED event %event.name; #IMPLIED > <!ELEMENT subdialog (%audio; | %event.handler; | filled | param | prompt | property)* > <!ATTLIST subdialog %item.attrs; src %uri; #REQUIRED %cache.attrs; fetchaudio %uri; #IMPLIED %submit.attrs; > <!ELEMENT submit EMPTY > <!ATTLIST submit %cache.attrs; %next.attrs; fetchaudio %uri; #IMPLIED %submit.attrs; > <!--======================= Miscellaneous =========================--> < ( field themuser.. Execute the catch (this may leave the FIA). continue } // Must have an utterance: process ones from outside grammars. if ( the utterance matched a grammar from outside the form ) { if ( the grammar belongs to a <link> element ) Execute that link’s goto or throw, leaving the FIA. slot values into corresponding // form item variables. Clear all “just_filled” flags. foreach ( slot in the user’s utterance ) { if ( the slot corresponds to a field item ) { Copy the slot value into the field item’s form item variable. Set this field item’s “just_filled” flag. } } // Set <initial> form item variable if any field items are filled. if ( any field item variable is set as a result of the user utterance ) Set the <initial> form item variable. // Next execute any <filled> actions triggered by this utterance. foreach ( <filled> action in document order ) { // Determine the form item variables the <filled> applies to. N = the <filled>’s “namelist” attribute. if ( N equals “” ) { if ( the <filled> is a child of a form item ) N = the form item’s form item variable name. else if ( the <filled> is a child of a form ) N = the form item variable names of all the form items in that form. } // Is the <filled> triggered? if ( any form item variable in the set N was “just_filled” AND ( the <filled> mode is “all” AND all variables in N are filled OR the <filled> mode is “any” AND any variables in N are filled) ) Execute the <filled> action. } }
In this section we will describe how the Java Speech Grammar Format (JSGF) can be used with VoiceXML <grammar> element.
As stated in the section on grammars, a VoiceXML grammar must:
specify a set of utterances that a user may speak to perform an action or supply information, and
provide a corresponding string value (in the case of a field grammar) or set of attribute-value pairs (in the case of a form grammar) to describe the information or action.
JSGF supports the first requirement above by providing a language for describing context-free grammars. The following table is a summary of the features of JSGF.
The JSGF tag facility provides a means for meeting the second requirement of providing values for forms to describe the action requested. In the case of field grammars, where only a single string value is needed, a tag may be used to supply the value. If no tag is specified, the text of the utterance itself is used as the value.
As described in the section on grammars, a grammar element be either inline or external. Furthermore, in the case of JSGF, an inline grammar may be either a grammar fragment or complete grammar. These three cases are described below.
The content of the <grammar> element is the right-hand-side of a JSGF rule. (In JSGF terminology this is called a "rule expansion"). In the most common case, where no reference to non-terminals is made, no use is made of the XML reserved special characters, and so the rule expansion may be specified inline without need for quoting or use of a PCDATA element. This form is thus particularly convenient for expressing simple lists of alternative ways of saying the same thing, for example:
<link event="help"> <grammar type="application/x-jsgf"> [please] help [me] [please] | [please] I (need|want) help [please] </grammar> </link> <field name="sandwich"> <grammar type="application/x-jsgf"> hamburger | burger {hamburger} | (chicken [sandwich]) {chicken} </grammar> </field>
In the first example, any of the ways of saying "help" result in a help event being thrown. In the second example, the user may say "hamburger" or "burger" and the "sandwich" field will be given the value "hamburger", or the user may say "chicken" or "chicken sandwich" and the "sandwich" field will be given the value "chicken".
The content of the <grammar> element is a complete JSGF grammar, consisting of one or more rule definitions, with possible reference to external grammars. In this case all public rules in the supplied grammar are used. Since this form requires the use of XML reserved special characters generally a PCDATA element will be needed.
A complete JSGF grammar is found at the URI specified by the src attribute of the grammar element; the <grammar> element content must be empty. The specified URI may take the form of
a URI naming a whole document, in which case all public rules in the grammar contained in the document at the specified URI are used, or
a URI naming a document fragment, that is, a URI ending with #fragment, in which case the fragment name is taken to be the name of a public rule from the grammar contained in the document at the specified URI; only the rule so named is used.
VoiceXML recommends that a platform support the playing and recording audio formats specified below. Note: a platform need not support both A-law and μ-law simultaneously. 5).
Figure 5: Timing diagram for timeout when no input provided.
In Figure 6, the interdigittimeout determines when the nomatch event is thrown because a DTMF grammar is not yet recognized, and the user has failed to enter additional DTMF.
Figure 6: 8: 9 10: 11: 12: Timing diagram for timeout when no speech provided.
In the example above, the user provided a utterance that was recognized by the speech grammar. After a silence period of completetimeout has elapsed, the recognized value is returned.
Figure 13: 14: Timing diagram for incompletetimeout with speech grammar unrecognized.
This is an example of extending VoiceXML with a new element.
The <transcribe> element is a field item that collects a transcription of the user's utterance. The transcription string is stored in the field item variable.
<?xml version="1.0"?> <vxml version="1.0"> <form> <transcribe name="message" beep="true" maxtime="30s"> <prompt> What is the message you want to leave? </prompt> <nomatch count="2"> Try to make your message simpler. </nomatch> <nomatch count="3"> Transferring to operator. <goto next="queue_caller.pl"/> </nomatch> </transcribe> <field name="confirm" type="boolean"> <prompt> Your message is <value expr="message"/>. </prompt> <prompt> To send it, say yes. To discard it, say no. </prompt> <filled> <if cond="confirm"> <submit next="send_page.pl" namelist="message"/> </if> <clear/> </filled> </field> </form> </vxml>
Not all interpreter contexts will support <transcribe>.
The attributes of <transcribe> are:
The <transcribe> shadow variable (name$) has the following ECMAScript properties after the transcription has been made:
The following are the required changes to the DTD:
<!--============================ Dialogs ===========================--> … <!ELEMENT form (%input; | %event.handler; | filled | initial | object | link | property | record | subdialog | transcribe | transfer | %variable;)* > <!ATTLIST form id ID #IMPLIED scope %scope; 'dialog' > … <!--========================== Audio Input =========================--> … <!ELEMENT transcribe (%audio; | %event.handler; | filled | grammar | prompt | property)* > <!ATTLIST transcribe %item.attrs; beep %boolean; 'false' maxtime %duration; #IMPLIED modal %boolean; 'true' finalsilence %duration; #IMPLIED dtmfterm %boolean; 'true' > …
The Form Interpretation Algorithm would be modified as follows:
// Execute the form item. if ( a <field> was selected ) Collect an utterance or an event from the user. else if ( a <record> was chosen ) Collect an utterance (with a name/value pair for the recorded bytes) or event from the user. else if ( a <transcribe> was chosen ) Collect an utterance (with a name/value pair for the transcription) or event from the user. else if ( an <object> was chosen ) Execute the object, setting the <object>’s form item variable to the returned ECMAScript value. …
This specification was written by the VoiceXML Forum technical working group:
|
http://www.w3.org/TR/voicexml/
|
CC-MAIN-2017-09
|
refinedweb
| 5,178
| 50.12
|
prBoB86Members
Content count374
Joined
Last visited
Community Reputation277 Neutral
About SnprBoB86
- RankMember
SnprBoB86 replied to hspirdal's topic in Graphics and GPU ProgrammingExtension methods have always needed to be defined in a static class like your SpriteManager class, but they are typically given an "Extensions" suffix on the name of the class to be extended. For example: "SpriteBatchExtensions" Nick just forgot to point out the static class bit in his tutorial, you should post a comment to him and let him know. Also, I don't agree with Nick that this is appropriate use of extension methods. Instead, I would declare Sprite.Draw with the signature `public void Draw(SpriteBatch batch)` to be used as `someSprite.Draw(spriteBatch)`. Why? Because it's simpler and extension methods don't really buy you anything here. Extension methods are really as syntactical sugar. They are useful for saving typing when you have helper methods that can be identified by the target object and method name (2 things) rather than a namespace (well, a static class name), target object, and method name (3 things). "user@microsoft.com".IsValidEmailAddress() vs EmailAddressHelpers.IsValid("user@microsoft.com") In the Sprite case, you have: spriteBatch.Draw(sprite) vs sprite.Draw(spriteBatch) Why bother with the extension method? It just confuses things! That said, Nick isn't necessarily wrong to suggest the use of extension methods here. It's just not the call I would have made :-)
- Quote:Original post by Koobazaur at least when I had ** ppSomething I knew exactly what was going on instead of having to wonder what is referencing what (not to mention extra flexibility). And wtf is up with the lack of template, errr, generic specialization? Seriously... You have nearly the exact same flexibility in C# and you can know "exactly what is going on" with great certainty once you learn the .NET model just as you learned the C++ model. C# can accomplish non-partial generics specialization through inheritance. For example: class SpecializedForBar : Foo<Bar> { //override virtual members of Foo }
- public Renderer(ref Bitmap DrawArea, ref cEntityManager EntityManager, ref cTimer Timer) { _DrawArea = DrawArea; //this doesn't do what I want _rEntityManager = EntityManager; _rTimer = Timer; } No, this is incorrect usage of "ref". You are not changing DrawArea, EntityManager, or Timer. Remove the ref keyword from all three and you will find that the code behaves 100% identically. Examine this test code: using System; using System.Collections.Generic; class UsingRef { static void AddTwo(int y) { y += 2; } static void AddTwo(ref int y) { y += 2; } static void AppendTwo(List<int> b) { b.Add(2); b = null; } static void AppendTwo(ref List<int> b) { b.Add(2); b = null; } public static void Main() { int x = 5; List<int> a = new List<int>(); AddTwo(x); Console.WriteLine(x); AddTwo(ref x); Console.WriteLine(x); AppendTwo(a); Console.WriteLine(a == null ? "null" : a.Count.ToString()); AppendTwo(ref a); Console.WriteLine(a == null ? "null" : a.Count.ToString()); Console.ReadLine(); } } Additionally, a nitpicky comment: your capitalization and naming conventions do not match the standard guidelines. Google-up the .net guidelines.
- Quote:really dislike the C#'s referencing model ><) That's because you are doing it incorrectly. You do not need any of those "ref" keywords that you included. In short: "ref" means to pass the VARIABLE by reference, not the object it points to. All reference types are, automatically, passed by reference. This means that returning a value is also automatically by reference!
- accidental double post
SnprBoB86 replied to Chire's topic in For BeginnersQuote:Original post by LordShade If this situation occurs, it usually marks the time to re-examine your class structure. There are plenty of good reasons, not the least of which is containment with back-references. That is, some class A which has a list of B and each B only has one A, so you should be able to also navigate from the B back to A.
SnprBoB86 replied to UnrealSolo's topic in General and Gameplay ProgrammingYou should try re-posting this question over at creators.xna.com XNA Framework and Game Studio Devs hang out there and provide a lot of official answers!
SnprBoB86 replied to rippingcorpse's topic in For BeginnersUm, what would it mean to convert an "Example" into a bool? If you mean is not null like pointers in C, you can easily do: Example e = ...; if (e == null) or... if (e != null) otherwise, just define a function much like the ToString() if it makes sense to do so: class Example { ... public bool ToBool() { ... } }
SnprBoB86 replied to one mind's topic in General and Gameplay ProgrammingCurious: Unless you are planning to target Mono, why not use XNA?
SnprBoB86 replied to szolDat's topic in For BeginnersCheck out Is that serious enough for you? XNA Racing Game runs silky smooth on the Xbox 360 despite being somewhat unoptimized and utilizing only a single thread (XNA allows you to use up to 4 of the 6 hardware threads from the 360's 3 cores). Professionals and hobbyists alike are discovering the magic of XNA. Hobbyists are producing amazing results with limited experience and professionals are building prototypes and casual games in a fraction of the time and at a fraction of the cost of using C++. Jump in:
SnprBoB86 replied to Pet123's topic in Graphics and GPU ProgrammingI might be wrong (never tried it) but I think you can declare and use a byte4
- new Vector2(210f,100f}, Should be: new Vector2(210f,100f), Notice the closing } should be a ) What other errors are you getting?
- Vector2[] block = new Vector2[] { new Vector2(200f,100f), new Vector2(210f,100f}, new Vector2(210f,110f), new Vector2(210f,120f) }; The whitespace isn't important.
SnprBoB86 replied to Mike.Popoloski's topic in Graphics and GPU ProgrammingOh, and there is a 1.1 release of XNA coming out very shortly which has many more math functions as well as font support. More information here:
SnprBoB86 replied to Mike.Popoloski's topic in Graphics and GPU ProgrammingUse the XNA Framework! It obsoletes MDX2 (and indeed, it was born of the same code base)
|
https://www.gamedev.net/profile/17433-snprbob86/?tab=idm
|
CC-MAIN-2017-30
|
refinedweb
| 1,017
| 55.34
|
UI images
Hello! I'm pretty much new to Python and I want to know a small example of the Images UI thing
From
Thank you!
file=cStringIO.StringIO(urllib.urlopen(inputUrl).read())
img = Image.open(file)
print img
The above will take a picture from a url stored at inputUrl and print it to the console.
Ok thanks!
To use UI module: create an empty script. Name it imageviewtest for the code snippet below to work. Press the UI editor button top left. Press the plus symbol. Add an image view. It will be named imageview1 by default but you can change this if you want and change the corresponding name in the code.
Warning: there is a bug in Pythonista where if you try to run this twice in a row it will hang the second time. After running it once be sure to exit to your home screen before running it again.
import ui v= ui.load_view("imageviewtest.pyui") imageView1=v["imageview1"] url="" imageView1.load_from_url(url) v.present()
To format the Python code in your post above...
- Tap the word
editat the upper right of your post to edit the text
- Enter a blank line with no text
- Enter a line containing only: ```python
- Enter your Python code
- Enter a line containing only: ```
The ` character is a backtick or accent grave character which you can get by doing a tap-and-hold on the ' keyboard key.
Make sure there are
no space characters before or after the backticks.
A nice additional suggestion from @JonB on creating a keyboard shortcut can be found at:
Sorry about that, posted from my phone. Thanks for the tip.
|
https://forum.omz-software.com/topic/1422/ui-images
|
CC-MAIN-2021-31
|
refinedweb
| 277
| 74.59
|
Name | Synopsis | Description | Return Values | Errors | Attributes | See Also | Notes
#include <sys/types.h> #include <unistd.h> pid_t fork(void);
pid_t fork1(void);
pid_t forkall(void);
The fork(), fork1(), and forkall()() replicates in the child process all of the threads (see thr_create(3C) and pthread_create(3C)) in the parent process. A call to fork1() replicates only the calling thread in the child process.
In Solaris 10, a call to fork() is identical to a call to fork1(); only the calling thread is replicated in the child process. This is the POSIX-specified behavior for fork().
In previous releases of Solaris,().
In Solaris 10, neither -lthread nor -lpthread is required for multithreaded applications. The standard C library provides all threading support for both sets of application programming interfaces. Applications that require replicate-all fork semantics must call forkall().
If a multithreaded application calls fork() or fork(), fork1(), and forkall() return 0 to the child process and return the process ID of the child process to the parent process. Otherwise, (pid_t)-1 is returned to the parent process, no child process is created, and errno is set to indicate the error.
The fork(), fork1(), and forkall()function.
See attributes(5) for descriptions of the following attributes:
alarm(2), exec(2), exit(2), fcntl(2), getitimer(2), getrlimit(2), memcntl(2), mmap(2), nice(2), priocntl(2), semop(2), shmop(2), times(2), umask(2), door_create(3DOOR), exit(3C), plock(3C), pthread_atfork(3C), pthread_create(3C), signal(3C), system(3C), thr_create(3C) timer_create(3RT), wait(3C), contract(4), process(4)attributes(5), privileges() or fork
|
http://docs.oracle.com/cd/E19253-01/816-5167/6mbb2jafg/index.html
|
CC-MAIN-2014-52
|
refinedweb
| 261
| 55.54
|
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How to set to draft the stock picking out when state is cancel?
Hi,
I want to set to draft the stock picking out when state is cancel. How can I do that?
I know that is possible create a button and set the state to draft, but in this particulary case change the state isn't enough because it has movement of products in stock move and in stock inventory.
I have created a button "Set to Confirmed":
This button call this function:
def set_to_confirmed(self, cr, uid, ids, context=None): """ Changes picking state to delivered. @return: True """ for stock_picking_out_ids in ids: stock_picking_out_obj = self.browse(cr, uid, stock_picking_out_ids, context) move_lines = stock_picking_out_obj.move_lines for move_lines_obj in move_lines: self.pool.get('stock.move').write(cr, uid, move_lines_obj.id, {'state': 'confirmed'} ) self.write(cr, uid, ids, {'state': 'confirmed'}) return True
This works and change the state to confirmed but after this I can't continue the workflow, in others words, the button that appears in this state "Check Availability" and "Force Availability" doesn't work and give me a error:
Not enough stock, unable to reserve the products
Any ideia the steps that I have to do to this functionality works?
here are many stuff your code aren't respecting the workflow of stock.picking you are jumping the transition from draft to confirm, you can't go back a state of picking by python code with function write() and hope that the workflow of picking work fine. the workflow of the picking has two node of flow stop, when the state of picking are cancel or done when the picking are in state cancel you must regenerate the workflow
in this way:
def set_to_draft(self, cr, uid, ids, *args): if not len(ids): return False move_obj = self.pool.get('stock.move') self.write(cr, uid, ids, {'state': 'draft'}) wf_service = netsvc.LocalService("workflow") for p_id in ids: moves = move_obj.search(cr, uid, [('picking_id', '=', p_id)]) move_obj.write(cr, uid, moves, {'state': 'draft'}) # Deleting the existing instance of workflow for PO wf_service.trg_delete(uid, 'stock.picking', p_id, cr) wf_service.trg_create(uid, 'stock.picking', p_id, cr) for (id, name) in self.name_get(cr, uid, ids): message = _("Picking '%s' has been set in draft state.") % name self.log(cr, uid, id, message) return True
don't forget import netsvc
best regards
I think the correct answer to the question described in the title is: using a module like
stock_picking_back you share your module for community
|
https://www.odoo.com/forum/help-1/question/how-to-set-to-draft-the-stock-picking-out-when-state-is-cancel-37927
|
CC-MAIN-2017-09
|
refinedweb
| 439
| 63.49
|
News Archive
From W3C XForms Group Wiki (Public)
Past News
- 09 December 2005: An updated version of the XForms 1.1 working draft has been published.
- 20 October 2005: A new release of formsPlayer 1.3 is now available for download from the formsPlayer site. The latest version includes: `incremental` is now timer-based, allowing 'suggestion' lists to be created (see XForms Patterns: Incremental and 'Google Suggest'); two new XPath functions, one allowing support for validity testing, the other providing the EXSLT 'evaluate' function; the author now has more control over styling of XForms form controls.
- 12 October 2005: The Mozilla project released a second preview of its XForms extension, available as a .xpi and ready to be used to extend the recently released Firefox 1.5 Beta 2.
- 6 October 2005: XForms 1.0 (Second Edition) has been published as a Proposed Edited Recommendation(PER). It reflects clarifications and corrections as a result of nearly two years of use by the community. PER review period ends on 3 November 2005.
- 6 October 2005: xGUItar, a cross-platform technology for GUI Construction based on XML, uses XForms for the definition of data model.
- 2 October 2005: eXforms provides a set of specification for extending an XForms processor in a uniform way.
- 28 September 2005: DataMovil is a platform for the development of PDA (Windows Mobile) applications, and it is based on XForms 1.0.
- 22 June 2005: XForms Wikis: at Edublogs.nl (Dutch), at java.net (English), at Nyetwork Wiki (English), at Synergy Incubate (Japanese), at WorldWideWiki (English), at xforms-wiki.com (English)
- 21 June 2005: An updated beta release of Novell XForms Explorer is now available, which includes a number of fixes/improvements and limited support for a `canvas` element (see release notes for details).
- 20 June 2005: X-Smiles 0.94 released.
- 17 June 2005: The new FormFaces variant is a pure JavaScript solution. XForms+HTML can be sent directly to the browser with the addition of a single script line, so that JavaScript transcodes the XForms controls to HTML form controls and processes the bindings directly within the browser - requiring ZERO server-side processing (common solution across disparate frameworks such as Java and .Net) and ZERO plug-ins (cross-browser compliance, including Opera).
- 6 June 2005: PureEdge Solutions has updated its extensible forms description language (XFDL) to be a host language, or skin, for XForms. These forms sport a union of rich XForms processing and intent-based user interface definition with XFDL's precision layout control, offline processing capabilities, digital signature security and other advanced features. An alpha release of XFDL Forms is publicly available.
- 23 March 2005: New article: XForms and Cause & Effect Programming by John Boyer.
- 19 March 2005: A preview of formsPlayer 2.0 is now available. Features include rendering and validation of mixed namespace documents (see announcement).
- 9 March 2005: A new <a hreflang="ja" href=" Japanese XForms mailing list] created.
- 8 March 2005: XFormation 2.0 released (see announcement).
- 1 March 2005: [/2003/10/REC-xforms-10-20031014-errata XForms 1.0 Recommendation Errata] has been updated.
- 11 February 2005: Chiba 1.0 released (see announcement).
- 9 February 2005: New article: Top 10 XForms Engines by Micah Dubinko.
- 2 February 2005: formsPlayer has been updated to version 1.3, which includes support for the `relevant` and `validate` properties on submission (from XForms 1.1) and more (see announcement).
- 2 February 2005: Mozilla Foundation announced the beta release of XForms support in Mozilla/Firefox browsers. Check the project page for details.
- 31 January 2005: X-Smiles 0.93 released.
- 29 January 2005: Xslt2Xforms 0.7.6 released (see announcement).
- 28 December 2004: Chiba 0.9.9 and Convex for IE preview released (see announcement).
- 10 December 2004: formsPlayer 1.2 released (see announcement).
- 17 December 2004: Novell announces XForms Explorer, a beta release plug-in for Microsoft Internet Explorer 6.0 and above.
- 19 November 2004: Chiba 0.9.8 released (see announcement).
- 15 November 2004: The first public Working Draft of XForms 1.1 has been published.
- 22 October 2004: xslt2Xforms 0.7beta released (see announcement).
- 20 October 2004: x-port.net Ltd. have produced a sample web application that allows a blog to be maintained on Blogger.com with XForms. The features are also demonstrated in a [1]set of Flash videos].
- 13 October 2004: The xslt2Xforms project launched (see announcement).
- 18 October 2004: formsPlayer has been updated to version 1.1. Alongside a number of bug fixes and performance enhancements, new features include the ability to set all aspects of a submission from instance data. Download and use is free.
- 26 September 2004: Examploforms 0.1 released (see announcement).
- 1 September 2004: Orbeon announces XForms engine and releases OXF Server (now called Presentation Server) on Sourceforge under LGPL.
- 31 August 2004: XForms 1.1 Requirements Working Group Note has been updated.
- 12 August 2004: Mozilla, IBM and Novell announce XForms development project
- 22 June 2004: [2003/xforms-for-html-authors.html,translations Translations] of XForms for HTML Authors are now available in Castellano/Spanish, Français/French, Nederlands/Dutch, and Japanese.
- 11 June 2004: Updated XForms 1.1 Requirements Working Group Note is now available.
- 22 February 2004: XForms Institute announced the launch of a new Web service: Free Online XForms Validation (currently in beta).
- 16 February 2004: Focus partners with x-port.net Ltd to launch XFormation incorporating formsPlayer, an XForms Integrated Development Environment (IDE). XFormation allows XForms to be built and managed, whilst the incorporation of the formsPlayer XForms processor allows form previewing, event tracing, and the examination of instance data and the model state. XFormation is available for a free 30-day trial.
- 13 February 2004: x-port.net announces formsPlayer 1.0 release, a 100% compliant XForms Processor.
- 8 February 2004: DENG is now an open source software distributed under GPL turning the Macromedia Flash Player 6 into a webbased, zero-install, cross browser/platform, modular and standards compliant XML/CSS2 browser.
- 26 January 2004: XForms 1.1 Requirements a W3C Working Group Note, released by the XForms Working Group.
- 19 January 2004: In advance of the forthcoming Version 1.0 release of formsPlayer, x-port.net have made a Release Candidate available. formsPlayer is a 100% compliant XForms Processor.
- 16 January 2004: An interactive tutorial for W3C XForms, by the xforms institute.
- 11 December 2003: XForms 1.0 Frequently Asked Questions is now available.
- 01 December 2003: Advantys is proud to announce that its WorkflowGen solution now supports the XForms 1.0 standard from W3C.
- 18 November 2003: A preview release of Oracle's XForms processor PlugIn for Internet Explorer is now available. The XForms Processor is a plug to Internet Explorer 6 on Win2000/WinXP. A User's Guide, Datasheet and several samples are provided with the preview release install.
- 14 October 2003 The W3C Forms Working Group is proud to announce that XForms 1.0has become a W3C Recommendation. See the press release and testimonials. To accompany the release, the group is also releasing XForms for HTML Authors.
- 14 October 2003: XForms 1.0 Basic Profile tailored to the needs of constrained devices and environments is a W3C Candidate Recommendation.
- 1 August 2003: XForms WG releases the [Test/XForms1.0/Edition2/front_html/XF102edTestSuite.html XForms 1.0 Test Suite] and [Test/ImplementationReport.html Implementation report.]
- 1 August 2003: W3C is pleased to announce the advancement of XForms 1.0 to Proposed Recommendation.
- July 2003: Orbeon announces new features and XForms enhancements with the release of OXF 2.0
- June 2003: Progeny Systems Corporation releases FormFaces, Java based interaction management technology for forms-based data entry.
- 15th April 2003: Orbeon has released OXF 1.5.2 providing an XForm Input processor for data extraction from the user request and an XForm Output processor for HTML Form generation and population.
- 10th April 2003: The IBM XML Forms Package is a toolkit consisting of software components designed to showcase the possibilities presented by XForms. The package consists of two main components: the data model component and the client component.
- 04 April 2003: Xero is a Web Form development framework developed by Type.a Corp. It consists of a client-side XForms Processor and a Form Editor.
- 01 April 2003: Release of the first version of the Chiba/Cocoon (Chicoon) integration package. By integrating Chiba into Cocoon the power and functionality of Chiba's XForms processing is now available to any Cocoon application.
- 31th Mar 2003: The Apache Cocoon XMLForm module is now available as a standalone servlet toolkit. It will be made for continuous synchronization of both the standalone version and the one integrated with Cocoon.
- 24th Mar 2003: The Chiba project has released a new version of its web-based XForms Processor. As a server-side implementation it delivers most of the functionality of the XForms CR to todays browsers regardless of their brand and capabilities.
- 27/28th Feb 2003: [2003/ImplementationWorkshop/Overview.html W3C Implementation Workshop] Waltham, MA, USA. Attendees must be either members of the W3C XForms WG or have an XForms 1.0 Implementation. Attendees will exchange experiences, hints and techniques, compare functionality, and discuss XForms 1.0 Candidate Recommendation issues.
- 20 January 2003: [Test/XForms1.0/Edition2/front_html/XF102edTestSuite.html XForms 1.0 Public Test Suite] now available on W3C site.
- 20 November 2002: FormsPlayer updated to XForms Candidate Recommendation version.
- 19 November 2002: X-Smiles version 0.7 released, featuring (partial) support for XForms Candidate Recommendation version.
- 12 November 2002: Novell's XForms Technology Preview is designed to provide developers with a hands-on introduction to the XForms standard. Supports XForms Candidate Recommendation version.
- 12 November 2002: XForms 1.0 now a Candidate Recommendation. See the press release and testimonials. Please send review comments to www-forms-editor@w3.org (archives).
- 23 October 2002: FormsPlayer, an XForms processor plug-in for Internet Explorer 6 SP 1.
- 21 August 2002: A new Working Draft of XForms 1.0 has been published. This documents includes all changes made during Last Call. The comment period closes on 4 September 2002.
- 02 july 2002: AchieveForms from Business Web Software is a server-based XFORMS designer with a web browser interface that can output forms as XFORMS and can process completed forms from an XFORMS browser to email recipients, databases, and forward XML files of completed form data.
- 26 june 2002: jXForms, a new implementation to work with XForms inside java based applications.
- 14 june 2002: The TrustForm System Viewer is a client side implementation based on the XForms last working draft.
-.
- 29 April 2002: X-Smiles 0.6 has been released, a java-based XML browser implementing most of XForms 1.0 Last Call Working Draft.This version brings new features and fixes bugs in the previous version.
- 25 March 2002: XFE, now released: a forms engine developed by E-XMLMedia, for development of forms based data entry systems.
- 21 January 2002: X-Smiles 0.5 has been released, a java-based XML browser implementing about 75% of XForms 1.0 Last Call Working Draft and full implementation of the XML Events Last Call Working Draft.
- 07 December 2001: An updated public Working Draft of XForms 1.0 has been published.
- 26 October 2001: X-Smiles 0.45 has been released, which has an experimental support for XML Events.
- 26 October 2001: The XML Events Working Draft has been published as a Last Call Working Draft. The Last Call review period ends on 30 November 2001. Please send review comments before the review period ends to www-html-editor@w3.org (archive).
|
http://www.w3.org/MarkUp/Forms/wiki/News_Archive
|
CC-MAIN-2015-06
|
refinedweb
| 1,927
| 51.95
|
celClientEventData Class ReferenceThe data about a client event. More...
#include <physicallayer/nettypes.h>
Detailed DescriptionThe data about a client event.
Definition at line 333 of file nettypes.h.
Member Data Documentation
The persistent data of the event.
Definition at line 349 of file nettypes.h.
The time at which the event occured.
Definition at line 344 of file nettypes.h.
The type of the event.
Definition at line 339 of file nettypes.h.
True if we need to be sure that the message has been received by the server.
Definition at line 354 of file nettypes.h.
The documentation for this class was generated from the following file:
- physicallayer/nettypes.h
Generated for CEL: Crystal Entity Layer by doxygen 1.4.7
|
http://crystalspace3d.org/cel/docs/online/api-1.0/classcelClientEventData.html
|
CC-MAIN-2017-04
|
refinedweb
| 122
| 54.39
|
Created on 2016-10-09 17:31 by stefanor, last changed 2018-11-21 22:16 by brett.cannon. This issue is now closed.
setup.py build for a library using py_limited_api will always generate a stable ABI tagged shared library, even under the pydebug interpreter.
This means that extensions that are built for a pydebug interpreter may be accidentally (and brokenly) imported in a non-dbg interpreter and vice-versa.
e.g. in python-librtmp, with cffi 1.8.3:
$ python3-dbg setup.py build
...
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,relro -g -Og -fdebug-prefix-map=/build/python3.5-H9Fri6/python3.5-3.5.2=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.5-pydebug/build/temp.linux-x86_64-3.5-pydebug/librtmp._librtmp.o -lrtmp -o build/lib.linux-x86_64-3.5-pydebug/librtmp/_librtmp.abi3.so
Then:
$ cd build/lib.linux-x86_64-3.5-pydebug
$ python3 -c 'import librtmp'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/python-librtmp-0.3.0/build/lib.linux-x86_64-3.5-pydebug/librtmp/__init__.py", line 8, in <module>
from ._librtmp import ffi, lib as librtmp
ImportError: /tmp/python-librtmp-0.3.0/build/lib.linux-x86_64-3.5-pydebug/librtmp/_librtmp.abi3.so: undefined symbol: _Py_RefTotal
setuptools decides whether to use the stable ABI, by looking at imp.get_suffixes(). And obviously, the importer is looking at that too. So, the stable ABI tag should simply not be in there.
PEP3149 agrees with this. It has this quote from Martin v. Löwis:
--with-pydebug would not be supported by the stable ABI because this changes the layout of PyObject , which is an exposed structure.
So, here's a patch, to disable support for the stable ABI under pydebug builds.
I'm not sure that you really want this, because it would make it impossible to build an extension for the stable ABI for a debug build. The problem is Debian specific, because we install the extension modules for normal and debug builds in the same location. A Debian solution would be to use a different soname for stable API debug mode extensions.
I wouldn't say it's *entirely* Debian-specific. It just bites anyone who actually needs these tags to differentiate between built extensions. (Mostly Debian)
Yes, changing the tag is a more complete solution. It just seemed that that option was decided against, in the relevant PEPs.
[Matthias Klose (doko) 2016-10-27 15:45]
> I'm not sure that you really want this, because it would make it impossible to build an extension for the stable ABI for a debug build.
It looks like that is already impossible:
/usr/include/python3.5dm/object.h:65:2: error: #error Py_LIMITED_API is incompatible with Py_DEBUG, Py_TRACE_REFS, and Py_REF_DEBUG
#error Py_LIMITED_API is incompatible with Py_DEBUG, Py_TRACE_REFS, and Py_REF_DEBUG
^~~~~
So in my opinion Stefano's patch makes sense.
So limited ABI modules can't be imported by a Py_DEBUG build. Stefano's patch just skips over them. That seems reasonable, but one question I do have is whether this would confuse users since they will simply get an ImportError instead of some other error and thus will they be able to realize why there's a problem?
> whether this would confuse users since they will simply get an ImportError instead of some other error and thus will they be able to realize why there's a problem?
It's the same behaviour we have for any other module on the import path, that doesn't have the right tag. I suppose abi3 is a bit of a special case there, because it's expected to be widely supported...
Also, there is a related problem: Because abi3 is in the supported extension list, setup.py build will build an abi3 extension (which isn't actually abi3), under a pydebug interpreter.
New changeset 338d54f0a59dc5e5b6c9e7397340169f3a3f8ea4 by Miss Islington (bot) (Stefano Rivera) in branch 'master':
bpo-28401: prevent Py_DEBUG builds from trying to import limited ABI modules (GH-1766)
Thanks for the PR!
|
https://bugs.python.org/issue28401
|
CC-MAIN-2021-21
|
refinedweb
| 692
| 56.96
|
Introduction.
Learn, compete, hack and get hired!You can also read this article on our Mobile APP
32 Comments
Hi Shivam, I was just looking for this information! NLTK Vs SpaCy. Thanks!
Awesome Article!
just implementing Spacy in Ubuntu. works great. thanks!
Leo Vogels
Thanks!
Great and useful article!
I’m wondering whether TextBlob is faster than NLTK, and whether it is slower than Specy
Hi Chang,Thanks.
Spacy > TextBlob > NLTK
Hi Shivam,
Im getting this error
NameError: name ‘character’ is not defined
Replace character with token,
Great info here, thanks!
Very useful article… Thank you so much !!
thanks Shivam. Do you have a similar article for R?
thank u for this awesome article:)
Hi shivam! very nice article.It helped me to get started with spacy. I have one question for you. I am trying to extract some entities like dates, location, name from the hundreds of resume’s. Will it be possible to do so using spacy? will it do the task quickly within few minutes and how much accurate it will be? Please provide your guidance as well as opinion.
Thanks.
Hi, i think there is a typo in 2.4 Dependency Parsing; in the function pos_words inside the second FOR.
if character in word.string:
There should be another FOR not a IF.
for character in word.string:
However nice post. really thank you for it. It helps me a lot.
Good catch!
I want to train Entity please share code or help me. Example: I want to train Airtel, Reliance and Vodafone as Biller Entity.
It’s behaving different plz share some error less n needful src.
Thanks.
Amit Jaiswal
Nice article , thank you for posting it here , i have one question for you , how can i use dependency tree output or pos information which i got from the spacy in multi class classification problem , i would be very thank full if can i give more elaborate information on this
Hi,
great article and great explanation!
I’m trying to work one step further by saving and reloading the trained pipeline:
`joblib.dump(fitted_pipe, path)`
Works fine as well, but apparently the pickle doesn’t store the custom classes and functions. Specially `predictors` and `space_tokenizer`.
So by loading the pipe.pkl it doesn’t find the required classes or modules.
Any hint to fix that?
Thanks
Ben
Hi,
It’s better to use this command for installing spacy
sudo pip install -U spacy
sudo python -m spacy.en.download all
Hi,
Thanks for this article.
Its better to use the following command below to install SpaCy package
sudo pip install -U spacy
sudo python -m spacy.en.download all
My one got fixed using this above command
For the install:
sudo python -m spacy.en.download all
did not work, but:
python -m spacy download en
did.
Hi all,
I am unable to install spacy in my python 2.7 version. Anyone who has worked on this please share your thoughts
Very informative article. Wish I had come across this the first time I searched for articles and comparisons. Also, what about intent recognition in spaCy?
Getting a “name ‘unicode’ is not defined” error on
document = unicode(open(‘Tripadvisor_hotelreviews_Shivambansal.txt’).read().decode(‘utf8’))
document = nlp(document)
What is the prereq to load to make that work…running python 3.6 jupyter notebook
With python 3.6, all you need do is:
document = open(‘Tripadvisor_hotelreviews_Shivambansal.txt’).read()
document = nlp(document)
That’s it.
Hi
2.2 Part of Speech Tagging
you **really** want to define a function is_not_noise
(to reduce the nested elif s here and make the code
read more like prose).
The evaluation cost is the
the same if you just use logical ‘and’s
def is_not_noise(token):
return ( token.pos_ not in noisy_pos_tags
and len(token.string) <= min_token_length
and not token.is_stop)
thanks a lot for this very informative article. But I didnot understand about how we get the parse tree ( not dependency) with spacy.
Excellent article ! Thank you.
If you have some bandwidth….can you check if following lines of code give you a list?
apple = parser.vocab[u’apple’]
cosine = lambda v1, v2: dot(v1, v2) / (norm(v1) * norm(v2))
others = list({w for w in parser.vocab if w.has_vector and w.orth_.islower() and w.lower_ != unicode(“apple”)})
for me print(others) gives me an empty [ ]
document = unicode(open(‘Tripadvisor_hotelreviews_Shivambansal.txt’).read().decode(‘utf8’))
line is depricated in Python 3.
Should be just
document = open(‘Tripadvisor_hotelreviews_Shivambansal.txt’).read()
However, dir(document)
does not produce any output! Any ideas why?
A Great Article, However, I believe R is missing a lot of these features. I have used tidytext package in R but I can hardly compare it to spaCy.
Is there some package very close to spaCy in R ?
I have below requirement::-
Can any one help on using python
Features that need to be extracted
Role :
There are different jobs – waiters, chefs, chauffeurs – (countrywise)
1) Information to be Extracted from the CV is all possible roles that the candidate can possible be work as.
2) Assign a ranking to these roles (eg : Candidate is a better waiter than a chef)
3) Identify from the CV if there are certifications that the candidate has
CV can be any docx or pdf or excel
Amazing article. Is there a way using the machine learning capability in Spacy to create something that can extract bilingual chunks from texts in 2 different languages?
Hi,
I am doing a task of cleaning and preprocessing of data and i dont know machine learning and NLP but i have to do that task using nlp and spacy can you please suggest me how to learn this step by step so that i can be able to code for cleaning of textual data using nlp and spacy
|
https://www.analyticsvidhya.com/blog/2017/04/natural-language-processing-made-easy-using-spacy-%E2%80%8Bin-python/
|
CC-MAIN-2021-17
|
refinedweb
| 970
| 67.55
|
Jim O'Neil
Technology Evangelist
‘Key’ is a rather overloaded term in .NET and programming circles in general. There are database primary and foreign keys, hash keys, keys to styles and templates in WPF, registry keys, key codes for each key on the keyboard, and many others. For this post, I’m going to touch on the concept of Key properties in anonymous types.
First though, what’s an anonymous type? Anonymous types were introduced in Visual Studio 2008 with C# 3.0 and Visual Basic 9 and figure prominently when using LINQ (Language Integrated Query).
In C#, anonymous types make use of a new keyword var which indicates the data type of the following variable reference is an anonymous type. Note, an anonymous type is not synonymous with a variant or late-bound type. Variables defined this way are strongly-typed; it’s just that the CLR is generating the type name and definition for you.
var
For example, here’s a complete (albeit simplistic) program that uses an anonymous type representing a city. On lines 16 and 17 you can see that the type can be used just as any other explicitly defined type would be; it just doesn’t have a name that you yourself have defined.
1: using System;
2:
3: namespace ConsoleCS
4: {
5: class Program
6: {
7: static void Main(string[] args)
8: {
9: var city1 = new
10: {
11: Name = "Boston",
12: State = "MA",
13: Zip = "02134"
14: };
15:
16: Console.WriteLine("{0}, {1} {2}",
17: city1.Name, city1.State, city1.Zip);
18: Console.ReadLine();
19: }
20: }
21: }
In this particular case, a call to Console.WriteLine(city1.GetType().ToString()) yields the following as the compiler-defined type name:
Console.WriteLine(city1.GetType().ToString())
<>f__AnonymousType0`3[System.String,System.String,System.String]
<>f__AnonymousType0`3[System.String,System.String,System.String]
The equivalent in Visual Basic would be:
1: Module ConsoleVB
2: Sub Main()
3: Dim city1 = New With { _
4: .Name = "Boston", _
5: .State = "MA", _
6: .Zip = "02134"}
7:
8: Console.WriteLine("{0}, {1} {2}", _
9: city1.Name, city1.State, city1.Zip)
10: Console.ReadLine()
11: End Sub
12: End Module
Note, that in Visual Basic we reuse the Dim keyword for declaring anonymous types and introduce the With keyword, but the rest of the syntax is more or less identical to C#. The compiler-generated type name in this case is
Dim
With
VB$AnonymousType_0`3[System.String,System.String,System.String]
VB$AnonymousType_0`3[System.String,System.String,System.String]
So what’s all this got to do with the Key keyword? Well, it turns out that anonymous types in C# and Visual Basic have different behaviors, and the Key keyword is, well, key in differentiating those behaviors.
Key
In Visual Basic, the following code snippet would result in ‘false’ being output on the console window:
1: Dim city1 = New With { _
2: .Name = "Boston", _
3: .State = "MA", _
4: .Zip = "02134"}
5: Dim city2 = New With { _
6: .Name = "Boston", _
7: .State = "MA", _
8: .Zip = "02134"}
9: Console.WriteLine(city1.Equals(city2))
In contrast, the analogous code in C# would yield ‘true’, since the Equals method for the Name, State, and Zip properties each return ‘true.’
Equals
Name
State
Zip
Now, let’s add Key to some of the properties of the Visual Basic anonymous class definitions:
2: Key .Name = "Boston", _
3: Key .State = "MA", _
4: .Zip = "02134"}
6: Key .Name = "Boston", _
7: Key .State = "MA", _
8: .Zip = "02134"}
Now, city1 does equal city2 because the equality test in Visual Basic compares those fields marked with Key. In fact, only the fields marked with Key are compared, so the following snippet also results in equality of the two objects, despite the fact that the zip code for city1 was modified in line 9 and differs from that of city2.
city1
city2
9: city1.Zip = "90210"
10: Console.WriteLine(city1.Equals(city2))
By the way, did you notice the property is mutable in Line 9? This is another difference between Visual Basic and C#’s handling of anonymous types. In C#, all fields of an anonymous type are read-only; in Visual Basic only fields marked with Key are read-only.
If you want to dig a little further into the topic of anonymous types and recommendations of when to use them (or not use them), here’s a few links that will come in handy:
|
http://blogs.msdn.com/b/jimoneil/default.aspx?PageIndex=575
|
CC-MAIN-2015-27
|
refinedweb
| 744
| 74.59
|
03 September 2010 11:07 [Source: ICIS news]
LONDON (ICIS)--Polypropylene (PP) buyers in ?xml:namespace>
“They are making absolutely fantastic margins,” said one frustrated buyer, complaining about the months of price increases that producers have imposed on the market this year.
“
Some PP producers are still targeting price increases for September, in spite of the €10/tonne ($13/tonne) drop in the September propylene monomer price.
Buyers, however, are keen to reject such advances.
“There will be no increases,” said another buyer. “They might be able to hold on to the €10/tonne that they have saved in the monomer, but they won’t get prices up.”
An undertone of frustration tinged with anger ran throughout the market.
“I can get what I need from importers and resellers this month. I am simply not going to buy from the Europeans in September if they keep harping on about increases,” said a third buyer.
The PP market has been left with limited availability following some production issues and a programme of strict inventory control.
Buyers have also kept low inventories in anticipation of an expected influx of imported volumes from new plants in the Middle East and
But this material has proved very slow to appear, and there was still limited imported availability in the European PP market.
Homopolymer injection prices were now trading at €1,190-1,200/tonne FD (free delivered) NWE (northwest
“We expect a firm, steady September,” said a producer, “and we don’t exclude price increases. Product is not long and demand is good.”
PP producers in
($1 = €0
|
http://www.icis.com/Articles/2010/09/03/9390453/Europe-polypropylene-buyers-resist-September-price-increases.html
|
CC-MAIN-2013-48
|
refinedweb
| 264
| 61.67
|
Credit to functions related to the Luhn credit card […]
I came up with two versions of my intermediate Luhn sum function: one that
creates a list and modifies it in-place, and another that uses iterators
instead. My solution is available on github.
Just numbers; just one recursive branch / two vectors.
First I missed that (- 10 (modulo 30 10)) is 10, not 0.
Then Ikarus thought that (modulo -30 10) => 10. Sigh.
Wanted to see if I still remember Linux assembly so I wrote my answer in it: github. It might be possible to make the answer more readable and shorter, but that would take me an additional hour…
Factor Language solution.
( scratchpad ) 2771 luhn? .
f
( scratchpad ) 2771 make-luhn dup . luhn? .
27714
t
( scratchpad ) 49927398716 luhn? .
t
( scratchpad ) 49927398716 make-luhn dup . luhn? .
499273987168
t
[…] or Canadian Social Insurance Numbers are validated you can take a look at this Programming Praxis article . It’s all about a simple, tiny, patented (now public domain) algorithm invented by […]
My python 3.x solution:
nice solution
My try in REXX
My solution in Python 3.2
def addCCDigits(number):
number = int(str(number)[::-1])
numString = str(number)
check = False
mySum = 0
for ch in numString:
num = int(ch)
if (check):
num = num * 2
strNum = str(num)
for c in strNum:
num2 = int(c)
mySum += num2
else:
mySum += num
check = not check
return mySum
def validate(number):
mySum = addCCDigits(number)
if (mySum % 10 == 0):
return True
else:
return False
def addCheckDigit(number):
mySum = addCCDigits(number * 10 + 1) – 1
digit1 = int(mySum / 10)
goal = (digit1 + 1) * 10;
diff = goal – mySum;
mySum = int(mySum / 10)
strNumber = str(number) + str(diff)
number = int(strNumber)
return number
[\code]
|
http://programmingpraxis.com/2011/04/08/credit-card-validation/?like=1&source=post_flair&_wpnonce=81d32a40f7
|
CC-MAIN-2015-22
|
refinedweb
| 281
| 54.02
|
#include <hallo.h> Adam Heath wrote on Thu May 30, 2002 um 12:58:48PM: > > You don't, you use makedev to create them in your postinst. > > > > Wichert. > > When this mail first hit the list, I checked dpkg. It should handle creation > of device files. If it doesn't, it's a bug. > > It's policy that enforces the "no devices in debs" principal. Common praxis is asking with Debconf and creating them in postinst using mknod. > permissions of files. Since permissions on devices are changed very often(as > compared to normal dirs/files), I believe it became policy to not ship device > files in debs. > > Maybe it's time to revisit this? Should be revisited. I remember a file against policy, dealing with this issue among others.
|
https://lists.debian.org/debian-devel/2002/05/msg03113.html
|
CC-MAIN-2017-39
|
refinedweb
| 128
| 77.53
|
blah 0.1.8
Thin wrapper around source control systems
The main use of Blah is being able to download repositories from a URI that specifies what version control system (VCS) is being used:
import blah blah.fetch("git+", "/tmp/blah") print open("/tmp/blah/README.md").read()
Blah can also be used as a script:
blah fetch git+ /tmp/blah
Specific commits can be selected by appending a hash to the URI, followed by the name of the commit:
blah.fetch("git+", "/tmp/blah")
At the moment, git and hg URIs are supported.
- Author: Michael Williamson
- Package Index Owner: michaelwilliamson
- DOAP record: blah-0.1.8.xml
|
https://pypi.python.org/pypi/blah/0.1.8
|
CC-MAIN-2016-50
|
refinedweb
| 108
| 61.67
|
12 October 2012 06:55 [Source: ICIS news]
By Ong Sheau Ling
?xml:namespace>
SINGAPORE
The affected ports include Dammam, Jubail and Jeddah. Most vessels continued to bypass the Saudi Arabian ports, as they were unable to squeeze in to unload cargoes, market players said.
“Some of our August cargoes have yet to be dispatched from [Dammam] port, a Saudi Arabian polyolefins producer said.
“We are just rolling over our cargoes, but we are still selling forward cargoes,” he added.
Saudi Arabian producers are hoping the port authorities could help address the problem and speed up processing at ports.
“The ports here are just not big enough to accommodate the vast volume that the country is producing,” a second Saudi Arabian producer said.
“Not just polymer resins are affected, finished goods as well. It is a nightmare,” a converter based in Dammam said.
Some traders based in
“We have to bear these additional logistics costs in order to shorten the delay in our shipments to our customers,” a Dubai-based trader said.
“We can’t be moving parcels in land to different ports all the time to reduce the delay period,” the trader in
Moving cargoes by land to less-congested ports like the Jebel Ali port in the UAE is not feasible as this will result in higher logistics costs, which polymer producers are not willing to bear.
“Our customers just have to wait,” a third Saudi Arabian producer said.
The port congestion will likely keep supply of Saudi Arabian polyolefins in the
Congestion at Saudi Arabian ports is expected to worsen, with the upcoming Islamic holidays – the Eid ul-Adha, the Haj and the Islamic new year – between mid-October to mid-November.
Such delivery delays, however, may not affect the supply condition in Asia significantly as bonded warehouses of Saudi Arabian producers in several countries in this region have sufficient stocks.
“As long as we can keep our bonded warehouses with ample stocks, our [Asian] customers will still receive our lots in time,” said a fourth polyolefins producer based in Saudi Arabia.
The producer has bonded warehouses in
“We still have to monitor the situation. [In the] meantime, I guess it may be good news to the market as demand is showing signs of weakness,” said the same maker.
Demand for polyolefins resins across Asia and the
($1 = €0.77)
Additional reporting by Chow Bee Lin
|
http://www.icis.com/Articles/2012/10/12/9603302/mideast-pe-pp-shipments-suffer-longer-delays-on-port-woes.html
|
CC-MAIN-2014-52
|
refinedweb
| 399
| 59.13
|
EVP_PKEY_asn1_get_count.3ssl - Man Page
enumerate public key ASN.1 methods
Synopsis
#include <openssl/evp.h> int EVP_PKEY_asn1_get_count(void); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find(ENGINE **pe, int type); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find_str(ENGINE **pe, const char *str, int len); int EVP_PKEY_asn1_get0_info(int *ppkey_id, int *pkey_base_id, int *ppkey_flags, const char **pinfo, const char **ppem_str, const EVP_PKEY_ASN1_METHOD *ameth);
Description
EVP_PKEY_asn1_count() returns a count of the number of public key ASN.1 methods available: it includes standard methods and any methods added by the application.
EVP_PKEY_asn1_get0() returns the public key ASN.1 method idx. The value of idx must be between zero and EVP_PKEY_asn1_get_count() - 1.
EVP_PKEY_asn1_find() looks up the EVP_PKEY_ASN1_METHOD with NID type._find_str() looks up the EVP_PKEY_ASN1_METHOD with PEM type string str. Just like EVP_PKEY_asn1_find(),_get0_info() returns the public key ID, base public key ID (both NIDs), any flags, the method description and PEM type string associated with the public key ASN.1 method *ameth.
EVP_PKEY_asn1_count(), EVP_PKEY_asn1_get0(), EVP_PKEY_asn1_find() and EVP_PKEY_asn1_find_str() are not thread safe, but as long as all EVP_PKEY_ASN1_METHOD objects are added before the application gets threaded, using them is safe. See EVP_PKEY_asn1_add0(3).
Return)
Licensed under the OpenSSL license (the “License”). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at <>.
Referenced By
The man pages EVP_PKEY_asn1_find.3ssl(3), EVP_PKEY_asn1_find_str.3ssl(3), EVP_PKEY_asn1_get0.3ssl(3) and EVP_PKEY_asn1_get0_info.3ssl(3) are aliases of EVP_PKEY_asn1_get_count.3ssl(3).
|
https://www.mankier.com/3/EVP_PKEY_asn1_get_count.3ssl
|
CC-MAIN-2021-39
|
refinedweb
| 243
| 50.73
|
Details
Bug
- Status: Closed
Major
- Resolution: Fixed
- 2.2.11
-
-
- None
- Novice
Description
There is an issue in the way how the current WS-RM implementation
downgrades the WS-A namespace/constants to the 2004/08 version. I
would like to first explain the problem and ask you which solution is
preferred.
CXF uses WS-A 2005/08 internally but for WS-RM, it uses the 2004/08
version because the older WS-RM (1.0)
requires the use of the 2004/08 version. So, it is correct to convert
the internally used 2005/08 namespace/constants to their 2004/08
counterparts.
However, one problem is that the 2005/08 WS-A spec defined two constants
While the 2004/08 WS-A version seems to have only defined
and not
The current conversion used in CXF creates this undefined value and
this is causing some interoperability issues.
More concretely, when the WS-A ReplyTo element is set to the none
value and this is serialized into the above undefined 2004/08 none
constant, it is not recognized by some systems. According to the WS-RM
1.0, in such a case, the ReplyTo element should be omitted to convey
this "none" value (as there is no "none" constant).
Initially, I thought we should fix this issue by introducing a configurable property "usingNoneAddress" for the addressing configuration bean to turn on or off the serialization of the none address. However, this approach had a drawback on requiring a different default value interpretation based on the used namespace versions (i.e., false for 2004/08 and true for 2005/08) to make the test cases all work.
Therefore, I am proposing the following approach to solve this issue.
There is no configuration property. The serialization is determined by the addressing namespace. Under 2004/08, the none value is omitted from serialization, while under 2005/08, the none value is serialized.
This will work for all the current tests except for the testVersioning test of MAPTest. This particular test uses the 2004/08 namespace and checks the presence of the ReplyTo header in the SOAP header, even though the header is associated with the none value and therefore it must not be present. In order to fix this test, I needed to modify the corresponding verification classes so that the presence of the ReplyTo header is not verified when the 2004/08 namespace is used.
In summary, the changes that I suggest are as follows:
For the runtime ws.addressing:
org.apache.cxf.ws.addressing.soap.MAPCodec
The ReplyTo header will not be serialized with the invalid none value. In other words, if the value is set to the none value while using the 2004/08 namespace.
org.apache.cxf.ws.addressing.ContextUtils
The back channel will be found even when the ReplyTo header is missing.
For the systests ws.addressing
org.apache.cxf.systest.ws.addressing MAPTestBase
Its verifyHeaders method takes additionally a Boolean parameter replyToRequired to indicate whether the presence of the ReplyTo header must be verified.
org.apache.cxf.systest.ws.addressing HeaderVerifier
Its verify method call the above verityHeaders method with the replyToRequired parameter set based on the namespace version.
The svn diff files of the above changes are attached.
Regards, Aki
|
https://issues.apache.org/jira/browse/CXF-3151?attachmentSortBy=fileName
|
CC-MAIN-2022-05
|
refinedweb
| 543
| 53.81
|
24 May 2010 14:13 [Source: ICIS news]
SINGAPORE (ICIS news)--India’s Oil and Natural Gas Corporation (ONGC) has issued a tender offering 35,000 tonnes of naphtha for loading on 21-22 June from Mumbai port, the company said on Monday.
The tender closes on 25 May, and bids would stay valid until later the same day, the company added.
The results also emerged of another ONGC tender which had offered 35,000 tonnes of naphtha for loading from Hazira port on 22-23 June. The tender was heard to have been awarded to a European trader at a premium of $19.00/tonne (€15.2/tonne) to ?xml:namespace>
($1 = €0.80)
|
http://www.icis.com/Articles/2010/05/24/9362138/ongc-offers-35000-tonnes-of-naphtha-for-june-loading.html
|
CC-MAIN-2014-10
|
refinedweb
| 115
| 67.69
|
In this section,you will learn how to read a specific line from the text file.In this section,you will learn how to read a specific line from the text file.
Here we are going to read a specific line from the text file. For this we have created a for loop to read lines 1 to 10 from the text file. If the loop reached fifth line, the br.readLine() method of BufferedReader class read that particular line and display it on the console.
Here is the code :
import java.io.*; public class ReadSpecificLine { public static void main(String[] args) { String line = ""; int lineNo; try { FileReader fr = new FileReader("new.txt"); BufferedReader br = new BufferedReader(fr); for (lineNo = 1; lineNo < 10; lineNo++) { if (lineNo == 5) { line = br.readLine(); } else br.readLine(); } } catch (IOException e) { e.printStackTrace(); } System.out.println("Line: " + line); } }
|
https://www.roseindia.net/tutorial/java/io/readSpecificFile.html
|
CC-MAIN-2022-27
|
refinedweb
| 143
| 76.62
|
searchenv()
Search the directories listed in an environment variable
Synopsis:
#include <stdlib.h> void searchenv( const char* name, const char* env_var, char* buffer );
Arguments:
- name
- The name of the file that you want to search for.
- env_var
- The name of an environment variable whose value is a list of directories that you want to search. Common values for env_var are "PATH", "LIB" and "INCLUDE".The searchenv() function doesn't search the current directory unless it's specified in the environment variable.
- buffer
- A buffer where the function can store the full path of the file found. This buffer should be PATH_MAX bytes long. If the specified file can't be found, the function stores an empty string in the buffer.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The searchenv() function searches for the file specified by name in the list of directories assigned to the environment variable specified by env_var.
Use pathfind() or pathfind_r() instead of this function.
Examples:
#include <stdio.h> #include <stdlib.h> #include <limits.h> void display_help( FILE *fp ) { printf( "display_help T.B.I.\n" ); } int main( void ) { FILE *help_file; char full_path[ PATH_MAX ]; searchenv( "lib_ref.html", "PATH", full_path ); if( full_path[0] == '\0' ) { printf( "Unable to find help file\n" ); } else { help_file = fopen( full_path, "r" ); display_help( help_file ); fclose( help_file ); } return EXIT_SUCCESS; }
Classification:
Caveats:
The searchenv() function manipulates the environment pointed to by the global environ variable.
|
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/s/searchenv.html
|
CC-MAIN-2020-29
|
refinedweb
| 242
| 58.58
|
READPASSPHRASE(3) BSD Programmer's Manual READPASSPHRASE(3)
readpassphrase - get a passphrase from the user
#include <readpassphrase.h> char * readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags);. readpassphrase() takes the following optional.
Upon successful completion, readpassphrase() returns a pointer to the NUL-terminated passphrase. If an error is encountered, the terminal state is restored and a null pointer is returned.
/dev/tty
The following code fragment will read a passphrase from /dev/tty into the buffer passbuf.));
[EINTR] The readpassphrase() function was interrupted by a signal. [EINVAL] The bufsiz argument was zero. [EIO] The process is a member of a background process attempting to read from its controlling terminal, the process is ig- noring.
|
http://www.mirbsd.org/htman/i386/man3/readpassphrase.htm
|
CC-MAIN-2015-35
|
refinedweb
| 116
| 59.3
|
Details
- Type:
Epic
- Status: Open (View Workflow)
- Priority:
Major
- Resolution: Unresolved
- Component/s: envinject-plugin
-
- Epic Name:Pipeline support in EnvInject
- Similar Issues:
Description
EnvInject does not support Pipeline now. Though there are many workarounds, it would be useful to address particular integration use-cases
Attachments
Issue Links
- blocks
JENKINS-33691 URLTrigger Plugin doesn't work in jenkins 2.0 alpha 3 when using job type Pipeline
- Closed
- is related to
JENKINS-27301 Pipeline support for XTrigger
- In Review
- links to
-
Activity
Is this Epic related to JENKINS-28921?
Martin d'Anjou No. This EPIC is only about EnvInject, global variables feature is a part of the core
I'm curious if work is still underway on this epic. I'd like to push my work to make urltrigger work with pipelines upstream, but that work is blocked on this epic.
Basil Crow What exactly are you missing in EnvInject plugin to make URLTrigger working? The most of API has been already adapted, so it should be possible to migrate the plugins
Hi Oleg Nenashev, I don't think I am missing anything. Thanks for addressing this! I have now posted two pull requests in order to add pipeline support to the URL Trigger plugin, using envinject-api 1.2 in order to do so.
As per description, there are multiple workarounds. Can anybody put link to workaround page, or mention some workarounds here?
In pipeline "Properties Content",Path=$Path;$JAVA
bin;C:
Program Files (x86)\\PuTTY;C:\\NGS\\bin;C:\\Python27;C:
Python27
Scripts
$Path is not evaluated.
How to "Inject environment variables" using pipeline syntax?
I would like to see workarounds documentation.
Pass text-yaml variable to job:
like
EXTRA_VARIABLES_YAML:
variabl1: value1
then, merge extra data into job env:
def mergeEnv(envVar, extraVars) { try { def extraParams = readYaml text: extraVars for(String key in extraParams.keySet()) { envVar[key] = extraParams[key] println("Parameter ${key} is updated from EXTRA vars.") } } catch (Exception e) { println("Can't update env parameteres, because: ${e.toString()}") } } extraVarsYAML = env.EXTRA_VARIABLES_YAML.trim() ?: '' if (extraVarsYAML) { mergeEnv(env, extraVarsYAML) extraVars = readYaml text: extraVarsYAML } else { extraVars = [:] }
Here's the use case I have today. We work on sprint branches in our SCM. As we advance sprint to sprint we change the branch name. To handle this we set a global variable (SPRINT_BRANCH) with the branch name as its value. Jenkins jobs designed to always focus on the "current sprint" use that global variable ${SPRINT_BRANCH} as the branch name in the SCM checkout. Elsewhere in Jenkins, using this variable works with the plugin SCM operations. This pattern allows us to migrate any number of jobs from one branch to the next by simply changing the value of SPRINT_BRANCH. With Pipeline, a variable can not be used as the branch name.
|
https://issues.jenkins.io/browse/JENKINS-42614?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&showAll=true
|
CC-MAIN-2021-10
|
refinedweb
| 459
| 56.25
|
How to make money and make everybody happy...
I:
Similar Threads
[Grid] How to make a row clickable as a link?By doodoolizm in forum Ext 2.x: Help & DiscussionReplies: 3Last Post: 21 Nov 2011, 3:05 AM
ComboBox, JsonRequest - can it make a GET request?By SteveEisner in forum Ext 2.x: Help & DiscussionReplies: 1Last Post: 12 Mar 2007, 8:05 PM
How to make a dialog window re-appear after it's closedBy namespace in forum Ext 1.x: Help & DiscussionReplies: 2Last Post: 10 Feb 2007, 9:20 PM
Trying to make a simple Dialogue BoxBy Bobafart in forum Ext 1.x: Help & DiscussionReplies: 7Last Post: 22 Jan 2007, 5:47 AM
Way to make BasicDialog not resizable?By swallace in forum Community DiscussionReplies: 5Last Post: 7 Nov 2006, 4:12 PM
|
https://www.sencha.com/forum/showthread.php?2455-How-to-make-money-and-make-everybody-happy...&s=79f50cbfb646fc9ae40d38649a6e3036&p=12454
|
CC-MAIN-2015-35
|
refinedweb
| 134
| 66.44
|
Download presentation
1
Treasurer’s Top Ten Tasks
May 2014 Treasurer’s Top Ten Tasks Duval County Council of PTAs Jenifer Morgan Treasurer, DCCPTA
2
#10 You are not alone. You have resources.
Experience with PTA Training Treasurer’s Toolkit dccpta.org National PTA “Money Matters” pta.org Florida PTA “Dollars and Sense” Floridapta.org
3
#9 Dues are important. State and National dues must be remitted to Florida PTA monthly ($3.50 per member). Duval County Council dues are due November 1 ($35 per local unit).
6
#8 Money In & Money Out: Deposits
Use Deposit Count Form every time you count or collect money. Two people count the money. Two people promptly deposit money into PTA’s bank account. Attach deposit slip to Deposit Count Form.
8
#8 Money In & Money Out: Checking
Use Check Request Form for every disbursement. Attach receipts. Three individuals authorized to sign checks should never be related to each other. At least two people must sign check. Pay all bills by check and in a timely manner. Never sign a blank check or make a check out to cash. DCC PTA does not recommend the use of debit/check cards for paying expenses.
10
#8 Money In & Money Out: Electronic Banking
National PTA highly recommends that debit or gift cards not be used as a form of payment. However, deposit only ATM cards are acceptable if your bank offers this service. Risks of Using Debit/Gift Cards If lost or stolen, your bank account could essentially be drained before you even realize the card is gone. When multiple volunteers or employees have access to a debit card, it can be difficult to track the purchases. Accounting is more difficult to maintain, since individual receipts are the only record of the purchase. Gift cards are not traceable once purchased.
11
#7 Budget A budget is an estimate of money coming in and money going out. A budget committee develops the budget. The committee should: Gather suggestions, needs, and probable costs. Review proposed programs and estimate expenses. Review past budgets, income and expenses. Estimate probable income and probable expenses. Carry-over funds represent the amount which is set aside to begin (and end) operations. Your budget should be adopted at the first general meeting usually in August or September. Funds should not be raised nor spent until a budget is approved. After the budget is adopted, it should be followed closely in all financial transactions. Changes to your budget must be approved by the membership at a general meeting. Expenditures in your budget must support the PTA mission.
13
#6 Document Everything Deposit Count Forms & deposit slips
Check Request Forms & copies of checks Receipts Invoices Returned Checks Board Meeting Minutes Correspondence Bylaws & Standing Rules
14
#5 Insurance All PTAs should have some form of insurance.
General Liability - covers routine activities, bodily injury, property damage. Bonding - protects PTA’s money from theft, if internal controls are in place. Officers Insurance - protects individual officers of the PTA financially from any personal liability in the event the PTA is sued or cannot pay its bills.
15
#4 Reporting is Important
Treasurer’s Report Should be given at each board meeting and general membership meeting. The report should show: The PTA’s cash balance A comparison of PTA income and expenses to budget The activity that has transpired since the last reporting
17
#4 Reporting is Important
Outside School Related Organization Monthly Reports must be submitted to the school’s bookkeeper each month. This is intended to be a reconciliation of your books with the monthly bank statement. Include all transactions that occurred during the month. (Deposits, checks written during the month, etc. even if they have not cleared the bank.)
19
#4 Reporting is Important
A financial review/audit is always completed: At the end of each fiscal year (June 30) Whenever there is a change in Treasurer’s positions Anytime the Executive Board requests an additional audit Financial review/audit must be completed before any checks are written for the new fiscal year. A financial review/audit is completed by three non-check signers. Forward a copy to and
21
#4 Reporting is Important
A request for fundraising activity form must be submitted and approved by the Principal before any fundraising begins.
23
#3 Rules you don’t want to violate (IRS, FLDOR, PTA, District)
EVERY UNIT, EVERY YEAR IS REQUIRED TO FILE A TAX RETURN. This must be done well before November 15. If gross receipts are less than $50,000, then you file a 990-N (takes only minutes to complete!). For gross receipts from $50,000 to $200,000, file Form 990EZ and Schedule A and G. For gross receipts over $200,000, file Form 990. Forward a copy to and .
24
#3 Rules you don’t want to violate (IRS, FLDOR, PTA, District)
Other IRS Rules: Issue receipts. Money must not be spent on an individual child; the PTA mission focuses on all children or the school. PTA cannot engage in political activity. Be sure to use your PTA’s EIN number on bank accounts and tax returns. Other IRS Rules: no private benefit, limited lobbying, non-commercial, non- religious, UBI (Unrelated Business Income). Bottom line follow IRS rules – don’t jeopardize your non-profit tax exempt status.
25
#3 Rules you don’t want to violate (IRS, FLDOR, PTA, District)
May 2014 #3 Rules you don’t want to violate (IRS, FLDOR, PTA, District) Florida Department of Revenue Sales Tax Rules: PTAs are not licensed to collect or remit sales tax. Simply, if you are going to re-sell an item, pay the sales tax to the vendor at the time of the purchase. The vendor must in turn, remit that sales tax to the Florida Department of Revenue. Always pay vendors with a PTA check.
26
#3 Rules you don’t want to violate (IRS, FLDOR, PTA, District)
PTA Rules: Financial Review/Audit at least once a year (June 30) Approve a budget Two signatures on checks Don’t pre-sign checks No checks made out to cash Do not pay bills with cash or debit cards Report and document everything Dual money count Remit dues to Florida PTA Complete and forward tax return (Form 990N, 990EZ or 990) to Florida PTA Deposit cash right away Treasurer’s Reports at every meeting Fraud or missing cash occurs when controls and procedures become sloppy. Don’t let that happen to you. Duval County Public School District Rules: The June 30 Financial Review/Audit must be submitted to the school’s bookkeeper. Outside School Related Organization Monthly Reports must be submitted to the school’s bookkeeper each month. The request for fundraising activity form must be submitted and approved by the Principal before any fundraising begins.
27
#2 Soliciting Funds Membership dues. are a primary source of funding for PTAs. Fundraising is not a primary function of PTA but can enhance the programs that promote the objectives of PTAs. PTAs should use the 3 to 1 rule. Plan 3 projects for every 1 fundraiser. The President signs contracts, as a representative of the PTA not as an individual. Sponsorships and in-kind donations are also an appropriate means of funding projects. Issue receipts and/or thank you letters. PTAs cannot endorse products, companies or foundations.
28
#1 Be Responsible A successful Treasurer is accurate, organized, honest, dependable, and consistent. Be transparent. The president should work closely with the treasurer. Ensure the money is spent to support the PTA mission.
29
Questions Jenifer Morgan, Treasurer, DCCPTA Thank you for attending!
Thank you for attending!
Similar presentations
© 2020 SlidePlayer.com Inc.
|
http://slideplayer.com/slide/4507836/
|
CC-MAIN-2020-10
|
refinedweb
| 1,275
| 56.96
|
.3: Inheritance and Class Hierarchies
About This Page
Questions Answered: Say I have a regular class; how can I define a subtype for it? How do the classes and traits of the Scala API form a family tree? How can I form such a family tree of data types for my program?
Topics: Inheritance: extending a superclass with subclasses. Some key classes in Scala’s class hierarchy. Abstract classes.
What Will I Do? Read and program.
Rough Estimate of Workload:? Three hours.
Points Available: B70.
Related Projects: Subtypes.
Introduction
In the previous chapter, we used traits to define supertypes for multiple classes. In this chapter, we’ll use a technique known as inheritance (periytyminen) that defines supertypes as regular classes rather than traits.
Let’s Continue with Shapes
In the previous chapter, we defined the trait
Shape and an implementing class
Rectangle:
trait Shape { def isBiggerThan(another: Shape) = this.area > another.area def area: Double }
class Rectangle(val sideLength: Double, val anotherSideLength: Double) extends Shape { def area = this.sideLength * this.anotherSideLength }
What if we also want to represent squares, that is, rectangles with four sides of equal
length? We’d like to be able to write
new Square(10) and the like.
Of course, we might simply extend
Shape in a
Square class:
class Square(val sideLength: Double) extends Shape { def area = this.sideLength * this.sideLength }
The bothersome thing about this solution is that the code is quite redundant: the algorithm
for computing the area of a square is the same as that for a rectangle; it just happens that
the sides are equal in length. This approach isn’t up to par in terms of conceptual
modeling, either: it makes squares a subtype of
Shape alongside rectangles, whereas
we humans prefer to think of a squares as a special case of a rectangle; each square is
a square, a shape, and a rectangle.
The fix is simple: we can define squares as a subtype of rectangles, as shown in the
diagram below. We can do this even though
Rectangle is a regular class, not a trait.
Subclasses and Superclasses
Let’s define
Square like this instead:
class Square(size: Double) extends Rectangle(size, size) { }
Squarehas only one constructor parameter that determines the length of each side.
Squareobject is created, we initialize a
Rectangleso that each of its two constructor parameters (each side length) gets the value of the new
Square’s single constructor parameter. (See the animation below.)
Inheritance vs. traits
Extending a superclass with a subclass looks much like extending a trait with a class. The two techniques are closely related.
There are differences, though; let’s compare. First, consider traits and how the
Rectangle class extends the
Shape trait:
And here is a similar table about inheritance and the example of
Rectangle as a superclass
for
Square:
There are many scenarios where it’s reasonable to use either of these techniques.
Abstract Classes
The distinction between traits and class-based inheritance is further complicated by the fact that it’s possible to define so-called abstract classes. We’ll approach this concept through an example.
Let’s return briefly to the domain of phone bills, previously featured in Chapter 2.3.
In that chapter, you used a given class
PhoneCall, which represented aspects of phone
calls that were relevant for billing purposes. Below is an implementation for such a class.
(For simplicity, the version shown here doesn’t add a network surcharge like the earlier
class did.)
class PhoneCall(initialFee: Double, pricePerMinute: Double, val duration: Double) { def totalPrice = this.initialFee + this.pricePerMinute * this.duration }
Suppose we now want to add text messages to phone bills. Moreover, we’d like to record, for each billable call and message, whether or not its price already includes a 24-percent value-added tax (VAT). Finally, we’d like to have a method for computing the tax-free price.
In other words, we’d like phone bills to list “billable transactions” that can be either phone calls or text messages. Here’s a first draft:
class Transaction(val vatAdded: Boolean) { def priceWithoutTax = if (this.vatAdded) this.totalPrice / 1.24 else this.totalPrice }
class PhoneCall(val duration: Double, val initialFee: Double, val pricePerMinute: Double, vatAdded: Boolean) extends Transaction(vatAdded) { def totalPrice = this.initialFee + this.pricePerMinute * this.duration }
class TextMessage(val price: Double, vatAdded: Boolean) extends Transaction(vatAdded) { def totalPrice = this.price }
vatAddedto each
Transactionin order to indicate whether the given prices include a 24% VAT. If the tax is included,
priceWithoutTaxsubtracts the amount of tax in order to return the tax-free price.
PhoneCalland
TextMessageeach take multiple constructor parameters. Most of these parameters are associated with these specific subclasses, but ...
vatAddedgets passed on as a constructor parameter to the superclass. The processing of that information is left entirely to
Transaction.
priceWithoutTaxmethod calls
totalPriceon a transaction object, but the program doesn’t ensure that all possible transaction objects actually have this method. (It so happens that each of the two subclasses that we’ve defined here do have the method, but more generally, it’s not clear that any instance of any subclass of
Transactionwill have it.) The compiler rejects this code.
What we need is a
totalPrice method that is common to all possible objects of type
Transaction but that is implemented in different ways by different subclasses.
Something like this:
class Transaction(val vatAdded: Boolean) { def totalPrice: Double def priceWithoutTax = if (this.vatAdded) this.totalPrice / 1.24 else this.totalPrice }
In this version, the
totalPrice method is abstract, with no implementation. It exists
in order to guarantee that such a method is somehow implemented on all transaction objects,
which makes it possible to implement
priceWithoutTax in general terms within the
Transaction superclass.
But ordinary classes weren’t supposed to have abstract methods, right!?
Indeed, the above second draft of
Transaction doesn’t make it past the compiler, either.
But this one does:
abstract class Transaction(val vatAdded: Boolean) { def totalPrice: Double def priceWithoutTax = if (this.vatAdded) this.totalPrice / 1.24 else this.totalPrice }
- If you want abstract methods on a
class, you can add
abstractto the class definition.
Such a class is called an abstract class. A class that is not abstract may be referred to as a concrete class.
An abstract class is similar to a trait. Let’s include it in our comparison:
An alternative implementation for
TextMessage
Above, we implemented text messages like this:
class TextMessage(val price: Double, vatAdded: Boolean) extends Transaction(vatAdded) { def totalPrice = this.price }
Perhaps you feel it’s redundant to use two names,
price and
totalPrice, that give you access to the same information. And
it is unnecessary. This works, too:
class TextMessage(val totalPrice: Double, vatAdded: Boolean) extends Transaction(vatAdded)
Simple as that. The only new thing about this is that the subclass
turns
totalPrice into a variable; there’s no
def that implements
the superclass method. But there’s nothing wrong with that; this is
a valid way to implement a parameterless abstract method. The important
thing is that an expression such as
myTextMessage.totalPrice must have
a
Double value, one way or another. For a user of the text-message
class, it’s generally irrelevant whether they are dealing with a
val or an effect-free, parameterless method that efficiently
returns the same value every time. (Further reading: the Wikipedia
article on the uniform access principle.)
Couldn’t we have used a trait there?
As an alternative to the approach we adopted above, we could have made
Transaction a trait, replacing
class with
trait in its definition.
However, that solution is unsatisfactory in one respect: Scala prohibits
traits from having constructor parameters, so we would have needed to
make other changes to work around that.
Optional assignment: Rewrite (mentally, at least)
Transaction and its
subclasses. Use a trait instead of an abstract superclass.
Generally speaking, should I use a trait or a superclass?
Rule of thumb: Unless you have a specific reason to use an abstract class, use a trait instead, since traits are more flexibly extendable.
The convenience of constructor parameters might be a reason to use a superclass rather than a trait.
It can be tricky to choose among a trait, an abstract superclass, or a concrete superclass. However, in O1, such decisions are generally made for you and provided in the assignment specifications. You can worry about learning to make these decisions yourself later, in Programming Studio 2, for example. For more information, you can also take a look at Section 12.7 of Programming in Scala (Third Edition), one of the book recommendations on our Books and Other Resources page.
Class Hierarchies and the Scala API
Chapter 7.2 demonstrated that we can represent conceptual hierarchies with traits.
Inheritance is likewise useful in forming such hierarchies. Even though a class can have
only one immediate superclass, it can have multiple indirect superclasses. In the diagram
above, for instance, the immediate superclass of
Spider is
Arthropod, but
Animal is
also one of its superclasses.
The ready-made classes of the Scala API also form hierarchies. Let’s consider a few examples.
A hierarchy of GUI elements
The package
scala.swing provides a selection of classes that represent GUI elements,
building blocks for graphical user interfaces. The diagram below depicts a part of this
hierarchy.
Some of these classes from package
scala.swing are traits, some
are regular classes. Each supertype defines generic properties
common to all the extending types. At the top level,
UIElement
defines properties common to all kinds of GUI elements, such as
background color and size.
About the Swing GUI library
Chapter 12.3 contains an introduction to the GUI library known as Swing. That optional chapter is at the rear end of O1 and this ebook, but if you’re itching to read more about GUIs, go ahead and read it. Now that you’ve been introduced to inheritance, you should have the sufficient prerequisite knowledge for the chapter.
The
Option hierarchy (and sealed superclasses)
There’s a small class hierarchy associated with the
Option type, too.
Since Chapter 4.2, you’ve known that there are two kinds of
Option objects. Any object
of type
Option is either a
Some object that contains a value or
None. This is
actually an example of inheritance:
Option is an abstract class that the concrete
class
Some and the singleton object
None extend.
Chapter 7.2 mentioned how to seal a trait: the
sealed keyword makes it impossible
to extend a trait outside the file where the trait itself is defined. A superclass can
also be sealed, and
Option is just such a sealed class: as noted in Chapter 4.2,
an
Option can be either a
Some or
None (which are defined in the same file) but it
can never, ever be anything else. Which is exactly what you want when you use
Option.
You can’t extend
Option with a class of your own, and that’s good.
The mother of all classes:
Any
Let’s examine some objects in the Scala REPL:
val miscellany = Vector(123, "llama", true, Vector(123, 456), new Square(10))miscellany: Vector[Any] = Vector(123, llama, true, Vector(123, 456), o1.shapes.Square@114c3c7)
Int, a
String, a
Boolean, a
Vectorof
Int, and a
Square.
Any. That is, what we have is a “vector of any sorts of objects”. This suggests that integers, vectors, squares, and what have you, are all of type
Any.
All Scala classes and singleton objects — including those you write — automatically
inherit from a class called
Any, even though we don’t usually record this inheritance
explicitly in code. All the objects in a Scala program always have the
Any type in
addition to any other types they may have.
It’s possible to use this top-level class as a type for a variable, as illustrated below.
var someObject: Any = "kumquat"someObject: Any = kumquat someObject.isInstanceOf[Any]res0: Boolean = true someObject.isInstanceOf[String]res1: Boolean = true someObject.isInstanceOf[Square]res2: Boolean = false someObject = new Square(10)someObject: Any = o1.shapes.Square@ecfb83 someObject.isInstanceOf[Any]res3: Boolean = true someObject.isInstanceOf[String]res4: Boolean = false someObject.area<console>:12: error: value area is not a member of Any someObject.area ^
Anyto refer to any object. The object can be a string or a square, for instance.
someObjectis
Any, and the expression
someObject.isInstanceOfis valid because (and only because) the
isInstanceOfmethod is defined in the
Anyclass and is therefore available on any Scala object.
someObject.areafails even though the variable happens to store a
Squareobject which has an
areamethod. The variable’s static type limits what you can do with it.
In most cases, it’s not sensible to use variables of type
Any, since the type’s genericity
so constricts what you can do with such variables. With
Any as the static type, you can use
the variable only for the operations that are defined on
Any; those extremely generic methods
that are common to all Scala objects include
isInstanceOf,
toString,
==,
!=, and a
handful of others. Generally, it makes sense to use variables with more specific types, which
is of course what we’ve been doing already. (See the optional material below for a further
discussion.)
Something you may have noticed in the docs
The Scaladoc pages for many classes say
extends AnyRef near the top. Here’s a familiar
example:
But we haven’t seen
extends AnyRef in the Scala code; why is it there in the docs? And
why
AnyRef, not
Any?
The mother of most classes:
AnyRef a.k.a.
Object
Scala’s root type
Any divides in two “branches”. It has two immediate subclasses,
AnyVal and
AnyRef:
This division to
AnyRef and
AnyVal has to do with the way the Scala language is
implemented and isn’t too significant to the Scala beginner or for learning the basics
of programming more generally. Nevertheless, it’s good to be aware that these types
exist so you know why they sometimes crop up in Scaladocs, REPL outputs, and error
messages.
AnyVal is a superclass for some API classes that define certain data types that are
simple but operate more efficiently than other classes do. The familiar data types
Int,
Double,
Boolean,
Char, and
Unit descend from
AnyVal, as do a few others. It’s
relatively uncommon to extend
AnyVal in an application; in O1, we don’t do that at all.
AnyRef, on the other hand, is a superclass for all other classes and singleton objects.
The classes
String and
Vector, for instance, derive from
AnyRef, as does the
Transaction class we just wrote.
When using the common JVM-based implementation of Scala (as we do; Chapter 5.2),
AnyRef
is sometimes (and somewhat confusingly) also known by the name
Object for JVM-specific
technical reasons.
We can spot
AnyVal and
AnyRef a.k.a.
Object in the REPL, too:
val miscellany2 = Vector(123, true)miscellany2: Vector[AnyVal] = Vector(123, true) val miscellany3 = Vector("llama", Vector(123, 456), new Square(10))miscellany3: Vector[Object] = Vector(llama, Vector(123, 456), o1.shapes.Square@667113)
Intand
Booleandescend from
AnyVal.
String,
Vector, and
Squaredescend from
Object, which is effectively synonymous with
AnyRef.
Overriding Supertype Methods
Since Week 2, we have used
override for replacing default method implementations with
class-specific ones. In particular, we have used this keyword in:
-
- the event handlers on
Views (such as
onClick; Chapter 2.8): the default implementations in class
Viewreact to events by doing nothing at all but you can override them with whichever behavior you wish your application to have.
You can also override other methods in type hierarchies. As an experiment, let’s write a few mini-classes.
class A { def test() = { println("Greetings from class A.") } }
class B extends A { }
class C extends A { override def test() = { println("Greetings from class C.") } }
class D extends C { }
class E extends D { override def test() = { println("Greetings from class E.") } }
Now let’s use our classes in the REPL:
(new A).test()Greetings from class A. (new B).test()Greetings from class A. (new C).test()Greetings from class C. (new D).test()Greetings from class C. (new E).test()Greetings from class E.
Bdoesn’t define an overriding implementation, so a
Bobject simply inherits the
testimplementation of
A.
Coverrides
test.
Ddoesn’t override the method. A
Dobject uses the implementation from its immediate superclass
C(which overrides the one from
A).
Edoes supply an overriding implementation that supersedes both the one in
Cand the one in
A.
Let’s explore further:
var myObject = new AmyObject: A = A@e1ee21 myObject.test()Greetings from class A. myObject = new CmyObject: A = C@c081a6 myObject.test()Greetings from class C.
A. Its value has the dynamic type
C.
teston any expression with the static type
A(or one of
A’s subtypes); that is, we can call it on any object that is guaranteed to have the method. On the other hand, what happens when we do so depends on the dynamic type of the object that receives the message. Here, we execute the
testimplementation defined on
Cobjects, even though the variable is of type
A.
One more class:
class F extends E { override def test() = { super.test() println("Greetings from class F.") } }
superkeyword to refer to an implementation defined in a supertype. Here, we first call the superclass’s version of
test. As a consequence, the
testmethod of an
Fobject first does whatever the
testmethod on its superclass
Edoes and then produces a printout specific to
F. See below for an example.
(new F).test()Greetings from class E. Greetings from class F.
In Scala, you must always explicitly use the
override keyword whenever you wish to
override a method.
Why require an explicit
override?
By writing
override in your program, you acknowledge that you
are deliberately superseding a method implementation defined on a
supertype. If the keyword was optional, you might very easily give
your method a name that is already used in a supertype. Such a
thing could happen quite accidentally and unknowingly, possibly
spawning exotic bugs.
Like static typing, this requirement is a language feature that reduces the chance of human error.
As an added benefit, the keyword makes overriding explicit to the program’s readers.
Practice on inheritance and overriding
The frivolous program below features a combination of many of the techniques that we just discussed. You can use it for checking your understanding. If you can tell — in detail! — what this program does, then you will have grasped some of the main principles of inheritance.
A story about driving
Read the code below. Painstakingly consider which exact lines of text it outputs and in which order. Ideally, you should write down what you think the program outputs.
object Cruising extends App { val car = new Car car.receivePassenger(new Schoolkid("P. Pupil")) car.receivePassenger(new ChemicalEngineer) car.receivePassenger(new MechanicalEngineer) car.receivePassenger(new ElectricalEngineer) car.receivePassenger(new ComputerScientist) car.start() }
class Car { private val passengers = Buffer[Passenger]() def receivePassenger(passenger: Passenger) = { passenger.sitDown() this.passengers += passenger } def start() = { println("(The car won't start.)") for (passenger <- this.passengers) { passenger.remark() } } }
abstract class Passenger(val name: String) { def sitDown() = { println(this.name + " finds a seat.") } def speak(sentence: String) = { println(this.name + ": " + sentence) } def diagnosis: String def remark() = { this.speak(this.diagnosis) } }
abstract class Student(name: String) extends Passenger(name) { def diagnosis = "No clue what's wrong." }
class Schoolkid(name: String) extends Student(name)
abstract class TechStudent(name: String) extends Student(name) { override def remark() = { super.remark() this.speak("Clear as day.") } }
class ChemicalEngineer extends TechStudent("C. Chemist") { override def diagnosis = "It's the wrong octane. Next time, I'll do the refueling." }
class MechanicalEngineer extends TechStudent("M. Machine") { override def diagnosis = "Nothing wrong with the gas. It must be the pistons." override def speak(sentence: String) = { super.speak(sentence.replace(".", "!")) } }
class ElectricalEngineer extends TechStudent("E. Electra") { override def sitDown() = { println(this.name + " claims a front seat.") } override def diagnosis = "Hogwash. The spark plugs are faulty." }
class ComputerScientist extends TechStudent("C.S. Student") { override def remark() = { this.speak("No clue what's wrong.") this.speak(this.diagnosis) } override def diagnosis = "Let's all get out of the car, close the doors, reopen, and try again." }
Did you read the program carefully? Did you write down the output you expect?
Now open project Subtypes and run
o1.cruising.Cruising (which is
the above program). Was the output precisely what you expected? If
not, find out why.
Assignment: Items within Items
Introduction
Imagine we’re working on an application that needs to represent items of various sorts.
We have a simple class
Item:
class Item(val name: String) { override def toString = this.name }
For this small programming assigment, let’s adopt the following goal: we wish our program to have not only “simple items”, as defined above, but also items that can contain other items. For instance, we might have a bag that contains a book and a box, and the box might further contain a ring.
Task description
Write a subclass for
Item. Name it
Container. This subclass will represent items that
can contain other items, such as bags and boxes. Containers each have a name, just like
other items do. Moreover, they have an
addContent method that places an item within the
container. Their
toString implementation differs from that of other items.
Your class should work as shown below.
val container1 = new Container("box")container1: o1.items.Container = box containing 0 item(s) container1.addContent(new Item("ring")) container1res5: o1.items.Container = box containing 1 item(s) val container2 = new Container("bag")container2: o1.items.Container = bag containing 0 item(s) container2.addContent(new Item("book")) container2.addContent(container1) container2res6: o1.items.Container = bag containing 2 item(s)
Instructions and hints
- There is some starter code in
o1.itemswithin the Subtypes project.
- Don’t forget to pass a constructor parameter to the superclass
Item.
- Don’t use
valto (re)define the instance variable
namewithin the
Containersubclass. That variable is already defined in the superclass. It’s perfectly fine to give
Container’s constructor parameter the name
name, though.
- The return value of
toStringshould count only the container’s immediate contents. For instance, in the REPL session above, the bag is shown as containing only two items, even though the box in the bag further contains the ring. (How could we count all the “contents of the contents”, too? You’ll see in Chapter 11.2.)
- Note that what you
overridein this assignment isn’t the generic
toStringfrom
AnyRef, as in many other programs, but the
toStringimplementation in
Item.
- Can you implement the
toStringin
Containerso that you use the superclass’s implementation rather than directly accessing the container’s name? (This is optional.)
- You don’t need to implement any other methods for, say, examining the contents of a container or removing them.
Submission form
A+ presents the exercise submission form here.
Assignment: Legal Entities
Task description
Study the documentation of
o1.legal in project Subtypes. The documentation lays out a
number of classes that represent court cases and the legal entities
involved in such cases (also known as “legal persons”).
Implement the classes as Scala files in the same project.
There are quite a few classes but they are very simple. This assignment is primarily concerned with the relationships between these classes, which are illustrated in the diagram below.
Recommended steps and other hints
You may wish to proceed as follows.
Browse the documentation for
CourtCase,
Entity,
NaturalPerson, and
JuridicalPersonto get an overall sense of those four classes.
Write
CourtCase. Note that each court case is associated with two variables whose type is defined by the superclass
Entity. The referred objects are legal entities of some kind, but
CourtCasedoesn’t care which.
Write class
Entityin a file of its own.
- As noted in the documentation, the class is abstract. Use
abstract.
- Some methods are also marked as abstract in the documentation. However, you neither need nor should use the keyword on methods. For defining an abstract method, it suffices to omit the method body as shown in earlier examples.
Write
NaturalPersonin a file of the same name.
- As stated in the docs, you’ll need to extend a class. Also remember that when inheriting from a class, you need to supply the superclass with values for any constructor parameters it defines. (Cf.
Containerabove.)
- This class passes one of its constructor parameters on to the superclass but not the other one. Note that the superclass already defines a variable that corresponds to the
nameparameter, so you don’t need a
valfor that.
- The Scaladocs tell you which methods of each class are inherited from a superclass and which ones are new to the specific class. Near the top of each Scaladoc page, there is a gray area labeled Inherited that contains buttons for adjusting which methods show on the page. Try the buttons.
Write
FullCapacityPerson.
- Especially since we’re dealing with short, closely related class definitions, it makes sense to define the subclasses of
NaturalPersonin the same file with their superclass.
Open
Restriction.scala, which will help you represent people whose capacity to act on their own behalf in court is reduced for one reason or another. The abstract class
Restrictionis there already, as is a singleton object
Illnessthat inherits it. Add
Underage, a similar singleton.
Write
ReducedCapacityPerson.
If you have implemented the earlier methods correctly, this should work as an implementation for the
kindmethod:
override def kind = super.kind + " with " + this.restriction
Write
JuridicalPerson. Just one line of code will do (since no additional methods are needed and you can omit the empty curly brackets).
Implement
HumanOrganizationand
GeographicalFeature.
- A parameterless, abstract
defin a superclass can be implemented with a variable in a subclass. Define a
contactvariable in
HumanOrganizationand a
kindvariable in
GeographicalFeature.
You don’t have to bother writing
Nation,
Municipality, and
Corporation; there is nothing novel about these classes. You can just uncomment the given implementations. If you have correctly defined the superclasses, these subclasses should work as given.
Implement
Group.
- Note that in this program, groups have no names. Pass a string literal as a constructor parameter to the superclass.
Submission form
A+ presents the exercise submission form here.
Tailoring Instances of a Supertype
In Chapter 2.4, you learned to create an object that has an instance-specific method in addition to the methods defined in a class:
val superman = new Person("Clark") { def fly = "WOOSH!" }superman: Person{def fly: String} = $anon$1@25ba32e0
Since then, we’ve used this technique when creating instances of the
View class:
we have given each of our
View objects a set of tailor-made methods that suits the
application.
Tailoring instances in this way is actually a form of inheritance. For example, what
the above command actually does is define a nameless subclass of
Person “on the fly”
and immediately create a single instance of that subclass. Along the same lines, we
have written diverse implementations for the abstract
makePic method of the superclass
View.
The same works in general for traits and superclasses. Read on if you wish.
Defining a subtype “on the fly”
You can also extend a trait “on the fly” as you create an object.
To set up the next example, let’s define a couple of traits and one concrete class. Note that these three types are entirely distinct from each other.
class Animal(val species: String) { override def toString = "an animal, more specifically a " + this.species } trait Spitting { def spit = "ptui!" } trait Humped { def numberOfHumps: Int }defined class Animal defined trait Spitting defined trait Humped
Let’s now define a new subclass of
Animal that has no name and
that has the trait
Spitting. While we’re at it, let’s instantiate
that class immediately. The result is an object of the combined type
Animal with Spitting, which we’ve defined on the fly:
val pet = new Animal("llama") with Spittingpet: Animal with Spitting = an animal, more specifically a llama
This object has all the properties of
Animals as well as all the
properties defined in the
Spitting trait:
pet.speciesres7: String = llama pet.spitres8: String = ptui!
Of course, we could have also defined a named class, as shown below, and instantiated it as per usual.
class Llama extends Animal("llama") with Spittingdefined class Llama
Adding methods on a type defined “on the fly”
Let’s continue our toy example. We’ll create an object of a type that:
- is a subclass of
Animal;
- additionally extends the traits
Humpedand
Spitting; and
- implements the abstract method
numberOfHumpsin the
Humpedtrait in a specific way.
val shipOfTheDesert = new Animal("dromedary") with Humped with Spitting { def numberOfHumps = 1 }shipOfTheDesert: Animal with Humped with Spitting = an animal, more specifically a dromedary
Finally, let’s create an object of a nameless class that has
the
Spitting trait and a couple of additional properties
(a
name variable and a particular implementation of
toString):
val fisherman = new Spitting { val name = "Eemeli" override def toString = this.name }fisherman: Spitting{val name: String} = Eemeli
Note that here we followed
new with the name of a trait rather
than a concrete class. However, this command does not directly
instantiate the trait (which isn’t possible; Chapter 7.2). Instead,
it defines a new type that extends the trait and additionally has
the properties listed inside the curly brackets. It is that new
type that is then instantiated.
Terms for googling: scala trait mixin, scala anonymous subclass.
Further Reading
Choosing static types for variables
Rule of thumb: static types in general and the static types of parameters in particular should be as “wide” as possible. That is, where possible, we’d like our variables to have a superclass or a trait as their type rather than a more specific class. That way, our methods and classes will be more generally useful and easier to modify.
Compare:
def doSomething(circle: Circle) = { // ... }
vs.
def doSomething(shape: Shape) = { // ... }
The first definition is sensible in case
doSomething should work
only on circles (say, because it depends on being able to access
the given object’s radius, which other shapes don’t have). Otherwise,
the second definition is probably better, since it works on different
shapes, including future subclasses of
Shape that haven’t even been
written yet.
You can’t always generalize; otherwise we’d just give everything
the
Any type. But do generalize when you can.
Between public and private:
protected
A subclass’s instances also have the superclasses’
private
variables as part of their state. Inherited methods commonly use
those private variables. However, you can’t directly refer to a
private member of a superclass from the subclass’s program code.
The same goes for private members on traits.
However, Scala, like some other languages, features another access
modifier,
protected. This modifier allows precisely what we just
said
private disallows: a
protected variable or method is
accessible not only to the class or trait itself but also within
the code of its subtypes. (But not just anywhere, like a public
member is.) An internet search should bring up many examples.
Multiple inheritance
As noted above, a class can extend only a single superclass directly. Why?
Search online for multiple inheritance (moniperintä). You may also wish to look up the “deadly diamond of death” that is sometimes associated with multiple inheritance and that is held to be a serious problem by some but not all programmers.
And here is some slightly provocative but interesting reading (mostly to those students who already know something about Java and its interface construct):'Interface' Considered Harmful.
If you extend multiple traits, which method implementations do you get?
Here’s a simple example:
trait X { def method: String } trait A extends X { override def method = "a's method" } trait B extends X { override def method = "b's method" }defined trait X defined trait A defined trait B class AB extends A with B class BA extends B with Adefined class AB defined class BA (new AB).methodres9: String = b's method (new BA).methodres10: String = a's method
For more information, look up scala linearization or follow this link here.
The Liskov substitution principle
“Square as a subclass of rectangle” is a classic example when discussing the Liskov substitution principle, which we’ll only paraphrase here. This well-known design guideline is often held up as a criterion of object-oriented program quality.
For a class S to follow this principle, the following must be true:
If S is a subclass of T, all operations that are available and meaningful on instances of T are equally available and meaningful on instances of S.
In other words: where you have an instance of T, you can also use an instance of S.
Let’s return to the shape example and these two classes that we defined earlier:
class Rectangle(val sideLength: Double, val anotherSideLength: Double) extends Shape { def area = this.sideLength * this.anotherSideLength }
class Square(size: Double) extends Rectangle(size, size)
Does this code follow the Liskov substitution principle? What if we
used
var instead of
val in class
Rectangle? Recall: our goal
when writing
Square was to model the fact that a square is a
rectangle whose sides are equal in length.
More in Wikipedia:
On dependencies between classes/traits
The chapter on traits (7.2) already brought up the notion that there is an asymmetric relationship between a subtype and a supertype: we define each subtype in terms of its supertype(s), not the other way around. This applies to inheritance, too:
- In a subclass definition, we record the superclass that the subclass extends. Given that relationship, we can rely on the fact that the inherited methods from the superclass are available for us to use within the subclass. We can write things like
this.methodInSuperclass. We may also use the
superkeyword to refer to the superclass definition.
- We do not record the inheritance relationship in the superclass, and the superclass’s code is independent of the subclasses in this respect. We can't call
this.methodInSubclass; we can invoke methods on
thisonly if they are common to all instances of the supertype. There is no
subkeyword.
If superclasses were dependent on their subclasses, changing those
subclasses would necessitate changes in the superclass. That would
be quite vexing. For instance: It’s fairly common to extend a
superclass defined in a library (e.g.,
View). There is no way
that the library’s creator can know all the possible subclasses
that may be created for their class or react to changes in those
subclasses.
On the other hand, it’s great that we can add methods to a superclass and those methods will then be available in all extending classes. Often, this works fine, but sometimes, we run into a weakness in inheritance-based program design:
On fragile superclasses
The fragile base class problem refers to situations where it’s impossible to modify a superclass without knowing details about its subclasses.
As one example, consider adding a method to a superclass: what if the new method happens to have the same name as one or more of the methods in the subclasses? We have a serious problem.
In a language such as Scala, our program will break down with a
compile-time error that complains about a missing
override
modifier. In languages that don’t have such a modifier or that
make it optional, we may get surprising and erroneous runtime
behavior instead.
O1’s follow-on courses will discuss object-oriented design more deeply. In the meantime, you may find the Wikipedia article on fragile base classes interesting; see also composition over inheritance.
Preventing overriding and inheritance:
final
If you add the
final modifier in front of a
def, the method
can’t be overridden: instances of all subtypes will inherit the
method as is. An attempt to override it will bring a compile-time
error.
In front of
class, the same
final keyword disallows inheritance
from that class altogether. (Cf.
sealed, which limits inheritance
to classes defined in the same file.)
When used appropriately, the
final modifier may make programs easier
to comprehend and prevent inappropriate use of a class. Some
programs’ efficiency is improved by
final, since the compiler
doesn’t need to worry about overriding. Many of the classes in the
standard Scala API are
final .
Summary of Key Points
- Inheritance is an object-oriented technique in which subclasses extend a superclass. The subclasses, which represent more specific concepts, inherit the generic properties defined in the superclass.
- Traits and superclasses have much in common, but there are differences, too. Specifically:
- A class may have only one immediate superclass but it may extend multiple traits.
- Unlike a trait, a superclass may take constructor parameters.
- You can define a class as abstract, in which case it can contain abstract methods and variables just like a trait can. An abstract class can’t be instantiated directly but only via its subclasses.
- Classes and traits form hierarchies that represent hierarchies of concepts. In Scala, all classes are part of a hierarchy whose base is the API class
Any.
- A subclass may override a superclass method with a subtype-specific implementation.
- Links to the glossary: inheritance, subclass, superclass, class hierarchy,
Any; abstract class; static type, dynamic type; to override; sealed.
extendskeyword, but this time we follow it with the name of a regular class rather than a trait. We say: the class
Squareinherits the class
Rectangle. The inheriting class is known as a subclass (aliluokka); the class being inherited from is known as a superclass (yliluokka).
Squares. This gives all
Squareobjects the additional type of
Rectangle.
|
https://plus.cs.aalto.fi/o1/2018/w07/ch03/
|
CC-MAIN-2020-24
|
refinedweb
| 6,265
| 57.37
|
Step 1:- Open Visual Studio
Step 2:- Create New Project, Rename Project if required (I have renamed it
as SinglePictureBox)
Step 3:- Add 1 No PictureBox control from Toolbox on your blank form
Step 4:- Add 3 Nos Button Control from toolbox on your form. (you can add
less or more buttons as you desired)
Our GUI is ready now, before adding any images please rename their file
names like Img1, Img2 & Img3, so that it will easy to add & pick names in
your code window, I have renamed 3 images as mentioned above.
Step 5:- Right click on picture box, go to property,
Select ‘Image’ property, select ‘Import’ option, you will get brows for
adding image files, now select any 3 Nos pictures (In this project I have
added 3 Nos Button Controls so we need only 3 Nos images also, you can
add less or more as you desired)
Step 6:- After addition of image, select option as ‘none’ & press Ok, so that
when you run your project then by default Picture box will show as blank.
Now time to code our app
Right click on your form & select view code,
Your code window will open
Step 7: Add namespace in your code for pick image resources in each
button, your name space will look like this
using SinglePictureBox.Properties;
In above code, SinglePictureBox is project name as I renamed it while
creating new project, if you have given any different name to you project
then you have to use that name only instead on SinglePictureBox
Now come back on your GUL (form Design)
Step 8:- Double click on Button1 & code this in click event
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Resources.Img1;
}
In above code, Img1 will display after button click.
Again double click on Button2 & code this in click event
{
pictureBox1.Image = Resources.Img2;
}
In above code, Img2 will display after button click.
Once again double click on Button3 & code this in click event.
{
pictureBox1.Image = Resources.Img3;
}
In above code, Img3 will display after button click.
Your coding is done & your final code will look like this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SinglePictureBox.Properties;
namespace SinglePictureBox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Resources.Img1;
}
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.Image = Resources.Img2;
}
private void button3_Click(object sender, EventArgs e)
{
pictureBox1.Image = Resources.Img3;
}
}
}
Now run you code & check it works? Press all (3 Nos) buttons one by one
you will get all image one by one in single picture box.
Thanks,
|
https://www.mindstick.com/blog/605/accessing-image-files-from-project-resources
|
CC-MAIN-2018-51
|
refinedweb
| 454
| 61.87
|
I tried out boost msm lite which is a very nice state machine implementation. As always I try to understand how it is working and found a code fragment which I can't understand.
As a remark: I would not post the whole file from boost here, it is here:
The test code only for understanding the things behind the curtain:
auto x2 = "test"_t; //compiles fine!
template <class T, T... Chrs>
auto operator""_t() BOOST_MSM_LITE_NOEXCEPT {
return event<aux::string<Chrs...>>; // ??? How this can work?
}
type
event
template <class>
struct event {
template <class T, BOOST_MSM_LITE_REQUIRES(concepts::callable<bool, T>::value)>
auto operator[](const T &t) const BOOST_MSM_LITE_NOEXCEPT {
return transition_eg<event, T>{*this, t};
} template <class T, BOOST_MSM_LITE_REQUIRES(concepts::callable<void, T>::value)>
auto operator/(const T &t) const BOOST_MSM_LITE_NOEXCEPT {
return transition_ea<event, T>{*this, t};
}
};
#include <cassert>
#include <iostream>
#include "boost/msm-lite.hpp"
namespace msm = boost::msm::lite;
int main()
{
using namespace msm;
auto x1 = "idle"_s;
auto x2 = "test"_t;
}
template <class T, T... Chrs> auto operator""_t() BOOST_MSM_LITE_NOEXCEPT { return event<aux::string<Chrs...>>; // ??? How this can work? }
It works because this operator is not returning a type, but an instance of the template variable
event, which is defined in line 1536:
template <class TEvent> detail::event<TEvent> event{};
Template variables were only introduced in C++14, which is likely why this was harder for you to find and understand. Also note that the _s operator relies on
state, which is not a template variable (thus why it has to be instantiated at the operator function).
|
https://codedump.io/share/oPrYXEEmjJtW/1/how-can-returning-a-type-instead-of-a-object-be-valid-misunderstanding-a-code-fragment
|
CC-MAIN-2017-43
|
refinedweb
| 258
| 52.49
|
Visual Basic Developer Center | VB Team Blog | How-Do-I Videos | Power Packs | Code Samples | VB Interviews
I've been asked by more than a few people in the community for an example of dynamic programming using Visual Basic. Most people understand the benefits of dynamic programming but are still unsure of the implementation details in VB. But for those readers that are unfamiliar with the term (which by the way seems only recently that dynamic programming became "cool") I want to first talk a little bit about what the heck it means to be "dynamic".
My background is actually rooted in a dynamic programming language, like Visual Basic, but it had much better data handling and integrated query, oh and it was also object oriented (pretty much) back in 1995-ish. The language was Visual FoxPro. Some of the advantages that VFP and VB both have is that it's really easy to code against objects and data structures that aren't really fully known at design time. The added benefits that VFP has is dynamic execution of code, interactivity, and integrated query against rectangular datasources, called cursors. This enables rich meta-data programming styles and applications where you can change the behavior of a running program without having to recompile. The downside is that VFP is completely dynamic, with no static type checking at all. As most programmers know this can lead you into big trouble if you aren't careful.
Of course, now that VB 9 has integrated query (and a much much fuller implementation than VFP) as well as having static type checking, you should be able to see the reasons why VB is now my language of choice. VB enables static typing where possible and dynamic typing when necessary. It's the only language I know that has both static and dynamic typing capabilities. This is a big win for the types of applications that I typically wrote -- data-based applications and information systems -- where we needed to be able to easily configure and customize the applications without recompiling them and we needed a language that allowed us do this easily with a lot less code to write.
There's still room for more dynamic programming constructs and interactivity with Visual Basic and I think we'll be seeing those improvements with VB 10, but I wanted to show you how you can take advantage of dynamic programming in VB 8 (VS 2005) as well as VB 9 (VS 2008). To demonstrate this I'll create a simple dynamic UI that lays out controls onto a Windows Form by reading an XML document. We'll do this with VB 8 and then I'll write the application in VB 9 with VS 2008 showing some LINQ to XML along the way.
An Example of Dynamic Programming in VB 8.0, VS 2005
I've created an XML document called questions.xml that contains some information about a survey form I want to dynamically create based on this information. Not only does it contain the questions themselves but it also contains the type of control it should display (as well as which assembly to find the control) and some other additional properties like fore and back colors:
<>
<forecolor>Blue</forecolor>
<backcolor>Control</backcolor>
</question>
<text>This is the second survey question.</text>
<height>100</height>
<forecolor>Red</forecolor>
<backcolor>Pink</backcolor>
<control>System.Windows.Forms.Label</control>
<text>This is the third survey question.</text>
<height>80</height>
<forecolor>Cornsilk</forecolor>
<backcolor>Black</backcolor>
<control>System.Windows.Forms.Button</control>
<text>This is the fourth survey question.</text>
<height>30</height>
<forecolor>HotPink</forecolor>
<backcolor>Cyan</backcolor>
</questions>
Then I have a Windows Form called Form1. I want to display some fixed content as well as this dynamic content in a scrollable area on the form. To do this I added a Panel, made it scrollable, and then inside the panel placed a TableLayoutControl. I set up this control so that it will always have two columns (for question and answer), but will dynamically grow the rows (based on the number of questions in the XML file). To work with the XML easier in VB 8, I'm going to load it into a DataSet, then we'll iterate the rows and dynamically create the controls:
Dim myData As New DataSet()
myData.ReadXmlSchema(CurDir() & "\questions.xsd")
myData.ReadXml(CurDir() & "\questions.xml")
Dim survey As DataTable = myData.Tables(0)
'Now add all the questions defined in the questions.xml file
For Each row As DataRow In survey.Rows
Me.AddQuestion(row)
But to put an added twist on things I also want to include a static question object that I created called QuestionInfo. So we want to display the list of statically defined questions along with the dynamic list of questions from the XML file. My QuestionInfo object is a simple class that defines a default property as well (you'll see why this is important in a minute):
Back in our form, I want to create one of these QuestionInfo objects and also add that as a question to our form:
Me.AddQuestion(New QuestionInfo())
So now let's do some dynamic programming. The AddQuestion method is going to call upon a dynamic class we create that will read the information object passed to it (in our case a DataRow or a QuestionInfo object) and return a control configured as described by that object:
Private Sub AddQuestion(ByVal info As Object)
''Dynamic' is a class we created that dynamically creates
' the control and sets properties. Notice that info parameter
' is an object. As long as it has the fields defined that we need,
' this will work as expected. Take a look at Dynamic.vb file
' to see how VB helps with dynamic programming.
Dim tbQuestion As Object = Dynamic.GetQuestion(info)
If TypeOf tbQuestion Is Control Then
With tbQuestion
.Dock = DockStyle.Fill
.TabStop = False
End With
Me.TableLayoutPanel1.Controls.Add(tbQuestion)
Me.AddAnswer() 'Each question has an answer
Else
'We could do something else with this object.
End If
End Sub
Option Strict Off
Public Class Dynamic
''' <summary>
''' Dynamically creates an object and sets properties on it
''' by reading properties on the passed in object.
''' </summary>
''' <param name="info">An object with the following properties:
''' assembly
''' control
''' height
''' text
''' forecolor
''' backcolor</param>
''' <returns></returns>
''' <remarks>If these properties are not present a runtime error occurs.
''' In that case a multi-line Textbox is returned with the error message.</remarks>
Shared Function GetQuestion(ByVal info As Object) As Object
Dim c As Object
Try
c = System.Reflection.Assembly.Load(info!Assembly).CreateInstance(info!Control)
'VB does an automatic conversion at *runtime* when
' setting these properties.
'This is because Option Strict is set to Off.
'Option Strict can be set on a file-by-file basis only
' so make sure you separate your dynamic classes and
' methods (via partial classes) into separate files.
c.Height = info!Height
c.Text = info!Text
c.ForeColor = Color.FromName(info!ForeColor)
c.BackColor = Color.FromName(info!BackColor)
'c.Text = info!Cool 'This will cause a runtime error
If TypeOf c Is TextBox Then
c.ReadOnly = True
c.MultiLine = True
c.ScrollBars = ScrollBars.Vertical
End If
Catch ex As Exception
'Try/Catch is required here, as this code will cause
' a runtime error if the info object is missing fields
' or the type cannot be created.
c = New TextBox
c.Text = ex.ToString
c.MultiLine = True
c.Height = 100
c.ReadOnly = True
c.ScrollBars = ScrollBars.Vertical
End Try
Return c
End Function
End Class
When we run this program we will see our static question as well as all the dynamic questions from the XML document in a scrollable area of our form:
So that's how we do it in VB 8 and Visual Studio 2005.
Same Example in VB 9.0, VS 2008, Using LINQ to XML
Now we want to upgrade to VB 9 and VS 2008 -- why? -- to take advantage of LINQ to XML and the Intellisense it brings so that we can make our program a little bit safer. It's important to see the balance between static and dynamic programming when you're coding.
When we create a project in VB 9, the setting for Option Strict is Off by default. However, there is a new setting called Option Infer and it is set to On. This means that we do not have to specify the types of our local variables explicitly but the compiler will infer them for us. When the compiler infers the types, they are actually strongly typed. These settings enable better dynamic support.
The first thing we need to do is Import a couple namespaces, System.Linq and System.Xml.Linq. The third namespace is the XML namespace we're going to use. I created an XSD schema from my questions.xml by opening the XML file in VS and from the XML menu selecting "Create Schema". Than I save this schema in the project. Once we do that we can import the namespace:
Imports <xmlns:
This enables XML Intellisense when we work with the question XElement objects. This helps us immensely when working dynamically. So instead of loading our XML into a DataSet, we're going to create a LINQ to XML query that will give us a collection of XElement objects that represent our questions. We'll then modify our Dynamic class to work with XElement instead of plain Object types. First load the XML document:
Dim survey = XElement.Load(CurDir() & "\questions.xml")
Note that the survey variable here is NOT an object, it's inferred as an XElement because of the right-hand side of the expression. Next we'll select all the question elements no matter how deep they are in the document, using the ... (dot dot dot) syntax. Because we imported the schema, Intellisense shows up when we type the "<" character in the query. Then we iterate over the collection of XElements that are returned from the query and create our question controls:
Dim questions = From q In survey...<question> Select q
'We then add questions for each of the XElements
For Each question In questions
Me.AddQuestion(question)
Now we need to change the Dynamic class to also import the same namespaces as before including our XML namespace and then modify the class to call the elements on the XElement object to obtain our values:
Option Infer On
Imports System.Xml.Linq
Imports System.Linq
''' by reading elements on the passed in XElement object.
''' <param name="info">An XElement with the following elements:
''' <remarks>If these elements are not present a runtime error occurs.
Shared Function GetQuestion(ByVal info As XElement) As Object
' using these properties, however XML intellisense
' is available because we imported the schema above,
' which can enables safer dynamic programming.
'This works because Option Strict is set to Off. In VB9,
' the default is to set Option Strict Off, but
' Option Infer ON. This gives static typing where possible,
' but dynamic typing where necessary. Since this is now
' project-wide, we could place this function directly into
' the form that uses it.
c = System.Reflection.Assembly.Load(info.<assembly>.Value).CreateInstance(info.<control>.Value)
c.Height = info.<height>.Value
c.Text = info.<text>.Value
'c.Text = info.<cool>.Value 'This will cause a runtime error
c.ForeColor = Color.FromName(info.<forecolor>.Value)
c.BackColor = Color.FromName(info.<backcolor>.Value)
'Try/Catch is required here, as this code will cause
' a runtime error if the XElement is missing fields
End Class
If we run this we'll see our form with all the questions from the XML file displayed dynamically on the form. The LINQ query we used was very simple but keep in mind we could easily select just certain questions or order them how we wanted by adding the appropriate Where or Order By expressions directly into the code. Very simple and elegant.
There is one thing left to do, however. We wanted to also include a question that was created statically from our QuestionInfo object. There are many ways we could do this, but to demonstrate embedded expressions we're going to incorporate our QuestionInfo object into the LINQ to XML query by creating an array of one QuestionInfo object (there could also be multiple objects in the array as well if we wanted), querying over that to select and create an XElement and then Union the results of that query with the query we wrote above.
Dim qInfo As QuestionInfo() = {New QuestionInfo()}
Dim questions1 = From q In survey...<question> Select q
Dim questions2 = From info In qInfo _
Select <question>
<assembly><%= info.Assembly %></assembly>
<control><%= info.Control %></control>
<backcolor><%= info.BackColor %></backcolor>
<forecolor><%= info.ForeColor %></forecolor>
<text><%= info.Text %></text>
<height><%= info.Height %></height>
</question>
Dim allQuestions = questions1.Union(questions2)
For Each question In allQuestions
Now we'll get the same resulting UI as we did before, but now we've made it easier to program dynamically using XML Intellisense to help us stay in check.
I hope this gives you more than a few ideas on how to take advantage of dynamic programming in Visual Basic right now and also in VB 9. I've attached the VS 2005 project as well as the VS 2008 project that should work with Beta 2 once that is released.
Enjoy!
UPDATE: Also take a look at this updated post that expands on the Dynamic class based on comments from the community.
If you would like to receive an email when updates are made to this post, please register here
RSS
Hey Beth,
That's not really what I would call dynamic as the desired cast is actually known at compile time, so it really is a matter of adding a few CTypes.
Dynamic to me would be more like allowing the user to change control properties and storing them in a database, where the property you want to assign to, and the type is all determined at runtime. Then it becomes nasty calls to CallByName if you're lucky, or more probably reflection, unless you use VB's late binding (aka dynamic) features ;)
Thanks for useful info, I am going to try it.
Beth,
I have to agree with Bill. These days, if you're going to taut a language as being dynamic, expect people to be a little disappointed if all you're demonstrating is how to create ad hoc objects, even if those ad hoc objects are statically typed.
Many programmers are working dynamic languages like JavaScript, Python, Ruby these days and have graduated onto lambda functions, closures, and other powerful features that make a dynamic language really powerful.
Don't get me wrong, I understand above languages are not statically typed and suffer performance hits as a result. All I'm saying is the expectations for dynamic programming languages are a lot higher today, with one expectation being significantly smaller and expressive code.
Hi Bill, Steve,
I understand what you are saying and VB has a ways to go to enabling more dynamic capabilites but even if the code is only halfway dynamic, it's still dynamic :-). Cutting all the casting code and having the VB do it for you at runtime is still a form of being dynamic -- it does give you significantly smaller code.
And I didn't mean this example as the only way to do dynamic programming, I just meant it as a single example that shows the runtime realization of the specific control types and the property types themselves. I explored using CallByName so that I could also store the properties in the XML -- and it would have fit the bill perfectly if it would do the casts automatically for you, unfortunately it doesn't.
I expect to see many more helpful constructs in VB 10 with many more posibilities in the future I just want people to get their head around mixing static and dynamic code in VB and knowing the correct balance.
As always, thanks for the comments!
CallByName in VB6 did do the cast. So really VB.NET as it stands today is a step backward from dynamic.
The example you showed is NOT dynamic. There is nothing "dynamic" about it, it is all fixed at compile time. If you can write the same in C# without using reflection, which you can wiht simple casts, then by definition it cannot be dynamic.
Sorry, but implicit typing is NOT dynamic coding.
Hi Bill,
I guess your definition of dynamic is different than mine :-). I think implicit typing is dynamic -- where I do not have to specify the casts. It's not fixed at compile time -- in the first example I do not know the type of the info object, I just know it has the info I need.
Cheers,
-B
But it is fixed at compile time. Let's take the example :
c.Height = info!Height
That can also be written as:
c.Height = info("Height")
or info.Item("Height")
So breaking that down we have an itme As Object from a keyed index where the key is a string. That object may be different but the code is still statically compiled to cast it to Integer in this case (Hieght). So at compile time, we, and the compiler both know what the type has to be. So this could be written statically as:
c.Height = Cint(info!Height)
And doesn't require Strict Off semantics. This is not dynamic, it's just impicit casting at compile time.
Now if c was As Object too, then that would be dynamic, as we wouldn't know at compile time c's type, hence we couldn't know if c.Height even exisited little alone what Type it was. So there, you couldn't jsut add a cast and statically type the same expression, you'd have to go to great lengths to achieve the same via reflection. Likewise the exampel fo getting the properties and values form a text file or database. These are dynamic because they occur at runtime, not implied at compile time.
c *is* an Object so it does require Strict Off. I could have easily generated a runtime error like this:
c.MyProp = whatever
The compiler would have let me write that here.
I'm implicity casting the object c out of the method as a Control, however, because I'm generating controls and I know that ahead of time, I just don't know which ones. I suppose I could return it as an object and check it in the static code on the form. I had done that originally, but changed to avoid the extra explicit cast.
LOL. Yes c was As Object, but it served no purpose in being an Object becuase the method was clearly returning it as a Control and all the methods/properties called were based on Control. So it gains nothing other than avoiding a couple of simple casts and at the same time introduces the possibility of errors like you suggest c.MyProp = ....
I'm sorry that's not using dynamic for good purposes (and I still argue it's not dynamic becuse everything there can be replaced with casts). So at the end of the day, the code can be calrrified and made mroe robust by addign casts and turning Strict On and still do the exact same thing ;)
But it's much much easier this way because I am not gaureenteed to be creating a control at all because I'm reading an XML file. That's the point here.
"Much much easier" ?? You're kidding me right ?
It's only the GetQuestion method that's using Strict Off. And it is defined as returning a control.
So define c as Control. (and turn strict On) Now intellisense actually helps you right the code ! And helps you pick up on and eliminate any other mistakes.
Shared Function GetQuestion(ByVal info As XElement) As Control
Dim c As Control
Dim tbx As TextBox
Try
c = CType(System.Reflection.Assembly.Load(info.<assembly>.Value).CreateInstance(info.<control>.Value), Control)
c.Height = CInt(info.<height>.Value)
c.Text = info.<text>.Value
c.ForeColor = Color.FromName(info.<forecolor>.Value)
c.BackColor = Color.FromName(info.<backcolor>.Value)
If TypeOf c Is TextBox Then
tbx = CType(c, TextBox)
tbx.ReadOnly = True
tbx.Multiline = True
tbx.ScrollBars = ScrollBars.Vertical
End If
Catch ex As Exception
'Try/Catch is required here, as this code will cause
' a runtime error if the XElement is missing fields
' or the type cannot be created.
tbx = New TextBox
tbx.Text = ex.ToString
tbx.Multiline = True
tbx.Height = 100
tbx.ReadOnly = True
tbx.ScrollBars = ScrollBars.Vertical
c = tbx
End Try
Return c
End Function
It's type safe, does the same thign and is much much safer, hence easier because the IDE helps you write it !! ;)
Hi Bill,
I was referring to the first example, it is much easier that way. And BTW, I find doing multiple casts all the time everywhere in my code to be a major PITA. And when I don't know the types how can that be done anyways without late binding. Point taken on returning the control. I will update to return object and then we could expand on our form example to not add objects to the UI if they weren't controls.
BTW, I was wrong about CallByName, it works in VB 8 with simple type conversions. It won't work however, with Color in the above example. I'll post a follow up with some simple properties that are read and set dynamically. Hopefully that will satisfy you a teeny bit more. :-)
In a previous post I showed how we could dynamically create a UI based on some XML, however the properties
So I decided to post a summary of all the content the VB team members, including myself, have created
|
http://blogs.msdn.com/bethmassi/archive/2007/07/17/an-example-of-dynamic-programming-in-vb.aspx
|
crawl-002
|
refinedweb
| 3,657
| 62.38
|
Hi all,
As described in a previous thread (" mod_python session trouble") I've
had some problems with the sessions. Now there is some progress, though
not really great...
My website is run from a set of python scripts, serving up different
pages, pretty much all from psp templates. To keep track of the user,
I'm using a session (for current session info) and a more persistent
cookie for longer term storage called "basic".
Now what I found:
- the homepage is run from "main.py", together with a few other pages.
Within these pages the session is passed on nicely, and if that doesn't
work, the "basic" cookie is accessed for the information.
- main.py contains a function (get_session(req)) to read the session,
and if expires read the cookie. Works nicely. Returns the session.
Except:
- when calling "req.session main.get_session(req)" from my script
user.py (via a hyperlink in the homepage) I get all kinds of errors,
that are not consequent! Sometimes it complains it can not find the very
function, another time it complains about unbound variables in this
function, sometimes it runs and returns a session. Reloading the
homepage and then moving to one of the subpages served by the other
script (user.py).
- when trying to read the cookies from user.py, I can not get my
original cookies. The session appears to be new all the time
(req.session.is_new returns "True"), and I can not read by "basic"
cookie that is happily visible from functions that are in main.py. As a
result I can not read the user's session settings, nor their defaults,
and the script falls back to system defaults.
I've also done some testing, and here a small script showing part of the
strange behaviour.
When starting up the very first time, you have no cookies (makes sense),
and "language" is set to system default "en". However if you start
switching it through the links, the language is NOT saved in the
session, nor a "basic" cookie is set at all. This cookie is supposed to
be set in the home function, to store the current user settings for
later use.
----------------- BEGIN test.py
from mod_python import Cookie
from mod_python import Session
import time
def home (req):
req.content_type = "text/html; charset=utf-8"
username = ""
if not hasattr(req, "session"):
req.session = get_session(req)
language = req.session["language"]
req.write("home got language: "+language+"<br>")
# update the cookie on the user's side
value = {"language": language, "username": username}
Cookie.add_cookie(req,
Cookie.MarshalCookie("basic", value, "gezellig",
expires = time.time() +
7776000 # 90 days
))
req.write("Language switcher: <a href=./en>en</a> <a
href=./cn>cn</a><br>")
def en(req):
if not hasattr(req, "session"):
req.session = get_session(req)
req.session["language"] = "en"
req.session.save()
home(req)
return
def cn(req):
if not hasattr(req, "session"):
req.session = get_session(req)
req.session["language"] = "cn"
req.session.save()
home(req)
return
def get_session(req):
# gets the current session, checks if complete, if not reads
defaults from
# the cookies.
sess = Session.Session(req)
req.content_type = "text/html; charset=utf-8"
# read user's settings from their cookies
language = "en" # system default
cookies = Cookie.get_cookies(req, Cookie.MarshalCookie,
secret = "gezellig")
req.write("found cookies: "+str(cookies)+"<br>")
if cookies.has_key("basic"):
# the basic info is stored in a cookie named "basic"
basiccookie = cookies["basic"]
if type(basiccookie) is Cookie.MarshalCookie:
try:
language = basiccookie.value["language"]
except:
pass
req.write("get_session got language: "+language+"<br>")
sess["language"] = language
return sess
-------------------------- END test.py
Wouter.
|
https://modpython.org/pipermail/mod_python/2005-May/018073.html
|
CC-MAIN-2022-21
|
refinedweb
| 595
| 60.11
|
The canonical way to return multiple values in languages that support it is often tupling.
Consider this trivial example:
def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0, y1, y2)
However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.
The next logical step seems to be to introduce some sort of 'record notation'. In Python, the obvious way to do this is by means of a
dict.
Consider the following:
def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0': y0, 'y1': y1 ,'y2': y2}
(Just to be clear, y0, y1, and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers.)
Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,
result['y0']
However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:
class ReturnValue: def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2)
In Python the previous two are perhaps very similar in terms of plumbing - after all
{ y0, y1, y2 } just end up being entries in the internal
__dict__ of the
ReturnValue.
There is one additional feature provided by Python though for tiny objects, the
__slots__ attribute. The class could be expressed as:
class ReturnValue(object): __slots__ = ["y0", "y1", "y2"] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2
From the Python Reference Manual:
The
__slots__declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because
__dict__is not created for each instance.
Using Python 3.7's new dataclasses, return a class with automatically added special methods, typing and other useful tools:
@dataclass class Returnvalue: y0: int y1: float y3: int def total_cost(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2)
Another suggestion which I'd overlooked comes from Bill the Lizard:
def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result
This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be.
A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are mutable, whereas tuples are not.
I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.
After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?
I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents.
On the other hand, there are some in the Python community that feel implied interfaces should be preferred to explicit interfaces, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning.
So, how do -you- return multiple values in Python?
Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.
>>> import collections >>> Point = collections.namedtuple('Point', ['x', 'y']) >>> p = Point(1, y=2) >>> p.x, p.y 1 2 >>> p[0], p[1] 1 2
In recent versions of Python 3 (3.6+, I think), the new
typing library got the
NamedTuple class to make named tuples easier to create and more powerful. Inheriting from
typing.NamedTuple lets you use docstrings, default values, and type annotations.
Example (From the docs):
class Employee(NamedTuple): # inherit from collections.NamedTuple name: str id: int = 3 # default value employee = Employee('Guido') assert employee.id == 3
|
https://pythonpedia.com/en/knowledge-base/354883/how-do-i-return-multiple-values-from-a-function-
|
CC-MAIN-2020-29
|
refinedweb
| 793
| 65.22
|
Opened 7 years ago
Closed 7 years ago
Last modified 4 years ago
#10992 closed (fixed)
Unable to re-save inlines with custom char primary key
Description
Define a simple models.py like this one:
from django.db import models class Master(models.Model): codice = models.CharField( primary_key=True, max_length=30, ) class Detail(models.Model): codice = models.CharField( primary_key=True, max_length=30, ) fk = models.ForeignKey(Master)
And an admin.py like this one:
from django.contrib import admin from models import Master, Detail class DetailInline(admin.TabularInline): model = Detail class MasterAdmin(admin.ModelAdmin): inlines = [DetailInline,] admin.site.register(Master, MasterAdmin)
Create and save a Master record with a Detail inline record.
Reopen the Master record, try to save it again.
Bang!
AttributeError at /admin/pluto/master/test/ 'unicode' object has no attribute 'pk' Exception Location: C:\work\esempio\lib\django\forms\models.py in save_existing_objects, line 521
I fixed it changing line 521:
try: pk_value = form.fields[pk_name].clean(raw_pk_value).pk except AttributeError: pk_value = form.fields[pk_name].clean(raw_pk_value)
Attachments (3)
Change History (15)
comment:1 Changed 7 years ago by russellm
- milestone set to 1.1
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted
comment:2 Changed 7 years ago by marcob
Russell, sorry for not having attached a patch, but the fix "runs" only with an Attribute Error Exception. So it's impossible it can break other cases.
You have to substitute line 521 with this 4 lines:
try: pk_value = form.fields[pk_name].clean(raw_pk_value).pk except AttributeError: pk_value = form.fields[pk_name].clean(raw_pk_value)
Btw I do agree this is a workaround. We need to fix clean (with charfield it doesn't return the instance).
comment:3 Changed 7 years ago by russellm
Apologies Marco - I misread your suggestion as just removing the .pk portion. However, you are correct - this is a workaround, not a solution.
comment:4 Changed 7 years ago by anonymous
- Owner changed from nobody to anonymous
- Status changed from new to assigned
comment:5 Changed 7 years ago by zain
- Owner changed from anonymous to zain
- Status changed from assigned to new
comment:6 Changed 7 years ago by zain
- Status changed from new to assigned
comment:7 Changed 7 years ago by zain
- Has patch set
When the pk isn't explicitly specified in the model, it is rendered with a ModelChoiceAdmin field. But when it is explicitly specified, it's rendered with the field for the data type of the pk (CharField in this case).
ModelChoiceAdmin's clean() method returns the model object instance, while CharField's clean() method returns a char. Thus the bug.
Fix incoming.
Changed 7 years ago by zain
Tests demonstrating the bug
Changed 7 years ago by zain
Fix for this bug
comment:8 Changed 7 years ago by russellm
- Patch needs improvement set
General approach to this problem looks good, but two problems with the patch:
- It breaks the modeltests.model_formsets unit test suite.
- The patch removes the use of "existing_objects". This exists as an optimization - the call to get_queryset() means that all inline objects can be retrieved with a single SQL statement, whereas the patch changes this so that each inline object requires a independent SQL select.
comment:9 Changed 7 years ago by russellm
comment:10 Changed 7 years ago by zain
- Patch needs improvement unset
Apparently there are cases other than ModelChoiceAdmin where the clean function will return a model instance (as demonstrated by the failing model_formsets test case), so I'm just checking for the existence of a pk attribute and using it if it exists. Also, uncommented your test case.
Changed 7 years ago by zain
comment:11 Changed 7 years ago by jacob
- Resolution set to fixed
- Status changed from assigned to closed
comment:12 Changed 4 years ago by jacob
- milestone 1.1 deleted
Milestone 1.1 deleted
Verified that the problem exists, but the suggested fix doesn't work - it may fix the problem for charfield PK's, but it breaks all other cases (and the test suite verifies this).
|
https://code.djangoproject.com/ticket/10992
|
CC-MAIN-2015-48
|
refinedweb
| 681
| 55.74
|
Decorate HTML docs by adding them classes by theme
Project Description
About Decorate
Decorate takes an HTML and decorates it with style.
Currently it just support Bootstrap, but it is built in order to allow any other framework.
MDL (Material Design Lite) current support is very poor.
How does it work
It parses the HTML, uses a set of rules and creates a new HTML with new classes.
You can say: “Well… I could have done the same by using JavaScript”, and you’d right. But there are some advantages in using it statically:
- It is faster. You have just to run it once.
- It can be used in third parties projects. Forget about the style from now on.
- Avoids the blink while javascript is being applied.
What was it intended for?
I was writting a static test runner, and I decided not to tie it to any style. This was a spin off. Indeed, it could be run as command line…
Usage
Command line
Please, run the help command with -h.
Here you are a basic example:
decorate my.html -t bootstrap -o output
Library
Easy: just import and use it:
from decorate import Decorate decorate = Decorate('bootstrap') with open('my.html') as fd: decorate.apply_to(fd.read(), 'output.html')
Release History
Download Files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/decorate/
|
CC-MAIN-2018-09
|
refinedweb
| 234
| 76.42
|
Even if JavaScript is single-threaded, there can be concurrency issues like race-conditions due to asynchronism. This article aims to tell you how I handled this using mutual exclusion. But first, let’s recall what is a race condition before getting into the problem and telling you how I solved it.
A race condition occurs when multiple processes try to access a same shared resource and at least one of them tries to modify its value. For example, imagine we have a shared value a = 3 and two processes A and B. Imagine process A wants to add 5 to the current value of a whereas process B wants to add 2 to a only if a < 5. Depending on which process executes first, the result won’t be the one expected. If process A executes first, the value of a will be 8 whereas it will be 10 if process B executes first. To avoid race conditions, we use mutual exclusion. I'll talk about it more in detail later in this article.
Now let me explain the issue I had.
One of my project at Theodo consisted in building a NodeJS application that proposed multiple events and contests for its customers. There was also a premium membership feature that allowed users to participate in free events. To participate, users just need to click on the participation button on the event page, and they receive a ticket. Multiple participations to the same event are disallowed by disabling the button after the participation success.
Moreover, there is a security check in the back-end to prevent users with an existing paid order to get another ticket. You can see the simplified code below:
async function participateInFreeEvent(user: User, eventId: number): Promise<void> { const existOrder = await findOrder(eventId, user.id); if (!existOrder) { const order = buildNewOrder(eventId, user.id); createOrder(order.id, eventId, user.id); } }
First, I search in the database for an existing order related to a user and an event. If no order exists, then a new order is created and saved in the database. Otherwise, nothing is done.
However, some people managed to get several tickets by clicking many times quickly on this button. This was a race-condition issue.
The previous condition wasn’t enough. Indeed, even if JavaScript is mono-threaded, it doesn’t prevent race-conditions. When you deal with asynchronous functions, the thread doesn’t block its execution but it either executes the next line that doesn’t depend on the asynchronous call or continues the execution corresponding to a response event. As a result, two different executions can intertwine.
Take the example below: a user makes 2 consecutive requests to the back-end, and suppose he or she has no order corresponding to this event. As JavaScript is mono-threaded, the execution stack will be:
But the execution order of the different lines of the function will be:
findOrder and
createOrder are asynchronous calls since they read and write into the database. As a consequence, the two requests will intertwine. As you can see in the figure above, the second
findOrder is executed right after the one of the first request. Hence, the second evaluation of
!existOrder will be
true since the call has been made before creating an order.
Conclusion: our user will receive 2 tickets.
I had to find a way of locking this part of the code to execute the whole function before allowing another request to execute the same code, and so avoid race-conditions. I did this using mutex, with the async-mutex library (you can install it by running
yarn add async-mutex).
A mutex is a mutual exclusion object which creates a resource that can be shared between multiple threads of a program. The resource can be seen as a lock that only one thread can acquire. If another thread wants to acquire the lock, it has to wait until the lock is released. But beware that the lock should always be released eventually, no matter what happens during the execution. Otherwise, it will lead to deadlocks, and your program will be blocked.
In order not to slow down the purchase of tickets, I used one mutex per user, that I stored in a Map. If the user isn’t mapped to a mutex, a new instance is created in the map using the user id as a key, and then I used the mutex like this :
import { Mutex, MutexInterface } from 'async-mutex'; class PaymentService { private locks : Map<string, MutexInterface>; constructor() { this.locks = new Map(); } public async participateInFreeEvent(user: User, eventId: number): Promise<void> { if (!this.locks.has(user.id)) { this.locks.set(user.id, new Mutex()); } this.locks .get(user.id) .acquire() .then(async (release) => { try { const existOrder = await findOrder(eventId, user.id); if (!existOrder) { const order = buildNewOrder(eventId, user.id); createOrder(order.id, eventId, user.id); } } catch (error) { } finally { release(); } }, ); } }
You can see that with the try-catch-finally block, I ensure that the lock will always be released. Now, the execution will look like the figure below:
This way, a user will only be able to participate once.
Of course, this is not the only way of solving this kind of problem. Transactions are also really helpful in this case.
Also, keep in mind that it solved the problem on a single server instance. If you have multiple servers, then you should use distributed mutex to let all processes know that the lock is acquired.
Web Developer at Theodo
|
https://blog.theodo.com/2019/09/handle-race-conditions-in-nodejs-using-mutex/
|
CC-MAIN-2021-17
|
refinedweb
| 916
| 64.3
|
Hey everyone!
We have a new version of Blender up on the launcher. This is based on Blender 3.1 alpha and includes many bug fixes and a few new features for the USD import and export pipeline!
Major Feature
We now have armature export! You now can export armatures to USD Skel meshes with time sampled animation. This is a great way to get your animations into Omniverse for use with some of our applications such as Machinima!
We also have included custom options to better transition from Blender armatures to USD Skel and to help maintain a hierarchy between formats. Check out the “Fix Skel Roots” and “Root Prim Path” options for more details.
Highlights below:
- Support UDIM textures when importing USD Preview Surface shaders.
- New “Material Name Collision” USD import option, to allow importing materials with duplicate names.
- Added default values for the “Default Prim Path”, “Root Prim Path” and “Material Prim Path” export options.
- If the “Root Prim Path” export option is set, the root path won’t be added if a Blender object matching the root name already exists.
- Now aborting with an error if the root prim, default prim and material prim path export options are not well formed USD paths, to prevent crashes when defining prims.
- Improved warning and error messages during UMM material conversion.
- Support importing USD attributes (string, int, float and vector types) as Blender custom properties.
- Property export improvements: support exporting vector types; provide options for setting the attribute namespace.
- Enable operator presets UI for USD import and export.
- Armature export improvements: fixed bugs causing skeleton bindings to fail; warning if the skinned prim and skeleton are not under a common SkelRoot; new “Fix Skel Root” experimental option to automatically correct invalid SkelRoot hierarchies.
- Importing existing USD Preview Surface shaders as a fallback if importing MDL is selected as an option but the material has no MDL shaders.
- Fixed bug preventing packed textures from being exported when exporting USD Preview Surface shaders.
- Fixed bug preventing USD Preview Surface textures from being imported in some cases.
|
https://forums.developer.nvidia.com/t/blender-3-1-0-alpha-on-launcher/198148
|
CC-MAIN-2022-21
|
refinedweb
| 345
| 54.93
|
Download presentation
Presentation is loading. Please wait.
Published byKylee Wayland Modified over 2 years ago
1
I/O Management and Disk Scheduling (Chapter 11) Perhaps the messiest aspect of operating system design is input/output A wide variety of devices and many different applications of those devices. It is difficult to develop a general, consistent solution. Chapter Summary –I/O devices –Organization of the I/O functions –Operating system design issue for I/O –I/O buffering –Disk I/O scheduling –Disk Caching
2
I/O Devices External devices that engage in I/O with computer systems can be roughly grouped into three categories: Human readable: Suitable for communicating with the computer user. Examples include video display terminals, consisting of display, keyboard, mouse, and printers. Machine readable: Suitable for communicating with electronic equipment. Examples are disk and tape drives, sensors, controller, and actuators. Communication: Suitable for communicating with remote devices. Examples are digital line drivers and modems.
3
Differences across classes of I/O Data rate: Refer to Figure 11.1 Application: The use to which a device is put has an influence on the software and policies in the O.S. and supporting utilities. For example: –A disk used for file requires the support of file- management software. –A disk used as a backing store for pages in a virtual memory scheme depends on the use of virtual memory hardware and software. –A terminal can be used by the system administrator or regular user. These use imply different levels of privilege and priority in the O.S.
4
Differences across classes of I/O (continue) Complexity of control: A printer requires a relatively simple control interface. A disk is much more complex. Unit of transfer: Data may be transferred as a stream of bytes or characters or in large blocks. Data representation: Different data-encoding schemes are used by different devices, includes differences in character code and parity conventions. Error conditions: The nature of errors, the way in which they are reported, their consequences, and the available range of responses differ widely from one device to another.
5
Organization of the I/O Function Programmed I/O: The processor issues an I/O command on behalf of a process to an I/O module; that process then busy-waits for the operation to be complete before proceeding. Interrupt-driven I/O: The processor issues an I/O command on behalf of a process, continues to execute subsequent instructions, and is interrupted by the I/O module when the latter has completed its work. The subsequent instructions may be in the same process if it is not necessary for that process to wait for the completion of the I/O. Otherwise, the process is suspended pending the interrupt, and other work is performed. Direct memory access (DMA): A DMA module controls the exchange of data between main memory and an I/O module. The processor sends a request for the transfer of a block of data to the DMA module and is interrupted only after the entire block has been transferred.
6
The Evolution of the I/O Function The processor directly controls a peripheral device. This is seen in simple microprocessor-controlled devices. A controller or I/O module is added. The processor uses programmed I/O without interrupts. With this steps, the processor becomes somewhat divorced from the specific details of external device interfaces. The same configuration as step 2 is used, but now interrupts are employed. The processor need not spend time waiting for an I/O operation to be performed, thus increasing efficiency. The I/O modules is given direct control of memory through DMA. It can now move a block of data to or from memory without involving the processor, except at the beginning and end of the transfer.
7
The Evolution of the I/O Function (continue) The I/O module is enhanced to become a separate processor with a specialized instruction set tailored for I/O. The central processor unit (CPU) directs the I/O processor to execute an I/O program in main memory. The I/O processor fetches and executes these instructions without CPU intervention. This allows the CPU to specify a sequence of I/O activities and to be interrupted only when the entire sequence has been performed. The I/O module has a local memory of its own and is, in fact, a computer in its own right. With this architecture, a large set of I/O devices can be controlled with minimal CPU involvement. A common use for such an architecture has been to control communications with interactive terminals. The I/O processor takes care of most of the tasks involved in controlling the terminals.
8
Operating System Design Issues Design Objectives: Efficiency and Generality Efficiency –I/O is always the bottleneck of the system –I/O devices are slow –Use multi-programming (process1 put on wait and process2 go to work) –Main memory limitation => all process in main memory waiting for I/O –Virtual memory => partially loaded processes, swapping on demand –The design of I/O for greater efficiency: Disk I/O hardware & scheduling policies Generality –simplicity & freedom from error, it is desirable to handle all devices in a uniform manner. –Hide most details and interact through general functions: Read, Write, Open Close, Lock, Unlock.
9
Logical Structure of the I/O Function Logical I/O: Concerned with managing general I/O functions on behalf of user processes, allowing them to deal with the device in terms of a device identifier and simple commands: Open, Close, Read, and Write. Device I/O: The requested operations and data are converted into appropriate sequence of I/O instructions. Buffering techniques may be used to improve use. Scheduling and control: The actual queuing and scheduling of I/O operations occurs at this level. Directory management: Symbolic file names are converted to identifiers. This level also concerned about user operations that affect the directory of files, such as Add, Delete, and Reorganize File system: Deals with logical structures of files. Open, Close, Read, Write. Access rights are handled in this level. Physical organization: References to files are converted to physical secondary storage addresses, taking into account the physical track and sector structure of file. Allocation of secondary storage space and main storage buffer is handled in this level.
10
I/O Buffering Objective: To improve system performance Methods: –To perform input transfer in advance of the requests being made; –To perform output transfer some time after the request is made; Two types of I/O devices –Block-oriented: Store information in blocks that are usually of a fixed size. Transfer are made a block at a time. –Stream-oriented: Transfer data in and out as a stream of bytes. There is no block structure. Examples are terminals, printers, communication ports, mouse, other pointing devices.
11
Process, main memory and I/O device Program Data Process1 Main memory I/O device Transfer data block I/O request (read) Program Data Process1 Main memory I/O device Transfer data block I/O request (write) Reading and writing a data block from and to an I/O device may cause single process deadlock. When the process invoke an I/O request, the process will be blocked on this I/O event and can be swapped out of the main memory. However, before the I/O device issue the transfer and the process is swapped out, a deadlock occurs. Solution to this problem is to have a buffer in the main memory. Reading a data block from an I/O deviceWriting a data block to an I/O device
12
The utility of Buffering Buffering is a technique that smoothes out peaks in I/O demand. No amount of buffering will allow an I/O device to keep pace indefinitely with a process when the average demand of the process is greater than the I/O device can service. All buffers will eventually fill up and the process will have to wait after processing each block of data. In a multiprogramming environment, when there is a variety of I/O activity and a variety of process activity to service, buffering is one of the tool that can increase the efficiency of the OS and the performance of individual processes.
13
Disk I/O The speed of processors and main memory has far outstripped that of disk access. The disk is about four order of magnitude slower than main memory. Disk Performance Parameters: –Seek time Seek time is the time required to move the disk arm to the required track. Seek time consists of two components: the initial startup and the time taken to traverse the cylinders that have to be crossed once the access arm is up to speed. The traverse time is not a linear function of the number of tracks. Ts = m X n + s where Ts = seek time, n = # of tracks traversed, m is a constant depends on the disk drive, and s = startup time.
14
Disk I/O (continue) –Rotational delay Disks, other than floppy disks, rotate at 5400 to rpm, which is one revolution per 11.1msec to 6 msec. On the average, the rotational delay will be 3 msec for a 10000rpm HD. Floppy disks rotate much more slowly, between 300 and 600 rpm. The average delay for floppy will then be between 100 and 200 msec. –Data transfer time Data transfer time depends on the rotation speed of the disk. T = b / (r X N) where T = Data transfer time, b = # of bytes to be transferred, N = # of bytes on a track, r = rotation speed in revolution per second. –Total average access time can be expressed as –Taccess = Ts + 1/2r + b/rN where Ts is the seek time.
15
A Timing Comparison Consider a typical disk with a seek time of 10 msec with 1000rpm, and 512- byte sectors with 320 sectors per track. Suppose that we wish to read a file consisting of 2560 sectors for a total of 1.3 Mbyte. What is the total time for the transfer? Sequential organization –The file is on 8 adjacent tracks: 8 tracks X 320 sectors/track = 2560 sectors –Time to read the first track: seek time: 10 msec rotation delay: 3 msec read a track (320 sectors): 6 msec time needed: 19 msec –The remaining tracks can now be read with essentially no seek time. –Since it need to deal with rotational delay for each succeeding track, each successive track is read in = 9 msec. –Total transfer time = X 9 = 82 msec = sec.
16
A Timing Comparison (continue) –Random access (the sectors are distributed randomly over the disk) For each sector: –seek time: 10 msec –rotational delay: 3 msec –read 1 sector: msec –time needed for reading 1 sector: msec Total transfer time = 2560 X = 33,328 msec = sec! –It is clear that the order in which sectors are read from the disk has a tremendous effect on I/O performance. –There are ways to control over the data / sector placement for a file. –However, the OS has to deal with multiple I/O requests competing for the same files. –Thus, it is important to study the disk scheduling policies.
17
Disk Scheduling Policies Referring to Table 11.3, there are a number of disk scheduling policies: Selection according to the requestor –RSS – Random scheduling (For analysis & simulation) –FIFO – First in first out (Fairest of them all) –PRI – Priority by process (Control outside the disk queue management) –LIFO – Last in first out (Max. locality and resource utilization) Selection according to requested item –SSTF – Shortest service time first (High utilization, small queues) –SCAN – Back & forth over the disk (Better service distribution) –C-SCAN – One way with fast return (Lower service variability) –N-step-SCAN – SCAN of N records at a time (Service guarantee) –FSCAN – N-step-SCAN with N = queue size at beginning of SCAN cycle (Load sensitive)
18
RAID (Disk Array) RAID –Redundant Array of Independent Disks –Redundant Array of Inexpensive Disks (Original from Berkeley) The RAID scheme consists of 7 levels (Level0 – Level6) Three common characteristics of the RAID scheme –1. RAID is a set of physical disk drives viewed by the operating system as a single logical drive –2. Data are distributed across the physical drives of an array –3. Redundant disk capacity is used to store parity information, which guarantees data recoverability in case of a disk failure
19
RAID (Disk Array) continue For details about the design, please refer to the following pages, Tables, and Figures. –Reading materials: Text Book, pp –Table 11.4 for the summary of the RAID Levels –Figures 11.9a and 11.9b for the implementation of a RAID device at various levels. Supplementary materials for parity check and hamming code are listed below for implementing RAID levels 2 & 3.
20
Error Detection and Error Correction msblsbparity msblsbparity Transmit: msblsbparity If Received: msblsbparity If Received: Parity-check = m7+m6+m5+m4+m3+m2+m1+parity-bit Parity Check: 7 data bit, 1 parity bit check for detecting single bit or odd number of error. For example, parity bit = m7 + m6 + m5 + m4 + m3 + m2 + m1 = 0
21
Error Correction (Hamming Code) Hamming code (3, 1) –if 0, we send 000, if 1, we send 111. –For error patterns: 001, 010, 100, it will change 000 to 001, 010, 100, or change 111 to 110, 101, 011 –Hence if this code is used to do error correction, all single errors can be corrected. But double errors (error patterns 110, 101, 011) cannot be corrected. However, these double error can be detected). –Hamming code in general (3,1), (7, 4), (15, 11), (31, 26),... –Why can hamming code correct single error? Each message bit position (including the hamming code) is checked by some parity bits. If single error occurs, that implies some parity bits will be wrong. The collection of parity bits indicate the position of error. –How many parity bit is needed? –2 r >= (m + r + 1) where m = number of message bits; r = number of parity bit, and the 1 is for no error.
22
Hamming Codes (Examples) Hamming code (7, 4) P P P1 Hamming code (15, 11) P P P P1
23
Hamming Code (continue..) Assume m message bits, and r parity bits, the total number of bits to be transmitted is (m + r). A single error can occur in any of the (m + r) position, and the parity bit should also be include the case when there is no error. Therefore, we have 2 r >= (m + r + 1). As an example, we are sending the string 0110, where m = 4, hence, we need 3 bits for parity check. The message to be sent is: m 7 m 6 m 5 P 4 m 3 P 2 P 1 where m 7 =0, m 6 =1, m 5 =1, and m 3 =0. Compute the value of the parity bits by: P 1 = m 7 + m 5 + m 3 = 1 P 2 = m 7 + m 6 + m 3 = 1 P 4 = m 7 + m 6 + m 5 = 0 Hence, the message to be sent is
24
Hamming Code (continue..) Say for example, if during the transmission, an error has occurred at position 6 from the right, the receiving message will now become To detect and correct the error, compute the followings: For P 1, compute m 7 + m 5 + m 3 + P 1 = 0 For P 2, compute m 7 + m 6 + m 3 + P 2 = 1 For P 4, compute m 7 + m 6 + m 5 + P 4 = 1 If (P 4 P 2 P 1 = 0) then there is no error else P 4 P 2 P 1 will indicate the position of error. With P 4 P 2 P 1 = 110, we know that position 6 is in error. To correct the error, we change the bit at the 6th position from the right from 0 to 1. That is the string is changed from to and get back the original message 0110 from the data bits m 7 m 6 m 5 m 3.
Similar presentations
© 2016 SlidePlayer.com Inc.
|
http://slideplayer.com/slide/1517286/
|
CC-MAIN-2016-50
|
refinedweb
| 2,697
| 59.53
|
# Collision detection and drawing omitted. # clock.tick returns the time that has passed since the last frame. dt = clock.tick(60) / 1000 # / 1000 to convert it to seconds. Risposto il 10/01/2018 a 11:14 2018-01-10 11:14 share
Sakshi epaper ap
import os import random import pygame ... for wall in walls: pygame. draw ... pygame collision ...
Math minor umich
Chapter 2: Advanced Python Functions Writing better structured code. Previously, if we wanted to carry out actions twice or (even!) three times in a row, we would use loops to do that or if-statements to select which parts of the code to execute in what cases.
The monopolistically competitive seller maximizes profit by producing at the point where_
Pygame provides sprites and sprite groups that help for collision detection. It is that the process when two objects on the screen collide each other. The Sprite module contains the varied simple classes to be used within the games. It's optional to use Sprite classes and different group classes when using pygame.
1973 aluminum penny weight
Pygame Sprite and Collision detection. ...
Flux mp17 price
May 24, 2020 · The Pygame library really made life a lot simpler, so first of all you have to install pygame. If you do not have pip installed I strongly recommend you do it. ... the wall_collision return true ...
|
https://skdif.ksiazkapapiernozyce.pl/pygame-wall-collision.html
|
CC-MAIN-2021-04
|
refinedweb
| 224
| 66.44
|
How to use FC to make a sub-component for FlexHandycam Jun 12, 2009 11:58 AM
Most of the examples and tutorials I've seen so far assume you are creating the app itself in FC.
However, what I need to do is create a custom component that will be a "screen" in a large Flex app, like a page in a Wizard.
So if I was doing this without FC, I'd make a new mxml component in Flex, e.g. "WizardStep.mxml" and then in the main app,
<mx:ViewStack>
<h:WizardStep
<h:WizardStep
</mx:ViewStack>
For example, assuming I have set up the namespace "h" to like "com.handycam.*"
How would I accomplish this scenario if "WizardStep" is what I have been building in FC?
1. Re: How to use FC to make a sub-component for FlexTerl2424 Jun 15, 2009 10:51 AM (in response to Handycam)
I think this is something we need, as well as a way to do iterative design on existing components that have already been imported to flex.
As a UX designer I need to be able to make changes at any point in the development process, and would prefer to make them myself, rather than pass them to developer and try and communicate the visual intent.
2. Re: How to use FC to make a sub-component for Flexbruce_adobe
Jun 16, 2009 10:05 AM (in response to Handycam)
I think the basic feature you need is "Export Library Package". This will export a .fxpl file that my be imported into Flash Builder.
When the fxpl is imported, it becomes a "library project" in Flash Builder.
To export a component from Catalyst:
- create your custom component (or other component).
- Open the Library panel.
- Right click on the the component in the Library panel.
- From the context menu, select "export library package".
-bruce
3. Re: How to use FC to make a sub-component for FlexHandycam Jun 16, 2009 10:26 AM (in response to bruce_adobe)
Thanks. The export part is easy to figure out. It's the import part that
is hanging me up.
when I import the fxpl file, it does indeed create a library project. I go
to properties on my main project, add that to the library paths.
But then, all I have access to is the parts of my FC project: the buttons,
scrollbars, etc. completely out of context. That is, there is no access to
the layout and/or actions I constructed in FC.
4. Re: How to use FC to make a sub-component for Flexbruce_adobe
Jun 16, 2009 10:53 AM (in response to Handycam)
I'm not entirely sure what you want to do. Could you tell me more?
5. Re: How to use FC to make a sub-component for FlexHandycam Jun 16, 2009 11:07 AM (in response to bruce_adobe)
I have an application that uses multiple screens.
Typically, I would create MXML components, lay them out, put the items on them i need. Then the main application instantiates them as needed, as in:
<com:MyViewScreen />
So, what I am trying to do is use FC to create such a sub-screen, in the example above "MyViewScreen.mxml".
In a typical scenario, let's say MyViewScreen.mxml is a panel component and has some labels, buttons, menu, scrollbars, an image, etc. etc. I can easily create such a screen in FC (or in AI and bring it into FC).
But so far I see only two options:
1. Bring it in as an FXP, which creates a Flex project. If I add this project to the source path of the main project, I can access the screen I made, but all its components are broken and it throws errors on build (e.g. "no such component Button1").
2. Bring it as an FXPL which creates a library project. If I add this to the Library path of the main application, I do not have access to the screen I just created in FC. I only have access to the screen's individual parts, such as Button1.mxml, Thumb2.mxml, etc.
So how can I create an MXML component to use in a larger project?
Make sense?
6. Re: How to use FC to make a sub-component for Flexmarc_hughes Jun 16, 2009 11:33 AM (in response to Handycam)
I was playing around with some of these ideas a couple weeks ago and came up with a workable solution that lets me use sub-components from FC in a FB project like you want. You can read that and see a code example here:
The ruby script that generates a swc probably isn't the best way to go, I've since figured out how to do that without using external scripts. I'll blog about that eventually.
Also, the trick is to select everything and "Convert to generic component" before you start actually working. Then do your work in catalyst inside that new component.
7. Re: How to use FC to make a sub-component for Flexbruce_adobe
Jun 16, 2009 11:41 AM (in response to Handycam)
OK - I get it now.
As the guy on the Flash Builder forum told you, there are two basic ways to do what you want: The "easy" way and the "hard" way.
The easy way is to make your entire "page" or "screen" as a single custom component in Catalyst. If you do this, you will end up with a Catalyst project that, at the top level, contains just one page/state, and an single component.
Your one "screen component" will in turn contain many other component (buttons, sliders, other custome components, etc...
The steps for doing this might be:
- create a new Catalyst project.
- Draw a single "screen sized" rectangle on the artboard (say 800X600).
- Use the "convert to custom component" command to turn your rectanagle into a custom component.
- double click on the custom component to edit it.
- In the component edit context, add all your sub-components, interactions, etc...
- When you are done, exit the component edit context to get back to the main application.
- save the top level "screen" component to an FXPL.
I think this will accomplish what you want.
The "hard" way to do this is to make your "screen" as a top level Catalyst project (application) rather than as a custom component. If you do this, you can save as FXP and try to bring multiple FXPs into Flash Builder and combine them all.
As you discovered, it is not trivial to do this. It is of course possible, as you have all of the source files sitting inside of Flash Builder. "All" you have to do is figure out how to move them around and fix up all the code. I agree with you that this is not easy to do!
If you try the "easy" method, above, you will be using the products more or less as designed. You will then be able to re-import an updated version of your screen into Flash Builder without re-doing everything.
- Bruce
8. Re: How to use FC to make a sub-component for FlexHandycam Jun 16, 2009 12:12 PM (in response to bruce_adobe)
The "custom component" idea is stellar, thanks.
9. Re: How to use FC to make a sub-component for Flexbruce_adobe
Jun 16, 2009 12:58 PM (in response to Handycam)
I'm glad that works for you. Let us know how it goes.
Your use case is interesting, in that it's not really a "primary use case" for Caralyst. But it's seems like something more people would want to do.
I'll pass this on to the reast of the team to see if we can come up with a way to make this more intuitive.
- Bruce
10. Re: How to use FC to make a sub-component for FlexMark60015 Jun 21, 2009 10:22 PM (in response to Handycam)
I am also thinking about the idea of using Catalyst to create components that would be integrated in FB rather than building the whole app in Catalyst. I was thinking of the best way to start working with Catalyst and considered taking a recent project where I created a fairly complex visual custom component in FB and try to replicate it in Catalyst to see how the workflow goes and the code looks. While I could probably re-create the whole project in Catalyst, that would be a pretty agressive first step. So one more vote for this idea of "sub-components", with a further suggestion- a artboard size based on a hbox or vbox for components that expand in one of those directions.
11. Re: How to use FC to make a sub-component for FlexHandycam Jun 22, 2009 4:01 AM (in response to Mark60015)
I agree.
Even though it's not a "primary use case", I personally think if would be foolish to ignore this workflow option. Since the main method of styling components in FB4 is via skinning, and this can get complicated, a tool like FC would make the process fast and easier.
I would venture to say that more shops would use it that way than the way described in the advertising videos for it.
12. Re: How to use FC to make a sub-component for FlexMorphicBen Jun 23, 2009 10:54 AM (in response to Handycam)
I've been working with FC for a couple of days now and I think I got an intermediate process for going back and forth between FC and FB: s-and-hacks/
I've been basically using FC to create "skins" for my components that I've built in Flash Builder. I've found that this method lets me re import the FC project into my FB multiple times as the design of the application evolves.
It's not perfect, and I really hope Adobe fleshes out Catalyst more to where natively it isn't just used for prototyping.
13. Re: How to use FC to make a sub-component for FlexMorphicBen Jun 24, 2009 11:17 AM (in response to MorphicBen)
I agree with you sentiment about the "hackish" quality of trying to get FC to better integrate with FB. I know a great deal of hassle could be removed by giving us the ability to specify "id" attributes for the components you create in FC as well as to be able actually create a Spark Skin component instead of a generic Group component.
I would think those two things would be easy enough to implement.
14. Re: How to use FC to make a sub-component for FlexHandycam Jun 24, 2009 11:45 AM (in response to MorphicBen)
Agreed. I do like your ideas, though. Clever solutions, and quickly done
too. Nice work.
15. Re: How to use FC to make a sub-component for Flexnat.b Jul 14, 2009 8:43 AM (in response to Handycam)
I have an existing mixed Flex3/FlashCS4 project. I have tried Flash Catalyst
for a week now and would like to continue using it in preference to Flash Pro.
My problem:
In Flex I have a ViewStack. Each button on the LinkBar controls an animation:
<mx:Canvas
source="
@Embed(source='insets/aPan1-nlog.swf')" />
</mx:Canvas>
I want to replace the .swf-file with the output from FC. I'm trying this with the
Flash Builder beta, using 3.4 because I have Halo-based components.
Compiling as .swf and importing to FB doesn't work (new Flex libraries?)
I've followed the cookbook instructions (Thank you, Bruce !!) for creating
an FC custom component and have imported the .fxpl file into FB.
What I can't figure out is how to get the .fxpl content to replace the
mx:Image provided content. Can someone please tell me either
how to do it or that I'm going about it completely ***-backwards.
Sorry to bother you with a "for dummies"-type question, but I'm a non-coder
and if I can't get this solved, I'll (sadly) have to go back Flash.
TIA
16. Re: How to use FC to make a sub-component for Flexnjadobe2
Jul 14, 2009 11:49 AM (in response to nat.b)
Hi squiddil,
Unfortunately, you can't directly use the code output by FC in a Flex 3 app, since FC outputs Flex 4 code. Flex 4 does include all the Flex 3 ("Halo") components, so it's not that hard to convert a Flex 3 app to a Flex 4 app, but it does require some fiddling.
However, your original idea of including the FC output SWF in your Flex 3 app should be workable. The one thing you might need to do is to add loadForCompatibility="true" to your <mx:Image> tag (actually, you should probably be using SWFLoader instead of Image, but either one should work). That should make it so the Flex 3 app can properly load the Flex 4 app as a sub-SWF.
Let me know if this works for you.
Thanks,
nj
17. Re: How to use FC to make a sub-component for Flexnat.b Jul 14, 2009 3:06 PM (in response to Handycam)
Thanks for your answer!
Unfortunately it still doesn't work.
In FC I used the file menu item "publish as swf" ( or however it's called in English -
I'm also struggling with the -unwanted- German workspace terms). This generated
the deploy-to-web and run-local folders. In Flex3, I imported haupt.swf (=main.swf)
from the run-local folder.
When I use the imported file in the Image tag with the
loadForCompatibily attribute set to "true",the application compiles,
opens the IE, the remaining LinkBar buttons are not affected - they
show/run the Flash Pro .swfs and their controls,
but the attempt to access the .swf in question produces:
VerifyError: Error #1053: Illegal override of z in mx.core.UIComponent.
at flash.display::MovieClip/nextFrame()
at mx.managers::SystemManager/deferredNextFrame()[C:\autobuild\3.2.0\frameworks\projects\fra mework\src\mx\managers\SystemManager.as:319]
at mx.managers::SystemManager/preloader_initProgressHandler()[C:\autobuild\3.2.0\frameworks\ projects\framework\src\mx\managers\SystemManager.as:2945]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.preloaders::Preloader/timerHandler()[C:\autobuild\3.2.0\frameworks\projects\framework\ src\mx\preloaders\Preloader.as:398]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
The alternative approach:
source="
insets/haupt.swf"/>
produces:
VerifyError: Error #1014: Class flash.text.engine::TextLine could not be found.
at global$init()
If I code the SWFLoader tag as:
<mx:SWFLoader x="3" y="35" width="970" height="425" loadForCompatibility="true"
source="
@Embed(source='insets/Haupt.swf')"/>
I get the same errors as I did for the Image tag approach.
Hope this helps.
18. Re: How to use FC to make a sub-component for Flexnat.b Jul 18, 2009 5:50 AM (in response to njadobe2)
Hi nj,
I posted to the list, so I don't know if you saw my reply or if I've maybe just fallen
off the radar.
My project is to create a website with visualizations of security processes - these
don't need fluttering butterflies or seascapes, but they do need a lot of boxes,
interfaces, arrows and the like. What started out as .svg has become Flex/Flash
being used as a web-based (=platform independent) PowerPoint on steroids.
Data-driven demos will be a follow-up project.
As indicated in my original post, I was disappointed but not surprised that
FC/Flex3 didn't mesh. The results of retrying were as I posted in the meantime.
When I tried Flex3beta, I created the project indicating the 3.4 SDK due to Halo
components. I used Bruce's instructions for creating an FC component. If I import
this .fxpl file as a flex project, I see the component. If I import as a flex library project,
I see the component and its' parts - in both cases in the lib under the scr in the
package explorer. I also see, in the components window, FlashComponent and
FlashContainer Placeholders (drag'n'drop). Searching the Flex Help gives no
returns for how to use these components and I haven't found a way to associate
them with the imported items.
I don't know what's in the pipeline for FC or just how Adobe sees the produkt
linkup working. I think what I want to do should be do-able (and fairly easy
if one just clicks the right options).
I'm uploading my Flex src-folder and would be tremendously super grateful
if someone could look at it and tell me what approach I should follow.
I think trying to retrofit it all in FC would be a no-go.
Sorry to be a bother, but I really would like to stay with FlashCatalyst!
19. Re: How to use FC to make a sub-component for Flexnat.b Jul 18, 2009 6:09 AM (in response to nat.b)
Zip didn't make it - Individual files attached
-
- aPan2-nopw.swf 29.8 K
20. Re: How to use FC to make a sub-component for Flexnat.b Jul 18, 2009 6:15 AM (in response to nat.b)
... and mxml file renamed to text
- sqlInj_4_prelim.text 7.4 K
- tPan9-close.swf 4.5 K
- tPan4-notes.swf 7.9 K
21. Re: How to use FC to make a sub-component for Flexacath Jul 20, 2009 9:47 AM (in response to nat.b)
Hi Squiddli,
I think the main issue is that you will only be able to use components create in Catalyst if you use the Flex 4 SDK (3.4 != 4) in Flex Builder, and run the SWF in Flash Player 10.
Before I send detailed instructions, there are 2 ways to do this:
Use Flex Builder 3 with the Flex 4 SDK (which not really supported, but works).
Use Flash Builder 4 beta and import your Flex 3 project. This will be easier and work better. Are you willing to do it this way? If so...do you have it installed yet?
-Adam
22. Re: How to use FC to make a sub-component for Flexnat.b Jul 20, 2009 10:07 AM (in response to acath)
Hi Adam,
Thanks for your reply.
I have the FlashBuilder 4beta installed, use Flash Player 10 and have suceeded in
turning a Flash Catalyst "application" into a "component" for importing.
I would like to go the second route - I think it's better to progress with the products,
but I'm not a coder (other than declarative syntaxes) and not very fit with the rather
extensive project framework surrounding Flex.
My other concern is that I presently make use of Halo components and probably
wouldn't know how to access them under-the-hood in Flash Builder 4.
TIA,
Natalie
23. Re: How to use FC to make a sub-component for Flexacath Jul 20, 2009 10:33 AM (in response to nat.b)
Hi Natalie,
So, just to be totally clear, let me try to reiterate your situation:
You have Flash Builder 4 Beta 1 installed.
You have Flash Catalyst Beta 1 installed.
You've imported components from Catalyst to Builder successfully, in a Flex 4 project.
You would now like to import components from Catalyst to Builder in a Flex 3 project.
You aren't an ActionScript coder.
Is that all right?
-Adam
24. Re: How to use FC to make a sub-component for Flexnat.b Jul 20, 2009 11:21 AM (in response to acath)
Hi Adam,
Almost there. Installs and Action Script - as you say.
I have an existing Flex3/Flash project. I want to reimplement my Flash stuff
in Catalyst, but not reimplement my Flex part at this point.
When I first opened the Flash Builder 4beta, all I saw were Spark Classes and
no Halo, which I use for full-html-page, auto-gradient background and the application
VBox-ed for resizability, using States with scaling factors.
I have a ViewStack, with the buttons on the LinkBar controlling canvases. Up till now,
each canvas gets filled-in with it's own .swf file, using the <mx:image> tag.
I then created a second project in FlashBuilder 4, but with the option "use 3.4.SDK".
I imported the Catalyst component (first as flash-project, then flash-library-project)
but couldn't drag the new component onto the canvas or find any way of associating
it with the new Flash component/container placeholders.
So what I need is - how best to integrate, preferrably with FB4.
What I'm missing is:
- how to get get the previous .swfs/now components to be displayable
- how to continue using Halo under Flash Builder 4
( nj said this was doable, but required some fiddling)
- alternatively, how to replace Halo "coding" with the equivalents,
without landing in a very long learning curve.
Natalie
25. Re: How to use FC to make a sub-component for FlexPeter Flynn (Adobe)
Jul 20, 2009 2:25 PM (in response to nat.b)
Hi Natalie,
You'll definitely want to use the Flex 4 SDK -- Catalyst components require Flex 4, and loading them in a separate SWF in a compatibility sandbox is a hack that would probably just prove confusing or frustrating.
You can use Flex 3 (Halo) components in your Flash Builder project even if you have the SDK set to Flex 4. However, they are hidden by default if Builder thinks there is a "better" alternative component in Flex 4. To see all the Halo components:
- In Design view, in the Components panel, click the triangle in the upper-right corner and uncheck Only Show Recommended Components
- In Code view, when you are looking in the code hints (autocomplete) popup, you'll see a little note at the bottom that says "Recommended - Press Ctrl+Space to show All." If you press Ctrl+Space, the list will expand to include Halo components that were originally hidden.
But bear in mind that if FB is hiding components, it probably thinks there is a better alternative in Flex 4. For example, you can use VGroup instead of VBox.
Hope that helps,
- Peter
26. Re: How to use FC to make a sub-component for Flexnat.b Jul 20, 2009 3:03 PM (in response to Peter Flynn (Adobe))
Hi, Peter,
First of all my sincere apologies to you folks at Adobe and all the forum members!!
From the Catalyst Videos, it wasn't at all clear to me that FB/Flex 4 wasn't just
Flex 3 with some add-ons, otherwise I wouldn't have started on the Catalyst
adventure. Having come this far though, I would like to see it through.
Since Adam pointed me to FB4 means the SDK-4 only, I've experimented some.
Am I doing this right:
use create: new Flex Project,
then import: the .fxpl from the file system ?
This does get me a component, which I can drag onto the application.
When I import a second component in the same way, it shows up in the package
explorer (libs) but not in the components tree or components window,
so I'm still doing something wrong it seems.
After that, I need to get the custom components rehoused in containers, right?
I'm assuming the ViewStack "logic" will not have changed much.
Thanks very much for the Halo info - that looks easy enough once you know how -
and that will give me time to put off getting to the FB4 new features until somewhat later.
I've previously asked if there's any training material available yet for FB4,
but not gotten a response?
Thanks for your help and your patience - at least you can see that I'm a Catalyst convert!
Natalie
27. Re: How to use FC to make a sub-component for Flexacath Jul 21, 2009 11:24 AM (in response to nat.b)
Assuming you already have the FXPL file, here's how you create a project that uses ViewStacks and your FXPL file:
1. File > New > Flex Project
2. Type a name ("Foo").
3. Make sure the Flex SDK Version is set to 4.0.
4. Hit "Finish".
5. You will go into a code editor. Switch to design view (click the "Design" button).
6. If you want to insert a view stack, go to the Components panel, find the Navigators category, and drag a ViewStack onto the canvas.
7. Now it's time to import your FXPL. Choose "File > Import Flex Project".
8. Navigate to your FXPL and import it.
9. This will create a new project. In the Package Explorer, drag the whole "components" package from the new project (which will have the same name as your FXPL) to the src folder of the "Foo" project.
10. The src folder of "Foo" should now have Foo.mxml as well as all the MXML files from your FXPL. It's time to insert your component into Foo.mxml. Here's the tricky part: this depends on the component you create in Catalyst.
If your component is a Custom Component (NOT a Button, Scrollbar, etc):
1. In the Components panel, open the "Custom" category. You should see your component in there. Drag it onto the canvas. Fin.
If your component is a skin (Button, Scrollbar, etc):
1. You have to do this in code. Switch to code view and find the place where you want to insert your component (e.g. inside the view stack).
2. Type this code: <s:Button, where MyButton is the name of the MXML file in the components package that is your skin.
3. Switch to design view. You should see your component. Fin.
Let me know if it works...
-Adam
28. Re: How to use FC to make a sub-component for Flexnat.b Jul 22, 2009 7:09 AM (in response to acath)
Hello Adam,
Thanks for your detailed answer.
I realize now that I probably got off the track a long time back. Nj's advice that
a Catalyst .swf should run in Flex3 didn't work. With your clarification that I needed
Flex4, I landed in custom components, libraries and project imports, thinking
that was the only possible way to proceed.
I now started over from scratch, generated a Catalyst .swf, did a simple file-system
import into the src tree in the Flex4 packet explorer, and I can reference it with an
<mx:image> or swf loader tag just as I've done in the past in Flex3. I don't know
if this practice is frowned upon, but it's easy, clear-cut, and the application runs.
That's the good news.
Since then I've spent some time looking closer at Flex4 itsef plus articles from the
Flex DevCenter and I stumbled across a Flex3/Flex4 compatibility matrix. While
I can't do ActionScript coding (beyond boilerplate timeline functions in FlashPro),
I can follw the Flex4 namespace usage and look up which attributes are supported
for which tags/classes.
The bad news is - between the spark classes and the new states architecture,
it seems almost none of my Flex3 framework will work in Flex4. What's worse is
I can't see any simple-to-do workarounds for the lost defaults and automatic
features from Flex3.
I find Flash Catalyst much more logically structured than Flash Pro.
It's quick and easy enough for rapid prototpying/iterative refinement - a great help in
talking with my scientists about vizualizations - where saying "storyboard" is a no-no!
Now I can just rough-it-in on the spot.
Nevertheless, I have a supervisor, who'd probably let me use and adapt with
Flash Catalyst even as a beta-level, but would draw the line at my delving deeply into
Flex4/ActionScript. So it's starting to look more and more like back to Flash Pro/Flex3
for my personal situation.
Thanks again for the help! If you'd feel this might be a part of a general problem and
would like to continue the discussion, would it perhaps be possible to do so outside
the forum? - I already feel quite guilty for the time I've taken up.
Natalie
29. Re: How to use FC to make a sub-component for FlexMarkSDesign Oct 30, 2010 10:39 AM (in response to Handycam)
I think this IS the primary use case and PRIMARY workflow for product. Designer prototyping with states doesn't scale with any real world application. States are too messy. The primary use case for enterprise is the designer creating skins for custom components that can be "round tripped" into Catalyst at any point in the developement cycle.
|
https://forums.adobe.com/message/2107096
|
CC-MAIN-2018-13
|
refinedweb
| 4,817
| 72.26
|
- Advertisement
gharen2Member
Content Count687
Joined
Last visited
Community Reputation520 Good
About gharen2
- RankAdvanced Member
Wankers
gharen2 commented on __Homer__'s blog entry in __Homer__'s JournalWhy are you guys still feeding this troll?
- Regarding camera controls: You apply matrices to your shader with code along the lines of DXEffect.GetVariableByName(name).AsMatrix().SetMatrix(someMatrix); . In your shader code, you have a matrix defined with a certain name, and that applies the value you want to it. I can't really go into a lot more detail, it sounds as if you really need to look up some tutorials. Shaders are somewhat complicated to get into at first, but god, I love them. The fine degree of control they give over everything is amazing. Regarding your comment about Device.ImmediateContext.Rasterizer.State, I haven't used Direct3D11 yet so can't help you with that one. The API of Direct3D10 and 11 are pretty much identical, but 11 lacks some high level features I don't feel like implementing, and I don't have a directx 11 capable video card anyways. Here's my recommendation: check out XNA if you haven't already. It sounds right up your alley. It has the simpler .net-esque api you want and is a LOT quicker to get into. It still requires that you use shaders, but it provides a basic one with lighting effects and such, so you won't need to worry about learning much about them right away. I avoid XNA nowadays because I always feel it's forcing me into a particular design paradigm and I prefer having a finer degree of control, but these are personal preferences and I otherwise highly recommend it.
- 1) The most important difference to know is that Direct3D 10 and 11 lack the fixed function pipeline. That means that many things that were previously done for you have to be done in shaders. You've encountered the first example of this: you have to pass the matrices to your shaders. 2) Another difference is that states are now set in bunches. So for example, you set all of the rasterizer states at once with Device.Rasterizer.State. Lighting is another fixed function pipeline feature that you need to implement in shaders 3) Look up InputElement. I'm working with Direc3D 10 for the first time, and I love it. However, you're going to find SlimDX documentation and samples for it limited. Fortunately, it's not so bad because the SlimDX api is deliberately close to the native API, so it's trivial to look at c++ code.
- Thanks, I can't believe I didn't think to try that. Interestingly enough, the sprite is visible if I use Matrix.OrthoLH instead of OrthoOffCenterLH. Why, I'm not sure. And even though the sprite is visible, the behavior doesn't match what I read in tutorials (specifically the sprite section of Beginning DirectX 10 Game Programming). For example, with the projection matrix set to OrthoLH(800, 600, -1, 1), the viewport set to (0,0,800,600, 0,1) and the transformation matrix set to (Matrix.Scaling(100, 100, 1) * Matrix.Translation(400, 300, 0)), the sprite should appear in the middle of the screen, but appears at the extreme upper right. The size of the sprite seems correct, while the position is not. Time for further experimentation. edit: using Matrix.OrthoOffCenterLH(0, 800, -600, 0, -10, 10); produces working results. The origin is the upper left, and the sprite moves down by decreasing Y in the world transformation, and moves left by increasing X. This works fine, but doesn't match the behavior I expected from my readings. Oh well, it works.
- Bumped for going onto the second page without even getting a view...
SlimDX, DirectX 10 sprite woes.
gharen2 posted a topic in Graphics and GPU ProgrammingI'm fairly familiar with graphics programming, but am trying out directx 10 for the first time and can't figure this one out. I just can't get a sprite to be visible. I've compared my code to countless tutorials and snippets. I've fiddled with the projection and world matrices to no end. Using the debug runtimes gives the warning "[1032] D3D10: WARNING: ID3D10Buffer::SetPrivateData: Existing private data of same name with different size found! [ STATE_SETTING WARNING #55: SETPRIVATEDATA_CHANGINGPARAMS ]" when the sprite object is created, but from what google has shown me this warning seems to be pretty common when the sprite is created and rendering still works. I have the feeling I'm missing something really obvious. If anyone can spot what I'm missing I'd greatly appreciate it. PS: Yes I understand the evil that is Application.DoEvents. using System; using System.Drawing; using System.Windows.Forms; using SlimDX; using SlimDX.Direct3D10; using SlimDX.DXGI; using Device = SlimDX.Direct3D10.Device; namespace SpriteTest { class Program { static void Main(string[] args) { var form = new Form(); form.ClientSize = new Size(800, 600); form.Show(); var swapChainDescription = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(800, 600, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Device device; SwapChain swapChain; Device.CreateWithSwapChain(null, DriverType.Hardware, DeviceCreationFlags.None, swapChainDescription, out device, out swapChain); var backBuffer = SlimDX.Direct3D10.Texture2D.FromSwapChain<SlimDX.Direct3D10.Texture2D>(swapChain, 0); var renderTarget = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); device.OutputMerger.SetTargets(renderTarget); device.Rasterizer.SetViewports(new Viewport(0, 0, 800, 600, 0, 1)); var textureView = ShaderResourceView.FromFile(device, "testtexture.jpg"); var sprite = new Sprite(device, 100); sprite.ProjectionTransform = Matrix.OrthoOffCenterLH(0, 800, 600, 0, 0, 100); var spriteInstance = new SpriteInstance(textureView, Vector2.Zero, new Vector2(1, 1)); spriteInstance.TextureIndex = 0; spriteInstance.Color = new Color4(1, 1, 1, 1); spriteInstance.Transform = (Matrix.Scaling(100, 100, 1) * Matrix.Translation(100, 100, 10)); var spriteInstances = new SpriteInstance[1]; spriteInstances[0] = spriteInstance; while (form.Created) { device.ClearRenderTargetView(renderTarget, Color.Red); sprite.Begin(SpriteFlags.GroupByTexture); sprite.DrawBuffered(spriteInstances); sprite.Flush(); sprite.End(); swapChain.Present(0, PresentFlags.None); Application.DoEvents(); } sprite.Dispose(); textureView.Dispose(); renderTarget.Dispose(); swapChain.Dispose(); device.Dispose(); } } }
C++ C# interop
gharen2 replied to MoreOpenGL's topic in For Beginners's ForumNo,.
C# physics engines for mono?
gharen2 replied to OffbeatPatriot's topic in Math and PhysicsCheck out Physics2D.net. I don't know for a fact that it works under mono, but from what I remember it doesn't do anything magical that mono wouldn't be able to handle.
Huge 'Warbots Online' Update / Lots of new stuff..
gharen2 commented on dgreen02's blog entry in Radioactive-SoftwareVery, very sexy work. One bit of constructive criticism though: the siege machine looks way too much like the jawa sand crawlers from star wars.
Warbots Update - Nearing the finishline - Lots of Screens
gharen2 commented on dgreen02's blog entry in Radioactive-SoftwareBeautifull as always! The only constructive criticism I can get is that in some of the distance shots, the contrast between the low detail terrain, and the sharp, detailed environment objects like buildings and wind turbines is quite jarring. In those shots the objects don't look like a natural part of the scene, they stick out too much (if that makes any sense at all).
Online Dating
gharen2 replied to Straudos's topic in GDNet LoungeI've occasionally thought of trying online dating. Why? Because I'm very mellow and overly nice, which despite what most women say, is not what most women want. Instead I seem to give off an aura that only draw crazy and/or annoying bitches. Usually women who've been mistreated by men in the past, and who see me as safe. I sympathise with women in that position, but they're always terrible for playing mind games and being extremely insecure about themselves and our relationship. Those are both MASSIVE turn offs for me. So why haven't I tried online dating? I'm TERRIBLE at small talk, so have a hard time going out with someone I just recently met. And a great fear that the service will be populated by the kind of women I just described (which probably isn't true).
QQ: Why do so many people play the race card?
gharen2 replied to Dex Jackson's topic in GDNet LoungeQuote:Original post by Dex Jackson Quote:Original post by Hodgman Wikipedia informs me: Quote:Since fried chicken could keep for several days, longer than other preparations, and traveled well in hot weather before refrigeration was commonplace, it gained further favor in the periods of American history when segregation closed off most restaurants to the black population. It's a lot simpler than that. A LOT SIMPLER. You wanna know what it is? My understanding from talking to american friends is that in some areas.... they really do eat a lot of fried chicken. But that in those same areas, the white people do too (hint: deep south). I like that notion that the stereotype applying only to blacks originated in segregation days, due to deep fried foods ease of preparation and storage. Sounds reasonable, and it wouldn't be the first stereotype I've encountered that had a hint of truth to it.
QQ: Why do so many people play the race card?
gharen2 replied to Dex Jackson's topic in GDNet LoungeQuote:Original post by Sneftel FWIW, I don't think you're racist... just hilariously ignorant. This is very true, I've known plenty of people who I didn't consider truly racist because I consider racism to have an element of hate. But I have met people with some pretty ignorant misconceptions The "all black people eat fried chicken" kind of racism, versus the "I'm afraid of you and/or won't give you a job because you're black" kind of racism.
QQ: Why do so many people play the race card?
gharen2 replied to Dex Jackson's topic in GDNet LoungeIt depends on how much racial tension there is in the area you live. Where I live, race issues come up very infrequently. If I lived in say, Alabama, I might have a different response. edit - I just read your post, Dex Jackson, and I don't consider that "playing the racist card". You were expressing racist attitudes, and he rightfully responded as such. To me, playing the racist card would be if I refused to hire someone of a minority simply because they weren't qualified, and was then accused of racism.
Duke Nukem For-never
gharen2 replied to Promit's topic in GDNet LoungeThis registers pretty low on my care-o-meter. It's just nostalgia that made people look forward to it. I fully expected that if it got released, it was probably going to be yet another generic shooter, that happened to have strippers. And while having strippers in a game was scandalous in the 90s, it's no more scandalous than what I see in any number of games I play today. Duke nukum had a lot that set it apart back then, but what would have set it apart today?
- Advertisement
|
https://www.gamedev.net/profile/116100-gharen2/
|
CC-MAIN-2019-04
|
refinedweb
| 1,851
| 57.06
|
30 July 2009 07:40 [Source: ICIS news]
By Salmon Aidan Lee
SINGAPORE (ICIS news)--The current boom in the Chinese polyester industry is supporting gains in feedstock purified terephthalic acid (PTA) pricing in the past two months, which in turn has pushed up paraxylene (PX) values.
But market participants said they believed the price uptrend was not merely demand-induced but also supply-led.
PTA spot prices hit as high as $950/tonne (€675/tonne) CFR China this week, a steep $70-80/tonne up from last Friday’s close of $870-880/tonne CFR China, according to ICIS pricing.
Just a month ago, PTA values were no more than $830/tonne CFR China, and in early June were still struggling to break above $800/tonne CFR China.
As for PX prices, the gains were almost equally robust. Between mid-June and this week, prices had spiked $170-200/tonne. And between mid-June and early July, PX prices were hovering around $1,000-1,030/tonne CFR China.
“The gains had come well beyond most people’s imagination, frankly we didn’t expect it ourselves either,” said a source from BP, a major producer of PTA in ?xml:namespace>
In fact, PTA producers had been enjoying profits for the most of this year, a departure from the loss-making days between late 2006 and most of 2007-2008.
“It’s obvious that downstream demand is pushing up prices [of PTA], but at the same time, we’re also not producing enough to meet this strong demand,” said a source from Yisheng Petrochemical, a leading Chinese PTA producer.
PTA makers had been cautious with pushing their operating rates to 100% of nameplate capacity, after the losses seen in the past 2-3 years, traders said.
“Yes, we did not produce full this year, as we were so concerned [earlier in the year] that the more you produce, the more losses you’d make,” said a source from a major PTA producer in
Such cautiousness among PTA makers had also compelled them to commit to less feedstock paraxylene (PX) contract volumes.
A rough estimate by traders suggested that most PTA producers had only locked in about 50-60% of their PX needs in contracts this year, setting the stage for the spectacular price gains of both PTA and PX.
“For whatever reasons, the downstream [polyester] market was so bullish, and we found ourselves regularly running out of PTA to sell this year,” said a source from Formosa Chemical & Fiber Corp (FCFC), major PTA maker in
“So we changed our minds and really wanted to have more PX after all, but with outages here and there, and limited PX to begin with, we cannot produce that much PTA,” added the FCFC source.
Those who managed to chase down the PX successfully maintained optimal PTA operating rates, and enjoyed profitability, said a source from Oriental Petrochemical (
“The strong downstream demand pushed up PX prices too naturally, and you know, the [cautiousness] seen among [PTA makers] was also seen among [PX producers],” said a PX broker from
Indeed, PX producers in
As such, they kept low operating rates of no more than 80% on average, and were very careful with their spot sales, said a Korean trader based in Singapore.
“As we all know now, the opposite happened, and PX suppliers were also caught off-guard, and they did not have enough PX to sell to a hungry downstream market,” said another PX broker, based in
Of course, poor returns for refineries since crude oil prices collapsed late last year also contributed to the relatively low PX output, market sources said.
“Refineries are seeing poor returns, so they would not run too high [operating rates], so naturally we see less aromatics in the market,” said a Singapore-based trader representing a Middle-Eastern owned company.
Besides poor refinery returns, lacklustre margins for chief aromatic benzene also hampered aromatics output, said a source from Japan Energy, a leading aromatics producer.
“Benzene margins were very bad earlier this year, so even if we want more PX, even if our customers want more PX, we cannot give them,” added the source.
Hence, to many market watchers, this year’s PTA-PX price trend so far seemed to be a case of misjudgement and wrong calculations.
“I think it’s fair to say most of us got it wrong; we thought prices would collapse but the opposite happened, and nobody is talking about the supposed oversupply [of PTA and PX] now,” said a source from Sam Nam Petrochemical, a leading producer of PTA in Korea.
($1 = €0.71)
For more on PX &
|
http://www.icis.com/Articles/2009/07/30/9236056/polyester-boom-in-china-pushing-up-pta-px-prices.html
|
CC-MAIN-2014-15
|
refinedweb
| 775
| 54.39
|
Sometimes it’s good to look back over history in order to find inspiration, and to see how things have changed over time. Overload started with epilogues rather than introductory editorials, and occasional letters to the editor. If we were to revert to this format, that would let me off the hook. If any readers wish to send a letter to the editor, Overload@accu.org, please feel free. Several of the epilogues had brave prediction or questions about the future. How would namespaces work in C++? C++ is here to stay. Is there anybody brave enough to dismiss OO-COBOL? The first editorial appeared in April 1995. This considered the future directions of Overload and asked ‘When are you lot going to stop messing around with the C++ standard?’ [Overload07] Seventeen years later, it seems the answer might be never. Sean Corfield also asked how many of the readers had email, stating ‘Please use email, where possible, for submissions – I am allergic to paper’ [Overload07]. As I explained last time [Overload111], I am becoming allergic to emails, but articles in an electronic format are certainly easier to deal with than paper ones. How times change. If any readers don’t use email, please write in and tell us what you do with all your spare time.
Eventually paper crumbles away, old documents and code, on paper tape, punch cards, floppy disks and various other types of hard copies become unreadable. Either the medium itself decays, or we lose the means to read or understand the information. Taking a long view, I was struck by a BBC news article about proto-Elamite tablets [Proto-Elamite]; very old clay tablets with scribbles on. Though the clay tablets themselves have survived 5000 years, no-one knows what the inscriptions actually mean. It is suspected they might be some form of early accountancy, as many surviving writings from a similar era and area seems to be. I wonder if one day, no-one will be able to read a pdf or a Sage account. We shall see. Rather than writing our records on clay tablets, nowadays many people choose to write blogs on the internet. I suspect the internet will not disappear for a long time, but I wonder if we will lose these glimpses of the everyday at some point. This might lead to another ‘Dark Age’. Wikipedia describes the Dark Age as ‘a period of intellectual darkness and economic regression that supposedly occurred in Europe’ [Wikipedia]. The main reason seems to be few written records have survived from the time. Perhaps people in Europe were writing their own equivalent of blogs, not in the lingua franca of the time, Latin, and these have decayed away. Imagine that one thousand years from now, a historian tries to gather together evidence of how we live today. Will they find copies of Overload to use as a source? Or a blog? Of course, I am not suggesting I would rather you send articles in on clay tablets, or carved them into hillsides. I just wonder what now might look like, from the future.
Aside from the problem of using perishable storage media, the proto-Elamite tablets show the problem of communication. The Rosetta stone was a lucky find that allowed translation between Greek and Egyptian hieroglyphs [Rosetta]. For the proto-Elamite tablets, without a triangulation point, we may never know what they say. Rosetta code [RosettaCode] plays on the name to provide a rich resource of code challenges implemented in a variety of programming languages, allowing comparison and potentially is a great learning resource. They claim to have a total of 481 different programming languages, which is phenomenal. I wonder if they’ve missed any. How many different programming languages are there? I wonder how many different human languages there are. Recently I have been reading my bible, starting at Genesis and have just reached the story of the tower of Babel. It suggests originally ‘The whole world had one language and a common speech,’ [Genesis 11] but God confuses peoples’ language so they no longer understand one another. Certainly, if you are confronted by a program in a language you don’t know, if may take a while to figure out how it works. Nonetheless, it is still possible to be bemused by a program written in a language you already know. My colleagues have recently written a tool to reverse engineer our config files, though that is another story. We have seen constant debates and considerations of the importance of naming variables and functions sensibly, in order to communicate our intent clearly. At the heart of this is avoiding the confusion of Babel. In August 2008, Ric Parkin’s editorial suggested, developing software is not so much a technical problem as a communication one. [Overload86].
Technology has attempted to make in-roads in to automatic translation between languages to help communication. Various online translators exist, and seem to be improving. I have noticed a few recent news stories about live speech translation, not done by people, but by machines. Specifically, Google Translate has branched out and might now try to translate your spoken words live, presumably allowing you to communicate with colleagues distributed across the world over the phone even if one of you only knows English and the other only Japanese [LiveSpeech]. Had the Dark Ages never happened, and we all still spoke Latin, this wouldn’t be necessary. The live speech has grown from Google’s machine translation technology, which is a computer-driven pattern recognition algorithm, nudged by feedback from users. We shall see if the live translation takes hold. Technologies come and go. Recently, we have seen the death of Ceefax. Started in 1974, before the internet, it gave instant news, TV listing and weather forecasts on a television set capable of reading and displaying the information feed. The Ceefax pages were created manually – people monitored the incoming information and produced metres of punched tape to upload, after being carried up several flights of stairs to the ‘central apparatus room’. We are told, ‘It proved an invaluable service for the editor who used to alert his wife that he was about to leave Television Centre on his way home by using a back page on Ceefax. [Ceefax]
Watching previous technologies starting to grow and the predictions sparked by these is fascinating. I enjoy reading sci-fi, though I do wonder why these stories still tend to insist on the idea of flying cars. Sometimes such auguries are limited by a lack of imagination, and constrained by the current. As an antidote to ridiculous means of transportation, I have been reading The Last Man [Shelly]. Futuristically set at the end of the 21st century, it is free from flying cars. People still use horseback or coach to travel, the English monarchy has only just ceased, and wars are still fought with cannons and swords. The characters and story are played through with more conviction than many sci-fi books though. Heartily recommended for delicious gothic doom and cheer.
It seems that predicting the future is hazardous. “Prediction is difficult, especially about the future.” As either Neils Bohr or Yogi Berra once said: no-one seems to be sure who [BohrYogi]. See, predicting the past is hard enough. Would be traders will spend hours backtesting a new strategy, trying to see if they could make money from the historical data they used to form the strategy in the first place. And even getting the present right is difficult. For example, ‘nowcasting’ the weather is much more difficult than just looking out of the window. "These predictions are very expensive and not available to the public " [Nowcasting1] and, I believe, frequently incorrect. To be fair, nowcasting isn’t trying to state what the weather is up to now, but rather what it will be doing in the very short-range, which does require accurate data on what is happening now, to predict rainfall, paths of tornadoes and so on [Nowcasting2]. The met office gathers a huge amount of data and does some serious high performance computing to analyse it, producing thousands of forecasts a day. A variety of ways of trying to elucidate sense from data about now are constantly springing up. Twitter will tell you which subjects are currently trending, but not to be out-done ‘Massachusetts Institute of Technology (MIT) associate professor Devavrat Shah has announced the creation of a new algorithm that can predict Twitter trends hours in advance. ’ [MIT] That will be hours in advance of twitter noticing, I presume, rather than the tweets actually being tweeted. That really would be something.
Sci-fi stories, along with letters to the editor, epilogues, and occasional stabs at editorials are all attempts to step back, and take stock of the now. They can draw on history, notice current trends, and try to make sense of it all. This is a time consuming activity, and as we have seen is increasingly being opened up to geeks armed with machine-learning algorithms. The next logical step is for the machines to write editorials for us. I have observed some automatic article generators of late. They seem to have started with an automatic Computer Science paper generator, [SCIGen] and sprouted new incarnations, such as a mathematics paper generator [Mathgen]. Some of these papers have been submitted and accepted by peer-reviewed journals [ThatsMaths]. A variant of this code this would get me off the hook. That does not let you, dear reader, off the hook. If you do feel the urge to submit an automatically generated paper, feel free, but rest assured, it will be read by our human review team, and we might just notice. Mind you, if it’s interesting, that is fine. I must stop for now, to brush up on my perl skills, in order to hack around the code from SCIGen and Mathgen, to get off having to write an editorial for next time.
References
[BohrYogi]
[Ceefax]
[Genesis 11]
[LiveSpeech]
[Mathgen]
[MIT]
[Nowcasting1]
[Nowcasting2]
[Overload07]
[Overload86]
[Overload111]
[Proto-Elamite]
[Rosetta]
[RosettaCode]
[SCIGen]
[Shelly] The Last Man, Mary Shelley, 1826.
[ThatsMaths]
[Wikipedia]
|
https://accu.org/index.php/journals/1879
|
CC-MAIN-2017-13
|
refinedweb
| 1,694
| 62.48
|
This document is part of the Driver Development Kit tutorial documentation.
Overview
In this chapter, we're going to learn about the fundamentals of drivers. We'll progress from simple through to moderately complex, with each driver illustrating a specific set of concepts as follows:
dev/misc/demo-null and
dev/misc/demo-zero:
- trivial, "no-state" sink / source drivers, used to explain the basics, like how to handle a client's read() and write() requests.
dev/misc/demo-number:
- a driver that returns an ASCII number, illustrates per-device context, one-shot read() operation, and introduces FIDL-based control operations.
dev/misc/demo-multi:
- a driver with multiple sub-devices.
dev/misc/demo-fifo:
- shows more complex device state, examines partial read() and write() operations, and introduces state signalling to enable blocking I/O.
For reference, the source code for all of these drivers is in the
//examples/drivers/ directory.
A system process called the device manager (
devmgr henceforth) is responsible for device drivers.
During initialization, it searches
/boot/driver and
/system/driver for drivers.
These drivers are implemented as Dynamic Shared Objects (DSOs), and provide
two items of interest:
- a set of instructions for
devmgrto use when evaluating driver binding, and
- a binding function.
Let's look at the bottom of
demo-null.c in the
dev/sample/null directory:
static zx_driver_ops_t demo_null_driver_ops = { .version = DRIVER_OPS_VERSION, .bind = null_bind, }; ZIRCON_DRIVER_BEGIN(demo_null_driver, demo_null_driver_ops, "zircon", "0.1", 1) BI_MATCH_IF(EQ, BIND_PROTOCOL, ZX_PROTOCOL_MISC_PARENT), ZIRCON_DRIVER_END(demo_null_driver)
The C preprocessor macros
ZIRCON_DRIVER_BEGIN and
ZIRCON_DRIVER_END delimit
an ELF note section that's created in the DSO.
This section contains one or more statements that are evaluated by
devmgr.
In the above, the macro
BI_MATCH_IF is a condition that evaluates to
true if
the device has
BIND_PROTOCOL equal to
ZX_PROTOCOL_MISC_PARENT.
A
true evaluation causes
devmgr to then bind the driver, using the binding ops
provided in the
ZIRCON_DRIVER_BEGIN macro.
We can ignore this "glue" for now, and just note that this part of the code:
- tells
devmgrthat this driver can be bound to devices requiring the
ZX_PROTOCOL_MISC_PARENTprotocol, and
- contains a pointer to the
zx_drivers_ops_ttable that lists the functions provided by this DSO.
To initialize the device,
devmgr calls the binding function null_bind()
through the
.bind member (also in
demo-null.c):
static zx_protocol_device_t null_device_ops = { .version = DEVICE_OPS_VERSION, .read = null_read, .write = null_write, }; zx_status_t null_bind(void* ctx, zx_device_t* parent) { device_add_args_t args = { .version = DEVICE_ADD_ARGS_VERSION, .name = "demo-null", .ops = &null_device_ops, }; return device_add(parent, &args, NULL); }
The binding function is responsible for "publishing" the device by calling device_add() with a pointer to the parent device, and an arguments structure.
The new device is bound relative to the parent's pathname — notice how we pass just
"demo-null" in the
.name member above.
The
.ops member is a pointer to a
zx_protocol_device_t structure that lists the operations
available for that device.
We'll see these functions, null_read() and null_write(), below.
After calling device_add(),
the device name is registered, and the operations passed in
the
.ops member of the argument structure are bound to the device.
A successful return from null_bind() indicates to
devmgr that the driver is now
associated with the device.
At this point, our
/dev/misc/demo-null device is ready to handle client requests,
which means that it must:
- support open() and close()
- provide a read() handler that returns end-of-file (EOF) immediately
- provide a write() handler that discards all data sent to it
No other functionality is required.
Reading data from the device
In the
zx_protocol_device_t structure
null_device_ops, we indicated that we support reading
and writing via the functions null_read() and null_write() respectively.
The null_read() function provides reading:
static zx_status_t null_read(void* ctx, void* buf, size_t count, zx_off_t off, size_t* actual) { *actual = 0; return ZX_OK; }
and ends up being called in response to a client's call to read().
Notice that there are two size-related arguments passed to the handler:
The following diagram illustrates the relationship:

That is, the available size of the client's buffer (here,
sizeof(buf)), is passed as the
count
parameter to null_read().
Similarly, when null_read() indicates the number of bytes that it read (0 in our case), this
appears as the return value from the client's read() function.
There are, of course, cases when the device doesn't have data immediately available, AND it's
not an EOF situation.
For example, a serial port may be waiting for more characters to arrive from the remote end.
This is handled by a special notification, which we'll see below, in the
/dev/misc/demo-fifo
device.
Writing data to the device
Writing data from the client to the device is almost identical, and is provided by null_write():
static zx_status_t null_write(void* ctx, const void* buf, size_t count, zx_off_t off, size_t* actual) { *actual = count; return ZX_OK; }
As with the read(), the null_write() is triggered by the client's call to write():

The client specifies the number of bytes they wish to transfer in their write() function, and
this appears as the
count parameter in the device's null_write() function.
It's possible that the device may be full (not in the case of our
/dev/misc/demo-null, though
— it never fills up), so the device needs to tell the client how many bytes it actually
wrote.
This is done via the
actual parameter, which shows up as the return value to the client's
write() function.
Note that our null_write() function includes the code:
*actual = count;
This tells the client that all of their data was written.
Of course, since this is the
/dev/misc/demo-null device, the data doesn't actually go
anywhere.
What about open() and close()?
We didn't provide an open() nor close() handler, and yet our device supports those operations.
This is possible because any operation hooks that are not provided take on defaults. Most of the defaults simply return "not supported," but in the case of open() and close() the defaults provide adequate support for simple devices.
/dev/misc/demo-zero
As you might imagine, the source code for the
/dev/misc/demo-zero device is almost identical
to that for
/dev/misc/demo-null.
From an operational point of view,
/dev/misc/demo-zero is supposed to return an endless stream
of zeros — for as long as the client cares to read.
We don't support writing.
Consider
/dev/misc/demo-zero's zero_read() function:
static zx_status_t zero_read(void* ctx, void* buf, size_t count, zx_off_t off, size_t* actual) { memset(buf, 0, count); *actual = count; return ZX_OK; }
The code sets the entire buffer
buf to zero (the length is given by the client in the
count argument),
and tells the client that that many bytes are available (by setting
*actual to the same number
as the client request).
/dev/misc/demo-number
Let's build a more complicated device, based on the concepts we learned above.
We'll call it
/dev/misc/demo-number, and its job is to return an ASCII string representing
the next number in sequence.
For example, the following might be a typical command-line session using the device:
$ cat /dev/misc/demo-number 0 $ cat /dev/misc/demo-number 1 $ cat /dev/misc/demo-number 2
And so on.
Whereas
/dev/misc/demo-null returned EOF immediately, and
/dev/misc/demo-zero returned
a never-ending stream of zeros,
/dev/misc/demo-number is kind of in the middle: it needs
to return a short data sequence, and then return EOF.
In the real world, the client could read one byte at a time, or it could ask for a large buffer's worth of data. For our initial version, we're going to assume that the client asks for a buffer that's "big enough" to get all the data at once.
This means that we can take a shortcut.
There's an offset parameter (
zx_off_t off) that's passed as the 4th parameter to the read()
handler function:
static zx_status_t number_read(void* ctx, void* buf, size_t count, zx_off_t off, size_t* actual)
This indicates where the client would like to begin (or continue) reading from.
The simplification that we're making here is that if the client has an offset of zero, it means
that it's starting from the beginning, so we return as much data as the client can handle.
However, if the offset isn't zero, we return
EOF.
Let's discuss the code (note that we're initially presenting a slightly simpler version than what's in the source directory):
static int global_counter; // good and bad, see below static zx_status_t number_read(void* ctx, void* buf, size_t count, zx_off_t off, size_t* actual) { // (1) why are we here? if (off == 0) { // (2) first read; return as much data as we can int n = atomic_add(&global_counter); char tmp[22]; // 2^64 is 20 digits + \n + nul = 22 bytes *actual = snprintf(tmp, sizeof(tmp), "%d\n", n); if (*actual > count) { *actual = count; } memcpy(buf, tmp, *actual); } else { // (3) not the first time -- return EOF *actual = 0; } return ZX_OK; }
The first decision we make is in step (1), where we determine if the client is reading the
string for the first time, or not.
If the offset is zero, it's the first time.
In that case, in step (2), we grab a value from
global_counter, put it into a string,
and tell the client that we're returning some number of bytes.
The number of bytes we return is limited to the smaller of:
- the size of the client's buffer (given by
count), or
- the size of the generated string (returned from snprintf()).
If the offset is not zero, however, it means that it's not the first time that the client
is reading data from this device.
In this case, in step (3) we simply set the number of bytes that we're returning (the value
of
*actual) to zero, and this has the effect of indicating
EOF to the client (just like
it did in the
null driver, above).
Globals are bad
The
global_counter that we used was global to the driver.
This means that each and every session that ends up calling number_read() will end up
incrementing that number.
This is expected — after all,
/dev/misc/demo-number's job is to "hand out increasing
numbers to its clients."
What may not be expected is that if the driver is instantiated multiple times (as might happen with real hardware drivers, for example), then the value is shared across those multiple instances. Generally, this isn't what you want for real hardware drivers (because each driver instance is independent).
The solution is to create a "per-device" context block; this context block would contain data that's unique for each device.
In order to create per-device context blocks, we need to adjust our binding routine. Recall that the binding routine is where the association is made between the device and its protocol ops. If we were to create our context block in the binding routine, we'd then be able to use it later on in our read handler:
typedef struct { zx_device_t* zxdev; uint64_t counter; } number_device_t; zx_status_t number_bind(void* ctx, zx_device_t* parent) { // allocate & initialize per-device context block number_device_t* device = calloc(1, sizeof(*device)); if (!device) { return ZX_ERR_NO_MEMORY; } device_add_args_t args = { .version = DEVICE_ADD_ARGS_VERSION, .name = "demo-number", .ops = &number_device_ops, .ctx = device, }; zx_status_t rc = device_add(parent, &args, &device->zxdev); if (rc != ZX_OK) { free(device); } return rc; }
Here we've allocated a context block and stored it in the
ctx member of the
device_add_args_t
structure
args that we passed to device_add().
A unique instance of the context block, created at binding time, is now associated with each
bound device instance, and is available for use in all protocol functions bound by
number_bind().
Note that while we don't use the
zxdev device from the context block, it's good practice
to hang on to it in case we need it for any other device related operations later.

The context block can be used in all protocol functions defined by
number_device_ops, like
our number_read() function:
static zx_status_t number_read(void* ctx, void* buf, size_t count, zx_off_t off, size_t* actual) { if (off == 0) { number_device_t* device = ctx; int n = atomic_fetch_add(&device->counter, 1); //------------------------------------------------ // everything else is the same as previous version //------------------------------------------------ char tmp[22]; // 2^64 is 20 digits + \n + \0 *actual = snprintf(tmp, sizeof(tmp), "%d\n", n); if (*actual > count) { *actual = count; } memcpy(buf, tmp, *actual); } else { *actual = 0; } return ZX_OK; }
Notice how we replaced the original version's
global_counter with the value from the
context block.
Using the context block, each device gets its own, independent counter.
Cleaning up the context
Of course, every time we calloc() something, we're going to have to free() it somewhere.
This is done in our number_release() handler, which we store in our
zx_protocol_device_t
number_device_ops structure:
static zx_protocol_device_t number_device_ops = { // other initializations ... .release = number_release, };
The number_release() function is simply:
static void number_release(void* ctx) { free(ctx); }
The number_release() function is called before the driver is unloaded.
Controlling your device
Sometimes, it's desirable to send a control message to your device.
This is data that doesn't travel over the read() / write() interface.
For example, in
/dev/misc/demo-number, we might want a way to preset the count to a given number.
In a tradition POSIX environment, this is done with an ioctl() call on the client side, and an appropriate ioctl() handler on the driver side.
Under Fuchsia, this is done differently, by marshalling data through the Fuchsia Interface Definition Language (FIDL).
For more details about FIDL itself, consult the reference above. For our purposes here, FIDL:
- is described by a C-like language,
- is used to define the input and output arguments for your control functions,
- generates code for the client and driver side.
If you're already familiar with Google's "Protocol Buffers" then you'll be very comfortable with FIDL.
There are multiple advantages to FIDL. Because the input and output arguments are well-defined, the result is generated code that has strict type safety and checking, on both the client and driver sides. By abstracting the definition of the messages from their implementation, the FIDL code generator can generate code for multiple different languages, without additional work on your part. This is especially useful, for example, when clients require APIs in languages with which you aren't necessarily familiar.
Using FIDL
In the majority of cases, you'll be using FIDL APIs already provided by the device, and will rarely need to create your own. However, it's a good idea to understand the mechanism, end-to-end.
Using FIDL for your device control is simple:
- define your inputs, outputs, and protocols in a "
.fidl" file,
- compile the FIDL code and generate your client functions, and
- add message handlers to your driver to receive control messages.
We'll look at these steps by implementing the "preset counter to value"
control function for our
/dev/misc/demo-number driver.
Define the FIDL protocol
The first thing we need to do is define what the protocol looks like. Since all we want to do is preset the count to a user-specified value, our protocol will be very simple.
This is what the "
.fidl" file looks like:
library zircon.sample.number; [Layout="Simple"] protocol Number { // set the number to a given value SetNumber(uint32 value) -> (uint32 previous); };
The first line,
library zircon.sample.number; provides a name for the library that will
be generated.
[Layout="Simple"] generates simple C bindings.
Finally, the
protocol section defines all of the methods that are available.
Each method has a name, and specifies inputs and outputs.
Here, we have one method function, called SetNumber(), which takes a
uint32 (which is
the FIDL equivalent of the C standard integer
uint32_t type) as input, and returns a
uint32
as the result (the previous value of the counter before it was changed).
We'll see more advanced examples below.
Compile the FIDL code
The FIDL code is compiled automatically by the build system; you just need to add a dependency
into the
BUILD. file.
This is what a stand-alone
rules.mk would look like, assuming the "
.fidl" file is called
demo_number.fidl:
import("$zx/public/gn/fidl.gni") // Defined in $zx/system/fidl/fuchsia-io/BUILD.gn fidl_library("zircon.sample.number") { sources = [ "demo_number.fidl", ] }
Once compiled, the interface files will show up in the build output directory.
The exact path depends on the build target (e.g., ...
/zircon/build-x64/... for x86
64-bit builds), and the source directory containing the FIDL files.
For this example, we'll use the following paths:
- ...
/examples/drivers//number/demo-number.c
- source file for
/dev/misc/demo-numberdriver
- ...
/zircon/system/fidl/zircon-sample/demo_number.fidl
- source file for FIDL protocol definition
- ...
/zircon/build-x64/system/fidl/zircon-sample/gen/include/zircon/sample/number/c/fidl.h
- generated interface definition header include file
It's instructive to see the interface definition header file that was generated by the FIDL compiler. Here it is, annotated and edited slightly to just show the highlights:
// (1) Forward declarations #define zircon_sample_number_NumberSetNumberOrdinal ((uint32_t)0x1) // (2) Extern declarations extern const fidl_type_t zircon_sample_number_NumberSetNumberRequestTable; extern const fidl_type_t zircon_sample_number_NumberSetNumberResponseTable; // (3) Declarations struct zircon_sample_number_NumberSetNumberRequest { fidl_message_header_t hdr; uint32_t value; }; struct zircon_sample_number_NumberSetNumberResponse { fidl_message_header_t hdr; uint32_t result; }; // (4) client binding prototype zx_status_t zircon_sample_number_NumberSetNumber(zx_handle_t _channel, uint32_t value, uint32_t* out_result); // (5) FIDL message ops structure typedef struct zircon_sample_number_Number_ops { zx_status_t (*SetNumber)(void* ctx, uint32_t value, fidl_txn_t* txn); } zircon_sample_number_Number_ops_t; // (6) dispatch prototypes zx_status_t zircon_sample_number_Number_dispatch(void* ctx, fidl_txn_t* txn, fidl_incoming_msg_t* msg, const zircon_sample_number_Number_ops_t* ops); zx_status_t zircon_sample_number_Number_try_dispatch(void* ctx, fidl_txn_t* txn, fidl_incoming_msg_t* msg, const zircon_sample_number_Number_ops_t* ops); // (7) reply prototype zx_status_t zircon_sample_number_NumberSetNumber_reply(fidl_txn_t* _txn, uint32_t result);
Note that this generated file contains code relevant to both the client and the driver.
Briefly, the generated code presents:
- a definition for the command numbers (the "
NumberOrdinal", recall we used command number
1for SetNumber()),
- external definitions of tables (we don't use these),
- declarations for the request and response message formats; these consist of a FIDL overhead header and the data we specified,
- client binding prototypes — we'll see how the client uses this below,
- FIDL message ops structure; this is a list of functions that you supply in the driver to handle each and every FIDL method defined by all the protocols in the "
.fidl" file,
- dispatch prototypes — this is called by our FIDL message handler,
- reply prototype — we call this in our driver when we want to reply to the client.
The client side
Let's start with a tiny, command-line based client, called
set_number,
that uses the above FIDL protocol.
It assumes that the device we're controlling is called
/dev/misc/demo-number.
The program takes exactly one argument — the number to set the current counter to.
Here's a sample of the program's operation:
$ cat /dev/misc/demo-number 0 $ cat /dev/misc/demo-number 1 $ cat /dev/misc/demo-number 2 $ set_number 77 Original value was 3 $ cat /dev/misc/demo-number 77 $ cat /dev/misc/demo-number 78
The complete program is as follows:
#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <ctype.h> #include <zircon/syscalls.h> #include <lib/fdio/fdio.h> // (1) include the generated definition file #include <zircon/sample/number/c/fidl.h> int main(int argc, const char** argv) { static const char* dev = "/dev/misc/demo-number"; // (2) get number from command line if (argc != 2) { fprintf(stderr, "set_number: needs exactly one numeric argument," " the value to set %s to\n", dev); exit(EXIT_FAILURE); } uint32_t n = atoi(argv[1]); // (3) establish file descriptor to device int fd = open(dev, O_RDWR); if (fd == -1) { fprintf(stderr, "set_number: can't open %s for O_RDWR, errno %d (%s)\n", dev, errno, strerror(errno)); exit(EXIT_FAILURE); } // (4) establish handle to FDIO service on device zx_handle_t num; zx_status_t rc; if ((rc = fdio_get_service_handle(fd, &num)) != ZX_OK) { fprintf(stderr, "set_number: can't get fdio service handle, error %d\n", rc); exit(EXIT_FAILURE); } // (5) send FDIO command, get response uint32_t orig; if ((rc = zircon_sample_number_NumberSetNumber(num, n, &orig)) != ZX_OK) { fprintf(stderr, "set_number: can't execute FIDL command to set number, error %d\n", rc); exit(EXIT_FAILURE); } printf("Original value was %d\n", orig); exit(EXIT_SUCCESS); }
This is very similar to the approach taken with POSIX ioctl(), except that:
- we established a handle to the FDIO service (step 4), and
- the API is type-safe and prototyped for the specific operation (step 5).
Notice the FDIO command has a very long name: zircon_sample_number_NumberSetNumber()
(which includes a lot of repetition).
This is a facet of the code generation process from the FIDL compiler — the
"
zircon_sample_number" part came from the "
library zircon.sample.number"
statement, the first "
Number" came from the "
protocol Number" statement, and the final
"
SetNumber" is the name of the method from the protocol definition statement.
Add a message handler to the driver
On the driver side, we need to:
- handle the FIDL message
- demultiplex the message (figure out which control message it is)
- generate a reply
In conjunction with the prototype above, to handle the FIDL control message in our driver we need to bind a message handling function (just like we did in order to handle read(), for example):
static zx_protocol_device_t number_device_ops = { .version = DEVICE_OPS_VERSION, .read = number_read, .release = number_release, .message = number_message, // handle FIDL messages };
The number_message() function is trivial in this case; it simply wraps the dispatch function:
static zircon_sample_number_Number_ops_t number_fidl_ops = { .SetNumber = fidl_SetNumber, }; static zx_status_t number_message(void* ctx, fidl_incoming_msg_t* msg, fidl_txn_t* txn) { zx_status_t status = zircon_sample_number_Number_dispatch(ctx, txn, msg, &number_fidl_ops); return status; }
The generated zircon_sample_number_Number_dispatch() function takes the incoming message
and calls the appropriate handling function based on the provided table of functions in
number_fidl_ops.
Of course, in our trivial example, there is only the one function,
SetNumber:
static zx_status_t fidl_SetNumber(void* ctx, uint32_t value, fidl_txn_t* txn) { number_device_t* device = ctx; int saved = device->counter; device->counter = value; return zircon_sample_number_NumberSetNumber_reply (txn, saved); }
The fidl_SetNumber() handler:
- establishes a pointer to the device context,
- saves the current count value (so that it can return it later),
- sets the new value into the device context, and
- calls the "reply" function to return the value to the client.
Notice that the fidl_SetNumber() function has a prototype that matches the FIDL specification, ensuring type safety. Similarly, the reply function, zircon_sample_number_NumberSetNumber_reply() also conforms to the FIDL specification's prototype of the result portion of the method definition.
Advanced uses
FIDL expressions can certainly be made more complex than what we've shown above.
For example, nested structures can be used, rather than the simple
uint32.
Multiple parameters are allowed for both inputs and outputs. See the
FIDL reference.
Registering multiple devices with
/dev/misc/demo-multi
So far, the devices discussed were "singletons" — that is, one registered name did one thing
(
null manifested the null device,
number manifested the number device, and so on).
What if you have a cluster of devices that all perform similar functions? For example, you might have a multi-channel controller of some kind that has 16 channels.
The correct way to handle this is to:
- create a driver instance,
- create a base device node, and
- manifest your sub-devices under that base device.
Creating the driver instance is good practice as discussed above, in "Globals are bad" (we'll discuss it a little more in this particular context later).
In this example, we're going to create a base device
/dev/misc/demo-multi, and then
we're going to create 16 sub-devices under that called
0 through
15 (e.g.,
/dev/misc/demo-multi/7).
static zx_protocol_device_t multi_device_ops = { .version = DEVICE_OPS_VERSION, .read = multi_read, .release = multi_release, }; static zx_protocol_device_t multi_base_device_ops = { .version = DEVICE_OPS_VERSION, .read = multi_base_read, .release = multi_release, }; zx_status_t multi_bind(void* ctx, zx_device_t* parent) { // (1) allocate & initialize per-device context block multi_root_device_t* device = calloc(1, sizeof(*device)); if (!device) { return ZX_ERR_NO_MEMORY; } device->parent = parent; // (2) set up base device args structure device_add_args_t args = { .version = DEVICE_ADD_ARGS_VERSION, .ops = &multi_base_device_ops, // use base ops initially .name = "demo-multi", .ctx = device, }; // (3) bind base device zx_status_t rc = device_add(parent, &args, &device->base_device.zxdev); if (rc != ZX_OK) { return rc; } // (4) allocate and bind sub-devices args.ops = &multi_device_ops; // switch to sub-device ops for (int i = 0; i < NDEVICES; i++) { char name[ZX_DEVICE_NAME_MAX + 1]; sprintf(name, "%d", i); args.name = name; // change name for each sub-device device->devices[i] = calloc(1, sizeof(*device->devices[i])); if (device->devices[i]) { args.ctx = &device->devices[i]; // store device pointer in context device->devices[i]->devno = i; // store number as part of context rc = device_add(device->base_device.zxdev, &args, &device->devices[i]->zxdev); if (rc != ZX_OK) { free(device->devices[i]); // device "i" failed; free its memory } } else { rc = ZX_ERR_NO_MEMORY; } // (5) failure backout, schedule the removal of the base device and its children // sub-devices. if (rc != ZX_OK) { device_async_remove(device->base_device.zxdev); return rc; } } return rc; } // (6) release the per-device context block static void multi_release(void* ctx) { free(ctx); }
The steps are:
- Establish a device context pointer, in case this driver is loaded multiple times.
- Create and initialize an
argsstructure that we'll pass to device_add(). This structure has the base device name, "
demo-multi", and a context pointer to the multi root device
device.
- Call device_add() to add the base device. This has now created
/dev/misc/demo-multi. Note that we store the newly created device into
base_device.zxdev. This then serves as the "parent" device for the sub-device children.
- Now create 16 sub-devices as children of the base ("parent") device. Notice that we changed the
opsmember to point to the sub-device protocol ops
multi_device_opsinstead of the base version. The name of each sub-device is simply the ASCII representation of the device number. Note that we store the device number index
i(0 .. 15) in
devnoas context (we have an array of contexts called
multi_deviceswhich we'll see shortly). We also illustrate allocating each sub-device dynamically, rather than allocating its space in the parent's structure. This is a more realistic use-case for "hot-plug" devices — you don't want to allocate a large context structure, or perform initialization work, for devices that aren't (yet) present.
- In case of a failure, we need to remove and deallocate the devices that we already added, including the base device and the per-device context block. Note that we release up to, but not including, the failed device index. This is why we called free() on the sub-device structure in step 4 in case of device_add() failure.
- We release the per-device context block in our release handler. Since the base device and 16 sub-devices do not implement unbind hooks, device_async_remove() will invoke the release hooks of the sub-devices, followed by the base device.
Which device is which?
We have two read() functions, multi_read() and multi_base_read(). This allows us to have different behaviors for reading the base device versus reading one of the 16 sub-devices.
The base device read is almost identical to what we saw above in
/dev/misc/demo-number:
static zx_status_t multi_base_read(void* ctx, void* buf, size_t count, zx_off_t off, size_t* actual) { const char* base_name = "base device\n"; if (off == 0) { *actual = strlen(base_name); if (*actual > count) { *actual = count; } memcpy(buf, base_name, *actual); } else { *actual = 0; } return ZX_OK; }
This just returns the string "
base device\n" for the read, up to the maximum
number of bytes allowed by the client, of course.
But the read for the sub-devices needs to know which device it's being called
on behalf of.
We keep a device index, called
devno, in the individual sub-device context block:
typedef struct { zx_device_t* zxdev; int devno; // device number (index) } multidev_t;
The context blocks for the 16 sub-devices, as well as the base device, are stored in the per-device context block created in step (1) of the binding function, above.
// this contains our per-device instance #define NDEVICES 16 typedef struct { zx_device_t* parent; multidev_t* devices[NDEVICES]; // pointers to our 16 sub-devices multidev_t base_device; // our base device } multi_root_device_t;
Notice that the
multi_root_device_t per-device context structure contains 1
multidev_t
context block (for the base device) and 16 pointers to dynamically allocated context
blocks for the sub-devices.
The initialization of those context blocks occurred in steps (3) (for the base device)
and (4) (done in the
for loop for each sub-device).
The diagram above illustrates the relationship between the per-device context block, and the individual devices. Sub-device 7 is representative of all sub-devices.
This is what our multi_read() function looks like:
static const char* devnames[NDEVICES] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", }; static zx_status_t multi_read(void* ctx, void* buf, size_t count, zx_off_t off, size_t* actual) { multi_root_device_t* root_device = ctx; multidev_t* device = &root_device->base_device; if (off == 0) { char tmp[16]; *actual = snprintf(tmp, sizeof(tmp), "%s\n", devnames[device->devno]); if (*actual > count) { *actual = count; } memcpy(buf, tmp, *actual); } else { *actual = 0; } return ZX_OK; }
Exercising our device from the command line gives results like this:
$ cat /dev/misc/demo-multi base device $ cat /dev/misc/demo-multi/7 seven $ cat /dev/misc/demo-multi/13 thirteen
and so on.
Multiple multiple devices
It may seem odd to create a "per device" context block for a controller that
supports multiple devices, but it's really no different than any other controller.
If this were a real hardware device (say a 16 channel data acquisition system),
you could certainly have two or more of these plugged into your system.
Each driver would be given a unique base device name (e.g.
/dev/daq-0,
/dev/daq-1, and so on), and would then manifest its channels under that name
(e.g.,
/dev/daq-1/7 for the 8th channel on the 2nd data acquisition system).
Ideally, the assignment of unique base device names should be done based on some kind of hardware provided unique key. This has the advantage of repeatability / predictability, especially with hot-plug devices. For example, in the data acquisition case, there would be distinct devices connected to each of the controller channels. After a reboot, or a hot unplug / replug event, it would be desirable to be able to associate each controller with a known base device name; it wouldn't be useful to have the device name change randomly between plug / unplug events.
Blocking reads and writes:
/dev/misc/demo-fifo
So far, all of the devices that we've examined returned data immediately (for a read()
operation), or (in the case of
/dev/misc/demo-null), accepted data without blocking
(for the write() operation).
The next device we'll discuss,
/dev/misc/demo-fifo, will return data immediately if
there's data available, otherwise it will block the client until data is available.
Similarly, for writing, it will accept data immediately if there's room, otherwise
it will block the client until room is available.
The individual handlers for reading and writing must return immediately (regardless of whether data or room is available or not). However, they don't have to return or accept data immediately; they can instead indicate to the client that it should wait.
Our FIFO device operates by maintaining a single, 32kbyte FIFO. Clients can read from, and write to, the FIFO, and will exhibit the blocking behavior discussed above during full and empty conditions, as appropriate.
The context structure
The first thing to look at is the context structure:
#define FIFOSIZE 32768 typedef struct { zx_device_t* zxdev; mtx_t lock; uint32_t head; uint32_t tail; char data[FIFOSIZE]; } fifodev_t;
This is a basic circular buffer; data is written to the position indicated by
head
and read from the position indicated by
tail.
If
head == tail then the FIFO is empty, if
head is just before
tail (using wraparound math)
then the FIFO is full, otherwise it has both some data and some room available.
At a high level, the fifo_read() and fifo_write() functions are almost identical, so let's start with the fifo_write():
static zx_status_t fifo_write(void* ctx, const void* buf, size_t len, zx_off_t off, size_t* actual) { // (1) establish context pointer fifodev_t* fifo = ctx; // (2) lock mutex mtx_lock(&fifo->lock); // (3) write as much data as possible size_t n = 0; size_t count; while ((count = fifo_put(fifo, buf, len)) > 0) { len -= count; buf += count; n += count; } if (n) { // (4) wrote something, device is readable device_state_set(fifo->zxdev, DEV_STATE_READABLE); } if (len) { // (5) didn't write everything, device is full device_state_clr(fifo->zxdev, DEV_STATE_WRITABLE); } // (6) release mutex mtx_unlock(&fifo->lock); // (7) inform client of results, possibly blocking it *actual = n; return (n == 0) ? ZX_ERR_SHOULD_WAIT : ZX_OK; }
In step (1), we establish a context pointer to this device instance's context block. Next, we lock the mutex in step (2). This is done because we may have multiple threads in our driver, and we don't want them to interfere with each other.
Buffer management is performed in step (3) — we'll examine the implementation later.
It's important to understand what actions we need to take after step (3):
- If we wrote one or more bytes (as indicated by
nbeing non-zero), we need to mark the device as "readable" (via device_state_set() and
DEV_STATE_READABLE), which is done in step (4). We do this because data is now available.
- If we still have bytes left to write (as indicated by
lenbeing non-zero), we need to mark the device as "not writable" (via device_state_clr() and
DEV_STATE_WRITABLE), which is done in step (5). We know that the FIFO is full because we were not able to write all of our data.
It's possible that we may execute one or both steps (4) and (5) depending
on what happened during the write.
We will always execute at least one of them because
n and
len can never both
be zero.
That would imply an impossible condition where we both didn't write any data (
n, the
total number of bytes transferred, was zero) and simultaneously wrote all of the data
(
len, the remaining number of bytes to transfer, was also zero).
In step (7) is where the decision is made about blocking the client.
If
n is zero, it means that we were not able to write any data.
In that case, we return
ZX_ERR_SHOULD_WAIT.
This return value blocks the client.
The client is unblocked when the device_state_set() function is called in step (2) from the fifo_read() handler:
static zx_status_t fifo_read(void* ctx, void* buf, size_t len, zx_off_t off, size_t* actual) { fifodev_t* fifo = ctx; mtx_lock(&fifo->lock); size_t n = 0; size_t count; while ((count = fifo_get(fifo, buf, len)) > 0) { len -= count; buf += count; n += count; } // (1) same up to here; except read as much as possible if (n) { // (2) read something, device is writable device_state_set(fifo->zxdev, DEV_STATE_WRITABLE); } if (len) { // (3) didn't read everything, device is empty device_state_clr(fifo->zxdev, DEV_STATE_READABLE); } mtx_unlock(&fifo->lock); *actual = n; return (n == 0) ? ZX_ERR_SHOULD_WAIT : ZX_OK; }
The shape of the algorithm is the same as in the writing case, with two differences:
- We're reading data, so call fifo_get() instead of fifo_put()
- The
DEV_STATElogic is complementary: in the writing case we set readable and cleared writable, in the reading case we set writable and clear readable.
Similar to the writing case, after the
while loop we will perform one or both of the
following actions:
- If we read one or more bytes (as indicated by
nbeing non-zero), we need to mark the device as now being writable (we consumed data, so there's now some space free).
- If we still have bytes to read (as indicated by
lenbeing non-zero), we mark the device as empty (we didn't get all of our data, so that must be because we drained the device).
As in the writing case, at least one of the above actions will execute.
In order for neither of them to execute, both
n (the number of bytes read) and
len
(the number of bytes left to read) would have to be zero, implying the impossible,
almost metaphysical condition of having read both nothing and everything at the same time.
An additional subtlety applies here as well. When
nis zero, we must return
ZX_ERR_SHOULD_WAIT— we can't return
ZX_OK. Returning
ZX_OKwith
*actualset to zero indicates EOF, and that's definitely not the case here.
Read and write interaction
As you can see, the read handler is what allows blocked writing clients to unblock, and the write handler is what allows blocked reading clients to unblock.
When a client is blocked (via the
ZX_ERR_SHOULD_WAIT return code), it gets kicked by
the corresponding device_state_set()
function.
This kick causes the client to try their read or write operation again.
Note that there's no guarantee of success for the client after it gets kicked.
We can have multiple readers, for example, waiting for data.
Assume that all of them are now blocked, because the FIFO is empty.
Another client comes along and writes to the FIFO.
This causes the device_state_set()
function to get called with
DEV_STATE_READABLE.
It's possible that one of the clients consumes all of the available data; the
other clients will try to read, but will get
ZX_ERR_SHOULD_WAIT and will block.
Buffer management
As promised, and for completeness, here's a quick examination of the buffer management that's common to both routines. We'll look at the read path (the write path is virtually identical).
In the heart of the read function, we see:
size_t n = 0; size_t count; while ((count = fifo_get(fifo, buf, len)) > 0) { len -= count; buf += count; n += count; }
The three variables,
n,
count, and
len are inter-related.
The total number of bytes transferred is stored in
n.
During each iteration,
count gets the number of bytes transferred, and it's used as the
basis to control the
while loop.
The variable
len indicates the remaining number of bytes to transfer.
Each time through the loop,
len is decreased by the number of bytes transferred, and
n is
correspondingly increased.
Because the FIFO is implemented as a circular buffer, it means that one complete set of data might be located contiguously in the FIFO, or it may wrap-around the end of the FIFO back to the beginning.
The underlying fifo_get() function gets as much data as it can without wrapping.
That's why the
while loop "retries" the operation; to see if it could get
more data possibly due to the
tail wrapping back to the beginning of the buffer.
We'll call fifo_get() between one and three times.
- If the FIFO is empty, we'll call it just once. It will return zero, indicating no data is available.
- We call it twice if the data is contiguously located in the underlying FIFO buffer; the first time to get the data, and the second time will return zero, indicating that no more data is available.
- We'll call it three times if the data is wrapped around in the buffer. Once to get the first part, a second time to get the wrap-around part, and a third time will return zero, indicating that no more data is available.
|
https://fuchsia.dev/fuchsia-src/concepts/drivers/simple
|
CC-MAIN-2021-04
|
refinedweb
| 6,562
| 50.06
|
This is an article on what you need and how to write a serviced component in C# that encapsulates all the intricacies of communicating with the IBM Mainframe.
I was assigned a new project that required to write a COM+ program to enable the clients (mainly Classic ASP and ASP.NET) to synchronize our online user profile with the user store on the IBM Mainframe. Before I started the project, I was surprised to find only a few articles on programming WebSphere MQ in the .NET environment. Therefore, I thought of sharing my work here to help fellow programmers who need to work with IBM Websphere MQ, to save time and headaches.
In order to use and test the code, you need to have IBM WebSphere MQ 5.3 with CSD05 or higher installed. Also install the AMQMDNET.DLL onto the GAC if not already done, by the WebSphere MQ 5.3 installation. Create the Queue Manager, Queue and Channel. You can follow the article Message Queuing by MQSeries with C# by Rosi Reddy to create the necessary WebSphere MQ configuration.
Here are the steps to create the project solution:
System.EnterpriseServices
using
using System.EnterpriseServices; // for ServicedComponent
using System.Runtime.InteropServices; //for Class Interface
using System.Diagnostics; //for Windows Event Logging
using IBM.WMQAX; //for IBM Websphere MQ in .NET
Class1
MQServices
MQPutMessage
MQGetMessage
IMQServices
JustInTimeActivation()
ServicedComponent
public class MQServices : ServicedComponent, IMQServices
Please note that you should replace all the GUIDs both from the MQServices.cs and the AssemblyInfo.cs files to ensure uniqueness. You can generate a new GUID by clicking the Tools menu and selecting Create GUID. Then copy and paste the newly generated GUID for the replacement.
MQServicedCom
That's all. Now you have a serviceable serviced component. To verify it, open up the Component Services Manager. You can find the COM+ application MQ service component library where this title was taken from the AssemblyInfo.cs file's ApplicationName attribute. You can use the TestCom.vbs file to test this newly created and registered serviced component. Good luck and have fun.
ApplicationName
Two books that helped me greatly on writing this Enterprise Serviced components.
|
https://www.codeproject.com/Articles/8685/A-C-Serviced-Component-for-Websphere-MQ
|
CC-MAIN-2017-34
|
refinedweb
| 358
| 60.31
|
The ActionScript Drawing API, introduced in Flash MX, allows you to draw inside movie clips at runtime. The handful of primitive Drawing API methods let you draw almost any imaginable shape, as demonstrated in this chapter's recipes. The Drawing API uses a pen metaphor, akin to a CAD line plotter, in which an imaginary pen is moved around the drawing canvas. The pen's stroke attributes can be customized, and the pen can draw lines or curves. Shapes can be empty or filled. Note that the coordinates are relative to the movie clip's registration point. Use the MovieClip._x and MovieClip._y properties to reposition the entire clip on the Stage.
The Drawing API is a subset of the methods of the MovieClip class, and therefore most of the recipes in this chapter are implemented as custom methods of the MovieClip class. You should add these custom methods to an ActionScript file named DrawingMethods.as (or download the final version from the URL cited in the Preface) and include it in your own projects.
All paths and shapes drawn with the Drawing API are drawn inside the movie clip from which the methods are invoked. For this reason the createEmptyMovieClip( ) method is often used in conjunction with any runtime drawing. The createEmptyMovieClip( ) method does just what its name implies?it creates a new, empty movie clip nested within the movie clip on which it is invoked:
// Create a new movie clip named myMovieClip_mc with a depth of 1 inside of _root. _root.createEmptyMovieClip("myMovieClip_mc", 1);
You can specify the pen style with the MovieClip class's lineStyle( ) method and draw lines and curves with the lineTo( ) and curveTo( ) methods. The pen can be repositioned without drawing anything by calling the moveTo( ) method.
Many of these recipes use the custom Math.degToRad( ) method from Recipe 5.12 to convert angles from degrees to radians. Your DrawingMethods.as file should include Math.as from Chapter 5 by using this statement on the first line:
#include "Math.as"
Also see Recipe 5.13 and Recipe 5.14 for an explanation of how to calculate X and Y coordinates using trigonometry, which is called for in some of this chapter's recipes.
|
http://etutorials.org/Programming/actionscript/Part+I+Local+Recipes/Chapter+4.+Drawing+and+Masking/Introduction/
|
CC-MAIN-2017-04
|
refinedweb
| 370
| 74.69
|
from IPython.display import YouTubeVideo YouTubeVideo('pHMzNW8Agq4')
Last time, we did a bunch of calculus to find the rate of change of our cost, J, with respect to our parameters, W. Although each calculus step was pretty straight forward, it’s still easy to make mistakes. What’s worse, is that our network doesn’t have a good way to tell us that it’s broken – code with incorrectly implemented gradients may appear to be functioning just fine.
This is the most nefarious kind of error when building complex systems. Big, in-your-face errors suck initially, but it’s clear that you must fix this error for your work to succeed. More subtle errors can be more troublesome because they hide in your code and steal hours of your time, slowly degrading performance, while you wonder what the problem is.
A good solution here is to test the gradient computation part of our code, just as developer would unit test new portions of their code. We’ll combine a simple understanding of the derivative with some mild cleverness to perform numerical gradient checking. If our code passes this test, we can be quite confident that we have computed and coded up our gradients correctly.
To get started, let’s quickly review derivatives. Derivates tell us the slope, or how steep a function is. Once you’re familiar with calculus, it’s easy to take for granted the inner workings of the derivative - we just accept that the derivative of x^2 is 2x by the power rule. However, depending on how mean your calculus teacher was, you may have spent months not being taught the power rule, and instead required to compute derivatives using the definition. Taking derivatives this way is a bit tedious, but still important - it provides us a deeper understanding of what a derivative is, and it’s going to help us solve our current problem.
The definition of the derivative is really a glorified slope formula. The numerator gives us the change in y values, while the denominator is convenient way to express the change in x values. By including the limit, we are applying the slope formula across an infinitely small region – it’s like zooming in on our function, until it becomes linear.
The definition tells us to zoom in until our x distance is infinitely small, but computers can’t really handle infinitely small numbers, especially when they’re in the bottom parts of fractions - if we try to plug in something too small, we will quickly lose precision. The good news here is that if we plug in something reasonable small, we can still get surprisingly good numerical estimates of the derivative.
We’ll modify our approach slightly by picking a point in the middle of the interval we would like to test, and call the distance we move in each direction epsilon.
Let’s test our method with a simple function, x squared. We’ll choose a reasonable small value for epsilon, and compute the slope of x^2 at a given point by finding the function value just above and just below our test point. We can then compare our result to our symbolic derivative 2x, at the test point. If the numbers match, we’re in business!
%pylab inline #Import Code from previous videos: from partFour import *
Populating the interactive namespace from numpy and matplotlib
def f(x): return x**2
epsilon = 1e-4 x = 1.5
numericalGradient = (f(x+epsilon)- f(x-epsilon))/(2*epsilon)
numericalGradient, 2*x
(2.9999999999996696, 3.0)
Add helper functions to our neural network class: #Helper Functions for interacting with other classes: def getParams(self): #Get W1 and W2 unrolled into vector: params = np.concatenate((self.W1.ravel(), self.W2.ravel())) return params def setParams(self, params): #Set W1 and W2 using single paramater()))
We can use the same approach to numerically evaluate the gradient of our neural network. It’s a little more complicated this time, since we have 9 gradient values, and we’re interested in the gradient of our cost function. We’ll make things simpler by testing one gradient at a time. We’ll “perturb” each weight - adding epsilon to the current value and computing the cost function, subtracting epsilon from the current value and computing the cost function, and then computing the slope between these two values.
def computeNumericalGradient(N, X, y): paramsInitial = N.getParams() numgrad = np.zeros(paramsInitial.shape) perturb = np.zeros(paramsInitial.shape) e = 1e-4 for p in range(len(paramsInitial)): #Set perturbation vector perturb[p] = e N.setParams(paramsInitial + perturb) loss2 = N.costFunction(X, y) N.setParams(paramsInitial - perturb) loss1 = N.costFunction(X, y) #Compute Numerical Gradient numgrad[p] = (loss2 - loss1) / (2*e) #Return the value we changed to zero: perturb[p] = 0 #Return Params to original value: N.setParams(paramsInitial) return numgrad
We’ll repeat this process across all our weights, and when we’re done we’ll have a numerical gradient vector, with the same number of values as we have weights. It’s this vector we would like to compare to our official gradient calculation. We see that our vectors appear very similar, which is a good sign, but we need to quantify just how similar they are.
NN = Neural_Network()
numgrad = computeNumericalGradient(NN, X, y) numgrad
array([-0.01570145, 0.04553206, 0.02332193, -0.01261438, 0.02962221, 0.02384717, -0.19123277, -0.24006099, -0.09635695])
grad = NN.computeGradients(X,y) grad
array([-0.01570145, 0.04553206, 0.02332193, -0.01261438, 0.02962221, 0.02384717, -0.19123277, -0.24006099, -0.09635695])
A nice way to do this is to divide the norm of the difference by the norm of the sum of the vectors we would like to compare. Typical results should be on the order of 10^-8 or less if you’ve computed your gradient correctly.
norm(grad-numgrad)/norm(grad+numgrad)
2.7533413768397804e-10
And that’s it, we can now check our computations and eliminate gradient errors before they become a problem. Next time we’ll train our Neural Network.
|
https://nbviewer.jupyter.org/github/stephencwelch/Neural-Networks-Demystified/blob/master/Part%205%20Numerical%20Gradient%20Checking.ipynb
|
CC-MAIN-2020-45
|
refinedweb
| 1,013
| 52.8
|
Hi,
I’ve been trying to plot a circle in plotly through a simple graph in python, but the result is an ellipsis instead of a circle. Although the values in the x-axis and y-axis are both correct, the image that appears to me is not a circle, as you can see.
Here’s the code:
import numpy as np import plotly.plotly as py import plotly.graph_objs as go # Polar Coordinates r = 1 theta = np.linspace(0, 2*np.pi, 200) x_circle = 1 + r*np.cos(theta) y_circle = 1 + r*np.sin(theta) # It plots the points of the list outside the circle trace = go.Scatter( x=x_circle, y=y_circle, name='Circle', mode='lines', line=dict( width=1.0, color='rgba(66, 28, 82, 0.9)' ) ) data = [trace] # It sends authentication py.sign_in('*******', '**********') # Intentionally hidden # It plots scatter py.plot(data, filename='basic-scatter')
How can I fix this distortion, so that it appears a circle instead of an ellipsis?
|
https://community.plotly.com/t/distortion-in-axes/5682
|
CC-MAIN-2020-40
|
refinedweb
| 163
| 61.22
|
tag:blogger.com,1999:blog-68323782012-05-25T19:17:03.696+10:00Emarketing Strategy in Australian ReviewAustralian SEO Consulting Services, Website Visibility, Digital Media, Internet BrandingAdvanet WebsitesGoogle can be used to search for specified phrase within a website. In order to do that you need to specify a command: site:URL "keyphrase" For example: site:advanet.blogspot.com "search engine".<br />With other useful command you may discover websites that offer similar content to the ones you already know. You can use this Google search command to find similar sites as well: related:advanet.blogspot.com.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet SEO ValueTwitter has gained huge popularity in last few years. And many ask the question about its SEO value. From Google perceptive <span style="font-weight:bold;">Twitter links</span> <span style="font-weight:bold;">social media tool</span> which creates community and relationships. And implementing social media tools can go a long way in building Internet <span style="font-weight:bold;">brand awareness</span> and raising company profile.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet SEO overratedSome of the customers are getting frustrated and asking: Is SEO overrated? It is probably like asking is recession overrated? It all depends where you live, and how good or bad your finances are. Global <strong>economic downturn</strong> has caused many companies losing their sales. And many of them are cutting down <strong>marketing budgets</strong> to increase cash flow. However without their current spending for search engine marketing, the sales numbers could have been even worse. Also search engine optimisation is still one of the best <strong>strategy to bring traffic to the website</strong> and it deos not requite big marketing budget. <strong>SEO</strong> is not overrated but in some cases it is misunderstood and poorly executed marketing strategy.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet SEO TipsSome may say - there is nothing simple about search engine optimisation. However, whether <strong>SEO is easy or not</strong> really depends on the particular website. In most cases SEO is not difficult as long as sufficient time and effort is invested into the project.<br />1. Create <strong>webpage titles</strong> related to targeted keywords.<br />2. Make your meta description unique for each webpage.<br />3. Use most important <strong>keywords</strong> in webpage name or URL.<br />4. Use cascading style sheets (CSS) rather then tables.<br />5. Add H1 tags preferably towards the top of each webpage.<br />6. Implement breadcrumbs functionality on your website.<br />7. Analyze your targeted keywords using Google suggest.<br />8. Implement the <strong>sitemap</strong> as text links.<br />9. Put CSS and JavaScript into external file.<br />10. Describe your images with the use of the <strong>alt tags</strong>.<br />11. Make sure your site logo alt tag contains your keywords.<br />12. Avoid automatic directory submission.<br />13. Find quality links to your website. Not easy.<br />14. Don't use same anchor text in all your inbound links. <br />15. Use <strong>deep linking</strong> to many webpages on your website.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet and SEOAre there any benefits in <strong>using subdomains</strong> for the purpose of website search optimisation? The answer is yes, but with a few reservations. Subdomain is a domain that is part of a larger domain. For example "serivces.seo.com" is a subdomain of the "seo.com". At present, <strong>maximum two results</strong> <strong>keywords, anchor text, and links</strong>. Know that every page on your site won’t rank for each query, so decide which are the most relevant.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet Engine BiasThe question of search engine bias can be easily verified by examining search results for popular words and phrases. I have performed search for very competitive and frequently searched word <strong>finance</strong> on Google and Yahoo.<br />As I expected Google lists as number one:<br /><strong>Google Finance</strong> <br />Google Finance offers a broad range of information about stocks, mutual funds, public and private companies. In addition, Google Finance offers interactive ... finance.google.com<br />And Yahoo shows in top position... no surpise here:<br /><strong>Yahoo! Finance</strong><br />Free sharemarket information, financial news, glossaries and guides to help you learn about Australian and international markets.<br />au.finance.yahoo.com<br />See if you can find other examples of search engine bias.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet Words PhrasesOne of the leading <span style="font-weight:bold;">web ranking</span> provider RankStat.com reported that most people use two word phrases in search engines. There is also a tendency developing that single word phrases searches are in decline and <span style="font-weight:bold;">multi word phrase searches are becoming most common</span>. Of all search engines world wide, 28.38 percent use 2 word phrases, 27.15 percent use 3 word phrases and 16.42 percent 4 word phrases.<br />The 10 most used word phrases in search engines on the web are:<br /> 1. Two word phrases 28.38 percent<br /> 2. Three word phrases 27.15 percent<br /> 3. Four word phrases 16.42 percent<br /> 4. One word phrase 13.48 percent<br /> 5. Five word phrases 8.03 percent<br /> 6. Six word phrases 3.67 percent<br /> 7. Seven word phrases 1.63 percent<br /> 8. Eight word phrases 0.73 percent<br /> 9. Nine word phrases 0.34 percent<br /> 10. Ten word phrases 0.16 percent<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet in DifficultyMajor online Australian <strong>property portal</strong> <strong>online property</strong> "<strong>property for sale</strong>". Failure to get to top 5 listings as well as usabilty issues had a negative impact on the whole business model.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet Events in 2008If you are looking to learn more about SEO I have a list of upcoming SEO events and search marketing conferences. This year <strong>Search Engine Strategies</strong> will be held on March 17-20, 2008 in New York City. WebmasterWorld's <strong>PubCon</strong> will be in Las Vegas Nevada in later months of 2008. <strong>Ad Tech</strong> online marketing conference is now hosting in 10 cities around the world with the first in Sydney on March 12, 2008. <strong>SXSW Interactive Festival</strong> will take place from March 7 to March 11 in Austin, Texas. Those are the most important shows, but please leave a comment if there are any other SEO events which could be included on this short list.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet SEOThings <strong>Christmas</strong> and just below we can find North Pole <strong>Santa Claus</strong> website as a second result. But I think it will be hard to dismiss Santa Claus which has become very strong tradition. The other news is that we will be able to <a href=""target=_"blank"><strong>track Santa in Google Earth</strong></a> on Christmas Eve in real time.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet Web ContentIn order to combat browser malware installations and make Internet safer, Google is displaying a brief message in the search results next to offending website as follows: <a href=""target=_"blank">This site may harm your computer</a>.: <br /><strong>SEO Consultant - Shimon Sandler Blog SEO Consultant ... </strong><br /><em>This site may harm your computer.</em><br />The SEO Consultant must start with understanding the clients’ business and marketing goals to develop the strategy and approach for a winning SEO campaign. ...<br /> - Similar pages<br />The <strong>question</strong> is that - if Google is a search engine, should it have a role to pass judgement on the websites?<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet and SEOArticle <strong>SEO techniques</strong> when searching for "<a href=""target=_"blank"><b>kitchen cabinets</b></a>" (very popular phrase in this category) her website pops up at the top of Google's very important first page, even ahead of one of the country's largest cabinetmakers, Merillat Industries. The small business website <strong>KitchenCabinetMart.com</strong> went up from few orders to $10,000 in sales per month and Villanueva says that she can hardly keep up with all the inquiries and orders.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet and Search Engines. <br /><strong>The Liberal Party of Australia</strong> <br />Official site of the Liberal Party of Australia. Features news, events, current topics, contact information and links ...<br /><strong>Australian Labor Party</strong><br />HOWARD'S ADVERTISING BLITZ. John Howard is wasting taxpayers' money at record speed. By election day later this year, he will have spent at least $850 ...<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet ConsolidationRecent article in Media section of The Australian has revealed that one of the top SEO companies in Australia - <strong>Found Agency</strong> is due to complete the sale of its business to specialist marketing services <strong>Photon Group Limited</strong> - <strong>Cogentis</strong> to <strong>BlueFreeway Limited</strong>. SEO companies consolidation is a new trend in Australia but it should not come as a surprise since in United States, big Madison Avenue marketing agencies have been buying SEO companies for last few years. For more details see the article:<br> <strong><a href=""target=_"blank">Link kings net rich pickings</a></strong> in The Australian.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet SEO SpeaksOn a recent <a href=""target=_"blank"><strong>SES London</strong></a> conference <strong>Matt Cutts</strong> who is a software engineer and the head of the Google's webspam team has shared his vision for Google in a keynote interview. According to Matt the main theme for Google in years to come will be <strong>personalization and localization</strong>. The ambition is to organize the world information and store data at Google with Gmail and other tools. Matt was also asked about the <strong>spam issue</strong>: – <strong>sneaky java scripts</strong>, techniques that are use help to determine the intent. Measuring how happy users are is important. Spam can be defined as noise, noise from your signal. Off topic spam – you type in your name and get porn. That is not in anybody’s interest. <strong>Cookie cutter sites</strong> that don’t add any value – 50 sites that there’s no diversity. No value add for the customer. There are definitely shades – some are more serious and some less." Matt was also asked about his favorite Non-Google tool. <strong>Yahoo site explorer</strong> was the answer.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet and Public Relations<a href="">John Andrews</a> and <a href="">Todd Malicoat</a> in their recent posts have attempted to describe 16 reasons why people hate SEOs. I think it is very funny insight about what SEOs struggle with on a daily basis. <strong>Expert SEO</strong> <a href=""target=_"blank">16 Reasons People Hate SEOs</a>.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet CommentsThoughtful comments on a subject of the post may <strong>benefit your blog</strong> in more ways than one. If your comment is well-written the blog owner will follow it keenly. Adding questions in comments may enhance the post and start a <strong>longer discussion</strong> which will lead to clarification of the main subject. Your comments will also add <strong>quality back links</strong> to your blog which in turn will make your blog more visible on search engines. By adding comments <strong>bloggers feel encouraged</strong> to continue with their writing. On the other hand authors of nuisance comments know what they are doing. And their strategy never goes a long way, since they will be ignored at best or simply deleted and forgotten.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet SEO WorkshopWe will be presenting an interactive SEO workshop on how to design and update the websites for <strong>search engine visibility</strong>. <strong>SEO tutor</strong> you will learn how to increase your <strong>branding</strong> and competitive advantage on the search engines. At the conclusion the clear SEO strategy will be presented on case by case basis.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet Web UsabilityIn a recent October issue of Government News magazine I have found an article about <strong>usability issues</strong> with respect to government organizations websites in Australia. <strong>Document dumping</strong> seems to be quite a common way of adding and building web pages. The end result is that things are hard to find and there is a lack of website functionally. On a bright side more government departments are conducting <strong>usability studies</strong> <a href=""target=_"blank"><strong>Australian government</strong></a>.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet Bootcamp SydneyThis year Search Engine Boot camp organized in Sydney on 30 November will be dedicated to SEO and SEM topics. The agenda will cover subjects from <strong>intelligent keywords research</strong>, SEO site structure, local search and PPC management tools. The afternoon sessions will focus on advanced SEO about optimising for flash and database driven websites. The case study or rather live interactive <strong>SEO clinic</strong> will have a website analysed for search engine friendliness. For more information visit:<br /><strong></strong><div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet Engine StrategiesLast month <strong>San Jose</strong> was a place to be for all search engine marketing professionals. And they came in thousands to find out about the latest trends in <strong>SEO market</strong>, Internet advertising, search optimization issues and all related areas. <strong>Search Engine Strategies</strong> conference was as usual very loud with bright lights and all the companies trying to outdo each other on the exhibition floor. The big fun moments came as we were invited to Mountain View Googleplex for the Fifth annual <strong>Google Dance</strong> where we had the opportunity to meet with Google engineers and visit Google Labs technology playground area. For more visit the official <a href=""target=_"blank"><strong>SES Strategies</strong></a> website.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet Wide Web OriginsThe <a href=""target=_"blank"><strong>original post</strong></a> he said: "The WorldWideWeb (WWW) project aims <strong>to allow links to be made to any information anywhere</strong>. The address format includes an access method (=namespace), and for most name spaces a hostname and some sort of path. The WWW project was started to allow high energy physicists to share data, news, and documentation. We are very interested in <strong>spreading the web to other areas</strong>, and having gateway servers for other data. Collaborators welcome!" <br />The greatest thing is that his idea is available freely, with no patent and no royalties due, so it keeps spreading like a wild fire.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet about SEOIn."<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet Cup Live SearchDuring the World Cup 2006 Google offers <strong>live scores and live tracking of matches</strong>. To see the results simply type in the names of the countries which play the game. For the latest game being played type in <a href=""target=_"blank"><strong>world cup results</strong></a>. In addition by following the top link <a href=""target=_"blank"></a> Google will show information about the live scores, when it starts, the teams, who scored and videos for each goal duiring the match.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet Contest for CharityThe <strong>SEO contest</strong> has been announced by the webmaster community forum <strong>Webmaster-talk.com</strong>. The keyword phrase for the contest is: "retsambew dash klat for Charity" which means "webmaster dash talk" spelled backwords. The end date is Friday 01 September 2006. To win the website will need <strong>to rank the highest</strong> for a brand new domain and a keyword phrase "retsambew dash klat for Charity" in Google. The total cash value of the prizes is $5,810.30. The contest conditions stipulate that one must use a brand new domain name and the winning page must link to a <strong>charity of your choice</strong> from <strong>Give.org</strong>.<div class="blogger-post-footer"><img width='1' height='1' src='' alt='' /></div>Advanet
|
http://feeds.feedburner.com/AdvanetPtyLtd-EmarketingAustralia
|
crawl-003
|
refinedweb
| 2,887
| 56.66
|
tf-idf Model for Page Ranking in Python
The tf-idf stands for Term frequency-inverse document frequency. It is a weighing schema that measures the frequency of every term in a document of the corpus. These weight vectors in a vector space are then used for information retrieval and text mining. Hence, tf-idf matrix tries to evaluate the importance of the word in a document of the corpus. The different weighting schemes are used for extracting information from the web, in the search engine for scoring, ranking, and retrieving relevant information and displaying the results.
This model has two components:
-> TF (Term Frequency)
-> IDF (Inverse Document Frequency)
tf-idf Model for Page Ranking
Let’s go step by step.
We are creating two documents for simplicity.
docA = "The car is driven on the road" docB = "The truck is driven on the highway"
Now we need to tokenize words. Tokenization is the first step of the preprocessing of the textual data. It creates a list of tokens of the document.
from nltk.tokenize import word_tokenize tokens1 = word_tokenize(docA) tokens2 = word_tokenize(docB)
tokens1, tokens2
output: (['The', 'car', 'is', 'driven', 'on', 'the', 'road'], ['The', 'truck', 'is', 'driven', 'on', 'the', 'highway'])
Secondly, we are creating a function for calculating the frequency of words in each document. This function returns the term frequency and normalized term frequency.
wordset = set(tokens1).union(set(tokens2)) def computeTF(doc): raw_tf = dict.fromkeys(wordset,0) norm_tf = {} bow = len(doc) for word in doc: raw_tf[word]+=1 ##### term frequency for word, count in raw_tf.items(): norm_tf[word] = count / float(bow) ###### Normalized term frequency return raw_tf, norm_tf
The first step to our tf-idf model is calculating the Term Frequency (TF) in the corpus. Corpus is the collection of all the documents.
Term Frequency: It is the frequency of words in each document in the corpus. It is the ratio of the frequency of words and the total number of words in the document.
tf_dictA, norm_tf_dictA = computeTF(tokens1) tf_dictB, norm_tf_dictB = computeTF(tokens2)
print('Term Frquency for doc1\n') print(tf_dictA) print('\n Normalized tf\n') print(norm_tf_dictA)
output: Term Frquency for doc1 {'highway': 0, 'driven': 1, 'The': 1, 'the': 1, 'road': 1, 'truck': 0, 'is': 1, 'car': 1, 'on': 1} Normalized tf {'highway': 0.0, 'driven': 0.14285714285714285, 'The': 0.14285714285714285, 'the': 0.14285714285714285, 'road': 0.14285714285714285, 'truck': 0.0, 'is': 0.14285714285714285, 'car': 0.14285714285714285, 'on': 0.14285714285714285}
The second step is to create Inverse Document Frequency
Inverse Document Frequency (IDF) : TF measures the frequency of words in each document in the corpus, so higher the frequency more important the word but this model doesn’t account for the word that occurs too often. So, IDF is an attenuation effect that scales down the term weights with its collection frequency. The idea is to reduce the TF weights with the factor of collection frequency. Hence it will give the higher weights to the terms which rarely occur.
def computeIdf(doclist): import math idf={} idf = dict.fromkeys(doclist[0].keys(),float(0)) for doc in doclist: for word, val in doc.items(): if val > 0: idf[word] += 1 for word, val in idf.items(): idf[word] = math.log10(len(doclist) / float(val)) return idf
idf = computeIdf([tf_dictA, tf_dictB]) idf
output: {'highway': 0.3010299956639812, 'driven': 0.0, 'The': 0.0, 'the': 0.0, 'road': 0.3010299956639812, 'truck': 0.3010299956639812, 'is': 0.0, 'car': 0.3010299956639812, 'on': 0.0}
And finally, compute the tf-Idf weights of every term in the corpus.
def computeTfidf(norm_tf,idf): tfidf = {} for word , val in norm_tf.items(): tfidf[word] = val*idf[word] return tfidf
tfidfA = computeTfidf(norm_tf_dictA,idf) tfidfB = computeTfidf(norm_tf_dictB,idf) tfidfA
output: {'highway': 0.0, 'driven': 0.0, 'The': 0.0, 'the': 0.0, 'road': 0.043004285094854454, 'truck': 0.0, 'is': 0.0, 'car': 0.043004285094854454, 'on': 0.0}
Now the model is ready for the Page Ranking or other scoring techniques for information retrieval which are relevant.
|
https://www.codespeedy.com/tf-idf-model-for-page-ranking-in-python/
|
CC-MAIN-2021-10
|
refinedweb
| 655
| 61.22
|
[ ]
Benjamin Francisoud commented on IVY-1029:
------------------------------------------
Thanks Maarten for your quick answer, unfortunalty if I use your declaration, I don't think any xsd validation is apply to the xml...
In eclipse I get the following warning message:
"No grammar constraints (DTD or XML schema) detected for the document."
In the xsd w3c standard, you can declare an external location for the xsd file that will override the default one describe at the beginning of your xml file.
In eclipse this is achieve by using the Preferences > XML > XML Catalogs menu.
I'll add screen captures of my eclipse configuration to this jira.
But you need to provide a "key" (aka target namespace) for eclipse to know where to apply the xsd that's why, in my opinion, the xsd is not apply if you remove the "xmlns" attribute.
I will try the trunk version of the xsd.
> Unable to specify xsi:schemaLocation or xsi:noSchemaLocation with ivy.xsd
> -------------------------------------------------------------------------
>
> Key: IVY-1029
> URL:
> Project: Ivy
> Issue Type: Bug
> Affects Versions: 2.0
> Reporter: Benjamin Francisoud
>
> I'm trying to get auto-completion of ivy.xml in eclipse but I just can make it work :(
> h2. ivy.xml with defaultNamespace
> {code:xml}
>
>
|
http://mail-archives.apache.org/mod_mbox/ant-notifications/200902.mbox/raw/%3C1023930675.1233909839639.JavaMail.jira@brutus%3E/
|
CC-MAIN-2016-26
|
refinedweb
| 201
| 72.56
|
ScriptManager.EnablePageMethods Property
Gets or sets a value that indicates whether public static page methods in an ASP.NET page can be called from client script.
Namespace: System.Web.UINamespace: System.Web.UI
Assembly: System.Web.Extensions (in System.Web.Extensions.dll)
You can add static page methods to an ASP.NET page and mark them as Web methods. You can then call these methods from script as if they were part of a Web service, but without creating a separate .asmx file. To create Web methods on a page, import the System.Web.Services namespace and add a WebMethodAttribute attribute to each static method that you want to expose. The methods must be marked public.
For more information, see Exposing Web Services to Client Script in ASP.NET AJ.
|
http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.enablepagemethods.aspx
|
CC-MAIN-2014-52
|
refinedweb
| 130
| 60.82
|
Network.Remote.RPC
Contents
Description
Declaration of the frontend for RPC.
Synopsis
- class Host a where
- data WIO w m a
- world :: forall w m. (Servable m, Host w) => WIO w m w
- class (Functor m, Monad m, MonadIO m, Forkable m) => Servable m
- liftIO :: MonadIO m => forall a. IO a -> m a
- runServer :: forall w m. (Servable m, Host w) => WIO w m () -> m ()
- runServerBG :: Host w => WIO w IO () -> IO ThreadId
- onHost :: forall w m. (Servable m, Host w) => w -> WIO w m ()
- autoService :: Name -> Q Exp
- makeHost :: String -> String -> Integer -> Q [Dec]
- makeServices :: [Name] -> Q Exp
- rpcCall :: Name -> Q Exp
- class Monad m => Forkable m where
- class MonadTrans t where
Documentation
declares that the world is a host. It should
only have one constructor, and the location and port should be invariant
of the given constructor.
Specifically,
Host World
getLocation and
getPort should work even if bottom is supplied.
Instances
class (Functor m, Monad m, MonadIO m, Forkable m) => Servable m Source
Instances
runServer :: forall w m. (Servable m, Host w) => WIO w m () -> m ()Source
runServerBG :: Host w => WIO w IO () -> IO ThreadIdSource
runServerBG runs a name server on a background thread and does return
onHost :: forall w m. (Servable m, Host w) => w -> WIO w m ()Source
autoService :: Name -> Q ExpSource
$( finds all services declared in the
module that definitely run on the given world,
and makes them listen for incoming requests.
autoService 'World)
makeHost :: String -> String -> Integer -> Q [Dec]Source
makeServices :: [Name] -> Q ExpSource
$( makes all given
services listen for incoming requests.
makeServices ['service1 ,..., 'serviceN])
rpcCall :: Name -> Q ExpSource
$( simply splices in
rpcCall 'serviceNm)
which is typed in a manner
similar to typeofcall.
realRemoteCall (undefined :: typeofcall) "serviceNm"
Example: Making remote Calls
This example shows how to make remote procedure from a Client to a Host. It also shows how to send functions, which can now be collected.
-- LANGUAGE TemplateHaskell, KindSignatures, FlexibleContexts module Main where import Network.Remote.RPC
First, hosts must be declared. In the future, hosts might be declared in a configuration file such that they can be configured at runtime rather than only at compile time.
$(
makeHost"Client" "localhost" 9000) $(
makeHost"Server" "localhost" 9001)
The following services will run on the server.
doubleServer :: Integer ->
WIOServer IO Integer doubleServer t = return $ t + t addServer :: Integer ->
WIOServer IO (Integer -> Integer) addServer t = return (t +)
When used,
addServer will return a function of type
Integer ->
because the resulting function will actually be a remote call. Every time
WIO w IO Integer
addServer
is called, it turns the function into a service which is collected when the function is no
longer needed.
client = do onHost Client double <- $(rpcCall 'doubleServer) 3 liftIO $ putStrLn $ "r(h3+h3) ? " ++ show double add <- $(rpcCall 'addServer) 4 r <- add 6 -- add :: Integer -> WIO Client IO Integer liftIO $ putStrLn $ "r(h4 +) h6 ? " ++ show r
Despite
rpcCall being a template splice, the resulting splice is type safe:
$(
rpcCall'doubleServer) :: (
Hostw,
Servablem) => Integer ->
WIOw m Integer
Now we declare the runtime. Usually this would be in two different mains, but for educational and testing purposes, both the client and server can be run from the same main.
main = do
runServerBG$(autoService 'Server)
runServerclient
$(looks for services declared in the file which definitely run on server, and runs them as services on the intended host (
autoService'Server)
Serverin this case).
runServerBGruns a service server on a background OS thread, and returns
runServerruns a service server and does not return.
- When run:
>>>
:mainr(h3+h3) ? 6 r(h4 +) h6 ? 10
Where
rVal means Val is on the server and
hVal means Val is on the client.
|
http://hackage.haskell.org/package/rpc-framework-2.0.0.2/docs/Network-Remote-RPC.html
|
CC-MAIN-2015-11
|
refinedweb
| 599
| 51.78
|
combining 2 web applications into a single one but making it look like 2 domain names?
Discussion in 'ASP .Net' started by Andy
combining into a single class_.-=, Jul 30, 2003, in forum: Java
- Replies:
- 3
- Views:
- 347
- Roedy Green
- Jul 30, 2003
Re: howto: combining form output from one of more fields to a single lineRichard, Feb 7, 2004, in forum: HTML
- Replies:
- 2
- Views:
- 618
- informant
- Feb 10, 2004
Domain Registering Companies Reserving Domain NamesAF, Aug 22, 2004, in forum: HTML
- Replies:
- 8
- Views:
- 1,301
- Chrissy Cruiser
- Aug 23, 2004
combining names and namespaces into a one URI, Feb 25, 2007, in forum: XML
- Replies:
- 4
- Views:
- 554
- Joe Kesselman
- Feb 25, 2007
combining different types into single data structuregirays, Apr 20, 2008, in forum: C++
- Replies:
- 5
- Views:
- 396
- girays
- Apr 24, 2008
|
http://www.thecodingforums.com/threads/combining-2-web-applications-into-a-single-one-but-making-it-look-like-2-domain-names.628089/
|
CC-MAIN-2015-27
|
refinedweb
| 137
| 53.89
|
Working with a nHibernate session in an asp.net web application is a subject to many a blog post, forum question or overflowing stack. Having already made a contibution before, I am nevertheless going to add another go at it combining all I’ve met and trying to find a way to meet the objections to the different approaches.
The problem
Accessing a database via nHibernate takes four steps.
- Create a sessionfactory.
- Open a session.
- Access data
- Close the session
Creating a sessionfactory is a very costly process, don’t do this to often. Opening an ADO connection results in an open connection to the database. Database connections are a costly external resource. Despite session pooling connections should be closed as soon as possible. An nHibernate session wraps up the ADO connection; it handles the opening and closing. Creating an nHibernate session is fast and will not be costly until the moment the ADO connection is opened. Nevertheless this is not a license to spill.
Strategies
Trying to balance to cost of creating a sessionfactory and the waste of creating sessions which will not be used I’ve found several ways to manage the session.
- Do it yourself. Create the factory whenever the app needs data and fiddle on from there optimized to the occasion. Needless to say that’s not going to work unless you have a very simple app.
- An action in a (MVC) controller. Using an attribute on the action a factory and session are created on the start of an action and disposed when the action is finished. This might look appealing but is a very poisonous recipe (pun intended). After the action is finished the page will be rendered. In case there are any lazy properties on the page they cannot be read because the session has already closed.
- The Web-HttP request. At the start of the request the session is opened, at the end it closed. This is by far the favored solution by almost everybody. The down side is that, in the default implementation, a session is created on every request. Also when no database access will take place, even when requesting an image or the like.
Objectives
The session manager presented here is controlled by web requests and has some extra’s
- Only create a factory and session when one is actually needed.
- Can also be used in a non web environment. Like Visual studio to run in an unit test.
The first extra is done by making the session a lazy property. The second one by setting the NH-session context based on the app’s context.
The (a) solution
So far for the theory, here’s the code. It’s using fluent nHibernate for setting the configuration. What else ?
public class SessionManager
{
private static ISessionFactory Factory { get; set; }
public static string ConnectionString { get; set; }
static SessionManager()
{
ConnectionString = @”Data Source=Bunocephalus;Initial Catalog=Epos4;Integrated Security=true”;
}
private static ISessionFactory GetFactory<T>() where T : ICurrentSessionContext
{
return Fluently.Configure().
Database(MsSqlConfiguration.MsSql2008.
#if DEBUG
ShowSql().
#endif
ConnectionString(c => c.Is(ConnectionString))).
Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())).
CurrentSessionContext<T>().
BuildSessionFactory();
}
public static ISession CurrentSession
{
get
{
if (Factory == null)
Factory = HttpContext.Current != null
? GetFactory<WebSessionContext>()
: GetFactory<ThreadStaticSessionContext>();
if (CurrentSessionContext.HasBind(Factory))
return Factory.GetCurrentSession();
ISession session = Factory.OpenSession();
CurrentSessionContext.Bind(session);
return session;
}
}
public static void CloseSession()
{
if (Factory == null)
return;
if (CurrentSessionContext.HasBind(Factory))
{
ISession session = CurrentSessionContext.Unbind(Factory);
session.Close();
}
}
public static void CommitSession(ISession session)
{
try
{
session.Transaction.Commit();
}
catch (Exception)
{
session.Transaction.Rollback();
throw;
}
}
}
A short walkthrough:
The public property CurrentSession is the only thing your other code is interested in. It will be used in your repositories.
public virtual T Get(int id)
{
var session = SessionManager.CurrentSession;
var domainObject = session.Get<T>(id);
return domainObject;
}
Which should speak for itself
The factory is a private member. CurrentSession checks if the factory is already created. When not it passes a type parameter, which depends on the context, to the GetFactory method which actually instantiates the factory. In case the manager is running in a web context the factory is given a WebSessionContext else a ThreadStaticContext. The latter working well when running a test. A sql2008 database is assumed with the table mappings in the same assembly. I leave it up to you to make this configurable. In case you really need it
The actual session is managed by nHibernate itself in the sessioncontext. CurrentSession checks that to try to get the session. When none is available it creates one and binds it to the context. Now all code in one webrequest will share one and the same session.
When closing the session the code should check for a factory. Perhaps the current webrequest never did any database access and thus never opened a session. Close session unbinds the session from the context and closes it.
In several solutions, including the one in the original version of this post, the sessionmanager handles (part of) transaction management. The most extreme version starts a transaction when opening the session and commits that when closing the session. Which could look nice at first sight. But it will fire back at you. We have several developers working on this project, not everybody that familiar with nHibernate. The things nHibernate (tries to) persist implicitly can be quite surprising, resulting in baffled co-workers. Making persisting object explicit in transactions is also good from an organizational point of view. Which strategy to follow is beyond the scope of this post. The CommitSession helper method handles the core of that.
Some checks in this code might seem superfluous. But this way it does survive some very nasty crashes doing heavy ajax stuff in VS always clearing all database connections. The last thing you need there is a conflict with your sql server.
Note this part in configuring the factory
#if DEBUG
ShowSql().
#endif
This results in all nHibernate generated sql to show up in your test.
The full picture
The database part of the solution has two projects. One are the repositories, the other one is this nHibernatemanager. Which contains
- The sessionmanager we discussed
- An HttpModule to load the manager in a website
- The mappings of the domain model
- A validator, not discussed here
The HttpModule to wrap up the manager:
public class CurrentSessionWebModule : IHttpModule
{
public void Init(HttpApplication context)
{
SessionManager.ConnectionString = ConfigurationManager.ConnectionStrings[“EposDB”].ConnectionString;
context.EndRequest += (sender, e) => SessionManager.CloseSession();
}
public void Dispose()
{
}
}
Closing the session is hooked into EndRequest. In the “usual” solution opening the session is hooked into the BeginRequest. Here this is not needed, the session will be opened on demand by any code actually needing a session.
<httpModules>
<add name =“CurrentSessionWebModule“ type=“Epos4.Database.NhibernateManager.CurrentSessionWebModule, NhibernateSessionManager, Version=1.0.0.0, Culture=neutral“/>
</httpModules>
This is the only mentioning of the manager needed by the website. To get to data it uses the repositories, the repositories reference the actual code of the manager.
That’s it. We have pushed the management of a session away into one specific corner, have a session at our disposal when needed and are not hindered by a performance or resource penalty when not needing a session. Nothing original, just works like a charm. And any remarks or suggestions are more than welcome.
<update>Your comments have been used to update this post where it was plain wrong. The original version assumed an nHibernate session always opens a connection to the database. It does not. Thank you for your feedback</update>
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #946
|
http://codebetter.com/petervanooijen/2011/09/26/yet-another-nhibernate-sessionmanager-for-asp-net-mvc/
|
CC-MAIN-2017-09
|
refinedweb
| 1,258
| 50.33
|
Recently, I made an app for fun based on a game called DOTA 2 (any players here?). I used their OpenDota API to fetch some data, manipulate some stats and display it on the app. It was my first time using React Hooks so it inspired me to make this beginner-friendly version to show you how to fetch and display API data to a list using Hooks in React Native. And then have a search bar that can autocomplete a query by providing search suggestions based on that list.
Some prerequisites you need to know for this tutorial:
- Good understanding of React Native (React is fine too)
- Basic understanding of React Hooks
- Good understanding of what an API is
The Simple Project
For those who don't know the game whose API we are using, don't worry. I'm simplifying the app to exclude all the stats and avoid the complicated game data for this tutorial so you can follow. Basically, we are going to:
- Fetch all the heroes (i.e. characters) from the game using their API
- Display their names as a FlatList in the app
- Then, implement a Search Bar that filters the list, only displaying matched names in real-time
Okay, I hope that clears it up. Let's begin!
Step 1: Install package
First, to have a search bar in our app:
npm install react-native-elements
Step 2: Import statements and initialize states
Now we can import the SearchBar component and our Hooks: useState and useEffect.
In App.js:
import { SearchBar } from 'react-native-elements'; import React, { useState, useEffect } from 'react';
Then below the App function, we initialize 3 states using useState:
- data: an array which contains the fetched API data. Initialize as empty array.
- query: the string value in the search bar. Initialize as empty string.
- heroes: an array which contains the names to output to the list. Initialize as empty array.
const [data, setData] = useState([]); const [query, setQuery] = useState(''); const [heroes, setHeroes] = useState([]);
Step 3: Fetch Data
Let's create a fetchData function to take care of fetching the API.
const fetchData = async () => { const res = await fetch(''); const json = await res.json(); setData(json); setHeroes(json.slice()); };
As seen in the code above, we first fetch data from the API, then set our local 'data' state to the value of the fetched data using setData(). Our heroes array will also contain the fetched data but we use .slice() to set heroes as a new array object, so that any changes to heroes will not affect the data array (as we will see later in this tutorial).
useEffect
Next, we use useEffect to call the fetchData function when the component mounts.
useEffect(() => { fetchData(); }, []);
The empty array passed in as the second argument prevent fetchData() from being called every time a component updates.
The API returns an array of hero objects in this structure:
Step 4: Display Data to FlatList
FlatLists Props
- data: an array that contains the elements the list will display. For this app, we will use the heroes array.
- keyExtractor: extracts a unique key for a given item at the specified index. For this app, we will use the 'id' property of our data.
- extraData: tells the list to re-render whenever a specified state changes. For this app, we want the list to re-render whenever the value of the query changes.
- renderItem: takes an item from the data prop and renders it to the list. As mentioned earlier, this app only displays the name property of the heroes from the game. Thus, we add
item.nameinstead of
iteminside a Text component to display the name as a text.
Here's how we implement the FlatList in our App.js:
<FlatList data={heroes} keyExtractor = {(i)=>i.id.toString()} extraData = {query} renderItem = {({item}) => <Text style={styles.flatList}>{`${item.name}`} </Text>} />
Add some styling below:
const styles = StyleSheet.create({ flatList:{ paddingLeft: 15, marginTop:15, paddingBottom:15, fontSize: 20, borderBottomColor: '#26a69a', borderBottomWidth:1 } });
Now we should have a working app that fetches the heroes and displays their names as a list!
But there is a problem. Apparently the API includes an npc_dota_hero_ in the beginning of every name and the names begin in small caps - looks terrible! Let's format the names so it looks nicer.
Step 5: Format Names
Create a function called formatNames that takes in a hero object. Inside the function, we will proceed in the following order:
- access the name property of the hero object (i.e. hero.name)
- remove the first 14 characters from the name (which is npc_dota_hero_)
- capitalize the first character of the hero's name (i.e. example_name --> Example_name)
- replace any '_' with a space using regex (i.e. Example_name --> Example name)
const formatNames = (hero) => { let heroName = hero.name.charAt(14).toUpperCase() + hero.name.slice(15); heroName = heroName.replace(/_/g, " "); return heroName; }
Then, we update the FlatList Text component by replacing the ${item.name} to formatNames(item).
<FlatList data={heroes} keyExtractor = {(i)=>i.id.toString()} extraData = {query} renderItem = {({item}) => <Text style={styles.flatList}>{formatNames(item)} </Text>} />
There we go! Now the list looks so much more readable and visually nicer! Let's move on to implement our search bar to filter the list in real-time.
Step 6: Search Bar
Search Bar Props
- onChangeText: calls a function whenever the input text value changes. For this app, we will create a function called updateQuery to update our query state to the text value in the search bar.
- value: the text value on the search bar. We will set it to our query state.
- placeholder: the string the user sees on the search bar before typing on it.
<SearchBar onChangeText={updateQuery} value={query}
Our updateQuery function will take the user's input and set the query state to be equal to that value like so:
const updateQuery = (input) => { setQuery(input); console.log(query); }
Our console shows how our query state is updated every time there is a single character change in the search bar input.
### Step 7: Filter Names
Just like how a Google Search suggestions work, we want the list to re-render and update in real time as the user is typing on the search bar. That way, when the user types "A", the list will immediately suggests all the names starting with A to autocomplete your query.
The extraData property in FlatList will re-render the list every time the query value changes. Therefore, as the list re-renders, we need to add some sort of filtering function to only return the names that match the query. Let's call it filterNames().
The Logic
Recall that the unformatted hero name is like: npc_dota_hero_example_name, which means we must compare the query with the name at starting from index 14, where the name actually starts.
Also, note that the user may type a query with capital letters or spaces. In some cases, this can cause formatNames to mistakenly think the query does not match the hero name.
For example, if hero name is npc_dota_hero_example_name and query is "Example NAME", it will not show a match even though it should be. We can solve this by transforming the query to all lower cases and replacing all spaces with '_' before we try to match it with our hero names.
Pseudocode
Here's the pseudocode for filterNames() to help you understand it better:
- Transform the query to all small caps and replace any spaces with '_'
- Use String.startsWith(word_to_match, start_index) to check if name starts with the query at index 14
- If it is a match (i.e. true), format name to its readable form by calling our formatNames() we did in Step 5.
- If it is not a match (i.e. false), we remove this hero element from the heroes array using splice() and do not render it to the list.
Our code would look like:
const filterNames = (hero) => { // 1. let search = query.toLowerCase().replace(/ /g,"_"); //2. if(hero.name.startsWith(search, 14)){ //3. return formatNames(hero); }else{ //4. heroes.splice(heroes.indexOf(hero), 1); return null; } }
Great! Now don't forget to update our Flatlist Text Component to call filterNames(item) instead of formatNames(item). Here's what the FlatList component should ultimately look like:
<FlatList data={heroes} keyExtractor = {(i)=>i.id.toString()} extraData = {query} renderItem = {({item}) => <Text style={styles.flatList}>{filterNames(item)} </Text>} />
### Step 8: Update the updateQuery function
Notice that we are changing the heroes array itself by removing elements that do not match the query. For example, if heroes is originally:
['Apple', 'Banana', 'Orange']
And our query is 'A', only 'Apple' would match so heroes would remove the elements that do not match. Now heroes only contains:
['Apple']
But what if the user changes the query to a name that was in the original array? Like 'O', which should match 'Orange'. Since 'Orange' has been removed, the FlatList would not display it anymore.
We can easily solve this problem by resetting the heroes array to its full length every time the user changes the query. Recall that we have a data array (see Step 2), which contains the original fetched data from the API. We never change this array so it still contains all 119 hero names. So, we can easily add:
setHeroes(data.slice());
into our updateQuery function so that the heroes array would create a new copy of the data array and therefore, contain the original length again for filterNames() to work as intended.
And ta-da! Our app should have a working search bar now!
It updates the list in real-time, providing autocomplete/search suggestions for hero names.
Thanks for reading!
I hope this has been a fruitful read for you. Please ask any questions in the comments below. For the complete code, check out my github repo for it. Also, it's my first time to use Hooks, if there's any better solutions, please suggest it in the comments so I will learn from your feedback.
Fetching from an API, displaying it to a list and implementing a real-time search bar can be useful in many applications. I hope you'll try to make an app with your favourite game or something similar as practice!
Have fun coding, good luck and cheers!
Special Thanks to:
- Rana Emad for her article on React Hooks
- Steffy Lo for her article on Introduction to React Hooks
- FlatList Documentation from React Native
- SearchBar Documentation from React Native Elements
- OpenDota API for inspiring me
Discussion (0)
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/lo_victoria2666/build-a-custom-autocomplete-search-bar-with-react-hooks-dpm
|
CC-MAIN-2021-49
|
refinedweb
| 1,749
| 64.2
|
The Stack class provides the capability to create and use stacks within the Java programs. Stacks are·.
Search() It allows us to search through a stack to see if a particular object is contained on the stack.
Peek() It returns the top element of the stack without popping it off.
Empty() It is used to determine whether a stack is empty.
The pop() and peek() methods both throw the EmptyStackException if the stack is empty. Use of the empty() method can help to avoid the generation of this exception.
import java.util.Stack;
import java.util.EmptyStackException;
class StackJavaExample
{
public static void main(String args[])
{
Stack Stk = new Stack();
int m,s;
Stk.push(new Integer(20));
Stk.push(new Integer(30));
System.out.println("Value Popped from Stack is : "+ Stk.pop());
Stk.push(new Integer(30));
s=0;
while(!Stk.empty())
{
m=((Integer)Stk.pop()).intValue();
s=s+m;
}
System.out.println("Sum of the Values Left in Stack is : "+ s);
}
}
Stack implementation in Java Example
import java.util.Stack;
import java.util.EmptyStackException;
class StackImpJavaExample
{
public static void main(String args[])
{
Stack Stk = new Stack();
Stk.push("Blue Demon");
Stk.push("Orchids");
Stk.push("Ganga");
System.out.println("Element Popped From Stack is : "+Stk.pop());
Stk.push("Ganga");
System.out.println("Element at the Top of the Stack is : "+Stk.peek());
while (!Stk.empty())
System.out.println("Elements Popped from Stack is : "+Stk
|
http://ecomputernotes.com/java/stream/stack-in-java
|
CC-MAIN-2018-51
|
refinedweb
| 235
| 53.88
|
Introduction:
Here I will explain how to highlight gridview rows on mouseover and mouseout using jQuery in asp.net.
Here I will explain how to highlight gridview rows on mouseover and mouseout using jQuery in asp.net.
Description:
In previous post I explained hightlight gridview rows on mouseover in asp.net. Now I will explain how to highlight gridview rows on mouseover and mouseout using jQuery in asp.net.
To implement this functionality in jQuery we need to write the code like this
If you observe above code I written like
By using this we are identifying row tr with td and applying css style for gridview. Instead of this we can write the code like this
But above code will apply css style for gridview header also for that reason we written above code to identity and apply css style for row tr with td
If you want to see it in complete example check below example
After that add following namespaces in code behind
C# Code
Once namespaces added then write the following code in code behind
VB.NET Code
Demo
8 comments :
Not working when "AlternatingRowStyle" is defined. Any Help..?
hiii suresh your articles are superb and i have a req on gridview i.e i want to insert data by using gridview into database through multiple tables if thr are 5 columns in the gridview those 5 columns belongs to 5 different tables in th database is it possible if yes how please gimme a suggestion to dis..
hi suresh,
i want to show dynamic data on mouse over of link button inside the repeater.
i am searching it from last 1 day.
Please help me asap.
use this css class* {
padding: 0;
margin: 0;
}
body {
font: 11px Tahoma;
background-color: #F7F7E9;
}
h1 {
font: bold 32px Times;
color: #666;
text-align: center;
padding: 20px 0;
}
#container {
width: 700px;
margin: 10px auto;
}
.mGrid { width: 100%; background-color: #fff; margin: 5px 0 10px 0; border: solid 1px #525252; border-collapse:collapse; }
.mGrid td { padding: 2px; border: solid 1px #c1c1c1; color: #717171; }
.mGrid th { padding: 4px 2px; color: #fff; background: #424242 url(grd_head.png) repeat-x top; border-left: solid 1px #525252; font-size: 0.9em; }
.mGrid .alt { background: #fcfcfc url(grd_alt.png) repeat-x top; }
.mGrid .pgr {background: #424242 url(grd_pgr.png) repeat-x top; }
.mGrid .pgr table { margin: 5px 0; }
.mGrid .pgr td { border-width: 0; padding: 0 6px; border-left: solid 1px #666; font-weight: bold; color: #fff; line-height: 12px; }
.mGrid .pgr a { color: #666; text-decoration: none; }
.mGrid .pgr a:hover { color: #000; text-decoration: none; } on grid ..
Hi Suresh,
I have been using lots of code from your samples. Everythings work fine. But whenever I try to implement your sample in JQUERY, I have never got any expected result. what could be the issue. I m using master page.
Nice
when i am using master page it is not worked and on simple page it works's like charm
can you explain why this happen please
plz tel me how bind data list in course,then the coursetype data will be display when mouse over the course.
|
http://www.aspdotnet-suresh.com/2012/11/highlight-aspnet-gridview-rows-on.html
|
CC-MAIN-2014-52
|
refinedweb
| 524
| 72.26
|
Hi,
I was making a small math quiz thing, when I came across some strange
behaviour in either me or Mod_Python.
1. If FORM in file test.html POST to ACTION 'test.py/someFunc', nothing
happens. If I rename test.py to t.py, it does. Is that by design?
2. I was experimenting with passing values from page to page, when I
discovered that I could do this without cookies, hidden values or URL
extensions like '?A=x&B=y' I could just call the function directly in the
POST statement. So I grokked a little with a script that basically - takes
input from user, - posts it to a function that stores the input in a
global variable (list) - calls a function that generates html for a new
page, now with a a form that'll post to another function. (See below if
you're interested in the files.)
And the global variable happily appends all the userinput from page to
page.
Then, shortly after completing the test, I can access the starting page
from another host in my network. What happens is that the list continues
to expand, it still holds the values posted from the first host. They
share memory!
Now, I suppose this makes sense with regards to modules, for
instance, but should a variable in a script be super global?
When accessing the files from a second or third host, the Apache error
log, appends: "[notice] mod_python: (Re)importing module 't' with path set
to '[path_to_files]'".
Is it something strange here, or should I be more careful with my
namespace ;-)
--rune
--------- The files to repro:
< [2Kb]
SPECS = [Win 2003 Server, Apache 2.0.49, Python 2.3.3, Mod_Python 3.1.3]
|
https://modpython.org/pipermail/mod_python/2004-September/016321.html
|
CC-MAIN-2022-21
|
refinedweb
| 287
| 75.3
|
Base class for several classes in the OMNeT++ library. More...
#include <cownedobject.h>
Base class for several classes in the OMNeT++.
Ownership management helps OMNeT++ catch common programming errors. As a definition, ownership means the exclusive right and duty to delete owned objects.
cOwnedObjects hold a pointer to their owner objects; the getOwner() method returns this pointer. An example will help to understand how it is used:
The above ownership mechanisms are at work when any cOwnedObject-subclass object gets inserted into any cOwnedObject-subclass container (cQueue, cArray).
Some more details, in case you are writing a class that acts as a container:
Create object without a name.
The object will be initially owned by defaultOwer().
Create object with given name.
The object will be initially owned by defaultOwer(). Name pooling is an optimization feature.
Returns the number of objects that currently exist in the program.
The counter is incremented by cOwnedObject constructor and decremented by the destructor. May be useful for profiling or debugging memory leaks.
Returns the total number of objects created since the start of the program (or since the last reset).
The counter is incremented by cOwnedObject constructor. Counter is
signed to make it easier to detect if it overflows during very long simulation runs. May be useful for profiling or debugging memory leaks..
Reimplemented in cDefaultList.
The assignment operator.
Derived classes should contain similar methods (
cClassName& cClassName::operator=(cClassName&)).
Assigment copies the contents of the object EXCEPT for the name string. If you want to copy the name string, you can do it by hand:
setName(o.getName()).
Ownership of the object is not affected by assigments.
Reset counters used by getTotalObjectCount() and getLiveObjectCount().
(Note that getLiveObjectCount() may go negative after a reset call.)
|
https://omnetpp.org/doc/omnetpp/api/classcOwnedObject.html
|
CC-MAIN-2016-07
|
refinedweb
| 289
| 52.05
|
Last Bar of Delayed Data from Interactive Brokers
- Squirrel Singing last edited by
Re: Backtest vs live bars "off-by-1" discrepancy?
Hi,
For those of you who use Interactive Brokers, are you all seeing the last bar of delayed data being formed even before the time period is over?
I am aware that rightedge = False for Delayed data and rightedge = True for Live Data.
For example, using the below screenshot as an example
At 08:05:00, Closing Price of 1.28926 is the closing price for the period 08:05:00 to 08:10:00
At 08:10:00, Closing Price of 1.28935 is the closing price for the period 08:10:00 to 08:13:33 (the time when connection to IB server was established)
At 08:15:00, Closing Price of 1.2891 is the closing price for the period 08:10:00 to 08:15:00
If the last bar of delayed data is indeed formed before time period is over, aren't indicators, such as 2 periods SMA in the below screenshot being skewed by this "Last Bar of Delayed Data"?
If you want to replicate the results, pls use the below code.
import backtrader as bt import datetime as dt import pytz as pytz class Test_Strategy (bt.Strategy): params = (('maperiod',10), ) def __init__ (self): self.data_live = False self.sma = bt.indicators.SimpleMovingAverage (self.data.close, period = self.params.maperiod) def next (self): self.log (str(self.data.close[0]) + '(Closing Price) ' + str(self.sma[0]) + '(2 periods SMA)') def notify_data(self, data, status): print('*' * 5, 'DATA NOTIF:', data._getstatusname(status)) if status == data.LIVE: self.data_live = True def log (self, text): print (self.data.datetime.datetime(0),": ", text) if __name__ == '__main__': ibstore = bt.stores.IBStore (host = '127.0.0.1', clientId = 111, port = 7497) data = ibstore.getdata (dataname = 'GBP.USD-CASH-IDEALPRO', #GBP.USD-CASH-IDEALPRO, BARC-STK-LSE-GBP rtbar = False, timeframe = bt.TimeFrame.Minutes, compression = 1, tz=pytz.timezone('US/Eastern'), ) cerebro = bt.Cerebro() cerebro.broker = ibstore.getbroker() ### cerebro.resampledata (data, timeframe = bt.TimeFrame.Minutes, compression = 5) cerebro.addstrategy (Test_Strategy, maperiod = 2) cerebro.run()
|
https://community.backtrader.com/topic/2129/last-bar-of-delayed-data-from-interactive-brokers
|
CC-MAIN-2020-10
|
refinedweb
| 354
| 52.76
|
?
The first thing to do is to avoid
import *. Import only specific names. What you could do in this case is a function
# file RenderUI.py def main(): app = QtGui.QApplication(sys.argv) app.setStyle("cleanlooks") win = Window() win.show() sys.exit(app.exec_())
and in the other file
# file Render.py from RenderUI import main if __name__ == "__main__": main()
how about doing this way ?
import RenderUI,sys from PyQt4 import QtCore,QtGui #class Actions(): if __name__ =='__main__': app = QtGui.QApplication(sys.argv) app.setStyle("cleanlooks") win = RenderUI.Window() win.show() sys.exit(app.exec_()) else: win = Window() win.show()
and no need of main() function in RenderUI.py
i defined a class in Render.py but if i define its constructor
__init__ i get error in the RenderUI.py while instantiating this class saying
Message File Name Line Position Traceback <module> \Render.py 39 __init__ \RenderUI.py 26 TypeError: __init__() takes no arguments (1 given)
please help out !!
__init__'s minimal signature is
def __init__(self):...
i shoudl have implemented UI separate from logic now it is such a pain...
|
http://www.daniweb.com/software-development/python/threads/442624/separating-ui-from-logic
|
CC-MAIN-2014-15
|
refinedweb
| 181
| 63.05
|
The basic assignment operator in C Programming Language is ‘=’, which we know as “equal to” in Mathematics. However, in C this is not to be confused with “equal to” but this performs different operation on its operands. This operator assigns value of expression/variable/constant at its right to the variable at its left. Every expression in C evaluates to some value. For example: Valid assignment statements.
result = (x * y) / (u + v); value = x + y; more = ++yes; int const TRUE = 1; int const FALSE = 0; /* * In C, variable names should be in lower case. However, Constants * are named in Capitals. Above, TRUE and FALSE are constants. */
The right side value of the assignment is called rvalue and left side of the assignment is called lvalue or modifiable lvalue. lvalue refers to memory location or region of actual data storage or data object to hold value into while rvalue refers to value of some expression or variable or constant which is to be assigned to lvalue. Not all data objects can have their values changed therefore data objects that can change values are called modifiable lvalues. lvalue can not be a constant. For example:
56 = x + y + z; /* * since lvalue must be a location to hold value into it. 56 is not a * location, instead this is a value. Not a valid assignment statement */
Another example:
/* assignment.c -- program displays use of assignment operator */
#include <stdio.h>
int main(void)
{
int one, two, three;
one = two = three = 68;
/* one, two and three, each assigned 68 */
/* associativity of assignment operator is from right to left */
printf(" one two three");
printf("First round score %4d %8d %8d\n", one, two, three);
return 0;
}
Operator Precedence
Consider the following line of code:
result = 19.0 + 20.0 * n / SCALE;
This statement has an addition, a multiplication, and a division operation. Which operation takes place first? Is 20.0 added to 19.0, the result of 39.0 then multiplied by n, and that result then divided by SCALE? Is 20.0 multiplied by n, the result added to 19.0, and that answer then divided by SCALE? Is it some other order? Let’s take n to be 6.0 and SCALE to be 2.0. If you work through the statement using these values, you will find that the first approach yields a value of 117.0. The second approach yields 69.5. A C program must have some other order in mind, because it would give a value of 79.0 for result.
Clearly, the order of executing the various operations can make a difference, so C needs unambiguous rules for choosing what to do first. C does this by setting up an operator precedence order. Each operator is assigned a precedence level. As in ordinary arithmetic, multiplication and division have a higher precedence than addition and subtraction, so they are performed first. What if two operators have the same precedence? If they share an operand, they are executed according to the order in which they occur in the statement. For most operators, the order is from left to right. (The = operator was an exception to this.) Therefore, in the statement
result = 19.0 + 20.0 * n / SCALE;
The order of operations is as follows:
20.0 * n
The first * or / in the expression (assuming n is 6 so that 20.0 * n is 120.0)
120.0 / SCALE
Then the second * or / in the expression
19.0 + 60
Finally (because SCALE is 2.0), the first + or – in the expression, to yield 79.0
Operators in Order of Decreasing Precedence
Operators Associativity () Left to right + - (unary) Right to left * / Left to right + - (binary) Left to right = Right to left
More Assignment Operators: +=, -=, *=, /=, %=
C,
scores += 20; is the same as scores = scores + 20;
dimes -= 2; is the same as dimes = dimes - 2;
bunnies *= 2; is the same as bunnies = bunnies * 2;
time /= 2.73; is the same as time = time / 2.73;
reduce %= 3; is the same as reduce = reduce % 3;
Well! The preceding list uses simple numbers on the right, but these operators also work with more elaborate expressions, such as the following:
x *= 3 * y + 12; x = x * (3 * y + 12); /* both statements are same */
The assignment operators we’ve just discussed have the same low priority that = does—that is, less than that of + or *. This low priority is reflected in the last example in which 12 is added to 3 * y before the result is multiplied by x.
You are not required to use these forms. They are, however, more compact, and they may produce more efficient machine code than the longer form. The combination assignment operators are particularly useful when you are trying to squeeze something complex into a for loop specification.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
|
http://www.sanfoundry.com/c-tutorials-different-assignment-operators-work-2/
|
CC-MAIN-2017-39
|
refinedweb
| 803
| 65.73
|
eg bad.c
{
int a=1;
{
int a=1;
}
}
[download]
If I have the below in perl how do I persuade perl to reject this as I can for C++ and Java ?
my $var=1;
{
my $var=1;
}
[download]
I was going to answer this but it didn't answer the question. Perhaps some hacking about with PadWalker? Braver souls could implement a CHECK time function to walk all over the generated code and look for duplicated lexical names.
Added I mean to say that while I don't know of any already implemented code, nothing that I'm aware of prevents someone (else) from creating it.
That's a feature, not a bug. Do you have a specific reason why it should be disallowed?
----I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer
Note: All code is untested, unless otherwise stated
I have just wasted 2 hours tracking down a bug that was caused by this flexibility and have had similar experiences in the past.
In C++ and Java its disallowed/disallowable - presumably cos its considered bad form or more likely to be a typo than genuine code.
#include <stdio.h>
int main() {
int a = 1;
{
int a = 5;
printf("inside a = %d\n", a);
}
printf("outside a = %d\n", a);
}
[download]
jeffa
L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)
I search CPAN for lexical and didn't find anything that might do the job. I'm sure it would be possible to write a source code filter for this (but you'll need perl 5.8.0).
If you do go ahead and write this - make it a lexically scoped directive, similar to strict and warnings.
-----'d want something that takes code a line at a time, and
spits out all the "my ..." declarations, one per line of
output, with the line number in the original code (which is
scrupulously preserved by B::Deparse, I think -- but even if
it isn't, just edit the output of B::Deparse, 'cuz it's
probably more readable than the original when there's a
difference).
update: Here is an example using
B::Deparse to tabulate sub defs and sub calls in perl code;
might not be too big a stretch to make it focus on variable
declarations instead.
CC +w bad.c "c.c", line 7: Warning: i hides the same name in an outer scope.
One does have to question the merits of this warning though.
What's easier to shut off this warning by removing the int
from the inner declaration - on in Perl's case - by removing
the my? Now you're warning free, but it's doubtful
whether the quality of the code did improve.
I've stumbled across this "warning" when compiling C as well.
It always makes wanting to shout "Yes, of course, you moron compiler.
That's why I use lexical variables, and not globals".
Abigail
-------->
SV* sv_bless(SV* sv, HV* stash);
[download]
I cannot imagine a case where I personally would want to use this language feature and so would like to be warned about it whenever I do this in my code.
Thx
Well, for one, this feature is extremely useful when
'slurping' an entire file into a scalar. To do this, you
must set $/ to an undefined value, but doing that
could break client code. By only 'reseting' that variable
inside a 'bare block', you guarantee that you will not
break someone's client code that might use yours. In
action, instead of using:
my $data;
while (<FILE>) {
$data .= $_;
}
[download]
my $data = do {local $/ = undef;<FILE>};
# $/ contains it's original value (\n) now
[download]
Not to make any assumptions, but how long is the sub, where did you originally declare the variable, how far away is its first use, and how far away the redeclaration? I'm just curious because I've never come across this problem and can't imagine it taking me hours to spot.
I generally declare variables right when I use them the first time, and scope them tightly, trying to declare them in the innermost of the blocks they're used in. My code blocks are as short as I can keep them - a screenfull is long, more than two is under most circumstances too much. As a result, there's very rarely any occasion where a variable name is declared further than a screen from where it goes out of scope.
For all intents and purposes these habits make it impossible to blunder in ways like this. Of course I may be way off mark, but it simply puzzles me that anyone would have this kind of trouble. My personal experience suggests it's just not possible to overlook duplicate declarations with habitual tight scoping and late declaration. YMMV of course.
Makeshifts last the longest.
jdporterThe 6th Rule of Perl Club is -- There is no Rule #6.
Dear oh
|
http://www.perlmonks.org/index.pl?node=246950
|
CC-MAIN-2015-35
|
refinedweb
| 859
| 68.5
|
--- Sebastien Sahuc <ssahuc@imediation.com> wrote:
> Stefano Mazzocchi wrote :
>
> > >?
>
> Sorry for misusing the processing-instruction term. Indeed by
> processing-instruction I meant the core and built-in logicsheets
> triggered
> by the presence of their namespace in the XSP page.
Don't forget the <?xml:logicsheet ...?>. I could be wrong but isn't
this a PI?
Giacomo
> I don't know why I had the PI in mind since I've never used them so
> far.
> Strange..,, I must have be infected by the Reactor pattern :-)
>
> Anyway, there is quite some performance problem in the current
> Cocoon2's XSP
> engine by the simple fact that it's DOM based. That's why I suggested
> to
> definitely get rid of DOM in the XSP code...
>
> Sebast!
|
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200010.mbox/%3C20001003112111.24015.qmail@web6203.mail.yahoo.com%3E
|
CC-MAIN-2016-18
|
refinedweb
| 124
| 67.45
|
Frequently asked questions (FAQ) about Azure Files
Azure Files offers fully managed file shares in the cloud that are accessible via the industry-standard Server Message Block (SMB) protocol. You can mount Azure file shares concurrently on cloud or on-premises deployments of Windows, Linux, and macOS. You also can cache Azure file shares on Windows Server machines by using Azure File Sync for fast access close to where the data is used.
This article answers common questions about Azure Files features and functionality, including the use of Azure File Sync with Azure Files. If you don't see the answer to your question, you can contact us through the following channels (in escalating order):
- The comments section of this article.
- Azure Storage Forum.
- Azure Files UserVoice.
- Microsoft Support. To create a new support request, in the Azure portal, on the Help tab, select the Help + support button, and then select New support request.
General
How is Azure Files useful?
You can use Azure Files to create file shares in the cloud, without being responsible for managing the overhead of a physical server, device, or appliance. We do the monotonous work for you, including applying OS updates and replacing bad disks. To learn more about the scenarios that Azure Files can help you with, see Why Azure Files is useful.
What are different ways to access files in Azure Files?
You can mount the file share on your local machine by using the SMB 3.0 protocol, or you can use tools like Storage Explorer to access files in your file share. From your application, you can use storage client libraries, REST APIs, PowerShell, or Azure CLI to access your files in the Azure file share.
What is Azure File Sync?
You can use Azure File Sync to centralize your organization's file shares in Azure Files, while keeping the flexibility, performance, and compatibility of an on-premises file server..
Why would I use an Azure file share versus Azure Blob storage for my data?.
For a more in-depth description on the differences between Azure Files and Azure Blob storage, see Deciding when to use Azure Blob storage, Azure Files, or Azure Disks. To learn more about Azure Blob storage, see Introduction to Blob storage.
Why would I use an Azure file share instead of Azure Disks?
A disk in Azure Disks is simply a disk. To get value from Azure Disks, you must attach a disk to a virtual machine that's running in Azure. Azure Disks can be used for everything that you would use a disk for on an on-premises server. You can use it as an OS system disk, as swap space for an OS, or as dedicated storage for an application. An interesting use for Azure Disks is to create a file server in the cloud to use in the same places where you might use an Azure file share. Deploying a file server in Azure Virtual Machines is a high-performance way to get file storage in Azure when you require deployment options that currently are not supported by Azure Files (such as NFS protocol support or premium storage).
However, running a file server with Azure Disks as back-end storage typically is much more expensive than using an Azure file share, for a few reasons. First, in addition to paying for disk storage, you also must pay for the expense of running one or more Azure VMs. Second, you also must manage the VMs that are used to run the file server. For example, you are responsible for OS upgrades. Finally, if you ultimately require data to be cached on-premises, it's up to you to set up and manage replication technologies, such as Distributed File System Replication (DFSR), to make that happen.
One approach to getting the best of both Azure Files and a file server that's hosted in Azure Virtual Machines (in addition to using Azure Disks as back-end storage) is to install Azure File Sync on a file server that's hosted on a cloud VM. If the Azure file share is in the same region as your file server, you can enable cloud tiering and set the volume of free space percentage to maximum (99%). This ensures minimal duplication of data. You also can use any applications you want with your file servers, like applications that require NFS protocol support.
For information about an option for setting up a high-performance and highly available file server in Azure, see Deploying IaaS VM guest clusters in Microsoft Azure. For a more in-depth description of the differences between Azure Files and Azure Disks, see Deciding when to use Azure Blob storage, Azure Files, or Azure Disks. To learn more about Azure Disks, see Azure Managed Disks overview.
How do I get started using Azure Files?
Getting started with Azure Files is easy. First, create a file share, and then mount it in your preferred operating system:
-
-
For a more in-depth guide about deploying an Azure file share to replace production file shares in your organization, see Planning for an Azure Files deployment.
What storage redundancy options are supported by Azure Files?
Currently, Azure Files supports locally redundant storage (LRS), zone redundant storage (ZRS), and geo-redundant storage (GRS). We plan to support read-access geo-redundant (RA-GRS) storage in the future, but we don't have timelines to share at this time.
What storage tiers are supported in Azure Files?
Azure Files supports two storage tiers: premium and standard. Standard file shares are created in general purpose (GPv1 or GPv2) storage accounts and premium file shares are created in FileStorage storage accounts. Learn more about how to create standard file shares and premium file shares.
Note
You cannot create Azure file shares from Blob storage accounts or premium general purpose (GPv1 or GPv2) storage accounts. Standard Azure file shares must created in standard general purpose accounts only and premium Azure file shares must be created in FileStorage storage accounts only. Premium general purpose (GPv1 and GPv2) storage accounts are for premium page blobs only.
I really want to see a specific feature added to Azure Files. Can you add it?
The Azure Files team is interested in hearing any and all feedback you have about our service. Please vote on feature requests at Azure Files UserVoice! We're looking forward to delighting you with many new features.
Azure File Sync
What regions are supported for Azure File Sync?
The list of available regions can be found on the Region availability section of the Azure File Sync planning guide. We will continuously add support for additional regions, including non-Public regions.
Can I have domain-joined and non-domain-joined servers in the same sync group?
Yes. A sync group can contain server endpoints that have different Active Directory memberships, even if they are not domain-joined. Although this configuration technically works, we do not recommend this as a typical configuration because access control lists (ACLs) that are defined for files and folders on one server might not be able to be enforced by other servers in the sync group. For best results, we recommend syncing between servers that are in the same Active Directory forest, between servers that are in different Active Directory forests but which have established trust relationships, or between servers that are not in a domain. We recommend that you avoid using a mix of these configurations.
I created a file directly in my Azure file share by using SMB or in the portal. How long does it take for the file to sync to the servers in the sync group?
Changes made to the Azure file share by using the Azure portal or SMB are not immediately detected and replicated like changes to the server endpoint. Azure Files does not yet have change notifications or journaling, so there's no way to automatically initiate a sync session when files are changed. On Windows Server, Azure File Sync uses Windows USN journaling to automatically initiate a sync session when files change.
To detect changes to the Azure file share, Azure File Sync has a scheduled job called a change detection job. A change detection job enumerates every file in the file share, and then compares it to the sync version for that file. When the change detection job determines that files have changed, Azure File Sync initiates a sync session. The change detection job is initiated every 24 hours. Because the change detection job works by enumerating every file in the Azure file share, change detection takes longer in larger namespaces than in smaller namespaces. For large namespaces, it might take longer than once every 24 hours to determine which files have changed.
Note, changes made to an Azure file share using REST does not update the SMB last modified time and will not be seen as a change by sync.
We are exploring adding change detection for an Azure file share similar to USN for volumes on Windows Server. Help us prioritize this feature for future development by voting for it at Azure Files UserVoice.
If the same file is changed on two servers at approximately the same time, what happens?
Azure File Sync uses a simple conflict-resolution strategy: we keep both changes to files that are changed on two servers at the same time. The most recently written change keeps the original file name. The older file has the "source" machine and the conflict number appended to the name. It follows this taxonomy:
<FileNameWithoutExtension>-<MachineName>[-#].<ext>
For example, the first conflict of CompanyReport.docx would become CompanyReport-CentralServer.docx if CentralServer is where the older write occurred. The second conflict would be named CompanyReport-CentralServer-1.docx.
Is geo-redundant storage supported for Azure File Sync?
Yes, Azure Files supports both locally redundant storage (LRS) and geo-redundant storage (GRS). If you initiate a storage account failover between paired regions from an account configured for GRS, Microsoft recommends that you treat the new region as a backup of data only. Azure File Sync does not automatically begin syncing with the new primary region.
Why doesn't the Size on disk property for a file match the Size property after using Azure File Sync?
See Understanding Cloud Tiering.
How can I tell whether a file has been tiered?
See Understanding Cloud Tiering.
A file I want to use has been tiered. How can I recall the file to disk to use it locally?
See Understanding Cloud Tiering.
How do I force a file or directory to be tiered?
See Understanding Cloud Tiering.
How is volume free space interpreted when I have multiple server endpoints on a volume?
See Understanding Cloud Tiering.
Which files or folders are automatically excluded by Azure File Sync?
By default, Azure File Sync excludes the following files:
desktop.ini
thumbs.db
ehthumbs.db
~$*.*
*.laccdb
*.tmp
635D02A9D91C401B97884B82B3BCDAEA.*
The following folders are also excluded by default:
\System Volume Information
$RECYCLE.BIN
\SyncShareState
Can I use Azure File Sync with either Windows Server 2008 R2, Linux, or my network-attached storage (NAS) device?
Currently, Azure File Sync supports only Windows Server 2019, Windows Server 2016, and Windows Server 2012 R2. At this time, we don't have any other plans we can share, but we're open to supporting additional platforms based on customer demand. Let us know at Azure Files UserVoice what platforms you would like us to support.
Why do tiered files exist outside of the server endpoint namespace?
Prior to Azure File Sync agent version 3, Azure File Sync blocked the move of tiered files outside the server endpoint but on the same volume as the server endpoint. Copy operations, moves of non-tiered files, and moves of tiered to other volumes were unaffected. The reason for this behavior was the implicit assumption that File Explorer and other Windows APIs have that move operations on the same volume are (nearly) instantaneous rename operations. This means moves will make File Explorer or other move methods (such as command line or PowerShell) appear unresponsive while Azure File Sync recalls the data from the cloud. Starting with Azure File Sync agent version 3.0.12.0, Azure File Sync will allow you to move a tiered file outside of the server endpoint. We avoid the negative effects previously mentioned by allowing the tiered file to exist as a tiered file outside of the server endpoint and then recalling the file in the background. This means that moves on the same volume are instantaneous, and we do all the work to recall the file to disk after the move has completed.
I'm having an issue with Azure File Sync on my server (sync, cloud tiering, etc). Should I remove and recreate my server endpoint?
No: removing a server endpoint is not like rebooting a server! Removing and recreating the server endpoint is almost never an appropriate solution to fixing issues with sync, cloud tiering, or other aspects of Azure File Sync. Removing a server endpoint is a destructive operation, and may result in data loss in the case that tiered files exist outside of the server endpoint namespace (see Why do tiered files exist outside of the server endpoint namespace for more information) or in inaccessible files for tiered files existing within the server endpoint namespace. These issues will not resolve when the server endpoint is recreated. Tiered files may exist within your server endpoint namespace even if you never had cloud tiering enabled. We therefore recommend that you do not remove the server endpoint unless you would like to stop using Azure File Sync with this particular folder or have been explicitly instructed to do so by a Microsoft engineer. For more information on remove server endpoints, see Remove a server endpoint.
Can I move the storage sync service and/or storage account to a different resource group or subscription?
Yes, the storage sync service and/or storage account can be moved to a different resource group or subscription within the existing Azure AD tenant. If the storage account is moved, you need to give the Hybrid File Sync Service access to the storage account (see Ensure Azure File Sync has access to the storage account).
Note
Azure File Sync does not support moving the subscription to a different Azure AD tenant.
Does Azure File Sync preserve directory/file level NTFS ACLs along with data stored in Azure Files?
NTFS ACLs carried from on-premises file servers are persisted by Azure File Sync as metadata. Azure Files does not support authentication with Azure AD credentials for access to file shares managed by the Azure File Sync service.
Security, authentication, and access control
Is Active Directory-based authentication and access control supported by Azure Files?
Yes, Azure Files supports identity-based authentication and access control with Azure Active Directory (Azure AD) (Preview). Azure AD authentication over SMB for Azure Files leverages Azure Active Directory Domain Services to enable domain-joined VMs to access shares, directories, and files using Azure AD credentials. For more details, see Overview of Azure Active Directory authentication over SMB for Azure Files (Preview).
Azure Files offers two additional ways to manage access control:
You can use shared access signatures (SAS) to generate tokens that have specific permissions, and which are valid for a specified time interval. For example, you can generate a token with read-only access to a specific file that has a 10-minute expiry. Anyone who possesses the token while the token is valid has read-only access to that file for those 10 minutes. Currently, shared access signature keys are supported only via the REST API or in client libraries. You must mount the Azure file share over SMB by using the storage account keys.
Azure File Sync preserves and replicates all discretionary ACLs, or DACLs, (whether Active Directory-based or local) to all server endpoints that it syncs to. Because Windows Server can already authenticate with Active Directory, Azure File Sync is an effective stop-gap option until full support for Active Directory-based authentication and ACL support arrives.
Is the preview of Azure AD over SMB for Azure Files available in all Azure regions?
The preview is available in all public regions.
Does Azure AD authentication over SMB for Azure Files (Preview) support authentication using Azure AD from on-premises machines?
No, Azure Files does not support authentication with Azure AD from on-premises machines in the preview release.
Does Azure AD authentication over SMB for Azure Files (Preview) support SMB access using Azure AD credentials from devices joined to or registered with Azure AD?
No, this scenario is not supported.
Are there REST APIs to support Get/Set/Copy directory/file NTFS ACLs?
The preview release does not support REST APIs to get, set, or copy NTFS ACLs for directories or files.
Can I access Azure Files with Azure AD credentials from a VM under a different subscription?
If the subscription under which the file share is deployed is associated with the same Azure AD tenant as the Azure AD Domain Services deployment to which the VM is domain-joined, then you can then access Azure Files using the same Azure AD credentials. The limitation is imposed not on the subscription but on the associated Azure AD tenant.
Can I enable Azure AD authentication over SMB for Azure Files with an Azure AD tenant that is different from the primary tenant with which the file share is associated?
No, Azure Files only supports Azure AD integration with an Azure AD tenant that resides in the same subscription as the file share. Only one subscription can be associated with an Azure AD tenant.
Does Azure AD authentication over SMB for Azure Files (Preview) support Linux VMs?
No, authentication from Linux VMs is not supported in the preview release.
Can I leverage Azure AD authentication over SMB capabilities on file shares managed by Azure File Sync?
No, Azure Files does not support preserving NTFS ACLs on file shares managed by Azure File Sync. The file ACLs carried from on-premises file servers are persisted by Azure File Sync. Any NTFS ACLs configured natively against Azure Files will be overwritten by the Azure File Sync service. Additionally, Azure Files does not support authentication with Azure AD credentials for access to file shares managed by the Azure File Sync service.
How can I ensure that my Azure file share is encrypted at rest?
Yes. For more information see Azure Storage Service Encryption..
Is it possible to specify read-only or write-only permissions on folders within the share?
If you mount the file share by using SMB, you don't have folder-level control over permissions. However, if you create a shared access signature by using the REST API or client libraries, you can specify read-only or write-only permissions on folders within the share.
Can I implement IP restrictions for an Azure file share?
Yes. Access to your Azure file share can be restricted at the storage account level. For more information, see Configure Azure Storage Firewalls and Virtual Networks.
What data compliance policies does Azure Files support?
Azure Files runs on top of the same storage architecture that's used in other storage services in Azure Storage. Azure Files applies the same data compliance policies that are used in other Azure storage services. For more information about Azure Storage data compliance, you can refer to Azure Storage compliance offerings, and go to the Microsoft Trust Center.
On-premises access
My ISP or IT blocks Port 445 which is failing Azure Files mount. What should I do?
You can learn about various ways to workaround blocked port 445 here. Azure Files only allows connections using SMB 3.0 (with encryption support) from outside the region or datacenter. SMB 3.0 protocol has introduced many security features including channel encryption which is very secure to use over internet. However its possible that port 445 has been blocked due to historical reasons of vulnerabilities found in lower SMB versions. In ideal case, the port should be blocked for only for SMB 1.0 traffic and SMB 1.0 should be turned off on all clients.
Do I have to use Azure ExpressRoute to connect to Azure Files or to use Azure File Sync on-premises?
No. ExpressRoute is not required to access an Azure file share. If you are mounting an Azure file share directly on-premises, all that's required is to have port 445 (TCP outbound) open for internet access (this is the port that SMB uses to communicate). If you're using Azure File Sync, all that's required is port 443 (TCP outbound) for HTTPS access (no SMB required). However, you can use ExpressRoute with either of these access options.
How can I mount an Azure file share on my local machine?
You can mount the file share by using the SMB protocol if port 445 (TCP outbound) is open and your client supports the SMB 3.0 protocol (for example, if you're using Windows 10 or Windows Server 2016). If port 445 is blocked by your organization's policy or by your ISP, you can use Azure File Sync to access your Azure file share.
Backup
- How do I back up my Azure file share?
You can use periodic share snapshots for protection against accidental deletions. You also can use AzCopy, Robocopy, or a third-party backup tool that can back up a mounted file share. Azure Backup offers backup of Azure Files. Learn more about back up Azure file shares by Azure Backup.
Share snapshots
Share snapshots: General
What are file share snapshots?
You can use Azure file share snapshots to create a read-only version of your file shares. You also can use Azure Files to copy an earlier version of your content back to the same share, to an alternate location in Azure, or on-premises for more modifications. To learn more about share snapshots, see the Share snapshot overview.
Where are my share snapshots stored?
Share snapshots are stored in the same storage account as the file share.
Are there any performance implications for using share snapshots?
Share snapshots do not have any performance overhead.
Are share snapshots application-consistent?
No, share snapshots are not application-consistent. The user must flush the writes from the application to the share before taking the share snapshot.
Are there limits on the number of share snapshots I can use?
Yes. Azure Files can retain a maximum of 200 share snapshots. Share snapshots do not count toward the share quota, so there is no per-share limit on the total space that's used by all the share snapshots. Storage account limits still apply. After 200 share snapshots, you must delete older snapshots to create new share snapshots.
How much do share snapshots cost?
Standard transaction and standard storage cost will apply to snapshot. Snapshots are incremental in nature. The base snapshot is the share itself. All the subsequent snapshots are incremental and will only store the diff from the previous snapshot. This means that the delta changes that will be seen in the bill will be minimal if your workload churn is minimal. See Pricing page for Standard Azure Files pricing information. Today the way to look at size consumed by share snapshot is by comparing the billed capacity with used capacity. We are working on tooling to improve the reporting.
Are NTFS ACLs on directories and files persisted in share snapshots? NTFS ACLs on directories and files are persisted in share snapshots.
Create share snapshots
Can I create share snapshot of individual files?
Share snapshots are created at the file share level. You can restore individual files from the file share snapshot, but you cannot create file-level share snapshots. However, if you have taken a share-level share snapshot and you want to list share snapshots where a specific file has changed, you can do this under Previous Versions on a Windows-mounted share.
If you need a file snapshot feature, let us know at Azure Files UserVoice.
Can I create share snapshots of an encrypted file share?
You can take a share snapshot of Azure file shares that have encryption at rest enabled. You can restore files from a share snapshot to an encrypted file share. If your share is encrypted, your share snapshot also is encrypted.
Are my share snapshots geo-redundant?
Share snapshots have the same redundancy as the Azure file share for which they were taken. If you have selected geo-redundant storage for your account, your share snapshot also is stored redundantly in the paired region.
Manage share snapshots
Can I browse my share snapshots from Linux?
You can use Azure CLI to create, list, browse, and restore share snapshots in Linux.
Can I copy the share snapshots to a different storage account?
You can copy files from share snapshots to another location, but you cannot copy the share snapshots themselves.
Restore data from share snapshots
Can I promote a share snapshot to the base share?
You can copy data from a share snapshot to any other destination. You cannot promote a share snapshot to the base share.
Can I restore data from my share snapshot to a different storage account?
Yes. Files from a share snapshot can be copied to the original location or to an alternate location that includes either the same storage account or a different storage account, in either the same region or in different regions. You also can copy files to an on-premises location or to any other cloud.
Clean up share snapshots
Can I delete my share but not delete my share snapshots?
If you have active share snapshots on your share, you cannot delete your share. You can use an API to delete share snapshots, along with the share. You also can delete both the share snapshots and the share in the Azure portal.
What happens to my share snapshots if I delete my storage account?
If you delete your storage account, the share snapshots also are deleted.
Billing and pricing
Does the network traffic between an Azure VM and an Azure file share count as external bandwidth that is charged to the subscription?
If the file share and VM are in the same Azure region, there is no additional charge for the traffic between the file share and the VM. If the file share and the VM are in different regions, the traffic between them are charged as external bandwidth.
How much do share snapshots cost?
During preview, there is no charge for share snapshot capacity. Standard storage egress and transaction costs apply. After general availability, subscriptions will be charged for capacity and transactions on share snapshots.
Share snapshots are incremental in nature. The base share snapshot is the share itself. All subsequent share snapshots are incremental and store only the difference from the preceding share snapshot. You are billed only for the changed content. If you have a share with 100 GiB of data but only 5 GiB has changed since your last share snapshot, the share snapshot consumes only 5 additional GiB, and you are billed for 105 GiB. For more information about transaction and standard egress charges, see the Pricing page.
Scale and performance
What are the scale limits of Azure Files?
For information about scalability and performance targets for Azure Files, see Azure Files scalability and performance targets.
What sizes are available for Azure file shares?
Azure file share sizes (premium and standard) can scale up to 100 TiB. Premium file shares sizes up to 100 TiB are available as a GA offering. Standard file shares sizes up to 5 TiB are available as a GA offering, while sizes up to 100 TiB are in preview. See the Onboard to larger file shares (standard tier) section of the planning guide for onboarding instructions to the larger file shares preview for the standard tier.
How many clients can access the same file simultaneously?
There is a quota of 2,000 open handles on a single file. When you have 2,000 open handles, an error message is displayed that says the quota is reached.
My performance is slow when I unzip files in Azure Files. What should I do?
To transfer large numbers of files to Azure Files, we recommend that you use AzCopy (for Windows; in preview for Linux and UNIX) or Azure PowerShell. These tools have been optimized for network transfer.
Why is my performance slow after I mount my Azure file share on Windows Server 2012 R2 or Windows 8.1?
There is a known issue when mounting an Azure file share on Windows Server 2012 R2 and Windows 8.1. The issue was patched in the April 2014 cumulative update for Windows 8.1 and Windows Server 2012 R2. For optimum performance, ensure that all instances of Windows Server 2012 R2 and Windows 8.1 have this patch applied. (You should always receive Windows patches through Windows Update.) For more information, see the associated Microsoft Knowledge Base article Slow performance when you access Azure Files from Windows 8.1 or Server 2012 R2.
Features and interoperability with other services
Can I use my Azure file share as a File Share Witness for my Windows Server Failover Cluster?
Currently, this configuration is not supported for an Azure file share. For more information about how to set this up for Azure Blob storage, see Deploy a Cloud Witness for a Failover Cluster.
Can I mount an Azure file share on an Azure Container instance?
Yes, Azure file shares are a good option when you want to persist information beyond the lifetime of a container instance. For more information, see Mount an Azure file share with Azure Container instances.
Is there a rename operation in the REST API?
Not at this time.
Can I set up nested shares? In other words, a share under a share?
No. The file share is the virtual driver that you can mount, so nested shares are not supported.
How do I use Azure Files with IBM MQ?
IBM has released a document that helps IBM MQ customers configure Azure Files with the IBM service. For more information, see How to set up an IBM MQ multi-instance queue manager with Microsoft Azure Files service.
See also
Feedback
|
https://docs.microsoft.com/en-us/azure/storage/files/storage-files-faq
|
CC-MAIN-2019-30
|
refinedweb
| 5,070
| 63.7
|
Lecture 4 Interest Rates and Interest Rate Determination. Key Interest Rates Federal Fund Rate The rate at which banks lend reserves to one another on an overnight basis. Important Points Key Federal Reserve Policy Variable Market Rate, not fixed Little FederalOR is the most widely used benchmark or reference rate for short term interest rates. It is compiled by the British Bankers Association and released to the market at about 11:00 each day. LIBOR stands for the London Interbank Offered Rate and is the interest rate at which the banks borrow funds (US Dollars) from other banks in the London interbank market.
Prime
LIBOR
Note:
- Not substitute libor for prime
- Must remember libor is variable rate prime is “fixed”
Another Way To See the Same Thing
Suppose you have a 4% bond with
Face Value $100 Coupon $4
If it sells for $100, its current return is 4% ($4/$100). Now suppose interest rates in the economy go up to 8%! Would someone pay you $100 for this bond? No, because if Price = $100 and coupon = $4, the return is 4%, not 8%.
What would someone pay? About $96.00 because
Where Do We See This in the Real World?
The yield on the 10-year Treasury note, a benchmark for corporate borrowing and home loans, soared to the highest in a year after Fed Chairmen Alan Greenspan in July testified before the House finance committee. Greenspan said conditions compelling the Fed to buy longer-term government debt in order to curb disinflation or buoy the economy “are most unlikely to arise”. (Wall Street Journal)
This quote says that when the Fed announced it would not buy long-term bonds, the market said “Demand for the bond will not be there in the future” so its price will fall. Everyone then “got out” of 10 year bonds causing its price to fall and its return to rise.
Recent Treasury Bill Auction Results
Term Issue Maturity Discount Investment Price CUSIP
Date Date Rate % Rate % Per $100
28-day 7-7-05 8-4-05 3.000 3.049 99.766 912795VK4
91-day 7/7/05 10/6/05 3.145 3.214 99.205 912795VU2
182-day 7/7/05 1/5/06 3.429 3.429 98.319 912705WH0
14-day 7/1/05 7/15/05 3.165 3.213 99.876 912795TN1
28-day 6/30/05 7/28/05 2.925 2.972 99.772 912795VJ7
91-day 6/30/05 9/29/05 3.080 3.147 99.221 912795VT5
Nominal Returns vs. REAL Returns
The Fisher Effect with Taxes
The real after tax purchasing power of a $1 investment
(1 + rat)
equals, by definition, my investment return after taxes divided by the new price of goods I purchase.
Where PE is expected inflation
2. Using “Open Market Operations” to change Fed Funds Rate
Benchmark interest rate monitored by Federal Reserve
Everyday Board of Governors informs New York Fed what Fed Funds should trade at.
At about 9:30 each day, New York Fed intervenes to set rates at the target level.
To raise Fed Funds rate, Fed must reduce amount of reserves in banking system so that banks have to pay more to borrow.
To raise rates, Fed sells Treasury Bills to government securities dealers. Dealer writes check to Fed drawn on a bank. Dealer’s bank now owes Fed $. Fed just takes it out of the banks reserves.
To lower the Fed Funds rate, Fed buys Bills from Securities dealers. It writes a check on itself which gets deposited in a bank. Bank sends check back to Fed to get $. Bank reserves rise, interbank borrowing is easier and rates fall.
Retail sweep decreased bank reserves
OMO can make Fed Funds volatile
New proposal to pay interest on reserves to keep reserve levels higher.
Yield curve spread: the difference between the 10 year Treasury Yield and 3 Month Treasury Discount.
A. Typically low right before a recession
• Boom raises short term real rates.
• Inflation has raised short rates.
• Higher short term rates kill consumer demand.
B. Primary reason spread widens in recession
• Slowdown in economic activity depresses short term rate.
• Investors expect interest rates to go up again when economy recovers so longer term rates are higher.
TWO POINTS ON YIELD CURVE SPREAD
1. You can use (somewhat reliably) the spread to forecast recessions.
NOTE: Spread low before recession
1) Short term rates high as Fed slows economy.
2) Long term rates low because markets see recession.
2. But, we must note that the spread can fall either because short rates rise, or long rates fall.
If the former (i.e. short rates rise), then falling spread reliably forecasts recession because borrowing cost increase means less borrowing, fewer car loans, fewer cars, etc.
But, if the latter (i.e. falling long rates) it is much less clear.
NOTE: Longer term rates can fall (thus narrowing the spread) because of good things
- inflation has been reduced permanently.
- government is borrowing less to finance deficits.
The Yield Curve as a Predictor
of U.S. Recessions
Arturo Estrella and Frederic S. Mishkin
Estimated Recession Probabilities for Probit Model Using the Yield Curve Spread
Four Quarters Ahead
Recession Probability Value of Spread
(Percent) (Percentage Points)
5 1.21
10 0.76
15 0.46
20 0.22
25 0.02
30 -0.17
40 -0.50
50 -0.82
60 -1.13
70 -1.46
80 -1.85
90 -2.40
Federal Reserve Bank of New York
Current Issues in Economics and Finance, June 1996, Vol. 2, No. 7
Long Rates Drop Because “inflation” is Dead !
Long rates drop because of Treasury refinancing and increased demand for Long-term govt’s.
3. Impact of Foreign Investors. Without them bidding for our debt, interest rates would be higher.
When will they bid more? When value of dollar is expected to rise. So a strong dollar lowers interest rates, all else fixed.
4. Why would Fed fear inflation?
inflation would raise interest rates and stall recovery.
inflation would raise interest rates and hurt stock market.
inflation would raise interest rates and raise government deficit.
50’s 60’s 70’s 80’s 90’s
5. Why would Fed fear deflation?
Since i = r + expected inflation, with r = 2% or 3%, deflation of 4% or more would cause normal rates to be negative ! How would loan markets then work ?
If you have deflation, debtors are in big trouble. They have to work harder to pay off loans.
Suppose you owe me $100 and you sell computers for $100 each. You only have to make 1 computer to pay me back. But if computers sell for $1 each, you now have to make 100 computers to pay me back ! Much more difficult, if not impossible.
If deflation is persistent, people will all wait to buy things (i.e. wait for the lowest price), which means economy will stall.
6. Pegging "Real" Rates. The Fed’s Current Policy?
Idea is that higher real rates slow the economy, lower real rates bolster the economy. So to slow it down, Fed raises real rates.
In place of the money supply, … Greenspan indicated he’s putting greater reliance on “real” short term rates…”
“because the ‘real’ federal funds rate, i.e. adjusted for inflation would still be positive and above its typical level.
7. Money and Interest Rates
• Liquidity effect: think of it one of these ways.
1. If something is plentiful, its price drops. So, the more money is around, the lower is the interest rate, or
2. When bank find money plentiful, they lower interest rates to get rid of it, or
3. To increase money, Fed buys Government Securities by “printing” money. When demand for Securities rises, price of securities rise. When price of a security rises, its return (interest rate) falls.
• Fisher Effect: creating to much money causes more money chasing some amount of goods. So, price of goods goes up. But if price increases cause inflation, interest rates will rise! More on this later…
|
https://www.slideserve.com/porter-christensen/lecture-4-interest-rates-and-interest-rate-determination
|
CC-MAIN-2018-34
|
refinedweb
| 1,344
| 76.52
|
Other AliasatUserValid, atScanUser, atUserName
SYNOPSIS#include <atfs.h>
#include <atfstk.h>
void atScanUser (char *userName; Af_user *resultUser);
char* atUserName (Af_user *user);
Uid_t atUserUid (Af_user *user);
int atUserValid (Af_user *user);
DESCRIPTIONatScanUser scans the given string userName and tries to derive an AtFS user identification (resultUser) from it. It does not verify the existence of a corresponding UNIX (/etc/passwd) user entry. Use atUserUid to test that. atScanUser understands the following formats:
- user
- When the string does not contain an at sign, it is considered to be a plain user name from the current host and domain.
- In the case that the part after the at sign doe not contain a period, it is assumed to be a hostname. Domain is the current domain.
- This format can only be recognized, when the given domain is equal to the current domain, and the hostname remains as rest between the at sign and domain name.
- An user identification string with a domain name different to the local domain is treated as [email protected], although this might be wrong.
atUserName returns a string of the form [email protected] generated from the given user structure. If no domain name is given in the structure, it returns [email protected] instead. With no host and no domain name, just user is returned. The result string resides in static memory and will be overwritten on subsequent calls.
atUserUid tries to map the given user structure to a UNIX user identification. It returns the uid on success, -1 otherwise.
atUserValid checks the given user structure for plausibility. It returns FALSE on fauilure, a non null value on success.
|
http://manpages.org/atuseruid/3
|
CC-MAIN-2021-49
|
refinedweb
| 268
| 56.55
|
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I've tried to use the example shown on Quark's site for multiple windows. (Linux on a BananaPi). Basically it works but the comparison of (event == MouseEvent.CLICK) fails with an error message that the two quantities can't be "compared". If I do a println(event) I get the valid long form of the event. Is there possibly a typo in the example that I haven't spotted? Thanks.
Answers
This is the code I've been using: // Experiment with inset window // quotes " " ' '
import g4p_controls.*;
GWindow window, window1; int mouseSel; void setup() { background(192, 192, 127); fill(127, 127, 192); stroke(0); window = GWindow.getWindow(this, "My new Window", 40, 20, 480, 320, JAVA2D); window1 = GWindow.getWindow(this, "My new new Window", 240, 20, 480, 320, JAVA2D); window.setActionOnClose(G4P.CLOSE_WINDOW); window.addMouseHandler(this, "windowMouse"); window.addDrawHandler(this, "windowDraw"); window1.setActionOnClose(G4P.CLOSE_WINDOW); window1.addDrawHandler(this, "windowDraw1"); window1.addMouseHandler( this, "windowMouse1"); window1.addData(new MyData()); window.addData(new MyData()); }
void draw() { rect(100, 100, 100, 100); //line(width/2, height/2, mouseX, mouseY); }
void windowDraw(PApplet app, GWinData data) { app.background(127, 127, 0); app.strokeWeight(2); app.stroke(0); app.line(app.width/2, app.height/2, app.mouseX, app.mouseY); }
void windowDraw1(PApplet app1, GWinData data) {
if (mouseSel ==1) app1.fill(127, 0, 0); else app1.fill(255); app1.background(127, 127, 0); app1.strokeWeight(2); app1.stroke(0); app1.line(app1.width/2, app1.height/2, app1.mouseX, app1.mouseY); app1.rect(50, 50, 100, 100); if (app1.mouseX >=50 && app1.mouseX <=150 && app1.mouseY >= 50 && app1.mouseY <= 150) mouseSel = 1; else { mouseSel = 0; //println(mouseSel); window1.setVisible(true); } }
public class MyData extends GWinData { public int lastClickX, lastClickY; }
public void windowMouse1(PApplet app1, GWinData data, MouseEvent event) { MyData myData = (MyData) data; if (event == app1.MouseEvent.CLICK) //println( MouseEvent.CLICK); println(); }
public void windowMouse(PApplet app, GWinData data, MouseEvent event) { MyData myData = (MyData) data;
println( MouseEvent.CLICK); println(event ); }
// void setVisible(false);
Java can have classes w/ same name but w/ diff.
package. :-S
I apologize for the poorly formatted code. I've noticed there are various versions of Java (4 I believe). Do you think I may be using the wrong one? The only problem I've run into is with the Mouse Event. It seems the mouse handler statement is calling the function ok but the function isn't returning data in a form that the "if" statement can handle. A simplistic question is where should I go from here?
Rather than apologize, you should edit your post and fix the formatting.
The way it is now it's not possible to help you.
Moreover I wonder if that even compiles?
Yes it compiled with no problem. What I cut and pasted into here is a much messier version of the actual program Word Pad wasn't kind! I'll try again to get a cleaner post. Thank you for your attention to my problem.
````// Experiment with inset window // quotes " " ' '
Hopefully this makes more sense!
As I had guessed, your posted code above failed to compile: :-w
if (event == app1.MouseEvent.CLICK) println();
processing.event.MouseEvent isn't some processing.core.PApplet's nested class but an actual top class:
Therefore there's no sense relying on app1, which is a PApplet reference, in order to reach MouseEvent!
And CLICK is an
intconstant. So you still need to get an
intoutta event, which holds a MouseEvent's reference.
I've found processing.event.Event's method getAction() for it btW:
if (event.getAction() == MouseEvent.CLICK) println();
Indeed, that worked, thank you for your effort on my behalf. I blame myself for not fully appreciating that the "processing" group, and Quark's G4P are independent of each other. In any case your suggestion worked fine. Have a Merry Christmas.
|
https://forum.processing.org/two/discussion/13952/i-m-having-a-mouse-event-problem
|
CC-MAIN-2020-34
|
refinedweb
| 654
| 61.73
|
On Nov 19, 2006, at 10:38 AM, Jeremy Quinn wrote:
> Hi Mark
>
> Many thanks for getting back to me so quickly.
You're welcome :-).
Normally I don't do this on Sunday... but today I ditched church to
work on my med school applications, so I am home.
So, why am I fooling around with Cocoon, then? Procrastination, I
guess :-/.
Anyway -- could you do me a quick favor and paste me an "svn diff" of
this file, taken from the context of trunk root? That will become my
patch :-). I'm creating the JIRA issue right now, and I don't want to
goof and submit bad code... :-/
> It compiled fine, and it seems to work with both namespaced and
> non-namespaced JavaScript.
Glad to hear it :-)
cheers,
—ml—
|
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200611.mbox/%3Cb370516a821c37be45ecab1116d7a1ad@wrinkledog.com%3E
|
CC-MAIN-2016-44
|
refinedweb
| 130
| 84.27
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.