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
|
|---|---|---|---|---|---|
Hi guys, so I'm writing a program that I can later implement into maybe a blackjack game or something if I want to. Anyways it's supposed to create a deck of cards, and each card is stored in 1 byte (each element of a 52 byte character array should store a card number/suit). I'm using bitwise operators etc to do this.
Anyways I'm not receiving the output that I want. The output that I should be getting (if it worked properly) would be an even amount of suits (13 of each suit). Instead I'm getting 5 clubs, 16 diamonds, 15 hearts, 16 spades. I'm pretty certain it's a flaw in my constructor, which is modifying the binary in each byte of the array.
Here is the output that I get when I run the program:
As you can see, that's not right.. It is SUPPOSED to be Club, Diamond, Heart, Spade, in that order for every card. So ovbiously there is something wrong with the method I'm using in the constructorAs you can see, that's not right.. It is SUPPOSED to be Club, Diamond, Heart, Spade, in that order for every card. So ovbiously there is something wrong with the method I'm using in the constructorCode:Card 0: 00000000 suit: Club Card 1: 00010001 suit: Diamond Card 2: 00100010 suit: Heart Card 3: 00110011 suit: Spade Card 4: 00000100 suit: Club Card 5: 00010101 suit: Diamond Card 6: 00100110 suit: Heart Card 7: 00000111 suit: Club Card 8: 00011000 suit: Diamond Card 9: 00101001 suit: Heart Card 10: 00001010 suit: Club Card 11: 00011011 suit: Diamond Card 12: 00101100 suit: Heart Card 13: 00001101 suit: Club Card 14: 00011110 suit: Diamond Card 15: 00101111 suit: Heart Card 16: 00010000 suit: Diamond Card 17: 00010001 suit: Diamond Card 18: 00110010 suit: Spade Card 19: 00010011 suit: Diamond Card 20: 00010100 suit: Diamond Card 21: 00110101 suit: Spade Card 22: 00010110 suit: Diamond Card 23: 00010111 suit: Diamond Card 24: 00111000 suit: Spade Card 25: 00011001 suit: Diamond Card 26: 00011010 suit: Diamond Card 27: 00111011 suit: Spade Card 28: 00011100 suit: Diamond Card 29: 00011101 suit: Diamond Card 30: 00111110 suit: Spade Card 31: 00011111 suit: Diamond Card 32: 00110000 suit: Spade Card 33: 00100001 suit: Heart Card 34: 00100010 suit: Heart Card 35: 00110011 suit: Spade Card 36: 00100100 suit: Heart Card 37: 00100101 suit: Heart Card 38: 00110110 suit: Spade Card 39: 00100111 suit: Heart Card 40: 00101000 suit: Heart Card 41: 00111001 suit: Spade Card 42: 00101010 suit: Heart Card 43: 00101011 suit: Heart Card 44: 00111100 suit: Spade Card 45: 00101101 suit: Heart Card 46: 00101110 suit: Heart Card 47: 00111111 suit: Spade Card 48: 00110000 suit: Spade Card 49: 00110001 suit: Spade Card 50: 00110010 suit: Spade Card 51: 00110011 suit: Spade
Here is the code:Here is the code:
I receive no compiler errors or warnings, and I'm using visual studio C++ in case you're wondering. Thanks!I receive no compiler errors or warnings, and I'm using visual studio C++ in case you're wondering. Thanks!Code:#include <iostream> #include <cstdlib> using namespace std; void outputBinary(char value); void checkSuit(char value); class CardDeck { public: CardDeck(); ~CardDeck(); unsigned char * cards; }; CardDeck::CardDeck() { int i = 0; int x = 0; int count = 0; this->cards = new unsigned char[52]; for (int i = 0; i < 52; count++) { this->cards[i] = i++ | x; x+=16; if (count == 3) { x = 0; count = 0; } } } CardDeck::~CardDeck() { delete [] this->cards; } int main() { CardDeck c; for (int x = 0; x < 52; x++) { cout << endl << "Card " << x << ": "; outputBinary(c.cards[x]); cout << " suit: "; checkSuit(c.cards[x]); } } void checkSuit(char value) { unsigned char x = 0x30 & value; switch ( x ) { case 0x30: cout << "Spade"; break; case 0x20: cout << "Heart"; break; case 0x10: cout << "Diamond"; break; case 0x0: cout << "Club"; break; default: cout << "No match found."; break; } }
|
https://cboard.cprogramming.com/cplusplus-programming/107051-bitwise-unwanted-output.html
|
CC-MAIN-2017-22
|
refinedweb
| 655
| 57.68
|
Many websites have started replacing the right-click context menu with one of their own. Firefox lets me choose whether a website can disable Firefox's menu, but not much else.
Neither value of the Firefox's setting is acceptable: allow it to be blocked, and I can never access some of the features on some websites. Disallow, and I have two menus on every website that uses this feature legitimately:
Is there an addon that would solve this problem elegantly? For example, by letting right-click do what the site wants, but making Ctrl+Right Click always show the Firefox menu?
Partial solution, but better than nothing:
With Toolbar Buttons, you have an additional button Toggle JavaScript on/off that you can add to any toolbar in Firefox.
Toggle JavaScript on/off
Then, you set Firefox to allow to replace context menus by the sites.
When you don't like context menu provided by the site you're on, you toggle JS off - then, on right-click you have original Firefox menu. Toggle on and you have site's menu back.
Remember however that when the page loads, you should probably have JS turned on, otherwise you may have to reload the page for certain onload JavaScripts to be invoked.
onload
BTW.
The Toggle JavaScript on/off button, contrary to Stop Flash button, does not kill JavaScript, only let's call it "pauses it". You have to use both to see the difference ;) "Stop Flash" will kill all preloaded YouTube videos for instance, and after switching it back on, all the Flash content will have to be reloaded. JavaScript is only paused.
Stop Flash
If you have a keyboard with a context menu button (to the right of the space bar on most English keyboards) you can always display the default applications context menu (ie. the browsers context menu) by hitting this key.
If you have a 3 (or more) button mouse then you could configure one of the other buttons to display the applications context menu (more commonly displayed with the right mouse button).
For what it's worth I have same issue dealing with hotmail.com it has a context menu override and I only want that site to be able to override the context menu (right mouse click) not EVERY SITE. It looks like a button to disable javascript (or should I say "pause") the intercepts seem like one work around.
I use Opera as a secondary browser as it has a "site prefences" where you can configure a per site override to stop context menu intercepts when you find a site that is deliberately blocking/overriding the standard context menu (copy, cut, paste etc). This is what Firefox needs.
You can disable Javascript changing the context menu per site, if you use a Greasemonkey script:
You can include or exclude pages as you like.
// ==UserScript==
// @name Enable Context Menu
// @description Restore context menus on specific sites that try to disable them
// @namespace
// @include http://*marktplaats.nl/*
// @include http*
// @exclude http*://maps.google.com/*
// ==/UserScript==
function doIt() {
unsafeWindow.document.onmousedown = null;
unsafeWindow.onmousedown = null;
unsafeWindow.document.oncontextmenu = null;
unsafeWindow.oncontextmenu = null;
if (document.all) {
allElemsCount = document.all.length;
for (var i = 0;i < allElemsCount;i++) { document.all[i].setAttribute("oncontextmenu", "return true;");
document.all[i].setAttribute("onmousedown", "return true;");
document.all[i].setAttribute("onmouseup", "return true;");
} }
else {
allElems = document.getElementsByTagName('*');
allElemsCount = allElems.length;
for (var i = 0;i < allElemsCount;i++) {
allElems[i].setAttribute("oncontextmenu", "return true;");
allElems[i].setAttribute("onmousedown", "return true;");
allElems[i].setAttribute("onmouseup", "return true;");
} } }
window.addEventListener("load", function() { doIt();
}, false);
I've tried it, and it works properly. No custom menu on Google docs nor on NewsBlur. The menu you showed in the picture, is a drop down menu and not a right-click menu.
Also, make sure you've installed the latest version.
By posting your answer, you agree to the privacy policy and terms of service.
asked
3 years ago
viewed
1157 times
active
|
http://superuser.com/questions/366016/firefox-right-click-easy-support-for-the-firefox-or-the-sites-menu/443734
|
CC-MAIN-2015-35
|
refinedweb
| 664
| 66.33
|
France
Ile de Re - best route from UK?-In Marseille 2 days before 1 week in Luberon -suggestions?
France
Travel Forums
Day trips out of Montpellier in February?–Limo hire in Paris HELP!
Ile de Re - best route from UK?-In Marseille 2 days before 1 week in Luberon -suggestions?
Ile de Re - best route from UK?
Ile de Re - Can anyone recommend a guidebook?
Ile de Re Bastille Day
Ile De Re Campsites
Ile de Re campsites
Ile de re for the day !
Ile de Re France
Ile de re in April
Ile de Re in April - must sees and day trips
Ile De Re in June
Ile de Re in one day
Ile de Re in September
Ile de Re New Year
Ile De Re or La Rochelle as a base
Ile De Re or Royan?
Ile de Re restaurants
Ile de Re Sep 08
Ile de Re this week!
Ile de Re to Beziers
Ile de Re transport
Ile de Re vs Ile Oleron
Ile de Re with a 2 year old
Ile de re with a baby
Ile de Re, ile d'oleron or noirmoutier (vendee)???
Ile de Re- Is Loix a good village to stay in self catering?
Ile de Re/La Rochelle in late August -- how busy?
Ile de re??
Ile de Rhe with 19 month old ADVICE NEEDED
Ile de Ré with a baby (10 months) - car or public transport?
Ile de Ré with a baby (10 months) - car or public transport?
Ile des Cygnes
Ile des Machines
Ile du Levant et Libertinage
Ile Du Re vs Porquerolles
Ile flottante dessert availability in Paris restaurants...
Ile Rousse and Hotel Napoleon Bonaparte...
Ile Rousse hotel query
Ile Rousse or Calvi for week stay? Travelling with 6 yr old.
Ile Rousse to Bonifaccio
Ile Rousse/St Florent or Calvi?
Ile Saint Louis
ile saint louis
Ile Saint Louis
ile saint louis - best hotel accommodation
Ile Saint Louis Apartment
Ile Saint Louis Apartment
Ile Saint Louis apartments
Ile Saint Louis for New Years Eve
Ile Saint Louis or 7th Arrondissement
ile Saint Louis or Eiffel Tower , which location?
Ile Saint Louis or La Marais---to stay?
Ile Saint Louis or St. Germain?
Ile Saint Louis Picnic Supplies
Ile Saint Louis recommendations
Ile Saint Louis vs. Le Marais
Ile Saint Louis...Help on finding lodging
Ile Saint-Louis
Ile Saint-Louis
Ile Saint-Louis hotels
Ile St Louis
Ile St Louis
Ile st Louis
ile st louis
Ile St Louis
Ile St Louis
Ile St Louis
Ile St Louis -Paris
ile st louis accommodation/luggage storage for 1 day
Ile st louis one bedroom apt with lift?
Ile St Louis or La Marais----to stay?
Ile St Louis Restaurants
Ile St Louis safe at night for solo woman?
Ile st Louis shops
ile st louis vs st germain apt
Ile St- Louis to Montmartre
ile st-loius apartments
Ile St-Louis - Romantic?
Ile St. Louis
Ile St. Louis
Ile St. Louis "not to miss restaurants"
Ile St. Louis Apartment....
Ile St. Louis or Left Bank
Ile St. Louis recommendations please!
Ile St. Louis Restaurants
Ile St. Louis- worth a visit?
Ile St. Marguerite
Ile st.-Louis and Ile de la Cite on Sunday
Ile Ste-Marguerite & Ile St-Honorat
Ile Ste-Marguerite questions
Ile-de-France is a good place to stay for site seeing
Ile-de-France Billet
Ile-de-France villa/gite
Ileana, I need your help!
Iles d'Hyeres - Port Cros
Iles de Lerins boats
Iles des Lerins
Iles Du Frioul
ill St LOuis - Marais - Bastille
Ille Rousse to Calvi
illefranche sur mer to Monaco
Illegal air bnbs in Paris?
illegal Airbnb rentals
Illegal vacation rentals
Illuminated Paris tour
Illuminating Light of Eiffel Tower in January
Illumination of Notre Dame at night
Illumination Tour
illumination tour advise
Illumination tour and a trip on the river
Illumination Tours
Illumination Tours : non-stopping?
Illuminations of PAris
Illuminations of Paris question
Illuminations Tour
Illuminations Tour
Illuminations tour / Paris at night
Illuminations tour with cuise and dinner?
ILP language school
Ils de Re - not dog friendly beaches
Ilse saint louis
Ilse-sur-le-Sorgue
Ilternary needed (urgent)
Im a single mother. Is it safe for me late at night?
Im a Vegetarian, will I struggle in Nice?
Im a writer - where can I go?
Im Back
im down to 4 hotels - can you help me decided please? ( I think)
Im going backkkkkkkkkkkkkkk!!!! =) =) =)
Im going to paris on december 12th and it says rain,rain...
Im going to study in Marbella soon ;)
Im here :D
im leaving soon!
Im leaving to NYC and Miami, have nice holidays!
Im looking for affordable accommodation
Im lost! Paris and what else? Marseille? Tours?
im sure its safe!!!
Image tours inc
Image Tours Inc. Heart of Europe Tour
Image Tours Inc. Heart of Europe Tour
Imax
IMEF Language School in Montpellier
Imigration information travelling on France work permit
Imitation Chanel
Immediate Help Needed about RER B
Immediate help needed from locals
Immediate help with sncf
Immersing my kids in France
immersion french for kids
Immersion French language schools
Immigrants
Immigrants Calais
Immigrants in Calais
immigration & custom
Immigration & Customs on the train to Ventimiglia
Immigration and Customs at CDG
Immigration and Passport Control Question
Immigration at CDG
Immigration at CDG for transit passengers
Immigration at Charles de Gaulle
Immigration at St Pancras: re Schengen visa type C
Immigration check at CDG
Immigration check St. Pancras to London
Immigration checkpoints
Immigration checks
Immigration Checks at Paris CDG when arriving from UK
Immigration checks: Venice to Paris, Paris to India
Immigration control at CDG Paris
Immigration counters at Terminal 2C and Terminal 2E
Immigration during re-entry
Immigration form
Immigration from london to paris
Immigration in Nice
Immigration Information
Immigration queue time?
Immigration Stamps Across Schengen Area
Immigration/ Customs in Paris for Connecting Flight
Immigration/customs in wheelchair
Immigration/Passport Control in Paris.
Immigrations & Customs Upon Entry to Europe
Immigrations and changing terminals at Charles DeGaulle
Immigrations and Customs
Immiigration queses at airport
Immobility Parking Paris
Immogroom - are the trustworthy?
Immogroom??? Urgent !!!
Impact from the Strikesss?
Impact of construction on airport bus
Impact of Euro Cup 2016
Impact of Holidays on Canal Barge Trip
Impact of Rainy weather on major toursit attractions
Impact of Tour de France on prices?
Impact of upcoming national holidays
Impact of World Equestrian Games on other places in Normandy
IMPERATOR hotel nimes
Imperial Theatre of Fountainbleu-opening?
import question - homebrew ok?
Important bus fare changes from 3rd may
Important bus stop changes from 5 November
Important Changes to bus routes - sunday 5th july
Important changes to the tramway during carnaval
Important French words and phrases
Important Info for car rental GVA
Important links for visitors to Paris
important news re burials at Fromelle
Important Note about Getting Euros
Important Observation!
Important piece of info for tourists!
Important Places in and around Toulouse
Important restaurant question -> see inside
important train cancellations -now till 6th july
Important train news - Nice to Antibes 27/28 march
Important Versailles Questions -- thanks in advance!
Important work on Nice-Breil train line sunday 10th june
IMPORTANT: Update to Monet at the Grand Palais dates
Imports - more expensive, or the same?
Impossible?
Impressionism and Fashion at the Musee d'Orsay
Impressionist artwork
Impressionist exhibition opened today
Impressionist train to Giverny
Impressionist Walking/Metro Tour
Impressionist Walking/Metro Tour
impressions
impressions of Paris
Impressions of Paris from a Firstimer
Impressions of Paris...our June trip report
Impromptu December ski trip to Chamonix
Impromptu ferry crossing with motorcycle
impromptu trip
Improved TER train service from December 14
Improving my French
Impulse trip to Paris booked today, leaving in 2 days. Help!
In & around Strasbourg with kids
in 7th for one day (sunday) want to find a certain wine
in a Paris for 3 days... What are a must see?
In addition to Rouen, what else?
In and around Notre Dame
In and around paris
In and out of Bastia for one week in June
in and out of the schengen zone
In Avignon from 14th to 17th August
In Avignon now...recommend stores please
In Avignon/Vaucluse in June (8th) for 10 days
In between Marseille and Paris?
In between Paris and Interlaken, Switzerland?
In Between Paris Visits
in biarritz--visit Balenciaga Museum or San Sebastian
In Bordeaux for 1 night with family in early July
In Brittany for 4 days in late March or early April
In by train and out by ferry a day and luggage
In Caen 1 month: What to do/avoid?
In Cannes 1 day
In Cannes during Film Festival..what to do with 4 days after
In Cannes for 11 hours....what to do?
In Cannes from 8 to 5
In case my 2-year old has a asthma attack
In case of a snowstorm
In case of an Emergency?
In case you missed it, Hotel du Pantheon *** is now.....
In case you missed Nuit Blanche 2018
In case you're undecided
In cassis for a little bit
In Chamonix now!
In college and on a tight budget....
In Collioure Oct 30 - Nov 1
In Colliure now, need some advice please
in Colmar -- need advice
In Consideration of the Arrondissements
In depth Loire Valley Stay
In desperate need of itinerary help!
In desperate need of suggestions.
In Dijon for 3 days
In disappear
In early May what time does it get dark?
In Europe from 12/03 to 12/11 arriving in Paris.
In France for 10 days
In France for 13 days any ideas for an Itinerary
In France for 3 Weeks Suggestions?
In France for 90/180 days, can I get a visa?
In France for approx 9 days
In France, the Customer is Always WRONG
In general.....?
in home chef and cooking classes
In Honfleur for a few hours. What to do?
In honor of Julia Child and French cuisine
in Hotel K+K now , need advice on cruise
In January to Paris for the 3 time!
In June, Provence and...?
In just 3 hours' time......
In land beaches or best kayaks places for children
In Langrune, France, where is Maurice Belliere buried?
In last 1-2 wks, anyone stay @ Ambassadeur in Juan Les Pins
In late July, when does Eiffel Tower start sparkling?
In less than a month I'll be in Paris! Question..
In love with Brittany!
in love with Claude Lelouch
In Lyon for three nights - tell me what to eat and where
In Marais - Hotel Beaubourg vs. Hotel Jeanne d'Arc
In Marseille 2 days before 1 week in Luberon -suggestions?
|
https://www.tripadvisor.com/SiteIndex-g187070-o194-q2-sShowTopic-France.html
|
CC-MAIN-2019-47
|
refinedweb
| 1,754
| 71.65
|
An interesting dilemma that I ran into when working on my game in Libgdx with your favorite subject! Fonts, specifically today, I wanted to talk about how to center text in Libgdx.
For example, let’s say you want to have text on an HP bar. How would you keep it in the center? You might try to manually position the text to be in the middle doing something like this:
steps.setPosition(60, 19);
If you do that, it will work and you might get something like this:
But let’s say w that if we want to keep the numbers in position where they are now and our 1,000 becomes 10,000, here’s what we get:
If you can see, our denominator was pushed further left. This might not be a problem for smaller numbers, but if you have larger ones or numbers of different sizes like 9999 vs 1111, then you might see a problem.
So what do we have to do if we want to always keep the division number in the center or our progress bar so that everything is consistent?
The answer is simple: we have to do some math to adjust the text!
If you want to center an image, in respect to something else, we should already know the position of the element we’re trying to center our text in.
So let’s say that our progress bar is located at: 100, 100 (x, y).
100, 100 (x, y)
The progress bar’s dimension is 100 x 20 (width, height).
100 x 20 (width, height)
Our text is 10,000/10,000 which we want to center on the “/”. To achieve this value, we need to position our text the width of the numerator to the left so that we can center the “/”. Let’s say the width of the numerator is 25 pixels.
10,000/10,000
/
Now that we know the position and size of our progress bar and the text, the first thing we have to do is set our text to be in the middle of the bar. In this example (ignoring height), that would be the:
And that’s it!
Now that we have the general idea on what to do, let’s get to see some real code.
The biggest problem that you’ll encounter is when trying to position the text is to figure out the size of the text. The text size varies based off of the length and even the type of number used.
Luckily in LibGdx, we have the GlyphLayout class that can help us figure out the exact size of the string of your choice!
GlyphLayout
string
Using it is pretty simple, here’s a method I wrote to get the position for me:
private float getPositionOffset(BitmapFont bitmapFont, String value) {
GlyphLayout glyphLayout = new GlyphLayout();
glyphLayout.setText(bitmapFont, value);
return (MenuConstants.HEADER_STEP_BAR_WIDTH / 2) - glyphLayout.width;
}
All you need to do is create an instance of GlyphLayout and give it the bitmapFont type you want to use with the text and then you can get the width and height of the text you inserted!
bitmapFont
In this example, I already did some calculations with HEADER_STEP_BAR_WIDTH, which as you might guess is the width of the progress bar. I divided it by 2 in order to figure out the center point of the progress bar.
HEADER_STEP_BAR_WIDTH
And I called the method in my constructor/draw()/or wherever else you want to add your logic by doing something like this to get the correct position:
draw()
steps.setPosition(60 + getPositionOffset(f, "1,000"), 19);
In this particular instance, the X location of my progress bar is at 60 and I added the width of it and then subtracted our numerator offset to put our division sign in the middle. You can ignore the rest.
With this line of code now, you’ll be able to have a dynamically changing text that will always be in the center no matter what the value of the numerator and the denominator is.
Here’s an example of our progress bar with our new code!
Notice that now the “/” is in the center of the bar now? Awesome!
Hopefully, you’ve found this helpful. If you have any questions, leave a comment below!
The post How to Center Text In Libgdx appeared first on Coding Chronicles.
CodeProject
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
|
https://www.codeproject.com/Articles/1207753/How-to-Center-Text-In-Libgdx
|
CC-MAIN-2017-51
|
refinedweb
| 751
| 77.16
|
Component Object Model is a method to facilitate communication between different applications and languages. There are many other ways to structure software components. What makes COM interesting is that it is a widely accepted interoperability standard. In addition, the standard explains the way the memory should be organized for all the objects.
Interfaces are the contract between the client and the server, i.e. an interface is the way in which an object exposes its functionality to the outside world. In COM, an interface is a table of pointers to functions implemented by the object. The table represents the interface, and the functions to which it points are the methods of that interface.
Creating COM components in .NET is not that difficult as in C++. The following steps explain the way to create the COM server in C#:
IManagedInterface
Guid
IID
GuidAttribute
System.Runtime.InteropServices
[Guid("3B515E51-0860-48ae-B49C-05DF356CDF4B")]
CLSID
ComVisible
[assembly: ComVisible (true)]
The COM server is ready. Now a client has to be created. It can be in any language. If the client is .NET, just add the above created COM assembly as reference and use it.
The following steps explain the method to create an unmanaged client. Here the client is in VC++ 6.0.
#import
#import “ComInDotNet.tlb” no_namespace named_guids raw_interfaces_only
CoInitialize
CoCreateInstance
pInterface->Execute(“blah blah blah”);.
|
http://www.codeproject.com/Articles/23400/COM-in-NET?msg=2808069
|
CC-MAIN-2014-42
|
refinedweb
| 224
| 52.26
|
The Riddle
Are you ready for a nice C# riddle? It’s not an easy one ;-) so be sure to take a deep breath before jumping on it. Ready? Yes. Great! Take a good look at this line of code (thanks for taking the photo Georg!):
To avoid any misunderstandings, here is the line I am talking about:
var var = await async as async;
Now, my question to you is - is this a potentially valid line of C# code? ;-)
In other words, is it possible to write a C# program that at the same time contains the above line and compiles?
To make the question less abstract and more concrete, let’s pack the line into a bit of surrounding code:
class AwaitAsyncAsAsync { void CanYouMakeMeCompilable() { var var = await async as async; } }
Now we can precisely formulate the riddle. Is it possible to make the above code compileable under the following three conditions:
- It is not allowed to modify any of the existing lines of code.
- It is not allowed to delete any of the existing lines of code.
- It is only allowed to add arbitrary text in-between the existing lines of codes.
Now take a deep breath again and try to solve the riddle on your own. Take your time. You can even close this browser tab if you want. Come back once you are done to compare your approach with the solutions (yes, solutions and not a solution ;-)) given below. Keep in mind that “No, it is not possible to make that code compileable under the conditions given above.” is also a valid answer, as long as you can back it up with an argument or two.
C’mon don’t scroll down now!
I’am serious. Close this browser tab.
Don’t look at the solutions!
Give the riddle a try.
Take your time.
Think of it. Try to solve it on your own.
Think. Don’t scroll down.
Still thinking? Good.
The not so Obvious Obvious Solution
I guess you were looking for some super complex solution and missed the obvious one. I mean this one:
class AwaitAsyncAsAsync { void CanYouMakeMeCompilable() { /* var var = await async as async; */ } }
“Wait a minute! That’s cheating!”, I can hear you saying. Why? It perfectly satisfies all the three conditions and the code compiles ;-) Thus, it’s a valid solution for our riddle. Yes, we walked around the labyrinth and not through it. But the goal was to get to the other side and not to escape the room ;-)
However, my purpose for this riddle was not to teach you thinking outside of the box but rather to point out these two facts:
- Not every C# programmer is aware of C#’s contextual keywords, although he or she should be ;-)
- Writing a semantical analyzer for C# code is a tremendously difficult endeavor. Thus, getting it for free in form of Roslyn is absolutely awesome :-)
Let’s talk about the contextual keywords first.
Contextual Keywords
The riddle was originally developed for my talk on Roslyn, the C# and VB.NET Compiler-as-a-Service. Up to now, I gave that talk several times in different countries and occasions and I always asked that question - is the
var var = ... line potentially compileable. The answers given on-the-fly from the numerous audiences varied from “No, it is not possible to make it compileable because a variable cannot be named
var.” to “Hm, maaaybeee. It might be that some existing code already had a variable called async at the time the
async keyword was introduced in C#, so…”
Most of the answers were in the first category. As far as I remember, dear talk participants correct me if I am wrong, none on of the answers ever was a clear “Yes, it is possible.”
Which tells me that the C# team didn’t do the best job possible in explaining the contextual keywords to the faithful users of the language it develops. Below is a short and simple explanation. It should be enough to grasp the idea behind C# contextual keywords. After all, they are a completely logical language feature, one of those easy to comprehend.
Let’s take the
var keyword as example. What makes it contextual? The
var keyword, was introduced in C# 3.0 somewhere back in 2007. At that point in time C# already existed for several years and there were already millions of lines of production code living out there in the wild. The chances were that somewhere in that haystack of code, there was a local variable or a filed or a property or a method, or… you name it named var. Not the best name for a variable, or a filed or a property or whatever, but yes, the possibility was there.
C# aims to be backward compatible. Thus, the code that potentially contained that unfortunate identifier called var still had to compile. Thus, the compiler had to distinguish between an identifier called var and the
var keyword. To get a feeling for what that actually means, try to distinguish on your own which vars in the example given below are identifiers, and which are the
var keyword:
int a = this.var(); var b = 0; int var = 0; var = this.var(var); int.TryParse("123", out var result);
I guess it wasn’t too hard to realize that only the
vars in the second and the last line represent the keyword. Other occurrences are valid C# identifiers.
In other words, var is just a regular C# identifier. Only in the context of a variable declaration, or an out variable it becomes a keyword. Thus - contextual keyword.
Long story short, this makes the
var var = ...
part perfectly valid. The same is with the
async keyword. The word async is a valid C# identifier. In the matter of fact I saw it once in a code written before
asyinc-await was introduced in the C# 5.0. It represented a boolean variable that was supposed to control a potentially asynchronous execution. The better name for the variable would most likely be isAsync or shouldBeAsync but that’s another story.
Back to our riddle. Equipped with the knowledge of contextual keywords, we can now formulate our first non-trivial solution.
A Non-Trivial Solution
So, the “
var var =” part simply declares and initializes a variable called var. What about the right side of the assignment? Obviously, we need a variable called async and a class called async with a single requirement. In order to use
await the expression:
async as async
must, of course, be awaitable. Which, after a bit of acrobatics in our mind, leads us to the following solution:
class async : Task<int> { public async() : base(() => 0) { } } class AwaitAsyncAsAsync { async void CanYouMakeMeCompilable() { Task<Task<int>> async = null; var var = await async as async; } }
The solution satisfies all the three conditions and compiles. I’ll let you figure out on your own how it works. Trust me, it’s straightforward to understand :-)
The Robert’s Solution
Robert Kurtanjek, a colleague of mine, sent me an another solution after I challenged him with the riddle. His solution is in my opinion much more elegant and based on a simple trick. Here it is:
using System.Threading.Tasks; using async = System.Threading.Tasks.Task; class AwaitAsyncAsAsync { async void CanYouMakeMeCompilable() { var async = new Task<Task>(() => new Task(() => { })); var var = await async as async; } }
Again, being a valid C# identifier, async can be used in the
using statement as done by Robert. The compiler then figures out the rest.
Although Robert’s solution is more elegant, in my talk on Roslyn I still use the first one. Why? Because it confuses ReSharper and clearly demonstrates how difficult it is to write a bullet-proof semantic analyzer for C# code. Which brings us to the final chapter.
An Extremely Difficult Endeavor
It is an extremely difficult endeavor, indeed. I was once in a team that decided to challenge that difficulty. We tried to utilize a community defined Antlr parser for C# in order to analyze C# source code and to extend the C# grammar a bit.
C# was a much simpler language at that time. The good, old version 2.0. No lambdas, no
vars no
async-awaits. No plenty of other language elements that poured in during the past ten years. To be frank, I wasn’t directly working on that task. (Actually, I was developing another one language from the scratch as a part of the same project.) But I was well informed about the effort behind the attempt to parse and analyze C# code on our own. And I was secretly worrying what is going to be in a month or two when C# 3.0 hits the market. Is the diligent community going to extend the Antlr parser? If yes, how quickly? Or are they just going to give up at certain point and leave us in a blind alley? (While writing this post I got curious if there are still Antlr parsers for C# available and if they cover the C# 7.2. The best thing I found after a bit of search is this parser for the C# 6.0 that apparently has some slight issues with “with deep recursion, unicode chars and preprocessor directives”.) And even if they do extend the parsers, it’s just the parser we are getting. As we will see later, the semantic analysis is where the things get really complex.
Luckily, our higher management killed the project before we were forced to face this unpleasant questions rooted in our bold decision to write a C# code analyzer on our own.
Facing the Difficulty
Still, there are those who are brave enough and skilled enough to face this extreme difficulty. The ReSharper team is a great example. Since 2004 ReSharper developers closely follow the evolution of C# and develop its own parser and analyzer in order to build an awesome product on top of them. Even now, when it appears that Roslyn made their efforts obsolete, ReSharper developers will continue to write their own C# parser and analyzer. And they have a plenty of good reasons for that. No, please do not dare to ask them (again!) if they are maybe still considering to change their mind. Here is the reaction you are going to provoke.
Although ReSharper is doing an awesome job in catching up with C# novelties its parser and analyzer implementation is not bullet-proof. As I mentioned before, the non-trivial solution confuses ReSharper quite a bit. You can see the output of that confusion below:
Plenty of red lines underlying a perfectly valid C# code.
I’ve never opened an official issue for this bug. Why? Because of two reasons. First, the example is fully artificial. Nobody is ever going to write such a code. Yes I know, this bug could potentially point out some places in the ReSharper parser/analyzer implementation that are worth improving, but still.
The second reason is actually the real one. It is a mixture of selfishness and educational purpose. As long as the bug is there, I can use it in my talks on Roslyn to clearly demonstrate how difficult it is to write a C# parser and analyzer on our own. Even the bests of the bests have hard time getting it 100% right.
Which pretty well underlines my personal belief that having a Compiler-as-a-Service is truly awesome. As my friend Bero once said, it gives super-powers to a regular every day C# developer.
I liked his statement so much that I called my talk on Roslyn “Super-powers and the Compiler” :-)
Let’s stop here for a while. I plan more posts on Roslyn awesomeness in the future. Meanwhile, feel free to invite me to give my talk on Roslyn at your Meetup, user group or conference :-)
The source code used in this blog post is available on GitHub. Download it here.
Wow, you've made it this far :-) The chances are you might like my next blog post as well ;-) Should I let you know when it's out?
|
http://thehumbleprogrammer.com/await-async-as-async/
|
CC-MAIN-2018-47
|
refinedweb
| 2,024
| 73.07
|
Created on 2012-07-18 23:32 by anon, last changed 2012-07-20 11:51 by mark.dickinson. This issue is now closed.
Many numeric algorithms require knowing the number of bits an integer has (for instance integer squareroots). For example this simple algorithm using shifts is O(n^2):
def bitl(x):
x = abs(x)
n = 0
while x > 0:
n = n+1
x = x>>1
return n
A simple O(n) algorithm exists:
def bitl(x):
if x==0: return 0
return len(bin(abs(x)))-2
It should be possible find the bit-length of an integer in O(1) however. O(n) algorithms with high constants simply don't cut it for many applications.
That's why I would propose adding an inbuilt function bitlength(n) to the math module. bitlength(n) would be the integer satisfying
bitlength(n) = ceil(log2(abs(n)+1))
Python more than ever with PyPy progressing is becoming a great platform for mathematical computation. This is an important building block for a huge number of algorithms but currently has no elegant or efficient solution in plain Python.
I think what you're looking for already exists:
Closing as Invalid. I think that Alex is right.
Anon, if you think this is a mistake, please reopen and argument.
Indeed, int.bit_length is the way to do this.
|
https://bugs.python.org/issue15391
|
CC-MAIN-2021-21
|
refinedweb
| 226
| 63.7
|
#import <AppKit/NSColor.h>
#import <Foundation/NSArchiver.h>
#import <Foundation/NSData.h>
#import <Foundation/NSAutoreleasePool.h>
#include <stdio.h>
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSColor *transparentColor = [NSColor colorWithCalibratedRed:0.0 green:0.0 blue:0.0 alpha:0.0];
NSData *theData = [NSArchiver archivedDataWithRootObject:transparentColor];
size_t length = [theData length];
unsigned char *bytes = malloc(length);
[theData getBytes:bytes];
#if 1
size_t i;
for(i=0; i<length; ++i)
{
printf("%02x", bytes[i]);
}
printf("n");
#else
fwrite(bytes, length, 1, stdout);
#endif
[pool release];
return 0;
}
defaults write com.apple.ActivityMonitor CPUIdleColor -data `./a.out`
When I put "defaults write com.apple.ActivityMonitor CPUIdleColor -data `./a.out`" in the Terminal, it just gives me the standard output as if I had typed "defaults" and nothing else. I copied and pasted from the hint, so I know I didn't mistype anything. Is it something wrong with my comptuer?
When I run a.out by itself, it gives me this output:n
I have no idea what that means, but I figured it might help to figure out my problem.
Same thing here.
I have narrowed it down to the 'n' at the end of the string. 'n' is not a hex character, I think it should be a '\n'. That made it work for me.
It also works when I change '#if 1' to '#if 0' and remove the '-data' option.
Well, both of those made the command execute without an error, but my icon is still opaque.
defaults write com.apple.ActivityMonitor CPUIdleColor -data
As anoher poster here has noted, Geeklog somehow munged the C source in an odd way and changed the last printf("n") (prints a newline) to printf("n") (prints a literal letter n). Just in case geeklog munges this post that is double-quote backslash n double-quote.
I also noticed that another poster here decided that if you change the if 1 to if 0 then it goes back to the original code I wrote that dumps it out as raw binary data. This can then be used as the argument to defaults write if you don't use the -data flag which causes the defaults command to use the data as is. Your mileage may vary on that one though.
um, why would I want this? and doesn't printf("n")=printf("n")?
Note the backslash '\\' seen in the subject line above. Obviously it gets filtered out in the body text of posts.
In fact I couldn't get myself to compiling an Objective C program, so I just opened the file ~/Library/Preferences/com.apple.ActivityMonitor.plist in the propertylist editor and changed the last bytes of the CPUIdleColor entry to "66660000 000086". Works like a charm.
For some reason the background in the Activity Monitor window is still black, but I prefer it that way anyhow...
Ah yes, and make sure to shut down Activity Monitor before you do this.
/Andreas
You've got a printf("n") there. You want a printf("\n").
You don't need all those includes either. All you need is Cocoa/Cocoa.h and stdio.:
|
http://hints.macworld.com/article.php?story=20070808011626352
|
CC-MAIN-2014-10
|
refinedweb
| 518
| 68.26
|
The Local namespace is a discrete, nondistributed namespace that exists
on an individual node and provides that node with a local database of
name and addressing information. The Local namespace replaces
functionality previously provided by the DECdns Local Naming Option.
Depending on the number of address towers stored, the Local namespace
is designed to scale to at least 100,000 nodes..
The DIGITAL Distributed Name Service (DECdns) is a networkwide service
that makes it possible to use network resources without knowing their
physical location. Users and applications can assign DECnet-Plus names
to resources such as nodes. The creator of a name also supplies other
relevant information, such as the resource's network address, for
DECdns to store. Users then need to remember only the name, and DECdns
acts as a lookup service, providing the rest of the data when
necessary. DECnet-Plus for DIGITAL UNIX does not contain DECdns server
software.
The DIGITAL Distributed Time Service (DECdts) is a networkwide service
that synchronizes the system clocks in the network's computers. DECdts
enables distributed applications to execute in the proper sequence even
though they run on different systems.
5.1 How DECnet-Plus Uses the Local Namespace and DECdns
All DECnet-Plus systems require a name service because the Session
layer of DECnet-Plus uses it to map node names to addresses.
DECnet-Plus provides access to the node name and addressing information
stored in one or more of the following name services.
While configuring DECnet-Plus, the system administrator specifies one
or more of the following name services to use on the node: the Local
namespace; DECdns; or Domain. Note that in this version of DECnet-Plus,
even when you are using the Local namespace the DECdns clerk software
is still required on each node by DECnet-Plus.
By using DECdns, you can save network resources, manage node names
automatically, and scale up to thousands of nodes.
When you make the transition from DECnet Phase IV to DECnet-Plus, the
nodes in your network are given DECnet-Plus full names. Along with the
node names, the name service stores the address and protocol
information that DECnet needs to make connections between nodes. The
DECnet-Plus software includes a tool,
decnet_register, to help you create and manage node
information in DECdns and the Local namespace.
The major benefit of using DECdns in a distributed namespace is the
ease of storing node names. With DECdns, it is not necessary to
maintain a node database on every system in the network. A few DECdns
servers store node names, and all other nodes in the network can depend
on those servers for node-name-to-address mapping. When data associated
with the node name changes, DECdns propagates the change automatically
to all servers that store that node name.
Another benefit of DECnet-Plus node full names is that they can be
longer and hence more descriptive than Phase IV node names. Whereas
Phase IV node names are limited to six characters, any full name,
including a node name, can be as long as 255 characters. See
Chapter 6 for complete guidelines for all node names.
The DIGITAL Distributed Time Service (DECdts) is another important user
of DECdns in DECnet-Plus. DECdts and DECdns actually depend on each
other. DECdts uses DECdns as a networkwide registry for global time
servers that synchronize system clocks in the network. DECdns uses
timestamps to determine the order in which changes to its data occur,
and it depends on DECdts to synchronize time on DECdns servers so their
timestamps are consistent. Synchronized clocks are important to any
distributed application that needs to keep track of the order in which
events occur across multiple systems.
5.2 The Name Service Search Path
DECnet-Plus constructs a name service search path file from information
entered during configuration. This file determines the order in which
the namespaces available on the node will be searched and, for each
namespace, any defaulting rules to allow users to enter abbreviated
node names.
The name service search path applies system wide.
If you choose to use a search path and configure more than one name
service on your system, the ordering of the name services is
very important.
The search path also contains a list of name service keywords, each.
Only one asterisk should be supplied per template. Only the first
occurrence of an asterisk (*) in the template is substituted with the
user-supplied name. Any additional asterisks are passed to the name
service as part of the full name. When you specify a template without
an asterisk, the template string is passed to the name service
unchanged.
If the user-supplied name should be passed to the name service as
entered by the user, the template should simply be specified as
follows: "*".
Note that the system maintains two separate search paths:
During DECnet-Plus configuration, the system administrator uses
net$configure.com (on OpenVMS systems) and
decnetsetup (on DIGITAL UNIX systems) to set up one or more
name services on each node and set up the search path. The procedure
for setting up and maintaining the search path on your node is specific
to the OpenVMS and DIGITAL UNIX systems. See your installation and
configuration guide for more information.
5.3 How DECdns Works
Operation of the name service involves several major participants:
DECdns uses a client/server model: an application, such as DECnet-Plus,
that depends on DECdns to store and retrieve information because it is
a client of DECdns. Client applications create names
for resources on behalf of their users. Through a client application, a
user can supply other information for DECdns to store with a name. This
information is stored in data structures called
attributes. Then, when a client application user
refers to the resource by its DECdns name, DECdns retrieves data from
the attributes for use by the client application.
A system running DECdns server software is a DECdns
server. A DECdns server stores and maintains DECdns names and
handles requests to create, modify, or look up data. You designate a
system as a DECdns server during configuration of the network software.
A component called the clerk is the interface between
client applications and DECdns servers. A clerk must exist on every
DECnet-Plus node and is created during configuration of the network
software. The clerk receives a request from a client application, sends
the request to a server, and returns the resulting information to the
client. This process is called a lookup. The clerk is
also the interface through which client applications create and modify
names. One clerk can serve many client applications.
The clerk caches, or saves, the results of lookups so
that it does not have to go repeatedly to a server for the same
information. The cache is written to disk periodically so the
information can survive a system
reboot or the restart of an application. Caching improves performance
and reduces network traffic.
Figure 5-1 shows a sample configuration of DECdns clerks and servers
on a nine-node LAN. Every node is a clerk, and DECdns servers run on
two selected nodes.
Figure 5-1 Sample DECdns LAN Configuration
Every DECdns server has a database called a
clearinghouse in which it stores names and other
DECdns data. The clearinghouse is where a DECdns server adds, modifies,
deletes, and retrieves data on behalf of client applications. Although
more than one clearinghouse can exist at a server node, DIGITAL does
not recommend it as a normal configuration.
Figure 5-2 shows the interaction between a DECdns client, clerk,
server, and clearinghouse during a simple lookup. First, the clerk
receives the lookup request from the client application (Step 1) and
checks its cache. Not finding the name there, the clerk contacts the
server on Node 2 (Step 2). The server finds the name in its
clearinghouse (Steps 3 and 4) and returns the requested information
over the network to the clerk (Step 5), which passes it to the client
application (Step 6). The clerk also caches the information so it does
not have to contact a server the next time a client requests a lookup
of that same name by the same user.
Figure 5-2 Simple Lookup
The total collection of names that one or more DECdns servers know
about, look up, manage, and share is called a DECdns
namespace. When you create a DECdns namespace, you
organize DECdns names into a hierarchical structure of
directories. DECdns directories are conceptually
similar to the directories that you create in your operating system's
file system. They are a logical way to group names for DECdns-specific
management or usage purposes.
The highest-level directory in the namespace is denoted by a dot (.)
and is called the root directory. The root is created
automatically when you initialize a namespace. You can then create and
name other directories below the root. Any directory that has a
directory beneath it is considered the parent of that
directory. Any directory that has a directory above it is considered a
child of the directory above it.
Figure 5-3 shows a simple hierarchy of directories. The root
directory (.) is the parent of the directories named West and
FarEast. The FarEast directory is a child of the root
directory and the parent of the Tokyo and Osaka
directories.
Figure 5-3 Example Namespace Directory Hierarchy
The complete specification of a DECdns name, going left to right from
the root directory to the entry being named, is called the full
name. Each element within a full name is separated by a dot
and is known as a simple name. For example, the
Osaka directory in the preceding figure might contain an entry
for a node whose simple name is Node01. The node's full name
would be .FarEast.Osaka.Node01. A full name also can include a
namespace nickname, but this is not needed when only one namespace
exists in a network. When you must specify a namespace, use the
following format:
NamespaceNickname:.DirectoryPath.NodeObject
5.4.1 Replicas and Their Contents
Each physical copy of a directory, including the original copy, is
called a replica. Directory replicas are the units by
which you distribute names in clearinghouses throughout the namespace.
You can think of a clearinghouse as a collection of directory replicas
at a particular server. After you create a directory in one
clearinghouse, you can create replicas of it in other clearinghouses.
All of the replicas of a specific directory in the namespace constitute
that directory's replica set.
DECdns performs a periodic skulk operation to ensure
that all replicas of a directory remain consistent. During a skulk
operation, DECdns collects all changes that have been made to the
directory since the last skulk completed and disseminates the changes
to all replicas of the directory. Every replica must be available for
the skulk to be considered successful. Two types of replicas can exist:
A replica's type affects the processing that can be done on it and the
way DECdns updates it. The type of replica DECdns uses when it looks up
or changes data is invisible to users. However, it helps to understand
how the two types differ.
The master replica is the first instance of a specific
directory in the namespace. After you make copies of the directory, you
can designate a different replica as the master, if necessary, but only
one master replica of each directory can exist at a time.
The master replica is the only directly modifiable replica of a
directory. DECdns can create, change, and delete information in a
master replica. Because it is modifiable, the master replica incurs
more overhead than read-only replicas, which DECdns keeps up-to-date
but never modifies directly. The master replica also is the place
where skulks originate.
A read-only replica is a copy of a directory that is
available only for looking up information. DECdns does not create,
modify, or delete names in read-only replicas; it simply updates them
with changes made to the master replica. Read-only replicas save
resources because DECdns does not make changes directly in them, nor
does it have to gather changes from them to disseminate to other
replicas.
Directory replicas can contain three kinds of entries:
An object is any real-world network resource, such as
a disk, application, or node, that is given a DECdns name. When an
object name is created, client applications and the DECdns software
supply additional data in the form of attributes to be
stored with the name. The name and its attributes make up the
object entry. When a client application requests
information associated with the name, DECdns returns the value of the
relevant attribute or attributes.
Every object has a defined class, which is stored as an attribute of
the object entry. For example, a node object's class is
DNA$Node. Another important class of object is the group
object (class DNS$Group). Groups let you
associate, or manage as a group, names that have something in common.
They do this by mapping a specific name (the group name) to a set of
names denoting the group members. DECdns managers can create groups
that assign several users a single set of access rights to names. Two
such access control groups are created automatically during
configuration of the DECnet-Plus and DECdns software. See Section 5.6.2
for a description of them and recommendations on their use.
5.4.1.2 Soft Links
A soft link is a pointer that provides an alternate
name for an object entry, directory, or other soft link in the
namespace. You can restructure a namespace on a minor scale by creating
soft links that point from an existing name to a new name. Soft links
can be permanent, or they can expire after a period of time that you
specify. If the name that a soft link points to is deleted, DECdns
deletes the soft link automatically.
DECnet-Plus uses backtranslation soft links to map a
node address to a node's full name when necessary. Another kind of soft
link, called a node synonym, enables applications that
do not support the length of a DECdns full name to continue using
six-character Phase IV-style node names. Section 5.5 explains how
DECnet-Plus uses backtranslation and node synonym soft links.
5.4.1.3 Child Pointers
A child pointer connects a directory to another
directory immediately beneath it in a namespace. Users and applications
do not create or manage child pointers; DECdns creates a child pointer
automatically when someone creates a new directory. The child pointer
is created in the directory that is the parent of (one level above) the
directory to which it points. DECdns uses child pointers to locate
directory replicas when it is trying to find a name in the namespace.
Child pointers do not require management except in rare problem-solving
situations.
5.4.2 Putting It All Together
To summarize, a DECdns namespace consists of a complete set of names
shared and managed by one or more DECdns servers. A name can designate
a directory, object entry, soft link, or child pointer. The logical
picture of a DECdns namespace is a hierarchical structure of
directories and the names they contain. Every physical instance of a
directory is called a replica. Names are physically stored in replicas,
and replicas are stored in clearinghouses. Any node that contains a
clearinghouse and runs DECdns server software is a server.
Figure 5-4 shows the components of a DECdns server. Every server
manages at least one clearinghouse containing directory replicas. A
replica can contain object entries, soft links, and child pointers. The
figure shows only one replica and one of each type of entry possible in
a replica. Normally, a clearinghouse contains many replicas, and a
replica contains many entries.
Figure 5-4 Components of a DECdns Server Node
5.5 How DECnet-Plus Uses the DECdns Namespace
DECnet-Plus Session Control uses DECdns to store three kinds of entries:
The decnet_register tool is available to help you create these
entries in the distributed namespace. The DECnet configuration
procedure starts the tool automatically after creating a new namespace.
If you choose to use the Local namespace, the decnet_register
tool also enables you to create entries in the Local namespace. You
also can run decnet_register separately to create and manage
node information in the namespace. This section introduces each type of
node entry and describes how it is created and used.
5.5.1 Node Object Entries
In a Phase V network using DECdns, every DECnet node has a
corresponding object entry in the DECdns namespace. During the DECnet
configuration procedure, you must supply a DECdns full name for your
node (the full name includes the complete path from the root directory
to the node's simple name) if you decide to use a distributed
namespace. The full name becomes the name of the node's object entry in
the namespace. If you decide to use a Local namespace, you must enter
local as your namespace name during the DECnet configuration
procedure.
The Local namespace exists on a single node and provides a local
database of names. The local name file, called
SYS$SYSTEM:DECNET_LOC_NODE_DEFINITIONS.TXT on OpenVMS and
/var/dna/decnet_loc_node_definitions on DIGITAL UNIX, contains
a list of node names, node synonyms, and network addresses. You can
also use the decnet_register tool to verify or modify node
addresses as your network changes.
In a distributed namespace, the node object entry has an attribute
called DNA$Towers, in which DECnet-Plus stores the node's
address. The attribute name reflects the fact that a DECnet Phase V
address consists of separate layers, sometimes called tower floors, in
the DNA and OSI network models. A DECnet-Plus node communicates with
another DECnet-Plus node by using the address information stored in the
node's DNA$Towers attribute.
You can store DECnet-Plus node object entries in any directory in the
distributed namespace. When you register a DECnet-Plus node in a
distributed namespace, the decnet_register tool creates any
directories in the node's full name that do not already exist. You also
can create directories with the DECdns Control Program. However,
DIGITAL recommends that you use decnet_register to create
directories that will contain node object entries. Using
decnet_register ensures that the directories are created with
the proper
access control; see Section 7.4 for details.
If your network includes nodes that are not yet upgraded to
DECnet-Plus, their names and addresses also must be in the namespace in
order for a DECnet-Plus node to communicate with them. You can use the
decnet_register tool to register each Phase IV node
individually in any directory in the namespace.
Alternatively, you can use the decnet_register export
and import commands to extract the node information from the
Phase IV database and enter it in the namespace.
|
http://h71000.www7.hp.com/doc/73final/6495/6495pro_008.html
|
CC-MAIN-2014-15
|
refinedweb
| 3,159
| 53.61
|
Functionally Solving Problems
In this chapter, we'll take a look at a few interesting problems and how to think functionally to solve them as elegantly as possible. We probably won't be introducing any new concepts, we'll just be flexing our newly acquired Haskell muscles and practicing our coding skills. Each section will present a different problem. First we'll describe the problem, then we'll try and find out what the best (or least worst) way of solving it is.
Reverse Polish notation calculator
Usually when we write mathematical expressions in school, we write them in an infix manner. For instance, we write 10 - (4 + 3) * 2. +, * and - are infix operators, just like the infix functions we met in Haskell (+, `ele a Haskell :: (Num a) => String -> a.
Cool. When implementing a solution to a problem in Haskell, Data.List solveRPN :: (Num a) => String -> a solveRPN expression = head (foldl foldingFunction [] (words expression)) where foldingFunction stack item = ... call head on that list to get the item out and then we apply read. Data.List solveRPN :: (Num a) => String -> a solveRPN = head . foldl foldingFunction [] . words where foldingFunction stack item = ...
Ah, there we go. Much better. So, the folding function will take a stack and an item and return a new stack. We'll use pattern matching to get the top items of a stack and to pattern match against operators like "*" and "-".
solveR
We laid this out as four patterns. The patterns will be tried from top to bottom. First the folding function will see if the current item is "*". If it is, then it will take a list like [3,4,9,3] and call its first two elements x and y respectively. So in this case, x would be 3 and y would be 4. ys would be [9,3]. It will return a list that's just like ys, only it has x and y multiplied. If it's a number, we just call read on that string to get a number from it and return the previous stack but with that number pushed to the top.
And that's it! Also noticed that we added an extra class constraint of Read a to the function declaration, because we call read on our string to get the number. So this declaration means that the result can be of any type that's part of the Num and Read typeclasses (like Int, Float, etc.). the added to the beginning of []. So the new stack is now [2] and the folding function will be called with [2] as the stack and ["3"] as the item, producing a new stack of [3,2]. Then, it's called for the third time with [3,2] as the stack and "+" as the item. This causes these two numbers to be popped off the stack, added together and pushed back. The final stack is [5], which is the number that we return.
Let's play around with our function:
ghci> solveRPN "10 4 3 + 2 * -" -4 ghci> solveRPN "2 3 +" 5 ghci> solveRPN "90 34 12 33 55 66 + * - +" -3947 ghci> solveRPN "90 34 12 33 55 66 + * - + -" 4037 ghci> solveRPN "90 34 12 33 55 66 + * - + -" 4037 ghci> solveRPN "90 3 -" 87.
import Data.List solveRPN :: String -> Float solveRPN = head . foldl foldingFunction [] . words where foldingFunction (x:y:ys) "*" = (x * y):ys foldingFunction (x:y:ys) "+" = (x + y):ys foldingFunction (x:y:ys) "-" = (y - x):ys foldingFunction (x:y:ys) "/" = (y / x):ys foldingFunction (x:y:ys) "^" = (y ** x):ys foldingFunction (x:xs) "ln" = log x:xs foldingFunction xs "sum" = [sum xs] foldingFunction xs numberString = read numberString:xs.
ghci> solveRPN "2.7 ln" 0.9932518 ghci> solveRPN "10 10 10 10 sum 4 /" 10.0 ghci> solveRPN "10 10 10 10 10 sum 4 /" 12.5 ghci> solveRPN "10 2 ^" 100.0
Notice that we can include floating point numbers in our expression because read knows how to read them.
ghci> solveRPN "43.2425 0.5 ^" 6.575903
I think that making a function that can calculate arbitrary floating point RPN expressions and has the option to be easily extended in 10 lines is pretty awesome.
One thing to note about this function is that it's not really fault tolerant. When given input that doesn't make sense, it will just crash everything. We'll make a fault tolerant version of this with a type declaration of solveRPN :: String -> Maybe Float once we get to know monads (they're not scary, trust me!). We could make one right now, but it would be a bit tedious because it would involve a lot of checking for Nothing on every step. If you're feeling up to the challenge though, you can go ahead and try it! Hint: you can use reads to see if a read was successful or not.
Heathrow to London:
- Forget Haskell for a minute and think about how we'd solve the problem by hand
- Think about how we're going to represent our data in Haskell
- Figure out how to operate on that data in Haskell so that we produce at a bast previous Haskell.
data Node = Node Road Road | EndNode Road data.
data Node = Node Road (Maybe Road) data Road = Road Int Node
This is an alright way to represent the road system in Haskell!
data Section = Section { getA :: Int, getB :: Int, getC :: Int } deriving (Show) type RoadSystem = [Section]
This is pretty much perfect! It's as simple as it goes and I have a feeling it'll work perfectly for implementing our solution. Section is a simple algebraic data type that holds three integers for the lenghts of its three road parts. We introduce a type synonym as well, saying that RoadSystem is a list of sections. Haskell. synonym: Path.
data Label = A | B | C deriving (Show) type Path = [ pair of paths and a section and produces a new pair of paths. The type is (Path, Path) -> Section -> (Path, Path). Let's go ahead and implement this function, because it's bound to be useful.
roadStep :: (Path, Path) -> Section -> (Path, Path) roadStep (pathA, pathB) (Section a b c) = let priceA = sum $ map snd pathA priceB = sum $ map snd pathB forwardPriceToA = priceA + a crossPriceToA = priceB + b + c forwardPriceToB = priceB + b crossPriceToB = priceA + a + c newPathToA = if forwardPriceToA <= crossPriceToA then (A,a):pathA else (C,c):(B,b):pathB newPathToB = if forwardPriceToB <= crossPriceToB then (B,b):pathB else (C,c):(A,a):pathA in (newPathToA, newPathToB)
What's going on here? First, calculate the optimal price on road A based on the best so far on A and we do the same for B. We do sum $ map snd previous,a):pathA. Basically we prepend the Label A and the section length a to the optimal path path on A so far. Basically, we say that the best path to the next A crossroads is the path to the previous A crossroads and then one section forward via A. Remember, A is just a label, whereas a has a type of Int. Why do we prepend instead of doing pathA ++ [(A,a)]?.
ghci> roadStep ([], []) (head heathrowToLondon) ([(C,30),(B,10)],[(B,10)])) = foldl roadStep ([],[]) roadSystem in if sum (map snd bestAPath) <= sum (map snd bestBPath) then reverse bestAPath else!
ghci> optimalPath heathrowToLondon [(B,10),(C,30),(A,5),(C,20),(B,2),(B,8),(C,0)] based on, [1..10], groupsOf 3 should return [[1,2,3],[4,5,6],[7,8,9],[10]].
groupsOf :: Int -> [a] -> [[a]] groupsOf 0 _ = undefined groupsOf _ [] = [] groupsOf n xs = take n xs : groupsOf n (drop n xs)
A standard recursive function. For an xs of [1..10] and an n of 3, this equals [1,2,3] : groupsOf 3 [4,5,6,7,8,9,10]. When the recursion is done, we get our list in groups of three. And here's our main function, which reads from the standard input, makes a RoadSystem out of it and prints out the shortest path:
import Data.List main = do contents <- getContents let threes = groupsOf 3 (map read $ lines contents) roadSystem = map (\[a,b,c] -> Section a b c) threes path = optimalPath roadSystem pathString = concat $ map (show . fst) path pathPrice = sum $ map snd path putStrLn $ "The best path to take is: " ++ pathString putStrLn $ "The price is: " ++ show pathPrice
First, we get all the contents from the standard input. Then, we call lines with our contents to convert something like "50\n10\n30\n... to ["50","10","30".. and then we map read to that to convert it to a list of numbers. We call groupsOf 3 on it so that we turn it to a list of lists of length 3. We map the lambda (\[a,b,c] -> Section a b c) over that list of lists. As you can see, the lambda just takes a list of length 3 and turns it into a section. So roadSystem is now our system of roads and it even has the correct type, namely RoadSystem (or [Section]). We call optimalPath with that and then get the path and the price in a nice textual representation and print it out.
We save the following text
50 10 30 5 90 20 40 2 25 10 8 0
in a file called paths.txt and then feed it to our program.
$ cat paths.txt | runhaskell heathrow.hs The best path to take is: BCACBBC The price is: 75
Works like a charm! You can use your knowledge of the Data.Random module to generate a much longer system of roads, which you can then feed to what we just wrote. If you get stack overflows, try using foldl' instead of foldl, because foldl' is strict.
|
http://learnyouahaskell.com/functionally-solving-problems
|
CC-MAIN-2018-30
|
refinedweb
| 1,619
| 79.8
|
This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project.
> #ifndef __WCLONE > #define __WCLONE 0x80000000 /* Wait for cloned process. */ > #endif > > I'm not sure whether we still encounter systems without these, and > if gdb works on them at all. Waiting for build failure reports would > be an option. > > We could move them to say, common/linux-ptrace.h. __WALL is already there. I normally suggest that we wait for build failure reports, but your suggestion seems so simple that I'd just play it safe, and add it there. Given the flag value, I'd even venture that if __WALL is defined, I'm guessing __WCLONE should be too? -- Joel
|
http://sourceware.org/ml/gdb-patches/2012-11/msg00479.html
|
CC-MAIN-2015-06
|
refinedweb
| 117
| 76.32
|
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
Hi everyone, we're looking for a way to have a user notified whenever a particular user (or user from a particular group) opens up a ticket in any project. So basically the second one of those users creates a ticket, this master user will get an email notification informing them of the creation.
I'm familiar with some of the reporting features, such as creating a filter for these user's issues and sending a report out every night, but it doesn't look like that's what we're looking for. I'd prefer to do this without any paid plugins if possible, as getting those things approved for purchase is kind of difficult.
I've done this with a custom listener; first I created a custom event, then I used the script runner listener for firing the event when a criteria was met, with the criteria being that the user was a member of the group. Then I added a notification for that event using the "issue updated" email template.
More streamlined would be to just emit a custom email and bypass the custom event, but then you'll need to write your own email template. There are pros and cons to both approaches; in this case, since you want it for all projects, you probably don't want the event as then you need to trust that every notification scheme will maintain the correct notification.
You wouldn't have to write this one, beyond the condition. The interface provides examples, I'll take a look and see if this is one of them.
For both "Fires an event when condition is true" and "Send a custom email", built-in listeners, there is a sample condition for "Reporter is in a particular group":
import com.atlassian.jira.component.ComponentAccessor
def groupManager = ComponentAccessor.getGroupManager()
groupManager.isUserInGroup(issue.reporter?.name, 'business-users')
So (as a JIRA admin) you'd go to Administration / Add-ons, then "Script Listeners" underneath "SCRIPT RUNNER" along the left. Then "send a custom email", project key "All Projects", Events "Issue Created", Condition as described above, adjusting for your group name, then provide an email template and a subject template. Something like:
Subject:
Issue: $issue.key opened by user/group X
Issue: $issue.key opened by user/group.
|
https://community.atlassian.com/t5/Jira-Core-questions/Receiving-notifications-when-a-user-from-a-particular-group/qaq-p/230548
|
CC-MAIN-2018-39
|
refinedweb
| 404
| 58.82
|
Hello, I have downloaded mingw, I'm playing with it to try and learn it from command line, but it is nothing like Visual studio 10 PE- which is why I want to learn it. anyway, I'm trying to compile a simple hello world program on it and it is giving me these errors, can you help me with their meanings:
from file z: mingw\bin\..lib/gcc/mingw32/4.5.2/include/c++/bits/postypes.h:42;0,
from file z: mingw\bin\..lib/gcc/mingw32/4.5.2/include/c++/ios:39, 40,
from file z: mingw\bin\..lib/gcc/mingw32/4.5.2/include/c++/cwchar:47:19; fatal error: wchar.h: No such file or directory
complilation terminated
here is the code
Code:#include <iostream> using namespace std; int main () { cout<< "hello world, it finally works!"<<endl; return 0; }//main
|
https://cboard.cprogramming.com/cplusplus-programming/139214-new-gcc-need-guidance.html
|
CC-MAIN-2018-05
|
refinedweb
| 145
| 56.55
|
Using ARDK User IDs
For features such as Lightship VPS, ARDK needs information associated with specific users of your AR experience. For example, with VPS, localization requests need to understand which user is scanning VPS activated locations at a given physical location.
To use these features, your AR experience should provide a User ID to ARDK, where the User ID is a unique value assigned to a given user of your app. Even if your game does not have VPS components, you should still provide a User ID if possible.
If you do not provide a User ID, ARDK will generate a Client ID and use this for requests (described in “Handling Scenarios Where No User ID Can Be Provided” below).
We strongly recommend generating and using User IDs. Accurate user information allows Niantic to support you in maintaining data privacy best practices and allows you to understand usage patterns of features among your users. Niantic also uses User IDs to help facilitate data requests made in accordance with GDPR (referred to throughout this page as “data management requests”).
User IDs and Client IDs may be considered personal information under privacy regulations. For more information about Lightship ARDK and privacy, please see Lightship ARDK Data Privacy FAQ.
Generating User IDs
ARDK has no strict format or length requirements for User IDs, although the User ID string must be a UTF8 string. We recommend avoiding using an ID that maps back directly to the user. So, for example, don’t use email addresses, or login IDs. Instead, you should generate a unique ID for each user. We recommend generating a GUID.
If your end user makes data management requests, you’ll need to be able to retrieve the User ID for that user, which you’ll then provide to Niantic as described in “End User Data Management Requests” below. How you retrieve the User ID will depend on your situation. Some example approaches are:
Securely store the User ID & user login in your cloud and provide a way for users to retrieve their User ID when they provide their login info.
Provide a way in your app for users to make data access requests, and use the generated User ID for the current app user.
Provide a secure web service that can generate the same User IDs for your user logins, using the same process you use in your app.
Note
The sample scenes in ARDK-Examples don’t generate or use User IDs (and instead use Client IDs as described in “Handling Scenarios Where No User ID Can Be Provided” below). We recommend not using ARDK-Examples scenes as templates for creating production apps. Instead you should make sure your app generates and uses User IDs if possible.
Using User IDs When Making API Requests
You’ll need to set the User ID whenever the active user of your app changes. For example, if your app is a multiplayer game that has a login feature, you’ll set the user ID when the user logs in and you’re starting or re-using a networked AR Session.
Call ArdkGlobalConfig.SetUserIdOnLogin() whenever the user logs in. You’ll provide a User ID that you’ve created as described in “Generating User IDs” above.
using Niantic.ARDK.Configuration; // Set the user id associated with the current user. ArdkGlobalConfig.SetUserIdOnLogin(your_generated_user_ID);
Once you’ve called
SetUserIdOnLogin(), the User ID is set in a request envelope and will be automatically used for any subsequent ARDK requests that need the User ID.
Call ArdkGlobalConfig.ClearUserIdOnLogout() whenever the user logs out. This clears the User ID to ensure any subsequent ARDK requests don’t use the User ID of the logged-out user.
using Niantic.ARDK.Configuration; // Clear the user id set by SetUserIdOnLogin. ArdkGlobalConfig.ClearUserIdOnLogout();
If
SetUserIdOnLogin() or
ClearUserIdOnLogout() return
False, there was an issue with device storage, or you may have used a non-UTF8 string for
SetUserIdOnLogin(). Check that you have proper device storage permissions and that your userId string is UTF8, and then try the call again.
Handling Scenarios Where No User ID Can Be Provided
Niantic strongly recommends always providing a User ID, even if your app is only intended to be used by a single user at a time. However, you may encounter situations where it is not possible to generate or provide a User ID.
If you use ARDK features such as VPS and no User ID is provided in your requests, ARDK will use a randomized Client ID. The Client ID is generated the first time your app is run after being installed on the device and is deleted when the app is uninstalled. This generated client ID will be used in place of a User ID for ARDK requests. The Client ID should not be modified at run-time. In your app you can:
Access the generated client ID using ArdkGlobalConfig.GetClientId(). For example:
using Niantic.ARDK.Configuration; // Returns the clientId - a unique identifier generated for the user/device // in cases where a userId is not provided. string clientID = ArdkGlobalConfig.GetClientId();
Provide the client ID to your user, which can then be used to make data management requests as described in “End User Data Management Requests” below.
Note that if your app is uninstalled, the client ID will be lost, so you’ll need to provide some way in your app for your users to get or use the Client ID if they make data management requests. How to do this will depend on the design of your app, but, for example, you could present the Client ID string, along with instructions or a web link to instructions on how to make data management requests, in your app.
End User Data Management Requests
For making data management requests on behalf of your user, you’ll need the following information:
The User ID, or Client ID if you’re not using User IDs
The Bundle ID/Package Name of your app
The type of request (GDPR Delete, GDPR Report, or both)
The lightship.dev Project name associated with your app
Provide this information in the following form:
Niantic aims to complete all requests within 30 days. Niantic will send email notification to the email address registered with your lightship.dev developer account when the request has been completed.
|
https://ar.dev/docs/ardk/ardk_fundamentals/using_ardk_user_ids.html
|
CC-MAIN-2022-40
|
refinedweb
| 1,050
| 51.28
|
In order to do that, I had to modify mint-make so it would accept arguments...
man wrote:SYNOPSIS
mint-make [program [needsRepository]]
that was just for you, scorp
I changed it so that that the user no longer has to look into "aptitude show program" to find the description if the program name is passed as an argument (if no arguments are passed, mint-make defaults to the original method)
I also try a feeble attempt to find the icon, and then resize it to 48x48 (it took me FOREVER to find a working GPL'd gimp script-fu to resize the icons, and I heavily edited it to get it to do what I wanted).
Also I tried to catch any mistakes in typing y/n for the repository... this way also if you only type in "mint-make program", it will still ask if you need a repo.
I still haven't made the bash script to generate all those .mint files, but I'll let y'all know how it turns out =)
Sorry for the long description
mint-make
- Code: Select all
#!/usr/bin/env python
#mint-make
import sys
import os
import commands
#___________________________________
def getRepository():
repository = "wrong"
while repository != "y" and repository != "n":
repository = raw_input("Do you need to enter a repository? (y or n): ").lower()[0]
return repository
#____________________________________
def tryToGetIcon(name):
pixDir = "/usr/share/pixmaps/"
width = "48"
height = "48"
icon = "ThereIsNoIconHereHaha"
trying = [name + ".png", name + "-icon.png", name + "_icon.png"]
for trial in trying:
if os.path.exists(pixDir + trial): icon = pixDir + trial
if icon != "ThereIsNoIconHereHaha":
print "-------Ignore the output from GIMP -------"
os.system("gimp -i -b '(let* ((image (car (file-png-load 1 "" + \
icon + "" "" + icon +"")))(drawable (car (gimp-image-active-drawable image))))" + \
"(gimp-image-scale image " + width + " " + height + ")(file-png-save 1 image drawable " + \
""./icon.png" "./icon.png" 1 0 0 0 0 0 0 ))' '(gimp-quit 0)'")
print "------------------------------------------"
os.system("mv icon.png icon")
#____________________________________
args = sys.argv[1:]
home = os.environ["HOME"]
if args:
name = args[0]
raw_name = str.replace(name, " ", "")
raw_name = name.lower()
description = ""
pipe = os.popen("aptitude show " + name + " | grep Description")
description = pipe.readline()[13:-1] # Get rid of the lead phrase "Description: "
pipe.close()
# If the user sent a second option (whether or not there needs a repository),
# then we set repository to the first character, lower-cased. If not, or incorrect
# input was given, it will be caught in the line following this if/else statement.
repository = ""
if len(args) > 1: repository = args[1].lower()[0]
else:
name = raw_input("name: ")
raw_name = str.replace(name, " ", "")
raw_name = raw_name.lower()
description = raw_input("description: ")
repository = raw_input("need repository? (y or n): ").lower()[0]
if repository != "y" and repository != "n": repository = getRepository()
directory = raw_name
os.mkdir(directory)
os.chdir(directory)
os.system("echo " + name + " > name")
os.system("echo " + description + " > description")
os.system("cp /usr/lib/linuxmint/mintInstall/icon .")
pipe = os.popen("which gimp")
hasGimp = pipe.readline()
pipe.close()
if hasGimp: tryToGetIcon(raw_name)
os.mkdir("steps")
os.chdir("steps")
if (repository == "y"):
os.system("echo "TITLE Adding 3rd Party Repository" > 1")
os.system("echo "SOURCE deb specify_repository_here" >> 1")
os.system("echo "TITLE Installing " + name + "" > 2")
os.system("echo "INSTALL " + raw_name + "" >> 2")
else:
os.system("echo "TITLE Installing " + name + "" > 1")
os.system("echo "INSTALL " + raw_name + "" >> 1")
|
http://forums.linuxmint.com/viewtopic.php?p=24954
|
CC-MAIN-2013-20
|
refinedweb
| 544
| 53.27
|
I would like a BASH command to list just the count of files in each subdirectory of a directory.
E.g. in directory
/tmp there are
dir1,
dir2, ... I'd like to see :
`dir1` : x files `dir2` : x files ...
Assuming you want a recursive count of files only, not directories and other types, something like this should work:
find . -maxdepth 1 -mindepth 1 -type d | while read dir; do printf "%-25.25s : " "$dir" find "$dir" -type f | wc -l done
bash
alias!! – syntaxerror Nov 25 '14 at 13:07
sort -rn -k 2,2 -t$':'you get the DESC list – Andre Figueiredo Apr 18 '18 at 23:05
This task fascinated me so much that I wanted to figure out a solution myself. It doesn't even take a while loop and MAY be faster in execution speed. Needless to say, Thor's efforts helped me a lot to understand things in detail.
So here's mine:
find . -maxdepth 1 -mindepth 1 -type d -exec sh -c 'echo "{} : $(find "{}" -type f | wc -l)" file\(s\)' \;
It looks modest for a reason, for it's way more powerful than it looks. :-)
However, should you intend to include this into your
.bash_aliases file, it must look like this:
alias somealias='find . -maxdepth 1 -mindepth 1 -type d -exec sh -c '\''echo "{} : $(find "{}" -type f | wc -l)" file\(s\)'\'' \;'
Note the very tricky handling of nested single quotes. And no, it is not possible to use double quotes for the
sh -c argument.
find . -type f | cut -d"/" -f2 | uniq -c
Lists a folders and files in the current folder with a count of files found beneath. Quick and useful IMO. (files show with count 1).
| sort -rnto sort subdirs by number of files. – Dennis Golomazov Sep 18 '19 at 8:12
Using find is definitely the way to go if you want to count recursively, but if you just want a count of the files directly under a certain directory:
ls dir1 | wc -l
findis so important. (let alone
-print0and
xargs -0, already pointed out by Scott in the other answer) – syntaxerror Nov 25 '14 at 13:03
find . -mindepth 1 -type d -print0 | xargs -0 -I{} sh -c 'printf "%4d : %s\n" "$(find {} -type f | wc -l)" "{}"'
I need often need to count the number of files in my sub-directories and use this command. I prefer the count to appear first.
What I use... This makes an array of all the subdirectories in the one you give as a parameter. Print the subdirectory and the count of that same subdirectory until all the subdirectories are processed.
#!/bin/bash directories=($(/bin/ls -l $1 | /bin/grep "^d" | /usr/bin/awk -F" " '{print $9}')) for item in ${directories[*]} do if [ -d "$1$item" ]; then echo "$1$item" /bin/ls $1$item | /usr/bin/wc -l fi done
You could use this python code. Boot up the interpreter by running
python3 and paste this:
folder_path = '.' import os, glob for folder in sorted(glob.glob('{}/*'.format(folder_path))): print('{:}: {:>8,}'.format(os.path.split(folder)[-1], len(glob.glob('{}/*'.format(folder)))))
Or a recursive version for nested counts:
import os, glob def nested_count(folder_path, level=0): for folder in sorted(glob.glob('{}/'.format(os.path.join(folder_path, '*')))): print('{:}{:}: {:,}'.format(' '*level, os.path.split(os.path.split(folder)[-2])[-1], len(glob.glob(os.path.join(folder, '*'))))) nested_count(folder, level+1) nested_count('.')
Example output:
>>> figures: 5 >>> misc: 1 >>> notebooks: 5 >>> archive: 65 >>> html: 12 >>> py: 12 >>> src: 14 >>> reports: 1 >>> content: 6 >>> src: 1 >>> html_download: 1
|
https://superuser.com/questions/474334/count-of-files-in-each-sub-directories/844817
|
CC-MAIN-2021-21
|
refinedweb
| 590
| 72.87
|
WebService::Upcoming - Perl interface to the Upcoming API
use WebService::Upcoming; my $upco = new WebService::Upcoming("*** UPCOMING API KEY HERE ***"); my $objc = $upco->call("event.search", { "search_text" => "music" }); die("ERROR: ".$upco->err_text()."\n") if (!defined($objc)); foreach (@{$objc}) { print("EVENT: ".$_->name()." on ".$_->start_date()."\n"); }
A simple interface for using the Upcoming API.
WebService::Upcoming is a subclass of LWP::UserAgent, so all of the various proxy, request limits, caching, and other features are available.
new($key [, $version ])
Creates an
WebService::Upcoming object. $key is the API key used to identify the client to the Upcoming server. $version is the version of the Upcoming API to call, and it defaults to "1.0" if excluded.
API keys may be obtained from.
key( [ $key ] )
Sets or retrieves the current API key.
call($method, \%args)
Constructs and executes a request to upcoming.org, returning an array of objects that define the response.
$method defines the Upcoming API method to call. \%args is a reference to a hash containing arguments to the method.
Each call() returns a reference to an array of
WebService::Upcoming::Object::* objects, depending on the request. event.getInfo, for instance, will return
WebService::Upcoming::Object::Event objects, with methods for each attribute: id(), name(), description(), etc. Empty arrays can also be returned, indicating a successful call(), but without any response, such as watchlist.remove.
On failure, call() returns undef. HTTP error codes are available through $upco->err_code(), human-readable error text is available through $upco->err_text().
Version 1.0 of the Upcoming API includes the following objects, all represented in the Perl namespace
WebService::Upcoming::Object: Category, Country, Event, Metro, State, User, Venue and Watchlist.
For a list of methods, their arguments and what object to expect in response, see. For each XML response in the Upcoming documentation, the attributes are available through methods of the same name on the
WebService::Upcoming::Object::* objects.
query($method, \$args)
Constructs and executes a request to upcoming.org, returning the XML response.
$method defines the Upcoming API method to call. \%args is a reference to a hash containing arguments to the method.
See <call()> for details.
parse($method, $response)
Parses an API response from upcoming.org, returning an array of objects that define the response.
$method defines the Upcoming API method that generated the response. $response is the XML sent by the server.
See <call()> for details.
err_code()
Returns the last HTTP error code. Only valid if call() returns undef.
err_text()
Returns the last human-readable error text. Only valid if call() returns undef.
|
http://search.cpan.org/~gknauss/WebService-Upcoming-0.05/Upcoming.pm
|
CC-MAIN-2014-23
|
refinedweb
| 423
| 52.56
|
DEV-CPP DLL and Delhpi source
This project received 7 bids from talented freelancers with an average bid price of $30 USD.Get free quotes for a project like this
Skills Required
Project Budget$30 USD
Total Bids7
Project Description
This is very easy job.
I need programmer person, who can write a sample DLL
in the programe compilator Dev-C++..
The delphi project [url removed, login to view] ,
import the function from dev-C++
[code delphi]
Program MyRun;
{$apptype console}
Function sum2numbers(a,b:integer):integer;
external stdcall '[url removed, login to view]' name 'sum2numbers';
Begin sum2numbers(10,20);
writeln('hello dev-c++ make
End.
[/code delphi]
The source sample.c++ export the functions:
EXPORTS:
sum2numbers
divide2no..
You must use the programe compilator DEv-C++ version 4.9
You must use the programe compilator Delphi3, Delphi5, .. Delphi7
I need complete projects file and full source in Dev-C++
The delphi programe [url removed, login to view] call the function sum2numbers and divide2no..
All sources must run OK on WindowsVista and windows7, and WindowsXP
Buget:10$-20$
This is a highschool
|
https://www.freelancer.com/projects/Delphi-CPlusPlus-Programming/DEV-CPP-DLL-Delhpi-source/
|
CC-MAIN-2016-30
|
refinedweb
| 181
| 63.49
|
07 July 2008 11:41 [Source: ICIS news]
LONDON (ICIS news)--Shipments of urea from the Black Sea port of Yuzhny totalled 247,003 tonnes in June, down more than 100,000 tonnes from May, customs data showed on Monday.
The reduced exports were attributed to turnarounds at several plants, including Ukrainian producer ?xml:namespace>
Exports of urea from Ukrainian producers totalled 233,234 tonnes and those from Russian producers were 13,768 tonnes.
This compares with 322,529 tonnes of Ukrainian urea and 33,577 tonnes of Russian urea shipped in May.
The majority of the urea, some 114,629 tonnes, shipped from Yuzhny in June was destined for
Other export destinations last month included
The Black Sea
For more on urea
|
http://www.icis.com/Articles/2008/07/07/9138071/black-sea-urea-exports-fall-100000-tonnes-in-june.html
|
CC-MAIN-2015-22
|
refinedweb
| 123
| 65.46
|
386 181 [details]
projects and screenshots
I have a WCF service running on a windows machine and an iPad client getting byte arrays from it. In the attachment, I have included the server project (created in Visual Studio 2010) and the iPad client project. After receiving a byte array of 100 MB, the amount of RAM used by the app skyrockets over 1 GB and stays up there. It does go down a little but never close to where it was before receiving the byte array from the server.
== READ ME.txt contents ==
1. Run the Server on a windows platform (inside TestTouchService.zip, which is a project created using Visual Studio 2010), which will start the service on 127.0.0.1:9999.
2. In the TestTouchServiceClient project, which was created as an iPad project using MonoDevelop, change the value of the TestTouchClient.Address constant to the ip of the machine currently hosting the service.
3. Run the TestTouchServiceClient, tap any button to get the number of bytes indicated on them from the server. If it crashes on boot, it probably just needs a clean and rebuild.
4. If you are running it on the device, the app will tell you when you are low on memory and in the next seconds your app is very likely to crash. When i tested on my iPad 2, the app crashed after receiving a little more than 42 MB, but I suggest running it on the simulator, so you can see how much memory it takes from the Activity Monitor. After pressing the 100 MB button, the app takes over 1 GB of RAM, as shown in the screenshots.
Created attachment 196 [details]
After clicking once on the 100mb button, the app receives 100mb from the server
Created attachment 197 [details]
At the same time, the activity monitor shows that the app takes way over 1GB of ram
forgot to say I am using Snow Leopard (10.6.6), not Lion
I did a quick check (using 10MB chunks) and yes memory goes way up and never down as much as expected.
Simulator (in MB)
up to stable
initial 34.9
10MB 163.1 85.2
20MB 191.9 128.0
30MB 242.3 169.1
40MB 262.8 210.2
50MB 324.5 226.2
60MB 324.6* 251.3
70MB 392.4 251.3
80MB 417.9 319.1
90MB 442.7 360.1
100MB 485.1 401.2
I'm not sure if it's a "real" leak or if some things never gets unreferenced (e.g. cache). Hopefully we'll soon have better tools (e.g. heapshot) to diagnose those. OTOH a console application would likely show the same behavior.
We happen to have the same problem for our app which uses WCF communication. When dealing with significant chunks through the wire memory just sky rockets both on simulator and on the device.
Even though its only a specific part of our app that is affected by the issue (small chunks never seem to cause the issue), we are feeling uneasy about releasing knowing that problem, any news on this one ?
Update : Recently I had another problem with a very long string built using StringBuilder ; Memory was allocated and never totally released, very similar to the problem I have been describing in this bug case. If MonoTouch is using StringBuilder in its WCF Deserialization, I guess it would make sense, because deserializing a few hundred MB using StringBuilder would most likely display the same behavior.
After some research, I also found an already existing question on StackOverflow describing this issue, but the answer provided no functional solution.
see here :
I am also joining a sample project (screenshots included) that I used to confirm the StringBuilder bug. I suspect that StringBuilder's implementation when faced with very large strings has a problem with heap fragmentation and subsequent memory de-allocation, which would lead to the leak (for a high amount of small strings built, there's no problem).
I hope this will help resolve the issue quickly.
Created attachment 524 [details]
StringBuilder memory leak projects and screenshots
A console version of the same program, exhibiting the same issue:
using System.Text;
using System;
class X {
static void Main ()
{
while (true){
Console.WriteLine ("Press return");
Console.ReadLine ();
Alloc ();
}
}
static void Alloc ()
{
var s = new StringBuilder();
// append lots of times
for (int j = 0; j < 1024 * 1024 * 200; j++)
s.Append('A');
s.Length = 0;
s = null;
}
}
This is the effect of us using some amount of conservative pointer scanning in the GC. A Typical 32 bit app has, say, 2 GB of address space available for allocations and the sample code above allocated 400+MB objects, so just 5 of them are enough to fill the memory space in the unfortunate case where we find a value on the stack that looks like a pointer to the area used by the object.
So this has nothing to do with the StringBuilder implementation specifically, as it can happen with any array that is just as large.
As a proof, remove the "* 200" bit and the app will run indefinitely (well, I stopped it after a few minutes here, but it didn't increase memory used). The original program likely runs fine as is on a 64 bit architecture.
As for a solution:
*) for the case of WCF the implementation shouldn't use StringBuilders if the amount of memory it could
retain is unbounded. Chunked byte[] buffers is likely the best solution there (though I didn't look at the implementation and the API requirements). Alternatively, try to avoid hundreds of megabyte transfers at the app level (it may or may not be possible, depending on who controls the two ends of the interfaces).
*) for direct uses of StringBuilder my advice is basically the same: it is not really suitable to manage really large strings. Think of it as processing XML files: it is a bad idea to use a parser that requires to keep all the content in memory if the input file size is unbounded, better use something like XmlReader.
It has been suggested that StringBuilder could internally use a chunked implementation: my opinion is that this is a bad idea, since it would slow down significantly the implementation for the common case to cover a corner case for which StringBuilder is not the right solution anyway.
I mainly used the StringBuilder as an example to represent the problem, the issue with WCF is much more pressing. If it's true that it is an issue related to large arrays, it is much more troublesome than I thought, as it brings out several other cases in our project where that may apply, although not as critical (a decent amount of those can be solved client-side).
Most of the data transfers in our project are actually of very reasonable sizes, with some corner cases around pictures, audio, and video that are our heavyweights, of those some can and will be chunked/streamed, some can't.
What worries me is that based on what you said, the moment a large array allocation appears, the app technically won't ever be able to release most of the memory allocated for it, and will be stuck with it. Thus, multiple instances of such an event without the app closing will inevitably result in an "out of memory" crash.
I think that chunking will unlikely solve problems in big transfer cases anyway. Yes, data will be received in managable chunks and deserialization will not leak, but most of the time there will be a need to merge it all back together eventually in a single array in order to actually consume the data received, at which point the array size problem kicks in regardless.
I suppose if we had any way to manually release the memory allocated for unused arrays it could probably work. Anyhow, do you guys have any other suggestion to solve this problem, at least temporarily, as it could very well delay our app submission in a significant manner.
We are going to look at the WCF problem and see if there is something we can do about it.
Meanwhile, for transferring images, you could use the plain HTTP stack and store the results on disk, instead of keeping those in memory and deserializing it (audio, video and pictures)
=> WCF
Louis, the recently released 5.1.0 beta has significantly improved the support for our new garbage collector (SGen), which should in theory resolve your issues. Can you try it to see if it actually does?
I just tested it with 5.1.0 beta, and it's still exactly the same. I received 10 MB through WFC and it skyrocketed (to around 161 MB) before falling back down a little but nowhere near what it was before receiving the 10 MB.
Louis, did you try enabling SGen in the project's properties?
That's probably a good idea.
Results after enabling SGen :
The memory still skyrockets in the same way, but it does go back down more than without SGen, though still not completely.
a few numbers :
if I just keep receiving chunks of 10 MB one after another, the mem goes up to 130 MB and stays there, If I then receive chunks of 5 MB or 1 MB, the memory goes back down under 130 MB (around 50 and 80 MB), but as soon as I go over 10 MB, such as 25 MB, the memory gets stuck at around 200 MB, and if I do it again, it just gets worst.
So my guess is that what enabling SGen did in this case was to rise the threshold of the byte array's size where it goes completely crazy.
Even though it's unreal to receive 25 MB through WCF in a real application, I still feel like I'm playing with explosives.
I guess it's safe for now..... (famous last words)
I can reproduce the memory graph you're seeing with sgen. I profiled it somewhat, but didn't find the cause of it (yet).
I found one bug in the threadpool, opened case #2619 for it. It looks like there is at least one other bug somewhere too.
Filed another bug for the second leak: #2620.
Both bug #2619 and bug #2620 have been fixed now. The fixes will be included in MonoTouch 5.2.
Issue is occurring again using the same test case as noted above
Xamarin Studio
Version 5.5.4 (build 15)
Installation UUID: 63e65309-d2a1-425e-a033-2dbdf229f771
Runtime:
Mono 3.10.0 ((detached/92c4884)
GTK+ 2.24.23 (Raleigh theme)
Package version: 310000031
Apple Developer Tools
Xcode 6.1 (6602)
Build 6A1052c
Xamarin.Android
Not Installed
Xamarin.iOS
Version: 8.4.0.43 (Business Edition)
Hash: 840a925
Branch:
Build date: 2014-11-16 21:03:22-0500
Xamarin.Mac
Version:
|
https://xamarin.github.io/bugzilla-archives/38/386/bug.html
|
CC-MAIN-2019-30
|
refinedweb
| 1,822
| 69.52
|
# Why it is important to apply static analysis for open libraries that you add to your project

Modern applications are built from third-party libraries like a wall from bricks. Their usage is the only option to complete the project in a reasonable time, spending a sensible budget, so it's a usual practice. However, taking all the bricks indiscriminately may not be such a good idea. If there are several options, it is useful to take time to analyze open libraries in order to choose the best one.
Collection "Awesome header-only C++ libraries"
----------------------------------------------
The story of this article began with the release of the Cppcast podcast "[Cross Platform Mobile Telephony](https://cppcast.com/telephony-dave-hagedorn/)". From it, I learned about the existence of the "[awesome-hpp](https://github.com/p-ranav/awesome-hpp)" list, which lists a large number of open C++ libraries consisting only of header files.
I was interested in this list for two reasons. First, it is an opportunity to extend the testing database for our PVS-Studio analyzer on modern code. Many projects are written in C++11, C++14, and C++17. Secondly, it might result in an article about the check of these projects.
The projects are small, so there are few errors in each one individually. In addition, there are few warnings, because some errors can only be detected if template classes or functions are instantiated in user's code. As long as these classes and functions aren't used, it is often impossible to figure out whether there is an error or not. Nevertheless, there were quite a lot of errors in total and I'll write about them in the next article. As for this article, it's not about errors, but about a caveat.
Why analyze libraries
---------------------
By using third-party libraries, you implicitly trust them to do some of the work and calculations. Nevertheless, it might be dangerous because sometimes programmers choose a library without considering the fact that not only their code, but the code of libraries might contain errors as well. As a result, there are non-obvious, incomprehensible errors that may appear in the most unexpected way.
The code of well-known open libraries is well-debugged, and the probability of encountering an error there is much less than in similar code written independently. The problem is that not all libraries are widely used and debugged. And here comes the question of evaluating their quality.
To make it clearer, let's look at an example. Let's take the [JSONCONS](https://github.com/danielaparker/jsoncons) library as an example.
> JSONCONS is a C++, header-only library for constructing JSON and JSON-like data formats such as CBOR.
A specific library for specific tasks. It may work well in general, and you will never find any errors in it. But don't even think about using this overloaded *<<=* operator.
```
static constexpr uint64_t basic_type_bits = sizeof(uint64_t) * 8;
....
uint64_t* data()
{
return is_dynamic() ? dynamic_stor_.data_ : short_stor_.values_;
}
....
basic_bigint& operator<<=( uint64_t k )
{
size_type q = (size_type)(k / basic_type_bits);
if ( q ) // Increase common_stor_.length_ by q:
{
resize(length() + q);
for (size_type i = length(); i-- > 0; )
data()[i] = ( i < q ? 0 : data()[i - q]);
k %= basic_type_bits;
}
if ( k ) // 0 < k < basic_type_bits:
{
uint64_t k1 = basic_type_bits - k;
uint64_t mask = (1 << k) - 1; // <=
resize( length() + 1 );
for (size_type i = length(); i-- > 0; )
{
data()[i] <<= k;
if ( i > 0 )
data()[i] |= (data()[i-1] >> k1) & mask;
}
}
reduce();
return *this;
}
```
PVS-Studio analyzer warning: [V629](https://www.viva64.com/en/w/v629/) Consider inspecting the '1 << k' expression. Bit shifting of the 32-bit value with a subsequent expansion to the 64-bit type. bigint.hpp 744
If I'm right, the function works with large numbers that are stored as an array of 64-bit elements. To work with certain bits, you need to create a 64-bit mask:
```
uint64_t mask = (1 << k) - 1;
```
The only thing is that the mask is formed incorrectly. Since the numeric literal 1 is of *int*type, if we shift it by more than 31 bits, we get undefined behavior.
> From the standard:
>
> shift-expression << additive-expression
>
> …
>
> 2. The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 \* 2^E2, reduced modulo one more than the maximum value representable in the result type. **Otherwise, if E1 has a signed type and non-negative value, and E1\*2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.**
The value of the *mask* variable can be anything. Yes, I know, theoretically, anything can happen because of UB. But in practice, most likely, we are talking about an incorrect result of the expression.
So, we have a function here that can't be used. Rather, it will only work for some special cases of the input argument value. This is a potential trap that a programmer can fall into. The program can run and pass various tests, and then suddenly crash on other input files.
You can also see the same error in *operator>>=*.
Now I'm going to ask you something rhetorically. Should I trust this library?
Maybe I should. After all, there are errors in all projects. However, it is worth considering: if these errors exist, are there any others that can lead to perky data corruption? Isn't it better to give preference to a more popular/tested library if there are several of them?
An unconvincing example? Okay, let's try another one. Let's take the [Universal](https://github.com/stillwater-sc/universal) mathematical library. It is expected that the library provides the ability to operate with vectors. For example, multiply and divide a vector by a scalar value. All right, let's see how these operations are implemented. Multiplication:
```
template
vector operator\*(double scalar, const vector& v) {
vector scaledVector(v);
scaledVector \*= scalar;
return v;
}
```
PVS-Studio analyzer warning: [V1001](https://www.viva64.com/en/w/v1001/) The 'scaledVector' variable is assigned but is not used by the end of the function. vector.hpp 124
Because of a typo, the original vector is returned, not the new *scaledVector* container. The same error occurs in the division operator. Facepalm.
Again, these errors don't mean anything separately. Although, this is a hint that this library isn't used much and there is highly likely that there are other serious undetected errors in it.
**Conclusion**. If several libraries provide the same functions, then you should perform preliminary analysis of their quality and choose the most tested and reliable one.
How to analyze libraries
------------------------
Okay, we want to figure out the quality of library code, but how do we do that? It's not easy to do this. One doesn't simply review the code. Or rather, you can look through it, but it will give little information. Moreover, such a review is unlikely to help you estimate the error density in the project.
Let's go back to the previously mentioned Universal mathematical library. Try to find an error in the code of this function. Seeing the comment next to it, I can't help but cite it for you :).
```
// subtract module using SUBTRACTOR: CURRENTLY BROKEN FOR UNKNOWN REASON
```

```
template
void module\_subtract\_BROKEN(const value& lhs, const value& rhs,
value& result) {
if (lhs.isinf() || rhs.isinf()) {
result.setinf();
return;
}
int lhs\_scale = lhs.scale(),
rhs\_scale = rhs.scale(),
scale\_of\_result = std::max(lhs\_scale, rhs\_scale);
// align the fractions
bitblock r1 = lhs.template nshift(lhs\_scale-scale\_of\_result+3);
bitblock r2 = rhs.template nshift(rhs\_scale-scale\_of\_result+3);
bool r1\_sign = lhs.sign(), r2\_sign = rhs.sign();
if (r1\_sign) r1 = twos\_complement(r1);
if (r1\_sign) r2 = twos\_complement(r2);
if (\_trace\_value\_sub) {
std::cout << (r1\_sign ? "sign -1" : "sign 1") << " scale "
<< std::setw(3) << scale\_of\_result << " r1 " << r1 << std::endl;
std::cout << (r2\_sign ? "sign -1" : "sign 1") << " scale "
<< std::setw(3) << scale\_of\_result << " r2 " << r2 << std::endl;
}
bitblock difference;
const bool borrow = subtract\_unsigned(r1, r2, difference);
if (\_trace\_value\_sub) std::cout << (r1\_sign ? "sign -1" : "sign 1")
<< " borrow" << std::setw(3) << (borrow ? 1 : 0) << " diff "
<< difference << std::endl;
long shift = 0;
if (borrow) { // we have a negative value result
difference = twos\_complement(difference);
}
// find hidden bit
for (int i = abits - 1; i >= 0 && difference[i]; i--) {
shift++;
}
assert(shift >= -1);
if (shift >= long(abits)) { // we have actual 0
difference.reset();
result.set(false, 0, difference, true, false, false);
return;
}
scale\_of\_result -= shift;
const int hpos = abits - 1 - shift; // position of the hidden bit
difference <<= abits - hpos + 1;
if (\_trace\_value\_sub) std::cout << (borrow ? "sign -1" : "sign 1")
<< " scale " << std::setw(3) << scale\_of\_result << " result "
<< difference << std::endl;
result.set(borrow, scale\_of\_result, difference, false, false, false);
}
```
I am sure that even though I gave you a hint that there is an error in this code, it is not easy to find it.
If you didn't find it, here it is. PVS-Studio warning: [V581](https://www.viva64.com/en/w/v581/) The conditional expressions of the 'if' statements situated alongside each other are identical. Check lines: 789, 790. value.hpp 790
```
if (r1_sign) r1 = twos_complement(r1);
if (r1_sign) r2 = twos_complement(r2);
```
Classic typo. In the second condition, the *r2\_sign* variable must be checked.
Like I say, forget about the "manual" code review. Yes, this way is possible, but unnecessarily time-consuming.
What do I suggest? A very simple way. Use [static code analysis](https://www.viva64.com/en/t/0046/).
Check the libraries you are going to use. Start looking at the reports and everything will become clear quickly enough.
You don't even need very thorough analysis and you don't need to filter false positives. Just go through the report and review the warnings. Be patient about false positives due to default settings and focus on errors.
However, false positives can also be taken into account indirectly. The more of them, the untidier the code is. In other words, there are a lot of tricks in the code that confuse the analyzer. They confuse the people who maintain the project and, as a result, negatively affect its quality.
**Note.** Don't forget about the size of projects. In a large project, there will always be more errors. But the number of errors is not the same as the error density. Keep this in mind when taking projects of different sizes and make adjustments.
What to use
-----------
There are [many](https://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis) tools for static code analysis. I obviously suggest using the [PVS-Studio](https://www.viva64.com/en/pvs-studio/) analyzer. It is great for both one-time code quality assessment and regular error detection and correction.
You can check the project code in C, C++, C#, and Java. The product is proprietary. **However, a free trial license will be more than enough to evaluate the quality of several open libraries.**
I also remind you that there are several options for free licensing of the analyzer for:
* [students](https://www.viva64.com/en/for-students/);
* developers of [open source projects](https://www.viva64.com/en/open-source-license/);
* developers of [closed projects](https://www.viva64.com/en/b/0457/) (you need to add special comments to the code);
* [Microsoft MVP](https://www.viva64.com/en/mvp/).
Conclusion
----------
The methodology of static code analysis is still undeservedly underestimated by many programmers. A possible reason for this is the experience of working with simple noisy tools of the "linter" class, which perform very simple and, unfortunately, often useless checks.
For those who are not sure whether to try implementing a static analyzer in the development process, see the following two posts:
* [How to introduce a static code analyzer in a legacy project and not to discourage the team](https://www.viva64.com/en/b/0743/).
* [Why You Should Choose the PVS-Studio Static Analyzer to Integrate into Your Development Process](https://www.viva64.com/en/b/0687/).
Thank you for your attention, and I wish you fewer bugs both in your code and in the code of the libraries you use.
|
https://habr.com/ru/post/520494/
| null | null | 2,081
| 58.28
|
During this past Red Hat Summit I worked on a session with Mobile, Fuse and BPMS. It was a great pleasure working with Phil Simpson, Javier Perez and Maggie Hu to build and present the demo. Below I walk through setting up and using the Push Notification Server. For information on submitting claims through the mobile application and the adjudicator review you can review Maggie's Blog on Red Hat Mobile Application Platform - Connecting to JBoss BPMSuite REST.
This article is part of a series we're putting together for the Build an Enterprise Application in 60 Minutes with JBoss Middleware session at the Summit. The original slide decks can be found below from Maggie on Slideshare. Please take a look at the slide decks to get a better idea on the use case we're working with.
Basically, we're allowing people to submit claims quickly from their mobile devices with some basic information when an auto accident happens. The claim will get submitted to the insurance company, an adjudicator will review the claim, set the settlement amount, and complete the claim. Then the policy holder will receive a push notification on their mobile device on the settlement amount.
Red Hat Summit 2015 - Build an Enterprise Application in 60 Minutes with JBoss Middleware
What is Push Notification and its benefits?
A push notification is a message or alert delivered by a centralized server (on premise or cloud) to a device. Red Hat Mobile Unified Push Server (Aerogear) can be seen as a broker that distributes push messages to different 3rd party Push Networks. The graphic below gives a little overview:
- One PushApplication and at least one mobile platform variant must be created.
- The variant credentials that are generated and stored by the UnifiedPush Server must be added to the mobile application source, enabling the application to register with the UnifiedPush Server once it is installed on mobile devices.
- Sending a push message can happen in different ways: The AdminUI can be used to send a (test) message to registered devices. However, in a real-world scenario the Push Notification Message request is triggered from a backend application, which sends its requests using the Sender API. Different SDKs for different languages are supported.
- The push request is then translated into platform specific details for the required variant Push Network. The Dashboard of the AdminUI gives a status report if a message is sent to the Push Network.
- The UnifiedPush Server does not directly deliver the message to the mobile device. This is done by the appropriate variant Push Network. Note: There can be latency in the actual delivery. Most Push Networks, such as APNs or GCM, do not guarantee to deliver messages to mobile devices.
Setting Up the Unified Push Server on Openshift
The.
In our example we setup the UPS on Openshift instead of on premise and we do this through the Openshift Application Manager. First we need a Openshift account. You can sign up for a free account for 3 small gears.
Next we will create an openshift application.
We will use the Unified Push Server 1.0 Cartridge which will also add MySQL to the Application. We can take the defaults and click Create Application Button. After creating the application a credentials screen is displayed with URLs and credentials.
Now we can sign onto the console to create applications, variants, etc and monitor messages. Let's open the dashboard for the Push Server, ie, and login with admin/admin which will bring up the dasboard main screen.
Now we want to add an application to receive the push notifications. We click on applications and the create application button. Once created we can look at the variants. This shows the application ID and Master Secret for the application which we will use in our example.
At this point we can create variants for Android and iOS. For this first example we will create an application but won't use variants and register devices. We will just show the notification getting to the push notification server. Now that the application is created let's do a quick test.
Test sending a message to the UPS
I used the Advanced REST Client in Chrome to test the message. I setup the project with the URL, the Authorization and Content Type as shown below. I put in some sample data for the notification.
After clicking on send I get a Job submitted response and can lookup the message in the dashboard.
Now let's move onto how we can make the call from BPMS.
Sending a notification message from BPMS to the UPS
First in our Business Process we add the message in a script task to the Response Body for the REST call.
kcontext.setVariable("requestBody", "{\"ttl\":3600," + "\"message\":{" + "\"alert\":\"Your Payment Amount is:" + kcontext.getVariable("paymentAmount") + "\"," + "\"action-category\":\"some value\"," + "\"sound\":\"default\"," + "\"badge\":2,\"content-available\":true" + "},\"simple-push\":\"version=123\"}");
Next in our Business Process we added a REST Task to make the call to the UPS to send the claim award message. A couple of items to note on the Task. The first is the data assignments. The username is the Application ID and the password is the Master Secret as seen in the screen shots below. Also note the URL for the domain REST API for UPS in addition to the Basic Authorization.
Note the App settings, in addition to the Android Variant settings, for Google Cloud messaging. Also in the REST Task we setup the Data Input and Output as indicated below.
One additional item that was required is the work definition as displayed below.
import org.drools.core.process.core.datatype.impl.type.StringDataType; import org.drools.core.process.core.datatype.impl.type.ObjectDataType; [ [ "name" : "Email", "parameters" : [ "From" : new StringDataType(), "To" : new StringDataType(), "Subject" : new StringDataType(), "Body" : new StringDataType() ], "displayName" : "Email", "icon" : "defaultemailicon.gif" ], [ "name" : "Log", "parameters" : [ "Message" : new StringDataType() ], "displayName" : "Log", "icon" : "defaultlogicon.gif" ], [ "name" : "WebService", "parameters" : [ "Url" : new StringDataType(), "Namespace" : new StringDataType(), "Interface" : new StringDataType(), "Operation" : new StringDataType(), "Parameter" : new StringDataType(), "Endpoint" : new StringDataType(), "Mode" : new StringDataType() ], "results" : [ "Result" : new ObjectDataType(), ], "displayName" : "WS", "icon" : "defaultservicenodeicon.png" ], [ "name" : "Rest", "parameters" : [ "Url" : new StringDataType(), "Method" : new StringDataType(), "ConnectTimeout" : new StringDataType(), "ReadTimeout" : new StringDataType(), "Username" : new StringDataType(), "Password" : new StringDataType() ], "results" : [ "Result" : new ObjectDataType(), ], "displayName" : "REST", "icon" : "defaultservicenodeicon.png" ] ]
That was all that is required to send a push notification from BPMS to the Unified Push server. You can see the messages in the UPS console.
All variants associated with the Application in UPS will receive the notification. We will cover the Android application in a follow up article to register the device with Google Cloud Messaging (GCM) and receive the notification.
References:
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/using-the-unified-push-server-with-bpms
|
CC-MAIN-2017-04
|
refinedweb
| 1,130
| 55.13
|
NAG Technical Report TR 4/09
Anna Kwiczala
Numerical Algorithms Group, May 2009
Abstract
This report gives detailed instructions on how to call routines in the NAG C and Fortran Libraries from the Octave programming environment.
Contents
Octave [1] is a freely redistributable programming language for numerical computations. It is mostly compatible with MATLAB. The NAG Libraries [2] contain a large selection of numerical and statistical routines, which can be accessed from different languages [3]. This article gives a brief introduction to one of the methods and examples of calling NAG routines from within Octave.
Octave can be extended by dynamically linked functions [4], which are used in the same way as Octave functions. Octave has been written in C++, so it is not surprising that the easiest way of extending it is by writing the linking code in that language. It can be called by Octave directly through its native oct-file interface. Due to the fact that C functions can easily be called from C++, our best choice is to use C++ code together with the NAG C Library.
2. C++ code and Oct-Files
Octave comes with a ready-made script mkoctfile, which can be used to compile C++ code into oct-files. All we have to do is to write a C++ function calling one of the NAG routines and then use the script. To define the entry point into the dynamically linked function, we need to use the Octave DEFUN_DLD macro in our C++ code. Therefore, our function will look like this:
#include <octave/oct.h> #include <appropriate NAG header files> DEFUN_DLD (function_name, args, nargout, "Function description") { octave_value_list retval; // retrieve input arguments from args // call NAG routine // assign output arguments to retval return retval; }
where:
- oct.h contains most of the necessary definitions for an oct-file in Octave;
- function_name will be our function's name seen in Octave and it must match the file's name, but be different from any NAG routine names;
- args is the list of arguments to the function of type octave_value_list;
- nargout is the number of output arguments;
- "Function description" is the string that will be seen as the function help text;
- the return type is always octave_value_list.
The rest of the code required will be easier to demonstrate with the use of examples. The code for this article was tested on a Linux machine running 64-bit Fedora 8 (Werewolf) with Octave 3.0.3, plus c++ (GCC) 4.3.3, gcc (GCC) 4.3.3, GNU Fortran (GCC) 4.3.3, Mark 8 of the NAG C Library and Mark 22 of the NAG FORTRAN Library.
3.1 Example 1 Log gamma function ln Γ(x)
3.2 Example 2 Scaled complex complement of error function, exp(-z2)erfc(-iz)
3.3 Example 3 Approximate solution of complex simultaneous linear equations AX = B
3.4 Example 4 Solving a nonlinear minimization problem
3.5 Example 5 Univariate time series, seasonal and non-seasonal differencing
Octave contains many tools that make extending it fairly easy. The method used in this article is just one of a few possible approaches which we believe is the easiest one. If you want to try different methods, consult Dynamically Linked Functions section on Octave website [4].
- [1] Octave
John W. Eaton
John W. Eaton of University of Wisconsin-Madison, 1998-2006.
- [2] NAG Numerical Libraries
Numerical Algorithms Group
Numerical Algorithms Group Limited, Oxford, UK, 2008.
- [3] Enhancing the Numerical Capability of Your Application
Numerical Algorithms Group
Numerical Algorithms Group Limited, Oxford, UK, 2004.
- [4] Octave - Dynamically Linked Functions
John W. Eaton
John W. Eaton of University of Wisconsin-Madison, 1996, 1997, 2007.
- [5] Calling NAG Fortran Library Routines from C Language Programs Using the NAG C Header Files
Ian Hounam
Numerical Algorithms Group Ltd, Oxford, UK, 2002
- [6] The NAG C Library
Numerical Algorithms Group Ltd, Oxford, UK, 2009
- [7] The NAG Fortran Library
Numerical Algorithms Group Ltd, Oxford, UK, 2009
[NP3674]
|
https://www.nag.co.uk/content/calling-nag-library-routines-octave
|
CC-MAIN-2020-24
|
refinedweb
| 660
| 54.32
|
What I got (red means: no live image available at that time/location):
Apparently, the live image is more or less consistently not available between some 38° east and 95° east. That's just based on one day, though, starting from unix timestamp 1534627704 (August 18th 2018, 21:28 UTC)
How I got there:
Here's a script that, whenever HDEV live image availability data is received via MQTT, requests the current ISS position from a web service and combines that information. The result is written to stdout, from where I wrote to a file. I had this script running for 24 hours (it self-terminates after that period of time):
# import urllib2 import json import paho.mqtt.client as mqtt import time def on_connect(client, userdata, flags, rc): client.subscribe("iss-hdev-availability/available-bool")() client.on_connect = on_connect client.on_message = on_message client.connect("test.mosquitto.org", 1883) client.loop_start() start_time = time.time() duration = 24*3600 while True: try: if time.time() > (start_time + duration): break time.sleep(1) except KeyboardInterrupt: break client.loop_stop()
So now we have live image availability vs location, for a 24h period. The dataset is here:
(it's also in the project files)
That data can be drawn on a map. I found out that there's a map toolkit for matplotlib, and installed it. The rest is quite simple:
import matplotlib as mpl mpl.use('Agg') # because the AWS EC2 machine doesn't have tkInter installed import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import numpy as np import csv # m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\ llcrnrlon=-180,urcrnrlon=180,resolution='c') m.drawcoastlines() x = [] y = [] xn = [] yn = [] npoints = 0 with open('hdev-availability.csv') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: npoints += 1 lat = float(row[1]) lon = float(row[2]) available = int(row[3]) if available: x.append(lon) y.append(lat) else: xn.append(lon) yn.append(lat) plt.title("HDEV live image availability (last {} h)".format(int(npoints*6/3600))) m.scatter(x,y,3,marker='o',color='black',latlon=True) m.scatter(xn,yn,3,marker='o',color='red',latlon=True) plt.savefig('hdev-availability-map.png') # plt.show()
In the last line you see the save-image-to-file operation, and the result is the map shown at the top and again here:
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.
|
https://hackaday.io/project/14729-iss-hdev-image-availability/log/151304-availability-map
|
CC-MAIN-2019-26
|
refinedweb
| 410
| 51.44
|
Agghhh, what’s with all those files when you spin up a new ASP.NET Core and React.js project?!
The “out of the box” experience if you’re new to either React or ASP.NET Core (or both) can be pretty overwhelming; it’s hard to know where to start.
So let’s break it down and see what we’ve got.
First up it’s fairly straightforward to spin up a new project which gives you both React and ASP.NET Core …
Using the dotnet CLI…
dotnet new react
Or Visual Studio/Rider etc.
Either way you’ll end up with something which looks like this…
Now at first glance there may seem to be a lot going on here (especially when you start drilling into the various folders) so let’s break it down.
The project is best considered as two entirely separate entities which happen to be co-located in the same place.
- A React application (using “Create React app”)
- An ASP.NET Core Web API backend
React front end
ClientApp houses the frontend part of your new application.
So long as you’re using version 2.1 or higher of the .NET SDK you’ll find this part of the application is a standard React application created using something called “Create React App”.
The only real difference between this and a CRA app is that the .NET team have also provided some example React components to help get you started.
When you run the application
ClientApp/public/index.html will be served to your browser.
In there you’ll see a div which looks like this…
<div id="root"></div>
This element is all important as React will render your application into this div.
Take a look at
ClientApp/src and you’ll see some .js files and a components folder.
In
index.js you’ll see the very “top” of your application; this is where it all starts.
import 'bootstrap/dist/css/bootstrap.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href'); const rootElement = document.getElementById('root'); ReactDOM.render( <BrowserRouter basename={baseUrl}> <App /> </BrowserRouter>, rootElement); registerServiceWorker();
The first few lines bring in various modules from other js files and node modules you need to run the app.
Then a variable is declared which points to that div we noticed earlier in
index.html (with id
root).
ReactDOM is called to render your application which consists of a
BrowserRouter and
App components into this
root div.
So far so good.
Now if you head into the
<App /> component you’ll see yet more of that funny looking “almost HTML” which points to yet more components…
export default class App extends Component { static displayName = App.name; render () { return ( <Layout> <Route exact path='/' component={Home} /> <Route path='/counter' component={Counter} /> <Route path='/fetch-data' component={FetchData} /> </Layout> ); } }
That “almost HTML” is actually “JSX”. It may look like HTML but is actually converted into javascript which React then uses to interact with the DOM in your browser.
This React component (
App) nests a few
Route components inside a
Layout component.
Already we’re beginning to see how React apps are built as lots of small components which can be composed together.
In this case,
Layout takes care of rendering things like a NavBar for the application then these
Route components let you assign paths to specific components.
So when you run the app in a browser and head over to
/fetch-data the
FetchData component will be rendered but if you head to
/Counter then
FetchData will be omitted from the DOM and you’ll get the
Counter component being shown instead.
Because the
Layout component is rendered by itself (not using a
Route component) it will remain visible all the time (irrespective of the path you navigate to).
Next Steps
The best way to figure out how the template works is to explore further and try to break some things!
When you run the application (from VS or the CLI) you’ll find the React app launches in your browser.
As you click on the links in the NavBar you’ll see how the general Layout (including NavBar) remain the same but the rest of the page updates to show the relevant component(s).
From here on, any changes you make to the front end part of your application will trigger an update in your browser, so you can quickly change/tweak and generally fiddle with stuff and immediately see the results of your efforts!
Next time we’ll take a quick tour of the Web API part of the project.
All posts in the
Getting started with the ASP.NET Core React Template series.
|
https://jonhilton.net/understanding-the-asp-net-react-template/
|
CC-MAIN-2022-05
|
refinedweb
| 801
| 63.59
|
1. Extension elements/attributes:
* proposal (norm): Elements and attributes that are not in the xproc
namespace or standard are gracefully ignored.
* suggestion (Jeni) "must understand" attribute that means if you
don't understand, don't run my pipeline.
* Murray: if you understand other elements and attributes, you can use
them.
* Richard: Other than documentation, what are the other use cases?
* Norm: take as a first measure: "they are ignored". If I don't
understand the element/attribute, ignore it.
Consensus: You ignore elements and attributes that you don't
understand.
Note: You can put extension elements into a when and then use the
choose to detect that that extension element isn't
available.
2. Declaring extensions components
Proposal:
This can occur in a pipeline library:
|
http://www.w3.org/XML/XProc/2006/08/04-pm-minutes.txt
|
CC-MAIN-2015-48
|
refinedweb
| 125
| 58.18
|
three ways for spider by python
Project Description
Release History Download Files
djangospider is light web crawling framework, it have a few code, but can do high speed crawling, it support three modes to crawl: multithreading, tornado IOloop, and twisted rector.you can easily to understand to how to use async crawler.
Requirement:
Python2.7 Works on Linux
- Install:
- you can download the zip package in github. then unpack the zip package, find the path of setup.py, Execute the command: $sudo python setup.py install
The entry function: Start(start_urls,mode)
start_urls parameter: is a list, and it’s element is tuple:the first of the tuple is url which you will crawl, the second of the tuple is the callback for url.
the mode parameter: the crawler’s way, it has three types:if mode is int 1 : multithreading ways if mode is int 2 : tornado async ways if mode is int 3 : twisted async ways
For example:
from djangospider.mycrawl.run import Start ,_crawl
- def callback(response,url):
- print “get the %s” %url
start_urls=[(‘’,callback),]
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/djangospider/
|
CC-MAIN-2017-39
|
refinedweb
| 199
| 59.33
|
Ubuntu.Components.ListItem
The ListItem element provides Ubuntu design standards for list or grid views. The ListItem component was designed to be used in a list view. It does not define any specific layout, but while its contents can be freely chosen by the developer, care must be taken to keep the contents light in order to ensure good performance when used in long list views. More...
Properties
- action : Action
- color : color
- contentItem : Item
- contentMoving : bool
- divider
- divider.colorFrom : real
- divider.colorTo : real
- dragMode : bool
- dragging : bool
- expansion
- expansion.expanded : bool
- expansion.height : real
- highlightColor : color
- highlighted : bool
- leadingActions : ListItemActions
- selectMode : bool
- selected : bool
- swipeEnabled : bool
- swiped : bool
- trailingActions : ListItemActions
Signals
Detailed Description
The component provides two color properties which configures the item's background when normal or highlighted. This can be configured through color and highlightColor properties. The list item is highlighted if there is an action attached to it. This means that the list item must have an active component declared as child, at least leading- or trailing actions specified, or to have a slot connected to clicked or pressAndHold signal. In any other case the component will not be highlighted, and highlighted property will not be toggled either. Also, there will be no highlight happening if the click happens on the active component.
import QtQuick 2.4 import Ubuntu.Components 1.2 MainView { width: units.gu(40) height: units.gu(71) Column { anchors.fill: parent ListItem { Button { text: "Press me" } onClicked: console.log("clicked on ListItem") } ListItem { leadingActions: ListItemActions { actions: [ Action { iconName: "delete" } ] } onClicked: console.log("clicked on ListItem with leadingActions set") } ListItem { trailingActions: ListItemActions { actions: [ Action { iconName: "edit" } ] } onClicked: console.log("clicked on ListItem with trailingActions set") } ListItem { Label { text: "onClicked implemented" } onClicked: console.log("clicked on ListItem with onClicked implemented") } ListItem { Label { text: "onPressAndHold implemented" } onPressAndHold: console.log("long-pressed on ListItem with onPressAndHold implemented") } ListItem { Label { text: "No highlight" } } } }
contentItem holds all components and resources declared as child to ListItem. Being an Item, all properties can be accessed or altered. However, make sure you never change x, y, width, height or anchors properties as those are controlled by the ListItem itself when leading or trailing actions are revealed or when selectable and draggable mode is turned on, and thus might cause the component to misbehave. Anchors margins are free to alter.
Each ListItem has a thin divider shown on the bottom of the component. This divider can be configured through the divider grouped property, which can configure its margins from the edges of the ListItem as well as its visibility. When used in ListView or UbuntuListView, the last list item will not show the divider no matter of the visible property value set.
ListItem can handle actions that can get swiped from front or back of the item. These actions are Action elements visualized in panels attached to the front or to the back of the item, and are revealed by swiping the item horizontally. The swipe is started only after the mouse/touch move had passed a given threshold. The actions are visualized by a panel, which is configurable through the ListItemStyle.
The actions are configured through the leadingActions as well as trailingActions properties.
ListItem { id: listItem leadingActions: ListItemActions { actions: [ Action { iconName: "delete" onTriggered: listItem.destroy() } ] } trailingActions: ListItemActions { actions: [ Action { iconName: "search" onTriggered: { // do some search } } ] } }
Note: When a list item is swiped, it automatically connects both leading and trailing actions to the list item. If needed, the same ListItemActions instance can be used in both leading and trailing side. In the following example the list item can be deleted through both leading and trailing actions using the same container:
ListItem { id: listItem leadingActions: ListItemActions { actions: [ Action { iconName: "delete" onTriggered: listItem.destroy() } ] } trailingActions: leadingActions }
The action is triggered only after all the animations are completed.
ListItem provides a set of attached properties which are attached to each panel of the ListItem. However not all properties are valid in all the circumstances.
The component is styled using the ListItemStyle style interface.
Selection mode
The selection mode of a ListItem is controlled by the ViewItems::selectMode attached property. This property is attached to each parent item of the ListItem exception being when used as delegate in ListView, where the property is attached to the view itself.
import QtQuick 2.4 import Ubuntu.Components 1.2 Flickable { width: units.gu(40) height: units.gu(50) // this will not have any effect ViewItems.selectMode: true Column { // this will work ViewItems.selectMode: false width: parent.width Repeater { model: 25 ListItem { Label { text: "ListItem in Flickable #" + index } } } } }
The indices selected are stored in ViewItems::selectedIndices attached property, attached the same way as the ViewItems::selectMode property is. This is a read/write property, meaning that initial selected item indices can be set up. The list contains the indices added in the order of selection, not sorted in any form.
Note: When in selectable mode, the ListItem content is not disabled and clicked and pressAndHold signals are also emitted. The only restriction the component implies is that leading and trailing actions cannot be swiped in. selectable property can be used to implement different behavior when clicked or pressAndHold.
Dragging mode
The dragging mode is only supported on ListView, as it requires a model supported view to be used. The drag mode can be activated through the ViewItems::dragMode attached property, when attached to the ListView. The items will show a panel as defined in the style, and dragging will be possible when initiated over this panel. Pressing or clicking anywhere else on the ListItem will invoke the item's action assigned to the touched area.
The dragging is realized through the ViewItems::dragUpdated signal, and a signal handler must be implemented in order to have the draging working. Implementations can drive the drag to be live (each time the dragged item is dragged over an other item will change the order of the items) or drag'n'drop way (the dragged item will be moved only when the user releases the item by dropping it to the desired position). The signal has a ListItemDrag event parameter, which gives detailed information about the drag event, like started, dragged up or downwards or dropped, allowing in this way various restrictions on the dragging.
The dragging event provides three states reported in ListItemDrag::status field, Started, Moving and Dropped. The other event field values depend on the status, therefore the status must be taken into account when implementing the signal handler. In case live dragging is needed, Moving state must be checked, and for non-live drag (drag'n'drop) the Moving state must be blocked by setting event.accept = false, otherwise the dragging will not know whether the model has been updated or not.
Example of live drag) { model.move(event.from, event.to, 1); } } moveDisplaced: Transition { UbuntuNumberAnimation { property: "y" } } }
Example of drag'n'drop) { // inform dragging that move is not performed event.accept = false; } else if (event.status == ListItemDrag.Dropped) { model.move(event.from, event.to, 1); } } moveDisplaced: Transition { UbuntuNumberAnimation { property: "y" } } }
ListItem does not provide animations when the ListView's model is updated. In order to have animation, use UbuntuListView or provide a transition animation to the moveDisplaced or displaced property of the ListView.
Using non-QAbstractItemModel models
Live dragging (moving content on the move) is only possible when the model is a derivate of the QAbstractItemModel. When a list model is used, the ListView will re-create all the items in the view, meaning that the dragged item will no longer be controlled by the dragging. However, non-live drag'n'drop operations can still be implemented with these kind of lists as well.
import QtQuick 2.4 import Ubuntu.Components 1.2 ListView { model: ["plum", "peach", "pomegrenade", "pear", "banana"] delegate: ListItem { Label { text: modelData } color: dragMode ? "lightblue" : "lightgray" onPressAndHold: ListView.view.ViewItems.dragMode = !ListView.view.ViewItems.dragMode } ViewItems.onDragUpdated: { if (event.status == ListItemDrag.Started) { return; } else if (event.status == ListItemDrag.Dropped) { var fromData = model[event.from]; // must use a temporary variable as list manipulation // is not working directly on model var list = model; list.splice(event.from, 1); list.splice(event.to, 0, fromData); model = list; } else { event.accept = false; } } }
When using DelegateModel, it must be taken into account when implementing the ViewItems::dragUpdated signal handler.
import QtQuick 2.4 import Ubuntu.Components 1.2 ListView { model: DelegateModel { model: ["apple", "pear", "plum", "peach", "nuts", "dates"] delegate: ListItem { Label { text: modelData } onPressAndHold: dragMode = !dragMode; } } ViewItems.onDragUpdated: { if (event.status == ListItemDrag.Moving) { event.accept = false } else if (event.status == ListItemDrag.Dropped) { var fromData = model.model[event.from]; var list = model.model; list.splice(event.from, 1); list.splice(event.to, 0, fromData); model.model = list; } } }
Expansion
Since Ubuntu.Components 1.3, ListItem supports expansion. ListItems declared in a view can expand exclusively, having leading and trailing panes locked when expanded and to be collapsed when tapping outside of the expanded area. The expansion is driven by the expansion group property, and the behavior by the ViewItems::expansionFlags and ViewItems::expandedIndices attached properties. Each ListItem which is required to expand should set a proper height in the expansion.height property, which should be bigger than the collapsed height of the ListItem is. The expansion itself is driven by the expansion.expanded property, which can be set freely depending on the use case, on click, on long press, etc.
The default expansion behavior is set to be exclusive and locked, meaning there can be only one ListItem expanded within a view and neither leading nor trailing action panels cannot be swiped in. Expanding an other ListItem will collapse the previosuly expanded one. There can be cases when tapping outside of the expanded area of a ListItem we woudl need the expanded one to collapse automatically. This can be achieved by setting
ViewItems.CollapseOnOutsidePress flag to ViewItems::expansionFlags. This flag will also turn on
ViewItems.Exclusive flag, as tapping outside practicly forbids more than one item to be expanded at a time.
import QtQuick 2.4 import Ubuntu.Components 1.3 ListView { width: units.gu(40) height: units.gu(71) model: ListModel { Component.onCompleted: { for (var i = 0; i < 50; i++) { append({data: i}); } } } ViewItems.expansionFlags: ViewItems.CollapseOnOutsidePress delegate: ListItem { Label { text: "Model item #" + modelData } trailingActions: ListItemActions { actions: [ Action { icon: "search" }, Action { icon: "edit" }, Action { icon: "copy" } ] } expansion.height: units.gu(15) onClicked: expansion.expanded = true } }
The example above collapses the expanded item whenever it is tapped or mouse pressed outside of the expanded list item.
Note: Set 0 to ViewItems::expansionFlags if no restrictions on expanded items is required (i.e multiple expanded items are allowed, swiping leading/trailing actions when expanded).
Note: Do not bind expansion.height to the ListItem's height as is will cause binding loops.
Note on styling
ListItem's styling differs from the other components styling, as ListItem loads the style only when either of the leadin/trailing panels are swiped, or when the item enters in select- or drag mode. The component does not assume any visuals to be present in the style.
See also ListItemActions, ViewItems::dragMode, ViewItems::dragUpdated, and ListItemStyle.
Property Documentation
The property holds the action which will be triggered when the ListItem is clicked. ListItem will not visualize the action, that is the responsibility of the components placed inside the list item. However, when set, the ListItem will be highlighted on press.
If the action set has no value type set, ListItem will set its type to Action.Integer and the triggered signal will be getting the ListItem index as value parameter.
Defaults no null.
Configures the color of the normal background. The default value is transparent.
contentItem holds the components placed on a ListItem. It is anchored to the ListItem on left, top and right, and to the divider on the bottom, or to the ListItem's bottom in case the divider is not visible. The content is clipped by default. It is not recommended to change the anchors as the ListItem controls them, however any other property value is free to change. Example:
ListItem { contentItem.anchors { leftMargin: units.gu(2) rightMargin: units.gu(2) topMargin: units.gu(0.5) bottomMargin: units.gu(0.5) } }
The property describes whether the content is moving or not. The content is moved when swiped or when snapping in or out, and lasts till the snapping animation completes.
This grouped property configures the thin divider shown in the bottom of the component. The divider is not moved together with the content when swiped left or right to reveal the actions. colorFrom and colorTo configure the starting and ending colors of the divider. Beside these properties all Item specific properties can be accessed.
When visible is true, the ListItem's content size gets thinner with the divider's thickness. By default the divider is anchored to the bottom, left right of the ListItem, and has a 2dp height.
The property reports whether a ListItem is draggable or not. While in drag mode, the list item content cannot be swiped. The default value is false.
The property informs about an ongoing dragging on a ListItem.
The group drefines the expansion state of the ListItem.
This property group was introduced in Ubuntu.Components 1.3.
Configures the color when highlighted. Defaults to the theme palette's background color. If changed, it can be reset by assigning undefined as value.
True when the item is pressed. The items stays highlighted when the mouse or touch is moved horizontally. When in Flickable (or ListView), the item gets un-highlighted (false) when the mouse or touch is moved towards the vertical direction causing the flickable to move.
Configures the color when highlighted. Defaults to the theme palette's background color.
An item is highlighted, thus highlight state toggled, when pressed and it has one of the following conditions fulfilled:
- leadingActions or trailingActions set,
- it has an action attached
- if the ListItem has an active child component, such as a Button, a Switch, etc.
- in general, if an active (enabled and visible) MouseArea is added as a child component
- clicked signal handler is implemented or there is a slot or function connected to it
- pressAndHold signal handler is implemented or there is a slot or function connected to it.
Note: Adding an active component does not mean the component will be activated when the ListItem will be tapped/clicked outside of the component area. If such a behavior is needed, that must be done explicitly.
ListItem { Label { text: "This is a label" } Switch { id: toggle anchors.right: parent.right } Component.onCompleted: clicked.connect(toggle.clicked) }
See also action, leadingActions, and trailingActions.
The property holds the actions and its configuration to be revealed when swiped from left to right.
See also trailingActions.
The property reports whether the component and the view using the component is in selectable state. While selectable, the ListItem's leading- and trailing panels cannot be swiped in. clicked and pressAndHold signals are also triggered. Selectable mode can be set either through this property or through the parent attached ViewItems::selectMode property.
The property drives whether a list item is selected or not. Defaults to false.
See also ListItem::selectMode and ViewItems::selectMode.
The property enables the swiping of the leading- or trailing actions. This is useful when an overlay component needs to handle mouse moves or drag events without the ListItem to steal the events. Defaults to true.
import QtQuick 2.4 import Ubuntu.Components 1.3 ListView { width: units.gu(40) height: units.gu(70) model: 25 delegate: ListItem { swipeEnabled: !mouseArea.drag.active Rectangle { color: "red" width: units.gu(2) height: width MouseArea { id: mouseArea anchors.fill: parent drag.target: parent } } } }
This QML property was introduced in Ubuntu.Components 1.3.
The property notifies about the content being swiped so leading or trailing actions are visible.
This QML property was introduced in Ubuntu.Components 1.3.
The property holds the actions and its configuration to be revealed when swiped from right to left.
See also leadingActions.
Signal Documentation
The signal is emitted when the component gets released while the highlighted property is set. The signal is not emitted if the ListItem content is swiped or when used in Flickable (or ListView, GridView) and the Flickable gets moved.
If the ListItem contains a component which contains an active MouseArea, the clicked signal will be supressed when clicked over this area.
The signal is emitted when the content movement has ended.
The signal is emitted when the content movement has started.
The signal is emitted when the list item is long pressed.
If the ListItem contains a component which contains an active MouseArea, the pressAndHold signal will be supressed when pressed over this area.
|
https://docs.ubuntu.com/phone/en/apps/api-qml-current/Ubuntu.Components.ListItem
|
CC-MAIN-2018-51
|
refinedweb
| 2,774
| 58.69
|
- Good to know
- Tutorials & references
- Notebooks (Workbench)
- With Hugging Face models (A-Z)
- Choose the same locations
- Container Registry to Artifact Registry
- Problems?
Like other notes on this site, this note contains only a few noteworthy points of the topic.
👉 My Github Repo for this note: dinhanhthi/google-vertex-ai
👉 All services needed for Data Science on Google Cloud.
Good to know
- You should choose the same location/region for all services (google project, notebook instances,...). 👉 Check this section.
- Troubleshooting.
- Access Cloud Storage buckets.
- Google Cloud Pricing Calculator
gcloud aireferences (for Vertex AI)
- ALways use Logging service to track the problems.
- When making models, especially for serving on prod, don't forget to use
loggingservices.
- When creating a new notebook instance, consider to choose a larger size for "boot disk" (100GB is not enough as it is).
- If you run the gcp command lines in workbench, you don't have to give the credential for the connecting to gcp. It's automatically passed.
Tutorials & references
- What is Vertex AI? -- Official video.
- Google Cloud Vertex AI Samples -- Official github repository.
- Vertex AI Documentation AIO: Samples - References -- Guides.
Notebooks (Workbench)
If you are going to create images with
docker inside the virtual machine, you should choose more boot disk space (default = 100GB but you should choose more than that). In case you wanna change the size of disk, you can go to Compute Engine / Disks[ref].
Remember to shutdown the notebook if you don't use it!!
Workbench notebook vs Colab
👉 Note: Google Colab.
"Managed notebook" vs "User-managed notebook"
👉 Official doc. Below are some notable points.
gcloud CLI
# Start instance
gcloud compute instances start thi-managed-notebook --zone=europe-west1-d
# Stop instance
gcloud compute instances stop thi-managed-notebook --zone=europe-west1-d
Sync with Github using
gh CLI
Inside the notebook, open Terminal tab. Then install the Github CLI (ref),
Login to gh,
gh auth login
Then following the guides.
Open Juputer notebook on your local machine
The JupyterLab is running on Vertex Notebook at port
8080. You have 2 options to open it on your local machine:
gcloud compute ssh \
--project <project-id> \
--zone <zone> <instance-name> \
-- \
-L 8081:localhost:8080
Then open
First, you have to sign up an account on ngrok, without this step, you cannot open HTML pages.
Open Terminal in the Vertex machine and then install
ngrok. Here, I use
snap,
sudo apt update
sudo apt install snapd
sudo snap install ngrok
# Check
ngrok --version
If it's not found, you can find it in
/snap/ngrok/current. Add this line to
.bashrc or
.zshrc,
export PATH="/snap/ngrok/current:$PATH"
Then
source ~/.bashrc or
source ~/.zshrc to make changes.
Log in to your ngrok account, go to your AuthToken page and copy the token here. Back to the terminal on Vertex machine,
ngrok authtoken <token>
Then,
ngrok http 8080
It returns something like,
Account Anh-Thi Dinh (Plan: Free)
Version 2.3.40
Region United States (us)
Web Interface
Forwarding ->
Forwarding ->
Go to and see the result!
SSH to User-managed notebook
You have to use User-managed notebook! Managed notebook doesn't allow you to use SSH (officially). If you wanna connect via SSH for managed notebook, read next section.
First, connect using
gcloud 👉 Note: Google Cloud CLI.
gcloudcommand + SSH port forwarding
👉 Official doc.
gcloud compute ssh --project <project-id> --zone <zone> <instance-name> -- -L 8081:localhost:8080
- You can find all information of
<thing>by clicking the notebook name in Workbench.
8081is the port on your machine and
8080is the port on vertex.
- For
<instance-name>, you can also use instance id (which can be found in Compute Engine > VM instances)
- For the popup "Build Recommended" in JupyterLab, you can run
jupyter lab build.
ssh(and also on VScode)
You can follow the official instructions. For me, they're complicated. I use another way.
Make sur you've created a ssh keys on your local machine, eg.
/Users/thi/.ssh/id_rsa.ideta.pub is mine.
# Show the public keys
cat /Users/thi/.ssh/id_rsa.ideta.pub
# Then copy it
On the vertex notabook instance (you can use
gcloud method to access or just open the notebook on browser and then open Terminal).
# Make sure you are "jupyter" user
whoami # returns "jupyter"
# If not
su - jupyter
# If it asks your password, check next section in this note.
# Create and open /home/jupyter/.ssh/authorized_keys
nano /home/jupyter/.ssh/authorized_keys
# Then paste the public key you copied in previous step here
# Ctrl + X > Y > Enter to save!
On your local machine,
ssh -i /Users/thi/.ssh/id_rsa.ideta [email protected]<ip_of_notebook>
The ip of the instance will change each time you reset the instance. Go to the Compute Engine section to check the up-to-date ip address.
You are good. On VScode, you make the same things with the extension Remote - SSH.
- After running above command, you enter the instance's container (with your username, eg. when you run
whoami, it will be
thi) and you can also open jupyer notebook on your local machine. To stop, type
exitand also cmd + C.
- The user (and folder) on which the notebook is running is
jupyter(you can check
/home/jupyter/). You can use
sudo - jupyterto change to this user.
For example, default user after I connect via ssh is
thi and the user for jupyter notebook is
jupyter. However, you don't know their passwords. Just change them!
sudo passwd thi
# then entering the new password for this
sudo passwd jupyter
Why? The default
bash has a problem of "backspace" button when you connect via ssh.
sudo i
sudo apt install zsh # install zsh
Make zsh default for each user, below is for
jupyter,
su - jupyter
chsh -s $(which zsh) # make zsh be default
exit # to log out
su - jupyter # log in again
# Then follow the instructions
Then, install
oh-my-zsh,
sh -c "$(curl -fsSL)"
Then install
spacehip theme (optional),
git clone "$ZSH_CUSTOM/themes/spaceship-prompt"
ln -s "$ZSH_CUSTOM/themes/spaceship-prompt/spaceship.zsh-theme" "$ZSH_CUSTOM/themes/spaceship.zsh-theme"
👉 An example of simple
.zshrc file.
SSH to managed notebook
When creating a new notebook, make sure to enable terminal for this notebook. Open the notebook and then open the terminal.
# On your local machine => check the public keys
cat ~/.ssh/id_rsa.pub
# On managed notebook, make sure you're at /home/jupyter
pwd
mkdir .ssh
touch .ssh/authorized_keys
vim .ssh/authorized_keys
# Paste the public key here
# Then save & exit (Press ESC then type :wq!)
# Check
cat .ssh/authorized_keys
# Check the external ip address of this notebook instance
curl -s
Connect from local,
ssh -i ~/.ssh/id_rsa [email protected]<ip-returned-in-previous-step>
AIO steps
Remark: This section is almost for me only (all the steps here are already described in previous steps).
Remember to shutdown the notebook if you don't use it!!
# Update system
sudo apt update
# You have to use below line to install zsh
# The terminal on workbench doesn't allow to do that!
gcloud compute ssh --project <project-id> --zone <zone> <name-of-instance> -- -L 8081:localhost:8080
# Change user's password
sudo passwd thi
sudo passwd jupyter
Go back to Terminal on Vertex (to make sure you're
jupyter)
# Install zsh
sudo apt install zsh
chsh -s $(which zsh)
# Install oh-my-zsh
sh -c "$(curl -fsSL)"
# Install theme "spaceship"
git clone "$ZSH_CUSTOM/themes/spaceship-prompt"
ln -s "$ZSH_CUSTOM/themes/spaceship-prompt/spaceship.zsh-theme" "$ZSH_CUSTOM/themes/spaceship.zsh-theme"
# Change theme to "spaceship"
nano ~/.zshrc # then change to "spaceship"
# Change the line of plugins too
plugins=(git docker docker-compose python emoji)
# Add alias
gs='git status'
ud_zsh='source ~/.zshrc'
# Update changes
source ~/.zshrc
# Add local ssh keys to this instance (for accessing via ssh)
# (Below is for local machine)
cat ~/.ssh/id_rsa.ideta.pub
# Then copy the public keys
# On vertex
mkdir ~/.ssh
nano /home/jupyter/.ssh/authorized_keys
# Then paste the key copied above to this and save
# If needed, make the same thing for user "thi"
# Install Github CLI
gh auth login
# Add conda path
nano ~/.zshrc
# Then add the following to the end of the file
export PATH="/opt/conda/bin:$PATH"
# After that Ctrl + X > Y > Enter to save
source ~/.zshrc
# Add more space to swap
# (to prevent the error: "[Errno 12] Cannot allocate memory")
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024k
sudo mkswap /swapfile
sudo swapon /swapfile
# Check
sudo swapon -s
Troubleshooting
[Errno 12] Cannot allocate memory
👉 reference to this solution
sudo swapon -s
If it is empty it means you don't have any swap enabled. To add a 1GB swap:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024k
sudo mkswap /swapfile
sudo swapon /swapfile
Add the following line to the
fstab to make the swap permanent.
sudo nano /etc/fstab
/swapfile none swap sw 0 0
Error processing tar file(exit status 1): write /home/model-server/pytorch_model.bin: no space left on device
It's because disk space are full. You can check by running
df -h,
# Filesystem Size Used Avail Use% Mounted on
# /dev/sda1 99G 82G 13G 87% /
If you use the notebook to create docker images, be careful, the spaces will be used implicitly (Use
docker info to check where the images will be stored, normally they are in
/var/lib/docker which belongs to boot disk spaces). You can check the unsed images by
docker images and remove them by
docker image rm img_id.
Wanna increase the disk space?: Go to Compute Engine / Disks > Choose the right machine and edit the spaces[ref].
With Hugging Face models (A-Z)
A-Z text classification with PyTorch
👉 Original repo & codes.
👉 The official blog about this task (the notebook is good but you need to read this blog too, there are useful points and links)
👉 My already-executed notebook (There are my comments here).
- Take a model from Hugging Face + dataset IMDB + train again with this dataset to get only 2 sentiments -- "Positive" and "Negative". They cut the head of the model from HF and put another on top (Fine tuning).
- They do all the steps (preprocessing, training, predicting, post processing) inside the notebook first and then use these functions in the container they create before pushing to Vertex AI's registry.
- They run a custom job on Vertex AI with a pre-built container 👈 Before doing that "online", they perform the same steps locally to make things work!
- They also show the way of using custom container for the training task.
- Create a new docker image locally with
Dockerfileand all neccessary settings.
- Push the image to Google's Container Registry.
- Using
aiplatformto init + run the job on vertex ai.
- Hyperparameter Tuning: Using Vertex AI to train the model with different values of the Hyperparameters and then choose the best one for the final model.
- Deploying: they use TorchServe + create a custom container for prediction step.
- All the codes are in folder
/predictor/
- The most important codes are in file
custom_handler.pywhich makes the same things in the step of predicting locally (the beginning steps of the notebook)
- A custom image is created via file
Dockerfile
- Test the image with a container locally before pusing to Vertex AI.
- Create a model with this image and then deploy this model to an endpoint (this step can be done on the Vertex platform).
# Vertex AI SDK for Python
#
pip -q install --upgrade google-cloud-aiplatform
# Create a new bucket
gsutil mb -l <name>
# Check
gsutil ls -al <name>
# To disable the warning:
# huggingface/tokenizers: The current process just got forked, after parallelism has
# already been used. Disabling parallelism to avoid deadlocks...
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
Load & train the model from Hugging Face's SDK,
tokenizer = AutoTokenizer.from_pretrained(
model_name_or_path,
use_fast=True,
)
# 'use_fast' ensure that we use fast tokenizers (backed by Rust)
# from the 🤗 Tokenizers library.
model = AutoModelForSequenceClassification.from_pretrained(
model_name_or_path, num_labels=len(label_list)
)
# Upload from local to Cloud Storage bucket
gsutil cp local/to/file file/on/bucket
# validate
gsutil ls -l file/on/bucket
# Init the vertex ai sdk
aiplatform.init(project=PROJECT_ID, staging_bucket=BUCKET_NAME, location=REGION)
# Check the healthy of the container just created
!curl
# The port and "/ping" are defined manually in the Dockerfile
# You have to wait ~1 minute after creating successfully the container to run this line
Make sure to add
location=REGION where your project locates. You should make this region/location be the same across the services (buckets, workbench, compute engine, registry,...)
For other tasks: creating docker container + test locally,..., let's read the notebook.
Just deploying?
In case you skip the training phase and just use the model given by Hugging Face community.
👉 Notebook for testing load/use models from Hugging Face.
👉 Notebook for creating an image and deploying to vertex AI.
👉 Export Transformers Models
I use the idea given in this blog.
from transformers import TFAutoModelForSequenceClassification
MAX_SEQ_LEN = 100
callable = tf.function(tf_model.call)
concrete_function = callable.get_concrete_function([tf.TensorSpec([None, MAX_SEQ_LEN], tf.int32, name="input_ids"), tf.TensorSpec([None, MAX_SEQ_LEN], tf.int32, name="attention_mask")])
tf_model = TFAutoModelForSequenceClassification.from_pretrained("joeddav/xlm-roberta-large-xnli")
tf_model.save(data_loc + '/xlm-roberta-large-xnli', signatures=concrete_function)
# Upload to bucket
! gsutil cp -r $modelPath $BUCKET_NAME
To make some tests with
curl, check this note. Below a shortcodes,
instance = b"Who are you voting for in 2020?"
b64_encoded = base64.b64encode(instance)
test_instance = {
"instances": [
{
"data": {
"b64": b64_encoded.decode('utf-8')
},
"labels": ["Europe", "public health", "politics"]
}
]
}
payload = json.dumps(test_instance)
r = requests.post(
f"{APP_NAME}/",
headers={"Content-Type": "application/json", "charset": "utf-8"},
data=payload
)
r.json()
Using Transformers'
pipeline with Vertex AI?
You can check a full example in this notebook. In this section, I note about the use of Transformers'
pipeline using
TorchServe and Vertex AI.
The principle idea focuses on the file
custom_hanler.py which is used with
TorchServe when creating a new container image for serving the model.
In this
custom_handler.py file, we have to create methods
initialize(),
preprocess(),
inference() which extend the class
BaseHandler. Most of the problems come from the format of the outputs in these methods.
For using
pipeline(), we can define
initialze(),
preprocess() and
inference() like below,
def initialize(self, ctx):
""" Loads the model.pt file and initialized the model object.
Instantiates Tokenizer for preprocessor to use
Loads labels to name mapping file for post-processing inference response
"""
self.manifest = ctx.manifest
properties = ctx.system_properties
model_dir = properties.get("model_dir")
self.device = torch.device("cuda:" + str(properties.get("gpu_id")) if torch.cuda.is_available() else "cpu")
# Read model serialize/pt file
serialized_file = self.manifest["model"]["serializedFile"]
model_pt_path = os.path.join(model_dir, serialized_file)
if not os.path.isfile(model_pt_path):
raise RuntimeError("Missing the model.pt or pytorch_model.bin file")
# Load model
self.model = AutoModelForSequenceClassification.from_pretrained(model_dir)
self.model.to(self.device)
self.model.eval()
# Ensure to use the same tokenizer used during training
self.tokenizer = AutoTokenizer.from_pretrained(model_dir)
# pipeline()
# We should create this pipe here in order to not creating again and again for each
# request
self.pipe = pipeline(task='zero-shot-classification', model=self.model, tokenizer=self.tokenizer)
self.initialized = True
def preprocess(self, data):
""" Preprocessing input request by tokenizing
Extend with your own preprocessing steps as needed
"""
text = data[0].get("data")
if text is None:
text = data[0].get("body")
sentences = text.decode('utf-8')
# Tokenize the texts
tokenizer_args = ((sentences,))
inputs = self.tokenizer(*tokenizer_args,
padding='max_length',
max_length=128,
truncation=True,
return_tensors = "pt")
return inputs
def inference(self, inputs):
""" Predict the class of a text using a trained transformer model.
"""
decoded_text = self.tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True)
prediction = self.pipe(decoded_text, candidate_labels=["negative", "neutral", "positive"])
return [prediction] # YES, A LIST HERE!!!!
Another way to define
preprocess() and the corresponding
inference() (thanks to this idea).
def preprocess(self, data):
""" Preprocessing input request by tokenizing
Extend with your own preprocessing steps as needed
"""
text = data[0].get("data")
if text is None:
text = data[0].get("body")
sentences = text.decode('utf-8')
processed_sentences = []
num_separated = [s.strip() for s in re.split("(\d+)", sentences)]
digit_processed = " ".join(num_separated)
processed_sentences.append(digit_processed)
return processed_sentences
def inference(self, inputs):
""" Predict the class of a text using a trained transformer model.
"""
prediction = self.pipe(inputs[0], candidate_labels=["negative", "neutral", "positive"])
if len(inputs) == 1:
prediction = [prediction]
return prediction # YES, IT'S ALREADY A LIST FROM preprocess()
Encode example text in
base64 format
For online prediction requestion, fortmat the prediction input instances as JSON with
base64 encoding as shown here:
[
{
"data": {
"b64": "<base64 encoded string>"
}
}
]
👉 Converting a text to
base64 online.
import base64
# Without non-ascii characters
instance = b"This film is not so good as it is."
b64_encoded = base64.b64encode(instance)
print(b64_encoded)
# b'VGhpcyBmaWxtIGlzIG5vdCBzbyBnb29kIGFzIGl0IGlzLg=='
# With (and also with) non-ascii characters (like Vietnamese, Russian,...)
instance = "Bạn sẽ bầu cho ai trong năm 2020?"
b64_encoded = base64.b64encode(bytes(instance, "utf-8"))
print(b64_encoded)
# b'QuG6oW4gc+G6vSBi4bqndSBjaG8gYWkgdHJvbmcgbsSDbSAyMDIwPw=='
b64_encoded.decode('utf-8')
# 'QuG6oW4gc+G6vSBi4bqndSBjaG8gYWkgdHJvbmcgbsSDbSAyMDIwPw=='
# To decode?
base64.b64decode(b64_encoded).decode("utf-8", "ignore")
# 'Bạn sẽ bầu cho ai trong năm 2020?'
Testing created endpoint
curl
Below codes are in Jupyter notebook.
ENDPOINT_ID="<id-if-endpoint>"
PROJECT_ID="<project-id>"
test_instance = {
"instances": [
{
"data": {
"b64": b64_encoded.decode('utf-8')
},
"labels": ["positive", "negative", "neutral"]
}
]
}
payload = json.dumps(test_instance)
# '{"instances": [{"data": {"b64": "VGhpcyBmaWxtIGlzIG5vdCBzbyBnb29kIGFzIGl0IGlzIQ=="}, "labels": ["positive", "negative", "neutral"]}]}'
%%bash -s $PROJECT_ID $ENDPOINT_ID
PROJECT_ID=$1
ENDPOINT_ID=$2
curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \{PROJECT_ID}/locations/europe-west1/endpoints/${ENDPOINT_ID}:predict \
-d '{"instances": [{"data": {"b64": "VGhpcyBmaWxtIGlzIG5vdCBzbyBnb29kIGFzIGl0IGlzIQ=="}, "labels": ["positive", "negative", "neutral"]}]}'
{
"predictions": [
{
"scores": [
0.92624515295028687,
0.04236096516251564,
0.031393911689519882
],
"labels": [
"negative",
"positive",
"neutral"
],
"sequence": "This film is not so good as it is!"
}
],
"deployedModelId": "***",
"model": "projects/***/locations/europe-west1/models/***",
"modelDisplayName": "***"
}
👉 My repo: dinhanhthi/google-api-playground
👉 Note: Google APIs
First, you have to create a Service Account (You can take the one you use to work with Vertex at the beginning, for me, it's "Compute Engine default service account").
Next, you have to create and download a JSON key w.r.t this Service Account.
// File .env
PRIVATE_KEY = "***"
CLIENT_EMAIL = "***"
// File predict.js
import { PredictionServiceClient, helpers } from "@google-cloud/aiplatform";
const credentials = {
private_key: process.env.PRIVATE_KEY
client_email: process.env.CLIENT_EMAIL
}
const projectId = "***";
const location = "europe-west1";
const endpointId = "***";
async function main(text = "I love you so much!") {
const clientOptions = {
credentials,
apiEndpoint: `${location}-aiplatform.googleapis.com`,
};
const predictionServiceClient = new PredictionServiceClient(clientOptions);
const endpoint = `projects/${projectId}/locations/${location}/endpoints/${endpointId}`;
const parameters = {
structValue: {
fields: {},
},
};
const buff = new Buffer.from(text);
const base64encoded = buff.toString("base64");
const _instances = {
data: { b64: base64encoded },
};
const instance = {
structValue: {
fields: {
data: {
structValue: {
fields: { b64: { stringValue: _instances.data.b64 } },
},
},
},
},
};
const instances = [instance];
const request = { endpoint, instances, parameters };
const [response] = await predictionServiceClient.predict(request);
console.log("Predict custom trained model response");
console.log(`Deployed model id : ${response.deployedModelId}`);
const predictions = response.predictions;
console.log("Predictions :");
for (const prediction of predictions) {
const decodedPrediction = helpers.fromValue(prediction);
console.log(`- Prediction : ${JSON.stringify(decodedPrediction)}`);
}
}
process.on("unhandledRejection", (err) => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
Then run the test,
node -r dotenv/config vertex-ai/predict.js "text to be predicted"
The results,
Predict custom trained model response
Deployed model id : 3551950323297812480
Predictions :
- Prediction : {"scores":[0.9942014217376709,0.0030435377266258,0.002755066612735391],"sequence":"You aren't kind, i hate you.","labels":["negative","neutral","positive"]}
Below are some links which may be useful for you,
Some remarks for Hugging Face's things
Without option
return_tensors when encoding
tokenizer = AutoTokenizer.from_pretrained(pt_model_dir)
inputs = saved_tokenizer("I am happy")
tokenizer.decode(inputs["input_ids"], skip_special_tokens=True)
With option
return_tensors when encoding
tokenizer = AutoTokenizer.from_pretrained(pt_model_dir)
inputs = saved_tokenizer("I am happy", return_tensors="pt")
# "pt" for "pytorch", "tf" for "tensorflow"
tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True)
Choose the same locations
👉 Vertex locations (You can check all supported locations here)
Below are some codes where you have to indicate the location on which your service will be run (Remark: They're not all, just what I've met from these notebooks),
# When working with notebooks
# (You can choose it visually on the Vertex Platform)
gcloud notebooks instances ... --location=us-central1-a ...
# When initialize the vertex ai sdk
aiplatform.init(project=PROJECT_ID, staging_bucket=BUCKET_NAME, location=REGION)
When pushing the image to the Container Registry, check this link for the right locations. For example,
gcr.io or
us.gcr.io is for US,
eu.gcr.io is for EU,
asia.gcr.io is for Asia.
Container Registry to Artifact Registry
Step 1: Artivate Artifact Registry API.
Step 2: Go to Artifacet Registry. If you see any warning like "*You have gcr.io repositories in Container Registry. Create gcr.io repositories in Artifact Registry?", click CREATE GCR. REPOSITORIES.
Step 3: Copy images from Container Registry to Artifact Registry. What you need is the URLs of "from" CR and "to" AR.
- Check in page AR, there is small warning icon ⚠️, hover it to see the "not complete" url. Example: Copy your images from
eu.gcr.io/ideta-ml-thito
europe-docker.pkg.dev/ideta-ml-thi/eu.gcr.io
- Check in page CR, click the button copy, a full url of the image will be copied to clipboard, eg. gcr.io/ideta-ml-thi/pt-xlm-roberta-large-xnli_3
- Finally, combine them with the tag (use
:lastestif you don't have others already).
- Example, from
gcr.io/ideta-ml-thi/pt-xlm-roberta-large-xnli_3:latestto
us-docker.pkg.dev/ideta-ml-thi/gcr.io/pt-xlm-roberta-large-xnli_3:latest.
👉 Transitioning to repositories with gcr.io domain support (also on this link, copy from container to artifact)
gcrane(this tool is recommended by Google)
Next, install
gcrane tool. (It uses "go"). In case you just want to use directly, you can download it, then put it in the
$PATH in your
.bashrc or
.zshrc. On MacOS, don't forget to go to System Preferences > Securitty & Privacy > Run it anyway.
Finally,Read this official guide.
gcloud
Good practice: Use Cloud Shell instead.
# Change to the current project with gcloud
gcloud config set project <project-id>
👉 Follow this official guide.
gcloud container images add-tag gcr.io/ideta-ml-thi/name-of-image:latest us-docker.pkg.dev/ideta-ml-thi/gcr.io/name-of-image:latest
Remark: It takes a long time to run in background. Don't close the terminal window!! That's why we should (or shouldn't?) try Cloud Shell instead.
Step 4: Route to AR (After step 3, the iamges in AR has the same route as in CR but the traffic only regconize it from CR. We need this step to make all traffics use AR's instead). You need these permissions to perform the action (click the button ROUTE TO ARTIFACT).
Problems?
I met this problem when my model is around 2.5GB but it's ok for the model around 500MB.
Solution: When creating a new endpoint, set "Maximum number of compute nodes" to a number (don't leave it empty) and also choose a more powerful "Machine type".
|
https://dinhanhthi.com/google-vertex-ai/
|
CC-MAIN-2022-33
|
refinedweb
| 3,807
| 50.12
|
Optimized (but not debug) builds fail to compile setlocale.cpp with the error:
$ cat t.cpp; CC -c t.cpp
#define _XOPEN_SOURCE
#include <cwchar>
"/opt/sunpro/12_3/prod/include/cc/wchar.h", line 90: Error: tm is not defined.
"/opt/sunpro/12_3/prod/include/cc/wchar.h", line 92: Error: fgetwc is not defined.
...
and so on for every wide-char function in wchar.h.
The definition of _XOPEN_SOURCE at the top of setlocale.cpp is not entirely
correct in that it interacts with the various guards in the C library headers.
AFAICT, Oracle/Sun wchar.h includes C library wchar.h, which includes C library
wctype.h, which includes again wchar.h, coming full circle to the compiler
wchar.h which uses the names w/o them being defined, yet. The fact that
Oracle/Sun headers include_next corresponding C library headers outside of a
inclusion guard does not help.
(Debug builds are not affected because of interaction from the difference in the
structure and includes of rw/_traits.h in debug vs. optimized builds).
The poor man's fix is to guard that _XOPEN_SOURCE define for SUNPro builds (see
below). However, I am not sure whose side the error is.
Thanks,
Liviu
PS. Is it still called SUNPro? Oracles seems it has sanitized that name out on
their website.
Index: src/setlocale.cpp
===================================================================
--- src/setlocale.cpp (revision 1388733)
+++ src/setlocale.cpp (working copy)
@@ -34,8 +34,10 @@
#include <rw/_defs.h>
#if defined (__linux__) && !defined (_XOPEN_SOURCE)
+# if !defined (__SUNPRO_CC)
// need S_IFDIR on Linux
# define _XOPEN_SOURCE
+# endif // !__SUNPRO_CC
#endif // __linux__ && !_XOPEN_SOURCE
#include <locale.h> // for setlocale()
|
http://mail-archives.apache.org/mod_mbox/incubator-stdcxx-dev/201209.mbox/%3C505D43C8.3080205@hates.ms%3E
|
CC-MAIN-2017-34
|
refinedweb
| 266
| 64.17
|
How to close python 3 external repl tab?
I am trying to make it so if they say end game then the external repl tab will close itself because i am trying to make a python 3 text based RPG chose your own adventure game.
Answered by a5rocks (535) [earned 5 cycles]
Voters
You can't control the browser (that would be scary), but you can
import sysand run
sys.exit()
@a5rocks Thank you so much! Wish that was possible because this is my code window that runs it as its own tab and i want to exit that :\ tinyurl.com/ZaniewZork
|
https://repl.it/talk/ask/How-to-close-python-3-external-repl-tab/14789?order=new
|
CC-MAIN-2019-51
|
refinedweb
| 102
| 76.96
|
Threads 1. When writing games you need to do more than one thing at once.
- Aron Stevens
- 2 years ago
- Views:
Transcription
1 Threads 1 Threads Slide 1 When writing games you need to do more than one thing at once. Threads offer a way of automatically allowing more than one thing to happen at the same time. Java has threads as a fundamental feature in the language. This will make your life much easier when you write games in Java. Threads are related to processes and multitasking. Example Slide 2 Suppose that you are a poor student and you need to earn money. To earn money you get a job answering technical support calls for a company specialising in software to derive new weaving patterns for Turkish carpets. As it turns out there is not a very large user base and you only get 4 or 5 calls a day (but the pay is good). You have to revise for an exam. You hit upon the idea of revising while you are waiting for calls. When a call interrupts you go away from you books and deal with the customer.
2 Threads 2 Example Continued Slide 3 The last example was easy. You had plenty of time to go back and forward between the books and the exam. Now consider a more important situation. You are going to play in a counter strike tournament and at the same time you need to watch an important Hockey match between Sweden and Russia while you are doing your revision. You can again multi-task. You spend a little bit of time on each activity swapping between them. If you are fast enough you might be able to do all three (almost at the same time). Context Switching Slide 4 Going back to the first example. Suppose that you have spent too much of your time on fast living and your memory is not as good as it should be. When you answer the phone you put a bookmark in the book so you can remember where you are. When you go back to the book you use the bookmark to work out where you are. This is an example of a context switch. You want to go from one task to another you save information to remember where to go back to.
3 Threads 3 Context Switching Slide 5 The computer does the same thing with running programs. If it wants to switch tasks. It saves all the information needed (program counter, values of variables), so the program can be returned to. This can happen without the program knowing it. Think of it as cryogenetics for programs. The operating system forcefully stops the current task saves that state and starts another task from a previously saved state. Threads and Processes Slide 6 There is a technical distinction between threads and processes. That need not worry us here. You can think of a process as a whole program (such as emacs, word, minesweeper, mozilla). The operating systems allows more than one process to run at the same time. A thread is a unit of execution with in a process. That has less overhead and quicker context switch time. Threads can share data while processes can not (not always true but true enough). Threads are lightweight processes.
4 Threads 4 Multitasking Slide 7 A computer can give the illusion of doing more than one thing at once by time slicing. Each task is given a small amount of time to run before the next task is switched in. Context switches take care of all this. Of course every thing runs slower, but you have more flexibility. Threads and Java Slide 8 In Java there is a special thread class that manages all the above for you. To create a new thread you could do the following : Thread mythread = new Thread(); mythread.start(); This would not do much since the default thread class does not do anything (apart from managing all the context switching stuff).
5 Threads 5 Threads and Java You have three choices: Slide 9 Extend the Thread class Implement a runnable interface Use anonymous classes. Simple example Slide 10 public class MyThread extends Thread { public void run() { System.out.println("Do Something."); Then later on when you actually want to do something. MyThread mythread = new MyThread(); You can even use constructors (see next example).
6 Threads 6 Slide 11 public class MyThread2 extends Thread { private int theadid; public MyThread2(int id) { threadid = id; public void run() { for(int i=0; i<10000 ; i++) { System.out.println(threadid + " : " + i); public static void main(string[] args) { Thread thread1 = new MyThread2(1); Thread thread2 = new MyThread2(2); thread1.start(); thread2.start(); Interfaces Inheritance (extends) has the problem you can only extend from one class. Slide 12 This would make your program design quite hard. To get over this we can use interfaces. In general, an interface is a device or a system that unrelated entities use to interact. According to this definition, a remote control is an interface between you and a television set, the English language is an interface between two people.
7 Threads 7 Interfaces Slide 13 A class can only extend another class while it can have many interfaces. Interfaces are declared in a similar way to classes. You probably won t need to define any yourself. But you will need to use some of the system provided ones for example MouseListener, Runnable, MouseEvent,... Slide 14 public class MyThread3 implements Runnable { public MyThread3() { Thread thread = new Thread(this); thread.start(); public void run() { System.out.println("Hello."); public static void main(string[] args) { MyThread3 thread = new MyThread3(); Exercise rewrite the first two examples using runnable.
8 Threads 8 Detour - Static Members. Slide 15 A static member of a class has only one instance no matter how many times the class is instantiated. Question what is printed on the following example and why? What happens if we change static int counter to int counter Static members are best avoided (they are error prone and it is hard to debug what is going on). But they are sometimes useful. public class StaticExample { static int counter = 0; public StaticExample() { counter++; public int HowManyTimes() { return(counter); Slide 16 public static void main(string[] args) { StaticExample x = new StaticExample(); StaticExample y = new StaticExample(); StaticExample z = new StaticExample(); System.out.println(z.HowManyTimes());
9 Threads 9 When does the context switching happen? It is up to the runtime system when the context switch happens. This means it could happen while you are doing something. Slide 17 In particular you could be updating a piece of shared data and the runtime system swaps tasks during this. The system is then left in an inconsistent state. In the following example we require (for illustration only) that xpos and ypos are always equal. We put a test to see if they are equal. The thread itself is very simple. public class BadSynch extends Thread { static private int xpos; static private int ypos; Slide 18 public void run() { for(int i=0; i<1000; i++) { xpos++; ypos++; if(xpos!= ypos) { System.out.println(":-( " + xpos + " " + ypos);
10 Threads 10 If we create two threads and run them in parallel. Slide 19 public static void main(string[] args) { Thread thread1 = new BadSynch(); Thread thread2 = new BadSynch(); thread1.start(); thread2.start(); We will see lots of unhappiness. (Try it and see). Be Warned!!! Slide 20 With threads you do not know which order things will be executed or when the context switched. It might be luck that that the program works.
11 Threads 11 Version without static members Slide 21 Instead of using static members, we should use objects and object references to communicate. The general idea is that you give the reference of an object to multiple threads to communicate with. To redo the previous example we use a class DoubleCounter to hold the values of x and y. public class DoubleCounter { private int x; private int y; Slide 22 public DoubleCounter() { x = 0; y = 0; public void add_one() { x++; y++; public boolean happy() { if (x==y) { return(true); else { return(false);
12 Threads 12 We can then redo the example by passing a double counter object via the constructor for the class. Slide 23 public class BadSynch extends Thread { private DoubleCounter counter; public BadSynch(DoubleCounter newcounter) { counter = newcounter; public void run() { for(int i=0; i< ; i++) { counter.add_one(); if(!counter.happy()) { System.out.print("!-( "); Then we create one double counter and pass this to both threads. public static void main(string[] args) { Slide 24 DoubleCounter sharedcounter = new DoubleCounter(); Thread thread1 = new BadSynch(sharedcounter); Thread thread2 = new BadSynch(sharedcounter); thread1.start(); thread2.start(); Run it and see, you will still see lots of unhappiness.
13 Threads 13 Synchronize Slide 25 The whole problem can be avoided by putting locks on data. You can put a piece of data in a room with a door. When a thread wants to modify the data it goes in through the door locks it so nobody else can get in and modify it. When it has finished it unlocks the door and leaves. This is achieved in Java with the Syncrhonized keyword. Example Replace with the new DoubleCounter and expect no unhappiness. Slide 26 public class DoubleCounter { private int x; private int y; public DoubleCounter() { x = 0; y = 0; public synchronized void add_one() { x++; y++; public synchronized boolean happy() { if (x==y) {return(true); else {return(false);
14 Threads 14 Object Synchronisation You can also objects as synchronisation points. You could rewrite the Slide 27 above as: public void add_one() { synchronized(this) {x++; y++; Remember this is a reference to the current object. When to synchronise Slide 28 When two or more threads access the same piece of data. Don t over synchronise. Synchronisation points force other threads to wait. Use the syncrhonized(this) construction to only synchronise at the critical points.
15 Threads 15 Anonymous Inner Classes Slide 29 new Thread() { public void run() { System.out.println("Hello.");.start(); Should only be used for short fragments of code. Deadlock Slide 30 The synchronise statement forces other threads to wait if they are accessing shared data. You have the situation where a thread has locked a piece of data that another thread wants which is locking a piece of data that the first thread wants.
16 Threads 16 Deadlock example Slide 31 We will use semaphores to illustrate deadlock. Semaphores are shared variables (and in Java guarded by getters and setters with syncrhonized statements). Where one value means locked and another unlocked. Semaphore Variables Slide 32 public class Deadlock { static int locka=0; /* 0 if unlock 1 if locked. */ static int lockb=0; public static synchronized int getlocka() { return locka; public static synchronized void setlocka(int newlocka) { locka = newlocka;
17 Threads 17 Slide 33 public static synchronized int getlockb() { return lockb; public static synchronized void setlockb(int newlockb) { lockb = newlockb; Threads Slide 34 In this example we will use anonymous classes. The first thread locks A then locks B, then unlocks B and unlocks A. First lock A and then do some work. new Thread() { public void run() { System.out.println("P1: Waiting for A."); while(getlocka()==1) {; System.out.println("P1: Got A"); setlocka(1); try { Thread.sleep(5000); catch (InterruptedException x) {
18 Threads 18 First thread continued Now try and lock B then unlock. Slide 35 System.out.println("P1: Waiting for B."); while(getlockb()==1) {; setlockb(1); System.out.println("P1: Got B."); setlockb(0); setlocka(0);.start(); Code for the second thread Slide 36 new Thread() { public void run() { System.out.println("P2: Waiting for B."); while(getlockb()==1) {; System.out.println("P2: Got B"); setlockb(1); System.out.println("P2: Waiting for A."); while(getlocka()==1) {; System.out.println("P2: Got A"); setlocka(1); setlocka(0); setlockb(0);.start();
19 Threads 19 Output Slide 37 P1: Waiting for A. P1: Got A P2: Waiting for B. P2: Got B P2: Waiting for A. P1: Waiting for B. How to avoid Deadlock There are no hard and fast rules to avoid deadlock. Slide 38 Essentially you have to look for cycles. There are tools that help, but they don t help that much. The interleaving of threads is not defined, so sometimes that code might deadlock sometimes it might not. In the previous example if thread 1 completely finishes before thread 2 starts then there should be no problem.
20 Threads 20 Wait and notify Statements such as Slide 39 while(getlockb()==1) {; Are not so efficient. This is called busy waiting, it has to check each time around the loop. Java provides and pair of statements wait and notify. The behaviour is a bit complicated so I ll just give an example. pair of statements Without wait and notify Slide 40 // Thread A public void waitformessage() { while (hasmessage == false) { ; // Thread B public void setmessage() {... hasmessage = true;
21 Threads 21 With wait and notify Slide 41 // Thread A public sychrnoized void waitformessage() { try { wait(); catch (InterruptedException ex) { // Thread B public synhronized void setmessage() {... notify(); wait and notify Slide 42 Essentially wait releases current locks and gives control back to other threads. notify wakes up a thread that is waiting. If there is more than one wait a random thread is woken up. notifyall(); wakes all the waiting threads.
22 Threads 22 Threads summary Threads allow you to do more than one thing at a time. Slide 43 Problems can occur with corrupted shared data. syncrhonized can solve this problem. Don t syncrhonize too much. Don t have too many threads (JavaVM can t cope). Threads are non-deterministic. That is if you one the program once and it works doesn t mean it is going to work next time. Be careful.
Introduction to Java A First Look
Introduction to Java A First Look Java is a second or third generation object language Integrates many of best features Smalltalk C++ Like Smalltalk Everything is an object Interpreted or just in time
Programming Language Concepts: Lecture 12
Programming Language Concepts: Lecture 12 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2009, Lecture 12, 04 March 2009 Concurrent
Java Threads. You will learn how to write programs that can simultaneously execute multiple activities using Java threads.
Java Threads You will learn how to write programs that can simultaneously execute multiple activities using Java threads. What You Know How to write Java programs to complete one activity at a time e.g.,
Threads and Synchronization
Threads and Synchronization Mark Allen Weiss Copyright 2000 1 What threads are Outline of Topics The Thread class and starting some threads Synchronization: keeping threads from clobbering each other Deadlock
CSC System Development with Java Threads
CSC 308 2.0 System Development with Java Threads Department of Statistics and Computer Science 1 Multitasking and Multithreading Multitasking: Computer's ability to perform multiple jobs concurrently More
G52CON: Concepts of Concurrency
G52CON: Concepts of Concurrency Lecture 11 Synchronisation in Java" Brian Logan School of Computer Science bsl@cs.nott.ac.uk Outline of this lecture" mutual exclusion in Java condition synchronisation
An Introduction to Java Threads
An Introduction to Java Threads What Are Threads? A Simple Thread Example Thread Attributes Multithreaded Programs What Are Threads? A thread--sometimes known as a lightweight process--is a single sequential
Monitors to Implement Semaphores
(Chapter 5.2) Monitors to Implement Semaphores Concurrency: monitors & condition synchronization 1 Monitors & Condition Synchronization Concepts: monitors: encapsulated data + access procedures mutual
Threads. Multithreaded program. Examples of threads. Threads and Processes. Problems of multitasking. Multitask in Java
Multithreaded program Threads A multithreaded program can start and execute several parts of its code in the same time A thread is a single sequential flow of control within a program R. Grin Java : threads
Multithreading in Java
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park Problem Multiple tasks for computer Draw & display images on screen Check keyboard
Robotics and Autonomous Systems
Robotics and Autonomous Systems Lecture 10: Threads and Multitasking Robots Simon Parsons Department of Computer Science University of Liverpool 1 / 38 Today Some more programming techniques that OUTLINE Basic concepts Processes Threads Java: Thread
CDP Threads in Java
CDP 2013 Threads in Java 1 Threads: reminder Basic sequential unit of execution. Multiple threads run in the context of single process: all threads within a process share common memory space (but not their
Threads, Part II. Thread Synchronisa3on CS3524 Distributed Systems Lecture 05
Threads, Part II Thread Synchronisa3on CS3524 Distributed Systems Lecture 05 Threads Mul3-threaded execu3on is an essen3al feature of Java A thread is a single sequen3al flow of control within a program
Thread states. Java threads: synchronization. Thread states (cont.)
Thread states Java threads: synchronization 1. New: created with the new operator (not yet started) 2. Runnable: either running or ready to run 3. Blocked: deactivated to wait for something 4. Dead: has
OBJECT ORIENTED PROGRAMMING LANGUAGE
UNIT-6 (MULTI THREADING) Multi Threading: Java Language Classes The java.lang package contains the collection of base types (language types) that are always imported into any given compilation unit. This
Introduction to Java Threads
Object-Oriented Programming Introduction to Java Threads 4003-243 1 What is a Process? Here s what happens when you run this Java program and launch 3 instances while monitoring with top On a single CPU
Crash Course in Java
Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is
JAVA - MULTITHREADING
JAVA - MULTITHREADING Copyright tutorialspoint.com Java is amulti threaded programming language which means we can develop multi threaded program
Monitors & Condition Synchronization
INF2140 Modeling and programming parallel systems Lecture 5 Feb. 13, 2013 Plan for Today: Concepts Monitors: encapsulated data + access procedures Mutual exclusion + condition synchronization Single access
Topics. What is a thread? Thread states Thread priorities Thread class Two ways of creating Java threads
Java Threads 1 Topics What is a thread? Thread states Thread priorities Thread class Two ways of creating Java threads Extending Thread class Implementing Runnable interface ThreadGroup Synchronization
Monitors, Java, Threads and Processes
Monitors, Java, Threads and Processes 185 An object-oriented view of shared memory A semaphore can be seen as a shared object accessible through two methods: wait and signal. The idea behind the concept
Synchronization Possibilities and Features in Java
Abstract Synchronization Possibilities and Features in Java Beqir Hamidi Lindita Hamidi ILIRIA College Bregu i Diellit, st. Gazmend Zajmi, no. 75 p.n., 10 000 Prishtine-Kosove -Prishtine beqirhamidi@hotmail.com,
Synchronization in Java
Synchronization in Java We often want threads to co-operate, typically in how they access shared data structures. Since thread execution is asynchronous, the details of how threads interact can be unpredictable.
Java Memory Model: Content
Java Memory Model: Content Memory Models Double Checked Locking Problem Java Memory Model: Happens Before Relation Volatile: in depth 16 March 2012 1 Java Memory Model JMM specifies guarantees given by
To start the new thread running you simply execute:
Java: Threads and Monitors Java supports concurrency via threads. These threads are lightweight processes and they synchronise via monitors. Threads A Java thread is a lightweight process that has its
Structuring the Control
Structuring the Control Hints on control-in-the-small Essential elements of control-in-the-large (parallel execution) Ghezzi&Jazayeri: Ch 4 1 Control in-the-small From if-then-else, while, case, for,...
CS11 Java. Fall 2014-2015 Lecture 7
CS11 Java Fall 2014-2015 Lecture 7 Today s Topics! All about Java Threads! Some Lab 7 tips Java Threading Recap! A program can use multiple threads to do several things at once " A thread can have local
Tutorial: Getting Started
9 Tutorial: Getting Started INFRASTRUCTURE A MAKEFILE PLAIN HELLO WORLD APERIODIC HELLO WORLD PERIODIC HELLO WORLD WATCH THOSE REAL-TIME PRIORITIES THEY ARE SERIOUS SUMMARY Getting started with a new platform
Intro to Programming in Java Practice Midterm
600.107 Intro to Programming in Java Practice Midterm This test is closed book/notes. SHORT ANSWER SECTION [18 points total] 1) TRUE/FALSE - Please circle your choice: Tr for true, Fa for false. [1 point
Java and Concurrency. CIT Concurrency
Java and Concurrency What do we need for concurrency? Process creation How do you specify concurrent processes? Communication How do processes exchange information? Synchronization How do processes maintain
Java Threads and Synchronization. Overview
Java Threads and Synchronization Overview The Class Thread Several ways to create threads. Using the class Thread Using the interface Runnable Runnable is more complex, but also more flexible (sometimes
Parallel programming in Java. Alexey A. Romanenko
Parallel programming in Java Alexey A. Romanenko arom@ccfit.nsu.ru arom@u-aizu.ac.jp Threads Threads use and exist within the process resources, yet are able to be scheduled by the operating system and
Building a Multi-Threaded Web Server
Building a Multi-Threaded Web Server In this lab we will develop a Web server in two steps. In the end, you will have built a multi-threaded Web server that is capable of processing multiple simultaneous 11 java track: lecture 4
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks arrays (1) array: linear sequence of values arrays are real objects in java have one public field:
Object Oriented Design with UML and Java PART XII: Threads
Object Oriented Design with UML and Java PART XII: Threads Copyright David Leberknight and Ron LeMaster Version 2011 Java Threads A Thread is an execution process. Only one thread at a time may be running
Chapter 8 Implementing FSP Models in Java
Chapter 8 Implementing FSP Models in Java 1 8.1.1: The Carpark Model A controller is required for a carpark, which only permits cars to enter when the carpark is not full and does not permit cars to leave
Advanced Java Programming. Agenda. Multi-Threaded Programming. Threads. Shmulik London
Advanced Java Programming Shmulik London Lecture #7 Threads Advanced Java Programming / Shmulik London 2006 Interdisciplinary Center Herzeliza Israel 1 Agenda Threads Scheduling Critical Sections Deadlocks
Synchronization of Java Threads
Synchronization of Java Threads The previous examples shows independent, asynchronous threads 1. each thread has all the data and methods it needs 2. threads run at their own pace, without concern for
Synchronization and Coordination between Threads
Synchronization and Coordination between Threads Part I Producer/consumer problems: Synchronization and coordination in between threads Synchronization and Coordination of Threads In the last class, we
Lecture 4: Synchronization Primitives
Lecture 4: Synchronization Primitives CS178: Programming Parallel and Distributed Systems February 5, 2001 Steven P. Reiss I. Overview A. Topics covered last time 1. Different types of synchronization
C340 Concurrency: Semaphores and Monitors. Wolfgang Emmerich Mark Levene
C340 Concurrency: Semaphores and Monitors Wolfgang Emmerich Mark Levene 1 Revised Lecture Plan 1 Introduction 2 Modelling Processes 3 Modelling Concurrency in FSP 4 FSP Tutorial 5 LTSA Lab 6 Programming
public sealed class Thread { public static void Sleep(int milliseconds) {...}... public Thread(ThreadStart startmethod) {...}
Threads 1 Types (excerpt) public sealed class Thread { public static Thread CurrentThread { get; public static void Sleep(int milliseconds) {...... public Thread(ThreadStart startmethod) {... // static
Monitoring of Tritium release at PTC.
Monitoring of Tritium release at PTC. Scope of the project From more than 20 projects supported by Equipment Manufacturing Support group this is one of the simplest. What is nice about it is that elegant
Deadlock Victim. dimanche 6 mai 12
Deadlock Victim by Dr Heinz Kabutz && Olivier Croisier The Java Specialists Newsletter && The Coder's Breakfast heinz@javaspecialists.eu && olivier.croisier@zenika.com 1 You discover a race condition 2
Monitors & Condition Synchronisation
Chapter 5 Monitors & Condition Synchronisation controller 1 Monitors & Condition Synchronisation Concepts: monitors (and controllers): encapsulated data + access procedures + mutual exclusion + condition
Multithreading in Java. What Are Threads? Thread Properties Thread Priorities Cooperating and Selfish Threads Synchronization
Multithreading in Java What Are Threads? Thread Properties Thread Priorities Cooperating and Selfish Threads Synchronization The Concept of Process A process represents a sequence of actions (statements),
SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I)
SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics
Selenium Online Course - Smart Mind Online Training, Hyderabad. Selenium Online Training Course Content
Selenium Online Training Course Content Faculty: Real time and certified (Includes theoretical as well as practical sessions) Introduction to Automation What is automation testing Advantages of Automation
Part I:( Time: 90 minutes, 30 Points)
Qassim University Deanship of Educational Services Preparatory Year Program- Computer Science Unit Final Exam - 1434/1435 CSC111 Time: 2 Hours + 10 Minutes 1 MG Student name: Select the correct choice:
Java Memory Management
Java Memory Management 1 Tracing program execution Trace: To follow the course or trail of. When you need to find and fix a bug or have to understand a tricky piece of code that your coworker wrote, you
EPITA Première Année Cycle Ingénieur. Atelier Java - J4
EPITA Première Année Cycle Ingénieur marwan.burelle@lse.epita.fr Overview 1 Subclass of Thread Implementing Runnable 2 3 Using Sockets Using URL Subclass of Thread Implementing
J a v a Quiz (Unit 3, Test 0 Practice)
Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points
Class 305 Focus On Threads: An Introduction Michel de Champlain ABSTRACT
Class 305 Focus On Threads: An Introduction Michel de Champlain ABSTRACT Threads are now supported by many new object-oriented languages. Java provides language-level support for multi-threading, resulting
Java Interview Questions and Answers
1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java.
Mutual Exclusion using Monitors
Mutual Exclusion using Monitors Some programming languages, such as Concurrent Pascal, Modula-2 and Java provide mutual exclusion facilities called monitors. They are similar to modules in languages that
Objective. Assumptions. Procedure
Installing Java programming tools on Mac OS 10.8 (Mountain Lion) Objective This document will guide you through installing and configuring the necessary software to write Java programs on your Mac computer.
Lecture 6: Introduction to Monitors and Semaphores
Concurrent Programming 19530-V (WS01) Lecture 6: Introduction to Monitors and Semaphores Dr. Richard S. Hall rickhall@inf.fu-berlin.de Concurrent programming November 27, 2001 Abstracting Locking Details
The Snake Game Java Case Study
The Snake Game Java Case Study John Latham January 27, 2014 Contents 1 Introduction 2 2 Learning outcomes 2 3 Description of the game 2 4 The classes of the program 4 5 The laboratory exercise and optional
3C03 Concurrency: Condition Synchronisation
3C03 Concurrency: Condition Synchronisation Mark Handley 1 Goals n Introduce concepts of Condition synchronisation Fairness Starvation n Modelling: Relationship between guarded actions and condition synchronisation?
Multiple Choice Questions (20 points)
CSC142 Midterm 1 1 Multiple Choice Questions (20 points) Answer all of the following questions. READ EACH QUESTION CAREFULLY. Fill the correct bubble on your scantron sheet. Each correct answer is worth
Correct and Efficient Synchronization of Java Technologybased
Correct and Efficient Synchronization of Java Technologybased Threads Doug Lea and William Pugh 1 Audience Assume you are familiar with basics of Java
ROBOTICS AND AUTONOMOUS SYSTEMS
ROBOTICS AND AUTONOMOUS SYSTEMS Simon Parsons Department of Computer Science University of Liverpool LECTURE 3 PROGRAMMING ROBOTS comp329-2013-parsons-lect03 2/50 Today Before the labs start on Monday,
CISC 213- Practice Test 2
CISC 213- Practice Test 2 Part A- The following questions are multiple choice or short answer: 1. Say we define a class called ABC and we don't define any constructor. Then which of the following is true:
Part I. Multiple Choice Questions (2 points each):
Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******
Term Project: Roulette
Term Project: Roulette DCY Student January 13, 2006 1. Introduction The roulette is a popular gambling game found in all major casinos. In contrast to many other gambling games such as black jack, poker,
OPERATING SYSTEMS. IIIT-Hyderabad
OPERATING SYSTEMS IIIT-Hyderabad OVERVIEW Introduction What is an OS/Kernel? Bootstrap program Interrupts and exceptions Volatile and Non volatile storage!!! Process Management What is a process/system
CMSC 433 Section 0101 Fall 2012 Midterm Exam #2
Name: CMSC 433 Section 0101 Fall 2012 Midterm Exam #2 Directions: Test is closed book, closed notes, no electronics. Answer every question; write solutions in spaces provided. Use backs of pages for scratch
CS 111 Classes I 1. Software Organization View to this point:
CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects
Chapter 6 Concurrent Programming
Chapter 6 Concurrent Programming Outline 6.1 Introduction 6.2 Monitors 6.2.1 Condition Variables 6.2.2 Simple Resource Allocation with Monitors 6.2.3 Monitor Example: Circular Buffer 6.2.4 Monitor Example:
Parallel Programming
Parallel Programming 0024 Recitation Week 7 Spring Semester 2010 R 7 :: 1 0024 Spring 2010 Today s program Assignment 6 Review of semaphores Semaphores Semaphoren and (Java) monitors Semaphore implementation
Build your own Java library
Build your own Java library Presented by developerworks, your source for great tutorials Table of Contents If you're viewing this document online, you can click any of the topics below to link directly
Introduction to Java
Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high
Simple Cooperative Scheduler for Arduino ARM & AVR. Aka «SCoop»
Simple Cooperative Scheduler for Arduino ARM & AVR Aka «SCoop» Introduction Yet another library This library aims to provide a light and simple environment for creating powerful multi-threaded programs
Comprehensive support for general-purpose concurrent programming; partitioned into three packages:
Java 1.5 Concurrency Utilities Comprehensive support for general-purpose concurrent programming; partitioned into three packages: java.util.concurrent support common concurrent programming paradigms, e.g.,
Object Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction
Lecture 6: Semaphores and Monitors
HW 2 Due Tuesday 10/18 Lecture 6: Semaphores and Monitors CSE 120: Principles of Operating Systems Alex C. Snoeren Higher-Level Synchronization We looked at using locks to provide mutual exclusion Locks
Using Two-Dimensional Arrays
Using Two-Dimensional Arrays Great news! What used to be the old one-floor Java Motel has just been renovated! The new, five-floor Java Hotel features a free continental breakfast and, at absolutely no
Java Review (Essentials of Java for Hadoop)
Java Review (Essentials of Java for Hadoop) Have You Joined Our LinkedIn Group? What is Java? Java JRE - Java is not just a programming language but it is a complete platform for object oriented programming.
Fundamentals of Java Programming
Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors
|
http://docplayer.net/220516-Threads-1-when-writing-games-you-need-to-do-more-than-one-thing-at-once.html
|
CC-MAIN-2018-17
|
refinedweb
| 5,242
| 53.71
|
An application that uses SDL_ttf to draw some basic text on a drawing buffer for the LCD. It demonstrates some very basic text rasterisation using SDL_ttf./lcd
root:/> export SDL_NOMOUSE=1
Note: You only need to do this once per uClinux boot. If you want your program to make use of the touch screen, do not run this environment variable and instead run the commands found in the touchscreen demos.
root:/> ./text Loading... Done! Drawing text... Displayed. Interrupt to exit.
#include <stdio.h> #include <stdlib.h> // Necessary Font Libraries #include <SDL_ttf.h>
As you can see, this program only grabs SDL_ttf.h really for the low level text API. It doesn't explicitly grab SDL.h as that will be done by SDL_ttf.
int main(int argc, char* argv[]) { int screen_width = 480; int screen_height = 272; int screen_bitdepth = 24; SDL_Surface *screen; SDL_Event input_event; char tuffy_font[100] = "Tuffy.ttf"; int font_size = 28; int running = 0;. The tuffy_font string just points to the font file to use (Tuffy is provided with this demo).
if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Error: Unable to init SDL: %s\n", SDL_GetError()); exit(1); } atexit(SDL_Quit); screen = SDL_SetVideoMode(width, height, depth, SDL_DOUBLEBUF); if (screen == NULL) { fprintf(stderr, "Error: Unable to grab screen\n"); SDL_Quit(); exit.
if(TTF_Init() == -1) { fprintf(stderr, "Error: Unable to init TTF: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } text_font = TTF_OpenFont(tuffy_font, font_size); if(text_font == NULL) { fprintf(stderr, "Error: Unable to open font file!\n"); SDL_Quit(); exit(1); } printf("Done!\n");
This section of code will initialise the font subsystem. This is for intiiating SDL_ttf and getting it ready for use. It also opens the Tuffy font file and loads it as the true type font for drawing, and aborts the program if the font file cannot be opened.
printf("Drawing shapes... \n"); // Draw white background SDL_Rect rect0 = {0,0,480,272}; SDL_FillRect(screen, &rect0, 0xFFFFFF); // Drawing text SDL_Color color = {0, 0, 0}; SDL_Surface *text_surface = TTF_RenderText_Solid(text_font, "Hello World!", color); SDL_BlitSurface(text_surface, NULL, screen, NULL); SDL_FreeSurface(text_surface); // display surface on LCD SDL_Flip(screen); printf("Displayed. Interrupt to exit.\n");
This section merely draws a white rectangle to the screen, then draws the string “Hello World!” on top of it of varying colours. You can see that the color provided is an SDL_Color struct, which is an RGB colour. It blits this text surface to the screen surface, and then displays it on the LCD.
SDL_ttf has many low level drawing functions and you can learn more about them on the official SDL_ttf documentation at
memset(&input_event, 0, sizeof(input_event)); while (running == 0) { if (SDL_PollEvent(&input_event)) { if (input_event.type == SDL_QUIT) { running = 1; } } }
This section is common in all SDL programs and it is a loop that will continuously check for any program input. This one is looking for an SDL_Quit call (from program termination) to perform an exit.
TTF_Quit();_ttf \ text.c -o text_ttf is loaded. Without this library, our program would not have access to the required font rendering functions.
The final parameters match up to standard gcc compiling; “text.c” is the source file while ”-o text” indicates the output file is “text”.
A standard make file is accompanies this demo and you can run that by simply calling
root:/> make text
SDL_ttf is a popular SDL true type font rendering api, and its documentation is located at
The LCD on the BF548 EZ-KIT is a 24bit lcd (8bit blue, 8bit green, 8bit red). This means some programs hard coded for the frame buffer do not work, for example pngview. If you run pngview and it appears wonky on the BF548 that is because it was made for the BF537 and a 16bit LCD. Since it does not write enough data to fill a pixel and will encode for rgb and not bgr, it will be interpreted wrongly, so be aware of this when working with programs that write directly to the frame buffer.
If the colour on the LCD screen appears wonky, this may be due to the LCD screen settings defined by SW17. These switches can set the bitrate of the LCD and if set differently than to what the program expecs will lead to a bit of mayham. Check the development environment page of this guide to make sure it is set to the default 24bit.
Information on the LCD driver for the BF548 EZ-KIT can be found here Linux framebuffer driver for ADSP-BF54x
|
https://docs.blackfin.uclinux.org/doku.php?id=quick-start:bf548-ezkit:demos:text
|
CC-MAIN-2019-13
|
refinedweb
| 735
| 71.85
|
Aurelia Update with Decorators, IE9 and More
Today's release finally brings full ES7 and TypeScript decorators, IE9 support and a new, simplified HTML Behavior programming model. We've also made a few performance enhancements along the way.
Decorators
With the release of Babel 5.0 and the TypeScript 1.5 Alpha, we now have support for ES 2016 Decorators in the major compilers. To accompany these releases, we have now enabled full support for decorators in Aurelia. We've also done some renaming in our fallback mechanisms to account for this terminology (see "Fallbacks" below).
As of this release, if you are using Babel 5.0 or TypeScript 1.5, you can now optionally use a decorator to control dependency injection. Here's what it looks like:
import {inject} from 'aurelia-framework'; import {HttpClient} from 'aurelia-http-client'; @inject(HttpClient) export class Flickr{ constructor(http){ this.http = http; } }
With decorators, there's no need for special static properties or callbacks on your class anymore. You can use this new language feature today. We've also updated the navigation skeleton to take advantage of it.
It's also worth noting that for dependency injection, you can still use the static
inject property/method in place of the decorator as well. It's up to you. In fact, that's all the decorator does. Here's the
inject decorator implementation, in case you are curious how that works:
export function inject(...rest){ return function(target){ target.inject = rest; } }
HTML Behaviors
While we were working on Decorators, we wanted to take the time to update the HTML Behaviors design. If you aren't familiar with this, HTML Behaviors are ways in which your JavaScript code can plug into the HTML compiler.
As of this release, there are two core types of HTML Behaviors: Custom Element and Custom Attribute. These ideas are based on core DOM primitives so hopefully they just "make sense".
Custom Elements
As always, you can use export conventions to identify these:
export class NavBarCustomElement {}
This creates a custom element named
<nav-bar></nav-bar>. If no naming pattern is matched, then it will default to a custom element. So, the export could also be called
NavBar.
Don't want to use conventions? No problem. You can always use decorators:
import {customElement} from 'aurelia-framework'; @customElement('nav-bar') export class NavBar {}
Custom Elements also have a number of other options. Here's a fun example to show a few things off:
@useShadowDOM export class Expander { @bindable isExpanded = false; @bindable header; ... }
This behavior shows how to indicate that the element's view is rendered in the Shadow DOM. It also shows how to create two properties which will be settable/bindable on the
<expander> element in HTML. In this case we are using the
bindable decorator with the new ES7 property initializer syntax. Property initializers are available in TypeScript and in Babel, with the "es7.classProperties" option. If you don't want to use initializers, you can also specify them on the class like this:
@useShadowDOM @bindable('isExpanded') @bindable('header') export class Expander { ... }
There are other options as well. Here's a summary of other decorators you may want to use on your custom elements:
@syncChildren(property, changeHandler, selector)- Creates an array property on your class that has its items automatically synchronized based on a query selector against its view.
@skipContentProcessing- Tells the compiler not to process the content of your custom element. It is expected that you will do custom processing yourself.
@useView(path)- Specifies a different view to use.
@noView- Indicates that this custom element does not have a view and that the author intends to handle its own rendering internally.
Custom Attributes
What about custom attributes? You can follow the convention:
export class ShowCustomAttribute { valueChanged(newValue, oldValue){ ... } }
Now you can just put a
show attribute on any HTML element to use it. If you'd rather be explicit with decorators:
import {customAttribute} from 'aurelia-framework'; @customAttribute('show') export class Show { valueChanged(newValue, oldValue){ ... } }
Note that in both cases, your attribute maps to a
value property on the class and you can be notified when it changes by implementing a
valueChanged method. If you want to map a single attribute to more than one property, you can simply create
bindable properties on the attribute itself and then use the options syntax in HTML. There are also some special options for custom attributes:
@templateController- Allows a custom attribute to turn the attributed HTML into an HTMLTemplate which it can then generate on the fly. This is how behaviors like
ifand
repeatcan be created.
@dynamicOptions- This allows a custom attribute to have a dynamic set of properties which are all mapped from the options attribute syntax into the class at runtime.
Note: With the move to decorators, you may have noticed that we renamed
withProperty to
bindable. We have also changed the signature. If all you need to do is provide the name, you can provide it like so
@bindable('someProperty') but if you need to specify more details, you should pass an options object like this:
@bindable({ name:'myProperty', //name of the property on the class attribute:'my-property', //name of the attribute in HTML changeHandler:'myPropertyChanged', //name of the method to invoke on property changes defaultBindingMode: ONE_WAY, //default binding mode used with the .bind command defaultValue: undefined //default value of the property, if not bound or set in HTML })
The defaults and conventions are shown above. So, you would only need to specify these options if you need to deviate.
Behaviors Summary
HTML Behaviors are powerful. Most of the time you can create them by following a simple naming convention and then adding some
@bindable decorators, but you can do much more. By combining ES7 Decorators and Property Initializers you can have a clean, standards-based way of defining advanced behaviors for any scenario.
IE9
We now have support for IE9! In order to get Aurelia to run in legacy browsers like IE9 and Safari 5.1 you need to polyfill MutationObservers and WeakMap. This can be achieved by a jspm install of
github:webreflection/es6-collections and
github:polymer/mutationobservers. Load these two scripts before system.js.
In Skeleton Navigation index.html will look like this:
<script src="jspm_packages/github/webreflection/es6-collections@master/es6-collections.js"></script> <script src="jspm_packages/github/polymer/mutationobservers@0.4.2/MutationObserver.js"></script> <script src="jspm_packages/system.js"></script> <script src="config.js"></script> <script> System.import('aurelia-bootstrapper'); </script>
It should be noted that WeakMap is not required by Aurelia itself but it is used by the MutationObserver polyfill. So, with this configuration, you should be able to get things working with IE9 today. We are looking into making this even smoother and there still may be a few random issues. If IE9 support is important to you, please try this out and provide us with some feedback.
Performance
This isn't primarily a performance release. However, I wanted to mention that Core Team Member Martin Gustafsson has done some optimization work on our repeater which gives it up to a 200x performance boost in certain scenarios. I've also done work to optimize our internal metadata read/write system and we are moving steadily torward getting our benchmarking infrastructure in place so we can make the big optimizations in the binding system. Stay tuned...
Other Goodies
We had tons of bug fixes naturally and we've continued to improve the binding engine as well, with support for more scenarios, but without adding any additional syntax or complexity. With the addition of decorators, we can now make it easy for computed properties to avoid dirty checking (only done for computeds anyways) by specifying their dependencies. Here's an example of how to do that:
import {computedFrom} from 'aurelia-framework'; export class Welcome{ firstName = 'John'; lastName = 'Doe'; @computedFrom('firstName', 'lastName') get fullName(){ return `${this.firstName} ${this.lastName}`; } }
Also, now that Babel and TypeScript have matured significantly, we see no more need to consider AtScript as a viable language for building apps. This release removes all support for AtScript.
Fallbacks
In this post we've been showing a lot of ways to leverage ES7 (ES 2016) features such as Decorators and Property Initializers with the new update. If you aren't using a compiler that supports these, don't worry. We still have a fallback mechanism that you can use. Take note though, we have removed the
metadata static member and replaced it with a
decorators static callback. We also have a
Decorators helper to use in place of the
Metadata helper. Here's what our first example from above would look like in ES5 with CommonJS using this fallback mechanism.
var Decorators = require('aurelia-framework').Decorators; var HttpClient = require('aurelia-http-client').HttpClient; function Flickr(http){ this.http = http; } Flickr.decorators = Decorators.inject(HttpClient); exports.Flickr = Flickr;
The
Decorators helper has methods that match every decorator in Aurelia, except
computedFor. The names and casing are identical. The helper methods are chain-able, so you can easily compose them like this:
Foo.decorators = Decorators.customElement('my-element') .bindable('someProperty') .inject(Element);
In fact there's nothing stopping you from using this in your ES7 code if you prefer it (though we think that decorators are superior for almost all cases).
How to Update
Clearly the new Decorators and HTML Behaviors design are breaking changes. The information above should get you through making the updates in your code, but I want to share here how to update your tooling and Aurelia itself.
First, you need to update the Babel compiler to 5.x. You can use the following commands to update your gulp tasks as well as your testing infrastructure:
sudo npm install --save-dev gulp-babel sudo npm install --save-dev karma-babel-preprocessor sudo npm install --save-dev karma-jspm
You will also need to update your compiler options. Here are the options we are now using in the Navigation Skeleton, located at
build/babel-options.js:
module.exports = { modules: 'system', moduleIds: false, comments: false, compact: false, stage:2, optional: [ "es7.decorators", "es7.classProperties" ] };
Make sure you also update the babel options in your
karma.conf.js file. If you are using TypeScript instead of Babel, you will need to move to using version 1.5 if you want to take advantage of decorators.
Next, you want to update Aurelia. Because these are breaking changes,.
Next Steps
This release also includes some work on the router, route recognition and route generation, thanks to the work of community member Bryan Smith. The next release will yield a couple of breaking changes related to fixing the final issues with the router and making it easier and more capable in all scenarios.
As I mentioned, we are gearing up for big performance work too and we've got a couple of demoes we're putting together to spotlight that which I know you will find interesting. Hang in there :) I think you're going to like it.
Note: There are lots of updates in this release. At the moment, our site's docs are out of sync with these changes. We wanted to get this release out to you as soon as we could, so please be patient while we update the docs over the next day or so.
Upcoming Presentations
Interested in getting a walkthrough of building your first Aurelia app? I've got good news for you. I'll be in Montreal on Monday April 13, 2015<<
|
http://blog.aurelia.io/2015/04/09/aurelia-update-with-decorators-ie9-and-more/
|
CC-MAIN-2017-09
|
refinedweb
| 1,915
| 55.84
|
You are not logged in.
Pages: 1
Good morning and thanks in advance for your time and help.
We're trying to develop an application that will let a handheld scanner (HH) to connect to a Windows server. Every now and then, the device gets a time out trying to get a response from the server. The HH has a time limit of 7 seconds.
I'm going to try to explain what the process is:
1. User presses the enter key to send the request for log in. This connection process goes HH <-> Access point <-> App Server
2. Once the server received the request, it tries to get the device Id and assigns it a session.
3. At the same time, the app builds the screen and sends it back to the HH.
4. HH displays screen.
We noticed that the problem seems to be in number 2. On the log file, we see the device id and right after that, takes an average of 10 secs to build the screen. Our guess is that the problem is here.
Thanks again for your help.
This is the source code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
using System.IO;
...
void RFOPEN(ref int iPTCNo, ref int iPTCType);
...
public void RFOPEN(ref int iPTCNo, ref int iPTCType)
{
//LogForDebugPurpose("RFOPEN");
SocketClient sockClient = SocketClient.GetClientInstance();
sockClient.SendDataToDevice("INFO", "", "PTC ID");
while (WhetherToLoopAgain) //WhetherToLoopAgain = true
{
if (SocketClient.DataRecieved != "")
{ WhetherToLoopAgain = false; }
Thread.Sleep(100);
}
string st = SocketClient.DataRecieved;
WhetherToLoopAgain = true;
RFCommands.LogForDebugPurpose("DIv id:" + st + " RFOPEN");
SocketClient.DataRecieved = "";
iPTCNo = Int32.Parse(st);
//Need to send PTC no and PTC Type to Process Manager
}
(Moved this to the C++ forum instead of the bugs one, which is for forum bugs.)
Try removing that Sleep(100), in general you never want to do anything like
that. If you need it to "work" then you probably have a bug somewhere.
That WhetherToLoopAgain = true; looks dodgy as well, you just set it to
false a moment before. So either you shouldn't set it to false there, or you
shouldn't set it to true here. Or I'm missing something.
If that WhetherToLoopAgain is meant to handle short reads, it's not doing
it correctly, as new data isn't appended to st but replaces it. That st part
should probably be out of the WhetherToLoopAgain loop and do
st += SocketClient.DataRecieved.
But 10 seconds to build the screen seems awfully lot, is that after receiving a
scanned image and you're sending it back or something?! It's a bit unclear
what exactly happens here.
Pages: 1
|
https://developerweb.net/viewtopic.php?id=5780
|
CC-MAIN-2021-21
|
refinedweb
| 446
| 69.48
|
On 2008 Sep 24, at 22:51, Daryoush Mehrtash wrote: > I am having hard time making sense of the types in the following > example from the Applicative Programming paper: > > ap :: Monad m ⇒ m (a → b ) → m a → m b > ap mf mx = do > f ← mf > x ← mx > return (f x ) > Using this function we could rewrite sequence as: > > sequence :: [ IO a ] → IO [ a ] > sequence [ ] = return [ ] > sequence (c : cs ) = return (:) 'ap' c 'ap' sequence cs > > > I am specifically confused over the type of "m" in: > > return (:) 'ap' c > > "c" is obviously an instance of IO a monad. "return (:)" on the > other hand (at least as I would expect it) is an instance of " ->" > monad. Note that he first argument to ap is a function wrapped by a monad. "return (:)" wraps the function/operator (:) in an arbitrary monad (but then the type signature of sequence makes the monad IO). (:) :: a -> [a] -> [a] return (:) :: IO (a -> ([a] -> [a])) -- b is ([a] -> [a]) ap (return (:)) :: IO a -> IO ([a] -> [a]) -- (IO a) is (m a) and (IO ([a] -> [a])) is (m b) return (:) `ap` c :: IO ([a] -> [a]) -- c is (IO a) per type signature return (:) `ap` c `ap` :: IO [a] -> IO [a] -- f in ap is the preceding IO ([a] -> [a]) return (:) `ap` c `ap` sequence cs :: IO [a] -- (sequence cs) is (IO [a]) per type:
|
http://www.haskell.org/pipermail/haskell-cafe/2008-September/048077.html
|
CC-MAIN-2014-41
|
refinedweb
| 223
| 51.99
|
POPEN(3) BSD Programmer's Manual POPEN(3)
popen, pclose - process I/O
#include <stdio.h> FILE * popen(const char *command, const char *type); int pclose(FILE *stream);
The popen() function "opens" a process by creating a pipe, forking, and invoking the shell. Since a pipe is by definition unidirectional, the type argument may specify only reading or writing, not both; the result- ing stream is correspondingly read-only or write-only. The command argument is a pointer to), stdio(3), system(3)
A popen() and a pclose() function appeared in Version 7 AT&T UNIX.
Since the standard input of a command opened for reading shares its seek offset with the process that called popen(), if the original process has done a buffered read, the command's input position may not be as expect- ed.. The popen() argument always calls sh(1)..
|
https://www.mirbsd.org/htman/sparc/man3/popen.htm
|
CC-MAIN-2016-07
|
refinedweb
| 143
| 58.11
|
Full Stack BDD in Xcode With Page Object Model: Part II
Full Stack BDD in Xcode With Page Object Model: Part II
Here is Part II, outlining how to set up 'XCUI POM Test Bundle' target, the 'Acceptance Test' target, and more!
Join the DZone community and get the full member experience.Join For Free
Did you miss out on Part I? Don't wait, read it now!
Set Up ‘XCUI POM Test Bundle’ Target
- From Xcode, create a new app(Or use existing app) and select File —> New —-> Target
- Now Select ‘XCFit’ for iOS app and Click on ‘XCUI POM Test Bundle’
- Once Clicked on the target e.g ‘XCUI POM Test Bundle’ Xcode will create UI testing target with properly structured Xcode Groups and required files. You can then make physical directories on Disk Or change the folder/group structure as per your need.
- You don’t have to so any setting to run those demo XCUI tests. Just CMD+U and You are good to go!
What’s in the XCUI POM Template ?
- YOUR_CUCUMBERISH_TARGETPageObjectTests.swift
- This file is at the base of the target. It’s exactly same file that Apple’s XCUI Test generate at first. You may use it for recording the tests or simply delete it if not needed.
- Screens
- This is groups where we can abstract logic of every screen in the app. Example file are ‘HomeScreen.swift’ and ‘BaseScreen.swift’ This assumes that your apps is made up of multiple screens. You can write individual screen class which extend BaseScreen. All the functionality related to screen can be included in this class.
- Sections
- This group has ‘HomeElements.swift’ class which stores all the locators of HomeScreen in enums. Sections are defined to store locators of the screen in the form of enums. Here are some samples we can store Images, Buttons and Static Texts of the HomeScreens. We can access those enums from anywhere from the Test methods or page objects.
- Protocols
- Swift is protocol oriented language so feel to start with Protocol per screen. This group has ‘HomeProtocol.swift’ file where there is a way to implement protocol oriented testing. Here is an example of sample protocol for the home screen. We can implement this protocol in the XCTest method as needed or we can write some extensions to support Testing.
- Tests
- This group has all the test for our app. Currently demo template has two tests ‘HomeScreenTest.swift’ and ‘ProtocolOrientedTest.swift’. This example shows how XCUI test can be implemented in the Object Oriented way and Protocol oriented way.
- TestBase
- Testbase is a group where we can abstract all set up, tear down and common stuff in the base class. Every screen then uses this class as base. You can add more stuff as needed e.g Fixtures, Launch Arguments.
FitNesse for iOS: Acceptance/Contract Tests
FitNesse is a fully integrated standalone wiki and acceptance testing framework for BDD Style testing. As of now, we have seen Cucumber and Page Object pattern test frameworks. If you really wanted to get more information about FitNesse for iOS, please follow documentation on OCSlim project. XCFit adopted the framework as dependency to make it full stack BDD. We will cover basic setup as part of this document.
Setup ‘Acceptance Test’ Target template
- From Xcode, create a new app(Or use existing app) and select File —> New —-> Target
- Now Select ‘XCFit’ for iOS app and Click on ‘iOS Acceptance Tests ‘
- Once Clicked on the target e.g ‘OS Acceptance Tests’ Xcode will create new target with all required files and groups for Acceptance testing
- Select ‘Acceptance Test’ Scheme from Xcode and try to build
- The build will fail as we need to fix some Swift3 related issue as well as we need to add XCFit/OCSlimProject Pod to the to the podfile.
** Watch it so far**
- To Fix Swift Issue : Just Click on ‘Edit-> Convert-> To Current Swift Syntax
- To Fix Pod issue : Add ‘XCFit’ for AcceptanceTests target
target 'AcceptanceTests' do pod 'OCSlimProject' end
$ pod install
You can install Pod by running ‘pod install’
Now, You should be able to build ‘Acceptance Tests” target.
You should also note that the script ‘Launch FitNesse’ has been created in the base of the project. Launch the fitness by executing that script from command line:
$ sh Launch Fitnesse
The browser will pop up with example test. You should be able to execute.
Setting up Fitnesse Acceptance Target with XCTest
You can also setup Fitnesse Acceptance Tests but you need to use Cocoapods for this target.
You can find detailed blog post on DZone.
Add Acceptance and Acceptance Unit Test Target to Project.
Add Pod Dependencies
We need to create a “Podfile” at the root of the project with the following content.
target 'AcceptanceUnitTests' do pod 'OCSlimProjectTestBundleSupport' end
$ pod install
Now, we can run ‘pod install’ at this stage and close the current Xcode session and open project workspace.
Build Acceptance Tests Target.
Test AcceptanceUnitTests Target.
Continuous Integration + Fastlane
Now that , we have seen how to run Cucumberish, XCUIPOM, FitNesse acceptance tests from Xcode but it’s a good idea to run it with Fastlane. We can also take control of version of Cocoapods and Fastlane by using Bundler. Let’s create a Gemfile at the root of the project with the following gem:
source "" gem 'cocoapods' gem 'fastlane'
Let’s also create directory “fastlane” and make “Fastfile” with following content:
fastlane_version "1.104.0" default_platform :ios platform :ios do before_all do system "rm -rf ../test_reports/" system "bundle install" system "pod install" system "bundle exec fastlane add_plugin trainer" end desc "Runs all the XCUI POM, Cucumberish tests" lane :xcfit_ui_test do scan( scheme: "XCFit2Demo", destination: 'platform=iOS Simulator,name=iPhone 7 Plus,OS=10.0', output_directory: "test_reports/", output_types: "html", fail_build: false ) end desc "Runs Fitnesse Tests" lane :fitnesse do scan( scheme: "AcceptanceUnitTests", destination: 'platform=iOS Simulator,name=iPhone 7 Plus,OS=10.0', output_directory: "test_reports/", output_types: "html", fail_build: false ) end end
After running “bundle install” we should be able to run those test from command line like this:
$ bundle execfastlane xcfit_ui_test
Once that's done, we can have clear HTML reports generated.
XCFit: Swift Package Manager
XCFit will be having full on support for XCUI Test helpers so that we can use Apple’s XCUI Test Framework painless to use. There is sample swift package on Github to test XCFit Full Documentation and API implementation still in progress. You can grab it like this
import PackageDescription let package = Package( name: "XCFit", dependencies: [ .Package(url: "", majorVersion: 2), ] )
Quick Demo With Example App
You can clone the existing repo which has a demo app we can run Unit, FitNesse and Cucumberish tests as XCTest.
$ git clone $ cd XCFit/XCFit2Demo $ open XCFit2Demo.xcworkspace
Run Unit, FitNesse and Cucumberish test with Xcode. “cmd + U”. We can execute it using Fastlane
$ bundle install $ bundle exec fastlane xcfit_ui_test
Conclusion
With XCFit 2.o, we can get started with BDD within a minute using fully automated Xcode Templates using very popular Page Object Pattern. XCFit enables Full stack BDD in iOS. }}
|
https://dzone.com/articles/full-stack-bdd-in-xcode-with-page-object-model-par?fromrel=true
|
CC-MAIN-2020-34
|
refinedweb
| 1,175
| 63.8
|
Need some explanation of which dependencies need to be added to a deploymentMartin Ahrer Nov 21, 2013 2:22 PM
I have recently started looking at Arquillian an like the many abstractions for various containers. My past attempts for full blown integration testing mostly involved some clumsy solutions based on various Maven plugins.
So I have been able to get a simple REST service running with embedded Tomcat 7 and running a test against that REST service. Here is how my test roughly looks:
@RunWith(Arquillian.class)
public class TaskTest {
@ArquillianResource
private URL contextPath;
@Deployment(testable = false)
@OverProtocol("Servlet 3.0")
public static WebArchive create() {
return ShrinkWrap
.create(WebArchive.class)
//.addPackage(ControllerConfig.class.getPackage())
//.addPackage(Task.class.getPackage())
//.addPackage(PersistenceConfig.class.getPackage())
.addPackage(RestExporterWebApplicationInitializer.class.getPackage())
;
}
@Test
public void test() {
given().
expect().
statusCode(200).
when().
get(contextPath+"service/tasks");
}
}
This is based on Spring framework libraries that are set up in my IDEA (using Gradle). So when starting up my test in IDEA or Gradle, Arquillian nicely boots Tomcat, starts my web application. But nowhere I have ever set up ShrinkWrap to include any libraries (JARs). I only add the web initialiser (Servlet 3.0) and this makes it happen magically and the container has a class path fully setup.
However, reading though all the Arquillian documentation, my expectation was that I have to add every single class file, package, web resource, JAR file, etc. that needs to be deployed to the container. Just running my sample application kind of ruined that impression. So I must have missed something important. Where can I find an explanation, how the container class path will be set up effectively. What items really need to be deployed explicitly by ShrinkWrap?
Thanks
1. Re: Need some explanation of which dependencies need to be added to a deploymentKarel Piwko Nov 25, 2013 4:34 AM (in response to Martin Ahrer)
Hey Martin,
there are basically two different things:
Microdeployments define only what is really needed to run the test. The point is they are small and thus quickly deployable. You can think of testing a EJB, for instance, you need only to deploy interface and its implementation. Microdeployments are basically core for unit testing. Microdeployments are usually tested in container = the test runs in the JVM of application server inside of the application, which is default behavior.
Full deployments define the application as you would deploy it. There are used mainly for functional testing, where you need to package your application the same way as you would do manually. Full deployments are usually tested in as client mode, defined by @Deployment(testable=false) or by @RunAsClient annotation. Client mode means that server with app is different JVM than test itself. So REST and Selenium are the most logical testing means here.
So, the point is to figure out what you exactly need. There are the bits you should take in mind:
- if the classes you want to deploy depend on libraries, you need to add those libraries into deployment unless they are provided by application server. That's the reason why Servlet 3.0 works fine and Spring is not. See ShrinkWrap Resolvers how to do that
- if you want to test UI, you likely need to deploy content of src/main/webapp. You can use ShrinkWrap Resolver MavenImporter, ShrinkWrap ZipImporter or ExplodedImporter or an utility that recursively traverse that directory.
- If you are running in Server, make sure that you deploy all the classes referenced by test class as well. For instance Apache Commons or such. They won't be available on server after deployment. (Note: Arquillian autoadds testing - junit, hamcrest, etc)
HTH,
Karel
2. Re: Need some explanation of which dependencies need to be added to a deploymentMartin Ahrer Nov 25, 2013 2:39 PM (in response to Karel Piwko)
Hi Karel,
thanks for your explanation. But I fear I have not expressed my problem clear enough. My server side implementation consists of about 5 classes that make up my REST service (+ a ton of 3rd party libraries which are setup as dependencies in my IDE/gradle build).
However, for my test I didn't add any of these classes nor did I add any of the 3rd-party libraries (as you see in my test code above) to the deployment. I only added the Servlet 3.0 Initializer but still when invoking the test (in IDE or from gradle command line) the test goes green.
I'd expect ClassNotFoundExceptions etc. as I haven't really done my micro deployment. But in fact the REST service implementation finds all dependencies (classes+libraries) in its classpath.
Thanks
Martin
|
https://developer.jboss.org/thread/234728
|
CC-MAIN-2018-17
|
refinedweb
| 773
| 55.64
|
This month we are focusing on OpenJDK projects you should know about. This time we will be covering Valhalla. We have also looked at Panama, Loom, Skara and Amber.
Project Valhalla was started back in 2014 by the HotSpot Group. It proposes to introduce some changes into the way types can be used in Java.
There are 3 main goals of Project Valhalla (defined on the wiki page):
- Align JVM memory layout behaviour with the cost model of modern hardware;
- Extend generics to allow abstraction over all types, including primitives, values, and even void;
- Enable existing libraries — especially the JDK — to compatibly evolve to fully take advantage of these features.
So Valhalla is partly about improving Java as a language and partly to change the way Java works to take advantage of modern hardware changes since Java was introduced in 1995 – a long time ago in technical terms when we live with Moore’s law.
Among other proposed changes, there are 2 Java Enhancement Proposals that propose will mark a major change:
1. Value Objects
Value types (like primitive types, such as int, boolean, char etc) provide better performance than reference types. Value types are the actual value, whereas reference types are references to another value.
One of the aims of Project Valhalla is to be able to create Value Objects, which will behave in a similar way to primitive types but can be defined by the user.
The aim of this JEP is to define a new operator called lockPermanently. This will take an object and returns it in a permanently immutable state. The benefit of this will be that they will be cheaper to work with, like primitive types.
This technique will be applied to wrapper types such as Integer and Boolean.
2. Generics over Primitive Types
One of the limitations of Generics in Java is that they can only be used with reference types (types that extend Object) and not primitive types. This would also mean that once value types were introduced, you would not be able to use them as arguments for Generic classes.
For example if I have a class called Test that looks like this:
public class Test<T> {
.......
}
I can do this:
Test<Integer> test = new Test<>();
But not this:
Test<int> test = new Test<>();
The main disadvantages of having to use a boxed type such as Integer is that it is more costly. Project Valhalla proposes to use specialization to allow primitives like int to be used instead, which means that there will no longer be the memory overhead. And, you will be able to pass in value types.
What are your thoughts on Project Valhalla? Let us know in the comments.
|
https://blog.idrsolutions.com/2019/02/openjdk-projects-you-should-know-about-valhalla/
|
CC-MAIN-2021-04
|
refinedweb
| 450
| 68.7
|
Previous: Invoking the garbage collector, Up: Type Information
With the current garbage collector implementation, most issues should show up as GCC compilation errors. Some of the most commonly encountered issues are described below.
GTY-marked type. Gengtype checks if there is at least one possible path from GC roots to at least one instance of each type before outputting allocators. If there is no such path, the
GTYmarkers will be ignored and no allocators will be output. Solve this by making sure that there exists at least one such path. If creating it is unfeasible or raises a “code smell”, consider if you really must use GC for allocating such type.
gt_ggc_r_foo_barand similarly-named symbols. Check if your foo_bar source file has
#include "gt-foo_bar.h"as its very last line.
|
http://gcc.gnu.org/onlinedocs/gcc-4.6.0/gccint/Troubleshooting.html
|
CC-MAIN-2016-50
|
refinedweb
| 131
| 65.73
|
go
/
go
/
346babe6a67fbbd570a2ec234ebf279cfb1a0078
/
.
/
src
/
cmd
/
link
/
link_test.go
blob: 4ec03abc8587151bcc2c4ead5e9b80700e146f65 [
file
] [
log
] [
blame
]
package main
import (
"internal/testenv"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"testing"
)
var AuthorPaidByTheColumnInch struct {
fog.`
wind int `.`
jarndyce int `.`
principle.`
}
func TestLargeSymName(t *testing.T) {
// The compiler generates a symbol name using the string form of the
// type. This tests that the linker can read symbol names larger than
// the bufio buffer. Issue #15104.
_ = AuthorPaidByTheColumnInch
}
func TestIssue21703(t *testing.T) {
testenv.MustHaveGoBuild(t)
const source = `
package main
const X = "\n!\n"
func main() {}
`
tmpdir, err := ioutil.TempDir("", "issue21703")
if err != nil {
t.Fatalf("failed to create temp dir: %v\n", err)
}
defer os.RemoveAll(tmpdir)
err = ioutil.WriteFile(filepath.Join(tmpdir, "main.go"), []byte(source), 0666)
if err != nil {
t.Fatalf("failed to write main.go: %v\n", err)
}
cmd := exec.Command(testenv.GoToolPath(t), "tool", "compile", "main.go")
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("failed to compile main.go: %v, output: %s\n", err, out)
}
cmd = exec.Command(testenv.GoToolPath(t), "tool", "link", "main.o")
cmd.Dir = tmpdir
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("failed to link main.o: %v, output: %s\n", err, out)
}
}
|
https://go.googlesource.com/go/+/346babe6a67fbbd570a2ec234ebf279cfb1a0078/src/cmd/link/link_test.go
|
CC-MAIN-2020-40
|
refinedweb
| 201
| 56.93
|
AuScanForTypedEvent.3x - Man Page
Name
AuScanForTypedEvent - return the first event of a specific type
Synopsis
#include <audio/audiolib.h>
AuBool AuScanForTypedEvent(server, mode, dequeue, type, event)
AuServer *server;
int mode;
AuBool dequeue;
int type;
AuEvent *event; /* RETURN */
Arguments
- server
Specifies the connection to the audio server.
- mode
Specifies how far to look for a match. This should be one of these constants: AuEventsQueuedAlready, AuEventsQueuedAfterReading, or AuEventsQueuedAfterFlush.
- dequeue
Specifies if a matching event is found, should it be removed from the queue.
- type
Specifies the type of event to match. The type should be one of these constants: AuEventTypeElementNotify, AuEventTypeGrabNotify, or AuEventTypeMonitorNotify.
- event
Returns the matching event if found.
Description
AuScanForTypedEvent scans the event queue looking for the first event that matches type. If mode is AuEventsQueuedAlready, AuScanForTypedEvent only checks for events already in the queue. If mode is AuEventsQueuedAfterReading, and a matching event isn't found already in the queue, AuScanForTypedEvent attempts to read more events out of the application's connection. If mode is AuEventsQueuedAfterFlush and a matching event isn't already in the queue or isn't waiting to be read, AuScanForTypedEvent flushes the output queue and attempts to read more events out of the application's connection. If dequeue is AuTrue, and a matching event is found, it is removed from the queue.
See Also
AuEventsQueued, AuScanEvents, AuNextEvent.
audiolib - Network Audio System C Language Interface
Referenced By
AuNextEvent.3x(3), AuRequeueEvent.3x(3), AuScanEvents.3x(3).
|
https://www.mankier.com/3/AuScanForTypedEvent.3x
|
CC-MAIN-2022-40
|
refinedweb
| 239
| 56.35
|
Learning goal:
This lesson learns how to use the sound sensor on the Tiny-bit microbit robot.
Preparation:
1.The position of the sound sensor module in the robot.
! ! ! Note:
In this experiment, we need to install the jumper cap in the position shown below.
2.The micro:bit pins connected to the sound sensor.
From the hardware interface manual, we can know that the sound sensor is directly driven by the micro:bit P1 pin.
Code:
from microbit import *
horn = Image("00090:"
"90990:"
"99990:"
"90990:"
"00090")
calibration_Val = pin1.read_analog()
sleep(500)
while True:
Voice_Val = pin1.read_analog()
if Voice_Val > calibration_Val + 50:
# Detected changes in the external environment of the
# current environment,
# this parameter can be changed by yourself
display.show(horn)
sleep(200)
else:
display.show(Image.HAPPY)
Programming and downloading:
1.You should open the Mu software, and enter the code in the edit window, , as shown in Figure6-1.
Note! All English and symbols should be entered in English, and the last line must be a space.
Figure 6-1
2.As shown in Figure 6-2, you need to click the Check button to check if our code has an error. If a line appears with a cursor or an underscore, the program indicating this line is wrong.
Figure 6-2
3.You need to connect the micro data cable to micro:bit and the computer, then click the Flash button to download the program to micro:bit as shown in Figure 6-3.
Figure 6-3
4.After downloading the program, we can a heart pattern is displayed on the micro:bit dot matrix. When we Shooting table, micro:bit dot matrix will display a horn pattern.
The code of the experiment: 6.Sound sensor
|
https://www.elephantjay.com/blogs/tutorial/107
|
CC-MAIN-2020-50
|
refinedweb
| 289
| 67.45
|
How to pass the JobId to a nsh script (from a NshScriptJob)Clément BARRET May 22, 2012 9:11 AM
Hi,
I got a BladeLogic unsolved problem... to solve.
Let's say I got a batch Job including two nsh script jobs.
The first one will be executed against a bunch of targets.
The second one is always executed on the same target and will agregate things produced by the first job.
The problem is the second one must retrieve the first job execution log to generate some reports.
I wish I could pass as a nsh script parameter something (like the "Batch Job Id") that could allow my second nsh script job to identify the first Job and get its job run.
Is that possible ? I mean, I don't want to get the "latest job run log with that name in that job group" because that would be a real mess to set up (I have to get multiple instances of the same Batch Job running concurently, which perfectly works atm with the nsh scripts I've written.)
I hope I've been clear and that somebody will be able to help me...
To summerize : Is there a ??xxxx.xxxx?? dynamic property that I can pass as a parameter to my nsh script to identify my current Job Run Id (or any way to transmit this info to my nsh script job) ?
Thanks !
1. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Bill Robinson May 22, 2012 9:19 AM (in response to Clément BARRET)
I have yet to find a way to do what you want.
I think you can derive the batch job key and possible the batch job run key from the nsh child jobs, if that’s the case, you can get the nsh child job run key.
Or you could re-work how this runs, and instead of using a batch job, use a nsh script to call the 1st script job, where you would have the run key after it finishes and then just start running whatever is in the second script.
2. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Clément BARRET May 22, 2012 9:35 AM (in response to Bill Robinson)
Thanks @Bill Robinson for your answer.
I already thought I could "start the jobs using a nsh script" to get the JobId...
I wonder if I could avoid this since that would make "the following of the job run" very difficult (the first nsh script job is quite verbose since my nsh script prints some processing step messages on the STDOUT, which is pretty handy when you're following the job progress)...
That would be really great to have some dynamic variable (something like ??JOB.JOBID??) that could be passed to nsh scripts...
Damned, I either have to get the jobId using the job name (which force me to put a unique ID for each instance of the job in the job name... without being able to run it concurently) and get the last run log... OR try to do what you told me with a "nsh script launcher".
Basically, that should be a real pain in the ... since I will have to transmit job names in it... since every job "instances" have different parameters as well as different target lists :/
Damned... I'm screwed
Any idea or advice ?
3. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Bill Robinson May 22, 2012 9:38 AM (in response to Clément BARRET)
In the second script if you run ‘echo $0 it will give you filename of the script that’s running. I believe that might contain some useful information like the job run key. You might be able to back trace that to the batch job run, and from that get the job run of the 1st nsh job in the batch.
4. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Clément BARRET May 22, 2012 11:39 AM (in response to Bill Robinson)
Well, I'm working on this really hard but I'm not going anywhere close to the solution...
I've created a nsh script job (type 2) to be able to "launch" both steps "manually".
Well, I wish I had not to do that since I will have to transmit the two job names and probably their "job group" also... which will be a real mess to maintain and to use (since I'm not responsible for the exploitation of things once their in production...).
Anyway, let's say I got this done, two job names as parameters plus the third one that would be the %h (targets list if I'm right).
How can I "launch" the first job transmitting the target list (as the first nsh script job is a type 1 one), get its dbkey ?
Then how can I wait for it to be finished before launching the second one (type 1 on a fixed target), transmitting the first job dbkey as a parameter ? (since this job already has many parameters already set, of the type "PARAM_NAME=VALUE" (which I parse in my nsh script to dynamically create a hash with param values).
Second solution (based on the $0) :
So, I print $0, "ok"
Where is the dbkey that could help me get the "sons log" in that name ?
For instance, my job actually print me this as $0 :
/opt/bmc/bladelogic/tmp/blasb01-js2/scripts/job__eabc2ba5-7906-4015-89fb-ee2c5a757489/script_DBKey-SJobKey-2147066-4__5ebe4bbd-1bff-4c3b-b651-a4efcc175706.2025174.1_test_job_args.nsh
Thanks again for your time and your help.
Regards.
5. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Clément BARRET May 23, 2012 12:17 PM (in response to Bill Robinson)
Could you please give me some piece of code that would allow me to retrieve the run log of a NshScriptJob using a part of its name* (this part is unique) ?
(*) I must NOT have to use the "JobGroup" in the "query" since the Jobs will be located in several places in the Job tree...
Thanks in advance.
Regards.
6. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Bill Robinson May 23, 2012 12:21 PM (in response to Clément BARRET)
If you echo $0 from the second script you should have something like:
Right?
What version of bsa are you using ?
7. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Clément BARRET May 23, 2012 12:42 PM (in response to Bill Robinson)
@Bill Robinson :
Atm we're using version 7.5 (or 7.6, duno exactly).
You can read my previous message to see I've given you what I got using $0.
Any idea ?
8. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Clément BARRET May 24, 2012 8:12 AM (in response to Clément BARRET)
@Bill Robinson :
At least, could you please help me retrieving the last "run log" of a NshScriptJob (which run is over) given a (unique) part of its name (without knowing the Job's JobGroup name) ?
Thanks in advance.
Regards,
9. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Rohit Nayyar May 24, 2012 8:22 AM (in response to Clément BARRET)
This is simple Perl code I have used to get the job id at run time of the job
Once u have the job id, you can use blcli to get its run id and other details
U can change this to NSH
my $script_path=$0;
$script_path=~tr/\\:/\//d;
my @temp=split("/",$script_path);
my $script_name=$temp[$#temp];
@temp=split("_",$script_name);
$temp[1]=~s/\-/:/;
$temp[1]=~s/\-/:/;
my $script_dbkey=$temp[1];
DB key is this variable $script_dbkey
10. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Clément BARRET May 24, 2012 8:36 AM (in response to Rohit Nayyar)
@Bill Robinson :
Thanks for this,
I know perl quite well so I assume for the exemple ($0) you gave in your previous message
( ) that would give to $script_dbkey the value :
04cc5d2a:04ac:469d-8b10-6780e4dfbcbe
is that right ?
11. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Clément BARRET May 24, 2012 9:17 AM (in response to Clément BARRET)
I'm so pissed of the BladeLogic blcli implementation... How comes there is no such namespace as "this" since it's a java based framework ??
That's so insane to have to transmit metadata (JobGroup + JobName) to a script to allow it to get informations about its running status...
This is just a complete fail.
My need is quite BASIC and I can't find a proper way to achieve it...
I DON'T WANT to have to transmit the JobGroup to my "nsh script launcher" since it will be use in multiple cases with several nshscriptjobs to launch and monitor and that would be a real pain in the ass to set up for each instance...
Damned... I'm screwed... This is such a shame there is no way (by my somehow limitated knowledge, may be there is ?) to get "self" information from "inside" a nsh script...
Who designed this by the way ? Has he EVER had to code something useful ?
I'm quite angry since I don't have much time to finish this and I can't do it.
Pfff... I think that might me the end of this job for me...
12. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Bill Robinson May 25, 2012 3:59 PM (in response to Clément BARRET)
you have the key for the script itself, the trick is getting the job run id for the script and the batch job that job run is happening inside of. we could use something like getLastRunKeyByJobKey to get the job run key/id but that might not be the correct run id if you have multipe runs of the batch job happening concurrnetly.
if you think we can assume that the latest job run is the one you want i can proably work something out here, otherwise i'm still digging.
13. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Clément BARRET May 29, 2012 6:00 AM (in response to Bill Robinson)
Well, I gave up on the "guess who was the first job" thing (because it's too slow to do a "recursive find" inside the jobs tree).
Instead, I designed a recursive find tool (that allows me to search only in a subtree jobs which name matches a given pattern) and I then get the DBKey and pass it as a parameter to my second job.
Then, in the second job, I just have to do :
blcli_execute JobRun findLastRunByJobKey <JOB_DBKEY>
blcli_execute JobRun getJobRunKey
and then (even if I wish I could do it another way, since I'll have to parse the output of this command and get only the lines with the "Exit Code x"...)
blcli_execute Utility exportNSHScriptResults <JOBRUN_KEY> <TMP_FILE>
Well, I'd like to get to this another way and I think there actually is one since the GUI is able to list the target servers on the left panel (right click on a job run then "Show Log") with only a green/red icon depending on the exit code... which is exactly what I need.
In fact, I wonder what are the kind of objects listed in this left panel...
Any idea to get this info straightforwardly assuming we got our job and jobrun dbkey ?
NB : in BladeLogic version 7.5, getLastRunKeyByJobKey doesn't exist
14. Re: How to pass the JobId to a nsh script (from a NshScriptJob)Clément BARRET May 29, 2012 10:59 AM (in response to Clément BARRET)
Well, I found something that could "be it" but I can't understand how to handle the list items I got...
I used the following commands :
blcli_execute JobRun findLastRunByJobKey <JOB_KEY>
blcli_execute JobRun getJobRunId
blcli_storeenv JOBRUN_ID
blcli_execute JobRun getFailedServersByRunId-api ${JOBRUN_ID}
and I got something like this :
[com.bladelogic.model.base.header.SDeviceHeaderImpl@1c2006a0, com.bladelogic.model.base.header.SDeviceHeaderImpl@7a9300cc]
This looks like a list but I really don't know how to iterate on each item of this list to get further details on each of them...
Any idea ?
Regards;
|
https://communities.bmc.com/message/245128
|
CC-MAIN-2015-40
|
refinedweb
| 2,082
| 72.09
|
3.1.5 Transform Node and Python
I am trying to use the new 3.1.5 version to use a python script to calculate the last x amount of days from today, I basically want a script to determine the last x amount of days via a python script and then filter out only those records. I need to use a script and not the filters, because it will vary from Last 7, Last 28, Last Year.
I am thinking it involves importing datetime and then subtracting a time delta, but the node seems to be more complicated now that python needs to be configured and I can't even figure out how to start with the script because it looks like it requires 3 different scripts.
Can someone at Lavastorm do a video example of how to work with the PYTHON nodes now? It looks like a multi step process to even get a script to work. Thank you.
Hi Nancy,
Your approach is correct. I just tried the following and it worked for me:
In ConfigureFields field of the Transform node I put the following:
---
from datetime import datetime, timedelta
N = 2
date_N_days_ago = datetime.now() - timedelta(days=N)
---
I can then use the date_N_days_ago value in scripts in ProcessRecords and ConfigureFields. For example to output the date_N_days_ago value as a field I could do the following:
ConfigureFields:
----
from datetime import datetime, timedelta
#define a new field of type datetime on output out1
out1.Date_N_Days_Ago = datetime
N = 2
date_N_days_ago = datetime.now() - timedelta(days=N)
---
ProcessRecords
---
#output the value of date_N_days_ago in field out1.Date_N_Days_Ago
out1.Date_N_Days_Ago = date_N_days_ago
---
Let me know if this helps.
Mark
Nancy,
If you want to suppress records in a transform node you need to set the output to None based on the condition you have identified. The example below based on Mark's above should give you all the information you need.
Step 1
Create a Create Data node with the following content in the Data field
id:int,create:datetime
1,2017-08-01 12:35:41
2,2017-09-01 02:00:00
3,2017-07-01 05:23:21
4,2017-04-17 18:12:21
5,2017-06-21 15:12:21
Step 2
Add a Transform node with the following in ConfigureFields
from datetime import datetime, timedelta
out1 += in1
N = 100
date_N_days_ago = datetime.now() - timedelta(days=N)
And the following in ProcessRecords
out1 += in1
if in1.create < date_N_days_ago:
out1 = None
Note the result will only output those records newer than 100 days.
Regards, Tim.
-
Hello, thanks for the tips.
This example works as reproduced but it's not working with my data. I have a datetime field but I am trying to filter off a converted date to string. So that's more than likely my problem,
So ideally I would want my filter to find the x number of days then filter off the new truncated date field I created.
When I output the datetime though I don't want to see the entire datetime format, just a truncated version of it.
Hi Nancy,
The data flow attached to this knowledgebase article provides some examples of extracting elements of a date object as a string. The example data in the article used a date object but the same code can be used to extract the corresponding elements from a datetime object.
There are a number of articles describing the use of Python within the Transform node in the Tips & Tricks section of the knowledge base.
Regards,
Adrian
Hi Nancy,
If you can provide an example or two of what the data looks like in the string, that will help.
Can you also clarify what you mean by these statements (with an example):
So ideally I would want my filter to find the x number of days then filter off the new truncated date field I created.
- What does the new truncated date field look like?
When I output the datetime though I don't want to see the entire datetime format, just a truncated version of it.
- So you want it to look like the new truncated date field you mentioned in your previous statement?
Hopefully this will give us enough information to be able to help you accomplish what you want.
Thanks,
Catharine
Please sign in to leave a comment.
|
https://support.infogix.com/hc/en-us/community/posts/360028736154-3-1-5-Transform-Node-and-Python
|
CC-MAIN-2020-29
|
refinedweb
| 723
| 67.69
|
How to create an Elixir provider for Raygun Crash Reporting (part one)Posted Nov 4, 2016 | 7 min. (1336 words)
With all the languages that Raygun Crash Reporting supports (over 30), we have been eagerly awaiting a chance to work on an Elixir provider. In this article, I’ll walk you through building a sample version to get you tracking and resolving errors.
To make this process a little more digestible, I’ve broken this post into a two part series.
In part one, I’ll go over creating a basic Elixir package to handle the REST API calls to the Raygun Crash Reporting service for error reporting. In part two, I’ll finish up the creation of the package and then add it to a todo list application adapted from an Elixir sample application on Todo-Backend.
Firstly, here’s a little background information on what you’ll need and why error tracking is important:
Elixir
Elixir is a functional programming language built on top of the Erlang Virtual Machine. Elixir’s creator, Jose Valim, built the language to offer higher extensibility and productivity over Erlang without losing compatibility with Erlang. Phoenix is a web framework created by Chris McCord for the Elixir programming language.
Phoenix
Phoenix aims to provide developers with a high performance and easy to work with framework that allows for large amounts of connected devices. With both Elixir and Phoenix being relatively new, there are bound to be errors and exceptions that pop up in production environments.
Raygun Crash Reporting
Rather than relying on user error reports or log scrapers, you can leverage Raygun Crash Reporting, which enables you to handle and report errors in real time so your team can resolve them as soon as possible.
What do we need to get started?
For the package:
For the Todo-Backend sample:
Getting started:
Firstly, we’ll create a new package by running the following command in your terminal of choice:
mix new laserpistol4elixir
This will create a new Elixir project for us with some default files. Now, change directory to our new laserpistol4elixir project and open the project in your editor of choice.
The next thing we will do is start working on our mix.exs file in the main application directory.
Here is how our mix.exs file will look when we’re done: (I’ll go over what the code means below.)
defmodule Laserpistol4elixir.Mixfile do use Mix.Project def project do [app: :laserpistol4elixir, version: "0.1.0", elixir: "~> 1.3", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps(), description: description(), name: "laserpistol4elixir" ] end def application do [applications: [:logger, :hackney, :poison], mod: {Laserpistol4elixir, []} ] end def deps do [{:hackney, "~> 1.6"}, {:poison, "~> 3.0"} ] end def description() do "Basic exception tracking tutorial." end def package() do [maintainers: ["Jesse James"], licenses: ["MIT"], links: %{"GitHub" => ""} ] end end
Breakdown:
def project do [app: :laserpistol4elixir, version: "0.1.0", elixir: "~> 1.3", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps(), description: description(), name: "laserpistol4elixir" ] end
This portion of the code specifies information about our project. In this case you can see the application name, version information, description, and dependencies:
def application do [applications: [:logger, :hackney, :poison], mod: {Laserpistol4elixir, []} ] end
In Elixir, an application is a component implementing some specific functionality that can be started and stopped as a unit, and which can be re-used in other systems. Here, we’re defining which applications we will have running (logger, hackney, and poison) and an application call back (the mod: {Laserpistol4elixir, []} portion). If needed, specify the default environment variables for these applications.
The application call back is necessary for setting up a supervision tree (more on this later). This supervision tree will need to start and stop when the application starts and stops.
def deps do [{:hackney, "~> 1.6"}, {:poison, "~> 3.0"} ] end
Defining external dependencies here allows Hex, the Elixir package manager, to be used to install these dependencies. Specifically we’re telling the system to install any Hackney version 1.6 or greater up to 2.0 and Poison version 3.0 or greater up to 4.0.
def description() do "Basic exception tracking tutorial." end def package() do [maintainers: ["Jesse James"], licenses: ["MIT"], links: %{"GitHub" => ""} ] end
Here the description() function just returns a string of the application description for use in the project section.
The package() function outlines the package information regarding who is maintaining the project, what the license is, and any relevant links concerning the package. It is also used in the project section.
You will want to change these values to reflect your own name, license preference, and link locations.
The next file we’ll need to update is the config.exs located in our config directory. The config.exs file will contain any necessary configuration options for our package:
Config.exs
use Mix.Config config :laserpistol4elixir, api_key: "your_key_here", environment: "production"
Breakdown:
use Mix.Config
This loads a module which allows our configuration options to be set in the application env and later accessed via Application functions.
config :laserpistol4elixir, api_key: "your_key_here", environment: "production"
Here, the application is being defined (:laserpistol4elixir ) and then the api_key and environment are being set. You’ll need to change the “your_key_here” to the Raygun Crash Reporting API key from your Raygun Crash Reporting application.
The next file we’ll need to update is the laserpistol4elixir.ex located in our lib directory. The lib directory will hold most of the actual code for the package:
Laserpistol4elixir.ex
defmodule Laserpistol4elixir do use Application def start(_type, _args) do import Supervisor.Spec api_key = get_config(:api_key) children = [ worker(Laserpistol4elixir.Client, [api_key]) ] Supervisor.start_link(children, strategy: :one_for_one) end @spec track_exception(:error | :exit | :throw, any, [any]) :: :ok def track_exception(kind, value, stacktrace) when kind in [:error, :exit, :throw] and is_list(stacktrace) and is_map(custom) and is_map(occurrence_data) do # provider and report calls will go here end end defp get_config(key) case Application.fetch_env(:laserpistol4elixir, key) do {:ok, {:system, var}} when is_binary(var) -> System.get_env(var) || raise ArgumentError, "#{inspect(var)} not set" {:ok, value} -> value :error -> raise ArgumentError, "config param #{inspect(key)} not set" end end end
Breakdown:
defmodule Laserpistol4elixir do
This line is just defining the laserpistol4elixir module itself:
use Application
Here we define that this module should be used to provide the application call back that we setup in mix.exs earlier:
def start(_type, _args) do import Supervisor.Spec api_key = get_config(:api_key) environment = get_config(:environment) children = [ worker(Laserpistol4elixir.Client, [api_key]) ] Supervisor.start_link(children, strategy: :one_for_one) end
The start method will be run every time the application starts and serves as the directions for the application call back. The import Supervisor.Spec gives access to convenience functions for defining supervisor specifications. In this case it gives us the ability to specify the children to be used under the supervisor with Supervisor.start_link/2. For more information on Supervisor, you can take a deeper look in the Elixir Supervisor docs:
@spec track_exception(:error | :exit | :throw, any, [any]) :: :ok def track_exception(kind, value, stacktrace) when kind in [:error, :exit, :throw] and is_list(stacktrace) do # provider and report calls will go here end end
@spec track_exception(:error | :exit | :throw, any, [any]) :: :ok is creating a typespec for the function that follows it, essentially indicating what type the result of the function will be in. In this case the function will be expected to return :ok .
The rest of this portion is the start of the track_exception function which we’ll work on more in part two of this blog post series on Elixir. For now, the function logic is set to check that the kind of the exception is one of the expected values (error, exit, or throw) and if the stacktrace is a list or not.
Summary
So far we’ve covered getting the basic setup done for our Elixir package. At this point we’ve created the Elixir package, updated the mix.exs , config.exs , and lasergun4elixir.ex files so we’re most of the way there. In part two we’ll finish the build out of the feature logic to send the error reports to Raygun Crash Reporting and then integrate the package with out todo list application.
Did you run into any issues so far or have any questions on what we did in part one? If so, let us know in the comments below!
|
https://raygun.com/blog/creating-elixir-provider-raygun-part-one/
|
CC-MAIN-2020-40
|
refinedweb
| 1,388
| 55.84
|
Jean-Sebastien Delfino wrote:
> ant elder wrote:
>> For the new Axis2 based WS binding we need to get WSDL defined to SDO so
>> that the SOAP Body XML can be (de)serialized to DataObjects
>> correctly. Could
>> that happen when the import.wsdl in the sca.module is being
>> processed? Thats
>> done by org.apache.tuscany.model.assembly.impl.AggregateImpl in the
>> initialize method. Adding the following line just after the
>> getAssemblyLoader().loadDefinition call seems to work:
>>
>> XSDHelper.INSTANCE.define(url.openStream(), null);
>>
>> Would this be ok?
>>
>> Thanks,
>>
>> ...ant
>>
>>
> Yes I think this is OK. If your service is flowing complex types and
> you have generated SDO classes then you just need one of the
> components in your application module to reference the generated SDO
> Factory to trigger the initialization of the metadata for your complex
> types. But in scenarios flowing elements of simple types e.g. <element
> you won't have generated SDO
> classes so you definitely need to invoke
> XSDHelper.INSTANCE.define(url.openStream(), null) to get the metadata
> for your elements in place.
>
I have a set of related SDO questions - and depending on the answers we
may have a problem or not :)
Let's say that at build time I give x.wsdl to the SDO code generator. I
get SDO classes generated for the XSD types defined in my WSDL <types>
section . Then at runtime I want to use these SDO classes in an SCA
component. To trigger the initialization of the SDO metadata for these
types I simply reference the generated factory or use
SDOUtil.registerStaticTypes(...) when my SCA component starts. Then
Ant's Axis2 Entry Point runtime does XSDHelper.INSTANCE.define(the exact
same x.wsdl)... My understanding is that this will dynamically generate
SDO metadata from the given WSDL..
Which version of the metadata is the SDO runtime going to use? the first
one that gets registered? the last one? Is XSDHelper going to detect
that already have SDO metadata registered with static types for the
given namespace? Do we get new SDO metadata each time we invoke
XSDHelper.define(...)?
--
Jean-Sebastien
|
http://mail-archives.apache.org/mod_mbox/tuscany-dev/200603.mbox/%3C4407898F.5050500@apache.org%3E
|
CC-MAIN-2016-07
|
refinedweb
| 349
| 59.9
|
Here is a solution to tell in which Mashup a Personalized Script for Lawson Smart Office is currently running, for example to tell Mashups A and B apart in a script. We’ll read the BaseUri and Uri properties of a MashupInstance.
This solution is useful in scenarios where we have two Mashups, each with a specific script attached to a common M3 program. Each script needs to tell in which Mashup it’s currently running as we don’t want to let the scripts run in the wrong Mashup.
Example
For example, I have two Mashups that both use the M3 program Item Toolbox – MMS200.
The first Mashup (MashupA) shows a list of items and detailed information about a selected item, such as shelf-life, buyer’s name, on-hand availability in all warehouses, lot information, etc. In this Mashup, we need a script (ScriptA) to append an additional column of information to the list of items by querying a third-party warehouse management system. This Mashup is useful for the sales team to accurately communicate detailed information to a customer on the phone to convert a potential customer order and get the sale.
The second Mashup (MashupB) shows a list of items and purchasing information about a selected item, such as demand, supply, inventory, item specifications, sales history, forecast, etc. In this Mashup, we need a script (ScriptB) to append an additional column of information to the list of items by querying a third-party purchasing order software. This Mashup is useful for the purchase planning process when buyers need to decide if to buy an item or not and create a purchase order.
Both Mashups A and B have the same M3 program MMS200 in common, and two different scripts A and B. Each script needs to execute in its corresponding Mashup, script A in Mashup A, and script B in Mashup B. Otherwise, the scripts would show the wrong information in the wrong Mashup.
Problem
The problem is that when we attach a script to an M3 program in Smart Office, we cannot tell for which Mashup to execute the script. We can only attach the script to an M3 program, in my case to MMS200/B, and then attach the M3 program to the Mashup. But that doesn’t tell the script which Mashup is which.
More generally, Smart Office can only do binary relationships Mashup-Program and Program-Script, whereas we need ternary relationships Mashup-Program-Script. We are trying to solve that problem.
Solution
The solution is to get the identifier of the Mashup. Actually we cannot get the identifier of the Mashup as is defined in the Project’s manifest file. But we can derive one from a combination of the path of the Mashup, for example Mashups\MashupA.mashup, and the filename of the XAML, for example MashupA.xaml. That’s given by the Mashup’s BaseUri and Uri respectively.
For that, we’ll start with karinpb‘s solution to check if a JScript is running in a Mashup.
var element = controller.RenderEngine.ListControl.ListView; var type = Type.GetType("Mango.UI.Services.Mashup.MashupInstance,Mango.UI"); var mashup = Helpers.FindParent(element, type);
That gives us a object that we can cast to MashupInstance from which we can get the BaseUri and Uri properties:
mashup.BaseUri // ex: Mashups\MashupA.mashup mashup.Uri // ex: MashupA.xaml
Here is a screenshot of the Smart Office SDK documentation:
Here’s my sample source code:
import System; import Mango.UI.Services.Mashup; import Mango.UI.Utils; package MForms.JScript { class Test { public function Init(element: Object, args: Object, controller : Object, debug : Object) { if (controller.PanelState.IsMashup){ var mashup: MashupInstance = Helpers.FindParent(controller.RenderEngine.ListControl.ListView, MashupInstance); switch (mashup.BaseUri + "\\" + mashup.Uri) { case "Mashups\\MashupA.mashup\\MashupA.xaml": debug.WriteLine("MashupA"); break; // MashupA case "Mashups\\MashupB.mashup\\MashupB.xaml": debug.WriteLine("MashupB"); break; // MashupB case "Mashups\\MashupC.mashup\\MashupC.xaml": debug.WriteLine("MashupC"); break; // MashupC default: debug.WriteLine("Mashup not supported"); // Mashup not supported } } else { // Not in Mashup debug.WriteLine("Not in Mashup"); } } } }
Here are screenshots of the result:
Thanks to karinpb, Peter K, and Joakim I for their help.
That’s it!
One thought on “How to tell Mashups apart in a Smart Office script”
|
https://m3ideas.org/2012/04/11/how-to-tell-mashups-apart-in-a-smart-office-script/
|
CC-MAIN-2018-47
|
refinedweb
| 709
| 65.42
|
Some time ago, I had to make a project to determine the shortest path inside a matrix. I thought to myself, "There's nothing better than path-finding for this." There is a huge amount of links and explanation about Path Finding, but didn't find a version written in C# that could meet my needs. So, I decided to make the A* implementation in C#. This code was really useful for me and I bet it can be useful for many other people, too. I won't explain the algorithm implementation too much because just typing "pathfinding algorithm A*" into Google brings up a lot of documents wherein you can find every single detail about it.
A* is a generic algorithm and there are no perfect parameters to be set. The algorithm has many things that can be set, so the best way to determine the appropriate parameters for your project is to test different combinations. As a also changed the implementation to use generics instead of ArrayList, which makes it run faster. This project is really useful for two reasons.
The call in the source code that does the entire job is the following:
public List<PathFinderNode> FindPath(Point start, Point end, byte[,] grid);
This method takes as parameters a start point, end point and the grid. It will return the path as a list of nodes with the coordinates. I made this call on a separate thread, which gives the opportunity to keep the control of the application when PathFinder is working.
This is the rendering speed; reducing speed permits detailed examination of how the algorithm opens and closes the nodes in real-time.
This hint will tell the algorithm if it is allowed to process diagonals as a valid path. If this check box is not set, the algorithm will process just 4 directions instead of 8.
If this check box is set, the cost of the diagonals will be bigger; this will make the algorithm avoid using diagonals.
If this check box is set, every time the algorithm changes direction it will have a small cost. The end result is that if the path is found it will be comparatively smooth without too many direction changes, thus looking more natural. The downside is that it will take more time because it must research for extra nodes.
If this is checked, the algorithm is allowed to reopen nodes that were already closed when the cost is less than the previous value. If reopen nodes is allowed it will produce a better and smoother path, but it will take more time.
This is a constant that will affect the estimated distance from the current position to the goal destination. A heuristic function is used to create an estimate of how long it will take to reach the goal state. The better the estimate, the shorter the found path.
This is the equation used to calculate the heuristic. Different formulas will give different results: some will be faster, others slower and the end may vary. The formula to be used depends strongly on the A* algorithm's use.
Sometimes when A* is finding the path, it will find many possible choices for the same cost and destination. The tie breaker setting tells the algorithm that when it has multiple choices to research, instead it should keep going. As it goes, the changing costs can be used in a second formula to determine the "best guess" to follow. Usually, this formula is incrementing the heuristic from the current position to the goal, multiplied by a constant factor.
Heuristic = Heuristic + Abs(CurrentX * GoalY - GoalX * CurrentY) * 0.001
This is the maximum number of closed nodes to be researched before a "Path not found" message is returned. This is a useful parameter because sometimes the grid can be too big and we need to know a path only if the goal is near the current position. It is also useful if the process can't spend too much time calculating the path.
This parameter just affects the front-end. It can change the grid size, where reducing the grid size gives a chance to create a bigger test but will take longer to render.
When unchecked, the implementation used is the algorithm as it usually appears in the books. When checked, it will use my own PathFinder implementation. It requires more memory, but it is about 300 to 1500 times faster depending on the map complexity. See the PathFinder Optimization section below for more details.
This permits observation of the algorithm as it operates in real-time. If this box is checked, the completion time will be the calculation time plus the rendering time.
This is the time that the algorithm took to calculate the path. To know the true value, uncheck "Show Progress."
After I implemented the original algorithm, I got frustrated because of the amount of time it took to resolve paths. This was especially the case for bigger grids and when there was no solution to the path. Basically, I noticed that the open and closing list were killing the algorithm. The first optimization was to replace the open list by a sorted list and the close list by a hashtable. This improved the calculation time, but was still not what I had hoped for. Later, I replaced the open list from a sorted list to a priority queue; it made a change but still not a big difference.
The big problem was that when the grid was big (1000x1000), the amount of open and closed nodes in the list was huge. Searching those lists took a long time, whatever method I used. At first, I thought to use classes to keep the node information, but that was going to make the garbage collection crazy between the nodes' memory allocation and releasing the memory of the nodes that were disposed of. Instead of using classes, I decided to use structures and reuse them in the code. I got more improvements from this, but still nothing close to what maybe StarCraft does to handle eight hundred units in real-time.
My current application is like a Visio application where I need to find a path between objects. The objects are not moving, so I didn't need a super-fast algorithm, but I needed something that could react in less than one second. I needed to find a way to get nodes from the open list in O(1) or closer to that. I thought the only way to get that was to not have an open list at all. That is when I thought of using a calculation grid. This calculation grid was going to store the nodes. Thus, if I knew the (X, Y) location then I could reach the node immediately O(1).
Because of this I could get rid of the close list; I could mark a closed node directly in the calculation grid. Also, since every node has a link to the parent node, I to get the node with the lowest cost. Priority queues are excellent for that, no linear access at all.
The only cons were that the memory consumption was huge to keep a second grid. That is because every cell stored a node and every node was 32 bytes long. Basically for a map (1000x1000) I needed 32MB of RAM. Because I was now accessing the second grid by coordinates (X, Y), I didn't need those values in the node anymore. That reduced 8 bytes multiplied by 1,000,000. I therefore saved 8MB of ram. Every node had a link to the parent nodes and those were int (32 bits) because the grid can never be too big. Then I replaced them for ushort (16 bits) and that made me save another 2 bytes by node. This saved me another 2MB. I also realized that the heuristic (H) is calculated for every node on the fly and it is not used for the algorithm anymore. So, I removed this from the node structure, too. Heuristic was an int (4 bytes) and so I saved another 4MB. I also had minimum nodes of 13 bytes, but because of memory alignment they took 16 bytes at run-time. I had to set the struct to use memory alignment for every byte:
[StructLayout(LayoutKind.Sequential, Pack=1)]
Finally, I got my 13 bytes for every node. For that reason, when running the sample, you will see that running FastPathFinder takes 13MB of extra memory.
I have to admit that it took me a fair amount of time to make it work because of the complexity of the A* debugging. I got my satisfaction when it worked, though. I could not believe that I got a minimum of 300 times faster for simple grids and more than 1500 times faster for complex grids. Still, I was inserting and removing nodes from the priority queue, which meant memory work and garbage collection coming into play. So, I figured out a way around keeping the nodes inside the priority queue: Instead of pushing and popping the node, I pushed and popped the address where the node is in the calculation grid. That let me save memory and run faster. The way I was storing coordinates in the priority queue was translating an (X, Y) coordinate into a linear coordinate:
Location = Y * grid width + X;
The problem arising there was that I had to translate back and forth between a linear coordinate and a map coordinate. So, I changed my calculation grid from a fixed map array:
PathFinderNode[,]
To a linear array:
PathFinderNode[]
That made the code a lot clearer because there was no translation between map and linear coordinates. I also added a constraint to the size of the grid. This constraint was that the map must be a power of 2 in width and height. Doing that allowed shifting and logical operations, which are much faster than mathematical operators. Where before it was:
LinearLocation = LocationY * Width + LocationX;
…
LocationY = LinearLocation / Width;
LocationX = LinearLocation – LocationY;
It now became:
LinearLocation = (LocationY << Log(Width, 2)) | LocationX;
…
LocationX = LinearLocation & Width;
LocationY = LinearLocation >> Log(Width, 2);
After all this, when the standard PathFinder algorithm resolved the path for the map HardToGet.astar in 131 seconds, the optimized PathFinder got the same result in 100 milliseconds. It was a 1300-times improvement. Another optimization was found in that if the current open node was already in the open list and the current node total cost was less than the store in the list, then the old node would be removed or replaced. Instead, I decided to leave the old open node in the open list and just add the new one. The old node would have a higher cost, so it would be processed later. However, when processed, this node would already be closed and so ignored. This is a lot faster than going to the open list and removing the old open node.
Another optimization arose from the fact that, between path finding calls, I had to clear the calculation grid. The calculation grid stores objects of type PathFinderNode and every object has a field Status. This field tells if the node is open, closed or neither. Status could be 0 = not processed, 1 = open or 2 = closed. Zeroing the grid usually took about 30 milliseconds for a 1024x1024 grid and that had to be done between path finding calls. To optimize it, instead of zeroing the grid what I do is change the values for the node status between calls. Then between calls, it increments the status value by 2. So in the first path finding search, we have:
In the second path finding search we have:
And so on…
In this way, between path finding calls, it doesn't need to clear the calculation grid. It just uses different values for open and closed nodes; any other value means it's not researched. Another small optimization was to promote all local variables to member variables. This allows creation of all variables in the heap at once instead of creating/destroying them in the stack for every pathfinder call. I changed my cost (G) and total cost (F) from int to float in order to obtain more detailed calculations of the total cost. The path produced for complex maps was 99% similar to when int was used for the cost and total cost. I noticed, however, that even when the float calculation time didn't vary too much from int, the number of nodes re-evaluated was huge. This was because the nodes were keeping the decimal values where before they made the algorithm skip the node. Now they were re-evaluated, which made the algorithm perform roughly 10 times slower. The difference was not appreciable, so for that reason I kept using int and discarding the decimals on the cost calculation.
In the optimization journey, I basically got rid of almost all memory allocation and sequential searches for fixed allocations and minimum search. It was analogous to replacing all mobile parts in a machine with fixed ones. Still, there are more optimizations that can be done and I'll probably keep working on those. If you have some feedback about the optimization or what can be done to improve it, feel free to add a comment and I'll reply as soon as I can.
The toolbar allows to us to load, create new and save test scenarios. It also allows to insert nodes (obstacles) in the grid with different costs. By default, all nodes in the grid have a cost of "1," but this can be changed to another cost. The "X" in the toolbar is cost "0" and represents an impassable node. The "start" and "end" buttons let us put the start and end positions inside the grid before running the algorithm. The costs of the nodes are not limited to the costs defined in the toolbar. The mouse buttons can change the current cost of the nodes, too. While moving the mouse and pressing the:
Left Button --> The current node is set to the cost specified by the active cost button in the toolbar.
Right Button --> The current node cost is incremented with the cost specified by the active cost button in the toolbar
Left & Right Buttons --> The current node cost is decremented with the cost specified by the active button in the toolbar.
When I did the A* implementation, I took a long time to find the best parameters for my real project. Because of that, I decided to create a front-end independently from the real application to help me find those values. The only reason for the front-end was testing and debugging, so the front-end currently has a poor design. There is a lot of things that can be done to make it better and run with better performance, but the objective of this article is to learn about A* implementation and not GDI optimization. For that reason, I did not spend too much time on it.
Some time ago, I saw a pretty cool application that implements A*, but I can't remember the name. It was in made in Delphi, but no source code was available. I took the main idea from there to create this front-end. I didn't want to make a clone of that application; rather, I thought it looked really interesting and that it could be nice to create something similar. There is a different namespace where it contains just the algorithm and the helper classes, the "Algorithms" namespace.
As a note, the rendering in real-time of the researching nodes is not persistent. Basically, the nodes are drawn directly in the window HDC (Device Context). Therefore if a portion of the window is invalidated, it won't be redraw again. If you move another window over the front-end, the current path will disappear. That can be resolved using a second grid and keeping the status of every node, but again, when I did the front-end it was just to debug the algorithm and see how the settings affect the path search.
You will probably notice that setting the speed to maximum (minimum value) still doesn't look like good performance. That's not because of the algorithm; that's because the algorithm is doing a lot of callbacks (events) to the front-end to allow the rendering. The first line inside PathFinder.cs is a #define:
#define DEBUGON
If this symbol is defined, then the algorithm will evaluate if the debugging events are defined. If they are, the algorithm will make a callback (event) for every step. When the application is used on a real project, it is strongly recommended that you remove that symbol from PathFinder.cs. Removing the symbol will hugely increase the performance of the algorithm. If the symbol is not defined, then the algorithm won't make any callback and will return just after it has found a path or a path was not found at all.
This application and code can help the beginner to the advance developer in exploring the A* algorithm step by step. Feel free to make any comments or recommendations.
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
CastorTiu wrote:I know that before upload I could do a copy and paste, but I never thought it could bother to the users. Also for that reason I do it at 1:30AM when I don't expect too much people on-line
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
http://www.codeproject.com/Articles/15307/A-algorithm-implementation-in-C?msg=1681670
|
CC-MAIN-2014-52
|
refinedweb
| 2,999
| 69.92
|
Conservapedia talk:What is going on at CP?/Archive298
Contents
- 1 CP at its most accurate ever
- 2 DDoS
- 3 Another classic from Kara"Scour the Desert"jou
- 4 Karajou reading fail, part MXXXLVIII...
- 5 Piers Morgan is a liberal?
- 6 Todd Akin - now a mystery
- 7 Dumb question
- 8 Has Thrustbuttocks given the game away?
- 9 The GOP not conservative enough for Andy
- 10 Ed tells it like it is.
- 11 Conservapedia down for 64.180.243.0/x?
- 12 No mention of Armstrong?
- 13 The Unhinged, starring CP sysops.
- 14 Media Bullying
- 15 Huh?
- 16 Ugh.
- 17 Where to begin...
- 18 Oh, so that's what God's realm on Earth will look like?
- 19 Launchbooty's Grand Plan
- 20 Someone noticed CP
- 21 Hey, Karajou
- 22 Breaking news!
- 23 I love Andy. He wears his heart on his sleeve.
- 24 Andy is insightful!
- 25 Oi, fuckers!
- 26 Redundant, but true.
- 27 I see the president is officially a satanist atheist muslim now.
- 28 JPratt in fantasy land
- 29 It's the most wonderful time of the year
- 30 CP Admins Don't Read the Linked Articles - Part Some Really Huge Number
- 31 Yes, Kendoll. Many differences.
- 32 Any athlete who disses Tebow is overrated
- 33 Abd
- 34 Hmmm...
- 35 Rev. Moon is Dead
- 36 Close encounters
- 37 "I love the smell of Napalm in the morning."
- 38 The US at the Paralympics
- 39 deja-vu all over again: idou and no end
- 40 RW and CP in August 2012
- 41 "Sandra Fluke sees freedom as having others pay for the condoms her dozens of weekly lovers use to please her."
- 42 Slingcolon flavour humour, Kara officially declaring war on facts and the racist, babykilling DNC
- 43 Classic Andy
- 44 Conservative ungrammatics
- 45 Irony alert: Kendoll sez talk is cheap.
CP at its most accurate ever[edit]
The database at CP is so bollixed right now the main page just says:
The entire site is also moving as fast as molasses in January. MDB (the MD is for Maryland, the B is for Bear) 11:29, 24 August 2012 (UTC)
- I'm guessing Ken's manic oversighting has finally broken the SQL table or something. I can't even get the main page or recent changes to load. --PsyGremlinHable! 11:47, 24 August 2012 (UTC)
- I guess the internet really does have a maximum level on bullshit?
NorsemanCyser Melomel 12:00, 24 August 2012 (UTC)
- If you're patient enough, it's as if the entire layout crashed so all you'd see are links and text. Just three whole actions the day of August 23rd, including Karajou's "we say crazy shit and it's your job to disprove us!" block.
NorsemanCyser Melomel 12:07, 24 August 2012 (UTC)
- It's back now. Looks like they've lost nearly a day of edits. MDB (the MD is for Maryland, the B is for Bear) 14:26, 24 August 2012 (UTC)
DDoS[edit]
Did RW organize a DDoS campaign to take down CP? The last couple days have seen spotty access to my favorite hateblog. Or is it the public rushing for conservative insights? Either way, I'm sure August traffic will be record-breaking. Occasionaluse (talk) 15:17, 24 August 2012 (UTC)
- The decline in bookshops in Laredo means people worldwide are flocking to Conservapedia and jamming in the doorway. This site is growing rapidly! 80.74.16.198 (talk) 15:19, 24 August 2012 (UTC)
- Nah, it looks like somebody broke the database - only 3 edits remain from yesterday. probably Ken through his over-eager oversighting. --PsyGremlinПоговорите! 15:24, 24 August 2012 (UTC)
- I could hardly get a response from CP yesterday. I think those edits are only there because Assly and Karajou were determined enough to make them. Does anyone remember seeing more edits than that? Occasionaluse (talk) 15:32, 24 August 2012 (UTC)
Another classic from Kara"Scour the Desert"jou[edit]
You accepted my challenge and provided us with peer reviewed papers that support your point? BUY THEM FOR ME! Even if you do, I will still ignore you, boy. ~Karajou. WilliamR (talk) 06:16, 23 August 2012 (UTC)
- I love how he saids it like he's a drill instructor. Still pissed you never got your own personal love boat Karajou? --Revolverman (talk) 06:54, 23 August 2012 (UTC)
- Wouldn't posting the papers for all to see be piracy? Is Karajou asking for CP to be used for piracy? --Opcn with regards to regarding my regardliness 07:46, 23 August 2012 (UTC)
- I might be wrong, but I doubt it. The price to pay is more for the effort of getting, and sending the papers then any royalty fees. --Revolverman (talk) 07:54, 23 August 2012 (UTC)
- Uh, what? This is the information age, the total processing power and electricity cost of sending those papers is a tiny fraction of a penny, like a few hundredths of a cent. Unless they are really old and someone is just being a dick the papers are probably still owned by the publisher, and selling access to them is what they do for a living. --Opcn with regards to regarding my regardliness 08:11, 23 August 2012 (UTC)
- Hey, I was suprised how little is electronic now a days. I know when I was at university, most of it was still just journals and the such. --Revolverman (talk) 10:05, 23 August 2012 (UTC)
- Can someone put this one into context for me? I had a quick scour through the guy's contributions and couldn't find anything that looked related. All his recent ones concern Todd Akin. --جئت ورأيت أنا القرف gross, isn't it? 09:53, 23 August 2012 (UTC)
- It's an oldie, but a goodie. You, Jamesmackenzie, are going to scour the area once known as the Kingdom of Urartuimg... rpeh •T•C•E• 10:28, 23 August 2012 (UTC)
- Ah, how I missed Kara's impotent drink-fueled rages. "Yes, you've shown me evidence that contradicts me, but YOU WILL abide by my totally arbitrary conditions, otherwise I will ignore you." I seem to recall him doing the same during the Kool Aid debate on CP - demanding that somebody physically read his source to Karajou. Presumably because kara was too pissed to read it himself. --PsyGremlinHable! 10:36, 23 August 2012 (UTC)
Didn't even notice this until now, after making said demand, he promptly blocks him. God, it must be nice to win arguments at the click of a button. --Revolverman (talk) 11:06, 23 August 2012 (UTC)PsyGremlinSpeak! 11:19, 23 August 2012 (UTC)
I honestly have trouble imagining him to admit to being too heavy-handed these days. I suppose he sobers up on occasion. Phiwum (talk) 14:59, 23 August 2012 (UTC)
- Does it seem to anyone else that with JPratt pretty much MIA, Popeye has taken it upon himself to take up the slack in the being a complete idiot department? --JeevesMkII The gentleman's gentleman at the other site 21:10, 23 August 2012 (UTC)
- Definitely. The corollary to that is that Popeye's reaction to a JPratt comment is to repeat "Yeah man" through froth-flecked lips whilst banging his head against the soft furnishings in his room. rpeh •T•C•E• 21:25, 23 August 2012 (UTC)
- Can you imagine how long this guy would have lasted on Wikipedia if he didn't get banned over what happened with Ed Poor? There would be no end to his edit warring. Even providing cited sources would be hopeless, as you'd have to buy your peer reviewed articles for him (nevermind the fact that he has in the past claimed to have access to a college's database of journals....speaking of which, maybe someone with a sock to burn could bring this up?) WilliamR (talk) 21:34, 23 August 2012 (UTC)
- Meh, the Koward was never in the running for sysop at WP so it's all immaterial. Also, he probably does have college access to journals. I think that I am correct in assuming that as an ex-serviceman he gets tax-payer funded further education Somehow that doesn't count as liberal sponging. Effing hypocrite. Lily Inspirate me. 21:45, 23 August 2012 (UTC)
- Karajerk is indeed sucking at the government teat when it comes to his education. Even more bizarre, he's apparently studying anthropology and archeology at LSU. Not sure how he equates that with being a YEC fuckhead? Maybe he yells at his lecturers and tells them they're wrong if they come up with a date older than 6,000 years ago. --PsyGremlinTala! 09:46, 24 August 2012 (UTC)
- Well, many YEC wingnuts take geology courses so that they can then brag about their credentials, but they're already so cemented in their mindset that they won't waver. They'll just parrot enough of the course material back for the benefit of the examiners and then revert to the party line but with added ORTHORITTEE!
Генгисevolving
11:11, 25 August 2012 (UTC)
- Perhaps its an act, and he really isn't anything but a bully, and just licks Andy's asshole because he gives him a place where he can feel powerful? --50.98.213.233 (talk) 09:50, 24 August 2012 (UTC)
An aside[edit]
Found it funny - whilst searching for the Kool Aid / Flavor Aid debate, to find Ed the Moonie Cultist objectingimg to use of the words "mind control" and "brainwashing" in the Jonestown article. I guess it hit a little close to home. --PsyGremlinTala! 09:46, 24 August 2012 (UTC)
Karajou reading fail, part MXXXLVIII...[edit]
NOt exactly a surprise that Karajou would take a hateful screed and promote it as truth without a cursory reading of the original source. Turns out that while the DOJ and other Federal offices are being instructed to try to hire more disabled people, this sentence in the document Karajou's source links to is curiously ignored:
- "A qualified individual with a targeted disability is a candidate who, based on his or her background, skills, and experience, would have been otherwise appropriate for selection for interview, with or without a disability."
So while having a targeted disability gets you right to the front of the hiring queue, you'd have to be able to do the job in the first place to score an interview. Classy as always, Karajou. --DinsdaleP (talk) 18:21, 23 August 2012 (UTC)
- I'm sure his fellow veterans support his anti-disability stance, because no ex-servicemen are disabled.
ГенгисOur ignorance is God; what we know is science.
07:11, 24 August 2012 (UTC)
- "have to be able to do the job" is tricky though. One of the things we really, honestly see in my profession is that most non-senior jobs will get a high ratio (sometimes more than 90%) of applicants who cannot do the job. They have paper qualifications and a glowing CV but I mean simply that they are unable to do the actual job, they aren't remotely capable of the core task for which they would be hired. We now use screening, but if you don't know to do that (or more likely if your work isn't suitable for screening) then you would have to interview these useless candidates as we used to. There's no reason to think that disabled candidates would magically reduce that number from 90% so that means more often than not the disabled candidate who jumped the queue is useless. How many times can you interview and reject such candidates before your management conclude that you're discriminating and require you to just hire the next one based on their paperwork? 82.69.171.94 (talk) 08:53, 24 August 2012 (UTC)
- Wouldn't that be the Peter Principle?
ГенгисIs the Pope a Catholic?
17:09, 24 August 2012 (UTC)
- Not really, no. The Peter Principle is when Bob, who is a perfectly good mechanic, gets promoted to manager, at which he's no good, usually because there is no mechanism for career advancement or salary increases outside of promotion to a different role. That's a problem with an organisation, it's not really Bob's fault that this happened to him. Whereas what I'm talking about is when we advertise a job for a Java programmer, we will get a large number of external applicants who cannot in fact write programs in Java. It's as if Bob quit his mechanic job and specifically went out looking for a job as a manager even though he's no good at that. Dunning-Krueger might have something to do with it, or some other cognitive problem in the incapable, or maybe they're just lying. It doesn't really matter to an employer which is the case. 82.69.171.94 (talk) 17:53, 25 August 2012 (UTC)
Piers Morgan is a liberal?[edit]
Um...yes, he is. If editing the Daily Mirror wasn't enough, he gave the paper an anti-Iraqi invasion position. London Grump (talk) 23:45, 23 August 2012 (UTC)
- So is Ann Coulter, Rush Limbaugh, and Sean Hannity according to Andy.
- Yes, but LG's point is that even by usual standards he'd be a liberal, making the comment seem odd. 81.137.227.129 (talk) 11:43, 24 August 2012 (UTC)
- That CP page has never existed. Was the unnamed editor being ironic, or has Andy called Coulter and Limbaugh liberals? --PsyGremlin講話 11:48, 24 August 2012 (UTC)
- Is that page's lack of visibility because CP is so futzed right now? (Okay, CP is always futzed, but this time, the reason is technological.) MDB (the MD is for Maryland, the B is for Bear) 11:58, 24 August 2012 (UTC)
- Maybe, but there's nothing in the logs for it either. --PsyGremlinTal! 12:04, 24 August 2012 (UTC)
- I saw in the logs that Andy created a page titled "RINO Backers" (or "RINO backers"?) yesterday, to list persons who were not RINOs but reacted against Akin's stupid claims. I saw it yesterday, but didn't bother to view the page. So, I suppose that the unsigned link noticed those three names were listed on the page and the page has since been unexisted. Phiwum (talk) 14:07, 24 August 2012 (UTC)
- Something is terribly borked over there. From what I see, only three edits occurred at CP yesterday, at 00:01, 00:40 and 00:45. I guess that August 23, 2012 just didn't really happen. Phiwum (talk) 14:15, 24 August 2012 (UTC)
- We'll have to wait until CP is less borked to find out for sure. --PsyGremlinZungumza! 14:17, 24 August 2012 (UTC)
- There are thirty-three missing hours in the logs. I'm not sure if it will become less borked. And I wouldn't be the least bit surprised if addle-brained User:Conservative was ultimately behind this lost day. That, or God. Mean ol' son-of-a-gun. Phiwum (talk) 14:36, 24 August 2012 (UTC)
- Looks like the article in question went west during The Day That Wasn't. Also, with Ed driving off August, there's not much chance that Andy will be able to recover the info this time. --PsyGremlinPrata! 14:39, 24 August 2012 (UTC)
- Insistence that data be recoverable is a liberal value. True conservatives know that God remembers everything. MDB (the MD is for Maryland, the B is for Bear) 14:47, 24 August 2012 (UTC)
- What happens to
socksaccounts that were created yesterday, the 23rd? C®ackeЯ 14:54, 24 August 2012 (UTC)
- Sorry, that was me who forgot to sign that reply. If you look at the new RINO Backers page, Andy has Coulter Limbaugh, and Hannity on the RINO side, which is just another word for liberal in Andy's mind. I am not shocked by Andy's support of Akin, given his and his mother's view on rape and women in general.--BMcP - Just an astronomy guy 20:59, 24 August 2012 (UTC)
Todd Akin - now a mystery[edit]
The GOP's party bosses are behind the bullying of Akin.
Good to see that Andy is sticking to the line that rape doesn't cause pregnancy, and defending it in his own batshit revolting way. --PsyGremlinZungumza! 12:40, 24 August 2012 (UTC)
- Perhaps Andy is beginning to realize what I realized ages ago: the GOP's leadership doesn't give a damn about social conservatives' issues; they just want their votes. And they have those votes so locked up they'll treat their social conservative members like shit if need be. MDB (the MD is for Maryland, the B is for Bear) 12:44, 24 August 2012 (UTC)
- Does andy know that in 31 states, Rapists can sue for custody of their victim's children. Or does that not happen, and these women being sued for custody by their CONVICTED rapists are just illusions? --
GodotIz a sekret Kristian 17:09, 24 August 2012 (UTC)
- WHAT?! That is seriously fucked up. So a convicted rapist can sue for custody of a child, but let a gay couple try and adopt... PsyGremlinParla! 17:23, 24 August 2012 (UTC)
- Citation needed.
- How many have actually managed to get custody? MDB (the MD is for Maryland, the B is for Bear) 19:05, 24 August 2012 (UTC)
Dumb question[edit]
If Andrew Schlafly's "Homeschool" is the pooled efforts of several teachers, he teaches classes over 30 kids, and it's in a church basement... is it even homeschooling at that point? It sounds more like a parochial school with no oversight. --TheLateGatsby (talk) 16:00, 24 August 2012 (UTC)
- It is, but because he gets to lead the class in prayer before feeding them his bullshit. Remember, prayer is more important than knowledge for Andy. --PsyGremlinParlez! 16:06, 24 August 2012 (UTC)
- Well, I believe it's 2 hours once a week, so it's pretty hard to call it "school" in any meaningful sense. I think this sort of endeavor isn't uncommon for homeschoolers, albeit with a less batshit insane instructor. Also, is it the pooled efforts of several "teachers"? I though it was at least 90% Andy. DickTurpis (talk) 16:41, 24 August 2012 (UTC)
- Andy has a rather, what should I say, "liberal" view of what constitutes home-schooling. Basically it can be anything that is not state-funded education, although he did apply for a government grant at one time.
ГенгисIs the Pope a Catholic?
16:57, 24 August 2012 (UTC)
- To be regulated as a "school" in Colorado, you need to meet with the students more than 1/2 time (I think fully time is 38 hours, but I could be wrong) and have more than 7 students. Otherwise, it can be framed as "tutoring" or "supplementation" or "specialized classes". The University of Boulder has a program for kids who are homeschooled, that teaches them languages, or advanced sciences, or advanced math. I'm sure that's how Andy's "school" is regulated.--
GodotIz a sekret Kristian 17:07, 24 August 2012 (UTC)
- Didn't we send off for some sort of care package to the NJ Department of Education was considering an application from Andy? Theory of Practice "Trampoline" is an Olympic sport now? 17:17, 24 August 2012 (UTC)
- Thank you all for explaining. That's pretty disturbing. --TheLateGatsby (talk) 17:21, 24 August 2012 (UTC)
- @TOP Yeah, I did. I imagine it probably got nuked during the great purging of the CP namespace. Occasionaluse (talk) 18:57, 24 August 2012 (UTC)
- File:SES_Application-0001resize.jpg Occasionaluse (talk) 18:59, 24 August 2012 (UTC)
- Notice how Andy says the learnin' will take place at a school, not a church. I think I remember something about him switching from church basement to school basement. Occasionaluse (talk) 19:02, 24 August 2012 (UTC)
- No, that was just Andy bullshitting. He doesn't have a venue that can satisfy New Jersey's SES requirements, so he just handwaved that the teaching would take place in schools. That whole incident was hilarious. --JeevesMkII The gentleman's gentleman at the other site 19:58, 24 August 2012 (UTC)
Has Thrustbuttocks given the game away?[edit]
An interesting insight into Terry Thrustbuttocks' views. Here's a rant by Roseanne Insanitary about evilution on TT's blog. Go to the comments and note Thrustbuttocks' response to the second comment: "[USA Constitution Amendment] XIV: Much of that text was an act of cynical revenge." Note that this was the amendment which, in 1868, gave equal rights to blacks and penalised states which refused to comply. What Thrust says just looks like a rant about wicked politicians defying the will of the Founding Fathers but actually, what he's really objecting to is the idea that people with a different colour to his should have the same political rights. I think I know where he's coming from in his rants about Obama. The Real James Brown (talk) 20:07, 24 August 2012 (UTC)
- Interesting. I didn't actually have a clue what the 14th amendment was about and I didn't bother to check, but that information does light up a few bulbs. I'm not personally sure about Terry being racist though; he's certainly a religious bigot, but he appears to have at least one Arab friend.--Fergus Mason Thruppence I got for selling my coat, tuppence for selling my blanket. If ever I 'list for a soldier again, the Devil shall be my Sergeant. 20:37, 24 August 2012 (UTC)
- Arab =/= Muslim and I doubt that Terry has "friends" in the way that we might define the term.
ГенгисRationalWiki GOLD member
11:02, 25 August 2012 (UTC)
- If you're referring to that equally racist Bader Qarmout, he's Jordanian Christian. And I doubt he's a friend. Terry latched onto his campaign (run by Unsanitary) so he could feel important again. Notice how Qarmout hasn't contributed to, nor been mentioned on, Terry's blog since he lost the primary. Hurlbut has no further need for him, so under the bus the raghead goes. --PsyGremlinPrata! 11:19, 25 August 2012 (UTC)
- Yes, that's the one I was talking about. So is Qarmout a full-on wingnut as well?--Fergus Mason Thruppence I got for selling my coat, tuppence for selling my blanket. If ever I 'list for a soldier again, the Devil shall be my Sergeant. 16:14, 25 August 2012 (UTC)
- I think that's a yes-and-no answer. Yes, he ran on a Tea Party platform, with Roseann Insanitary as his campaign manager. However, he was also in favour of granting amnesty to illegals, something with apparently sent Roseann spare. Also, it seems fellow conservatives were less than enamoured with Qarmout. He was also associated with Col Manly Rash, aka Gene Hoyas. --PsyGremlinHable! 13:51, 26 August 2012 (UTC)
- Nope, Terry is blatant with his racism, as can be seen from this poll he added.
- As you can see, the two options are:
- Agree. Obama has betrayed those he promised to serve.
- Disagree. Obama is doing exactly what the country, and black people, need.
- Nope, not racist at all. --PsyGremlinParlez! 10:05, 25 August 2012 (UTC)
- That's not even his most blatant. Nebuchadnezzar (talk) 16:20, 25 August 2012 (UTC)
- I can only attribute his shockingly bad faith (not just poorly researched for a "journalist") attack on Obama for Congress' removal of "Advice and consent" requirements for a few non-key positions to racism. Other presidents have done this far more. The disgusting part is that he uniformly misrepresents the effects of the statute by misnaming positions, etc., solely to tar Obama as seizing "kingly power." When I challenged him to either correct his essay or simply remove it because it's irredeemably fucked, he started 86'ing my posts. What a hatchet job. What a scumbag liar. How can one exult so stridently in a program of deceit? Is that a traditional xtian or "conservative value"?
16:30, 25 August 2012 (UTC)
- Terry's also got a pretty clear history of racism closer to home, against them damn illegals and anyone who looks even vaguely like them. Part of that is his knee-jerk fandom of whoever the far right decides is a golden boy, so Sheriff Joe's racist acts become A-OK in his books, but that's clearly not all of it. He just doesn't seem to care for Latinos in the first place. --Kels (talk) 16:50, 25 August 2012 (UTC)
- I don't understand why Andy tolerates him. I thought that genuinely not being racist (qv hero-worship of Clarence Thomas) was one of Andy's few creditable character traits. The Real James Brown (talk) 21:44, 25 August 2012 (UTC)
The GOP not conservative enough for Andy[edit]
Now that the RINOs have had a power grab that "marginalises social conservatives and Tea Party folks like Todd Akin."
I wonder if we'll be getting a breakaway wingnut party after Romney loses? Also, it's called "damage control," Andy. Unlike you, who thinks the best way to put out flames is to add petrol. --PsyGremlinTal! 14:40, 25 August 2012 (UTC)
- Petrol is nourishing and good for the environment. The Real James Brown (talk) 14:58, 25 August 2012 (UTC)
- Whilst I'd love to see a breakaway party, I doubt it's going to happen. There are now two parties within the Republicans: Teabaggers versus the old fiscal Conservative types, but both sides will claim to represent the "real" GOP. Over the past few years, there's been a steady shift to the former, which has led the more reasonable GOP members to switch parties (Arlen Specter) or just quit (Olympia Snowe).
- This election is going to be largely boring. I know things look close at the moment, but Obama will crush Romney. The interesting bit will be what happens next: does the GOP shift right or left? If it goes right, it'll be out of power for a generation. If it goes left, it could well win in 2016. rpeh •T•C•E• 16:39, 25 August 2012 (UTC)
- I don't get it. You people can reach CP today? It's been unreachable for well over 24 hours for me. Phiwum (talk) 17:12, 25 August 2012 (UTC)
- Methinks Karajerk is tired of being made fun of, so he's ranging blocking the planet. Odd how conservatism is so powerful that only certain people can be exposed to it, it's like nuclear waste in that regard. Shame Capturebot is off on one her little benders at this point in time though. -- Iscariot Andy Schlafly for Congress 2012! 17:36, 25 August 2012 (UTC)
- It was slow earlier but it's fine now. rpeh •T•C•E• 17:46, 25 August 2012 (UTC)
- Think Johnny Sedition will be calling for a Teabagger "secession" soon? Nebuchadnezzar (talk) 17:54, 25 August 2012 (UTC)
- Ah, that's it, Iscariot! I hadn't bothered to check, but my phone can load Conservapedia while my computer cannot. Phiwum (talk) 20:15, 25 August 2012 (UTC)
Ed tells it like it is.[edit]
Respect my authority. I am a professional. Theory of Practice Haters gonna hate. 20:03, 25 August 2012 (UTC)
- Ah, Ed does teaching writing too. Is there anyone on CP who doesn't? --JeevesMkII The gentleman's gentleman at the other site 20:08, 25 August 2012 (UTC)
- That quote that praises him is anonymous. How pathetic can he get? lol
NorsemanCyser Melomel 20:44, 25 August 2012 (UTC)
- "I know how to write encyclopedia articles" Bwahahahahahahahaha! Vulpius (talk) 21:08, 25 August 2012 (UTC)
- "it just so happens that nearly every word I type, link I create, article or template I start - gains instant and widespread acceptance" - by whom???!!! The Real James Brown (talk) 21:39, 25 August 2012 (UTC)
- Himself and the little demon that sits on his shoulder who must be having a whale of a time. --جئت ورأيت أنا القرف gross, isn't it? 23:07, 25 August 2012 (UTC)
- Here he is getting all pissy again. I like how he needs to remind everyone he is a 'senior admin' not once but twice. Oh and there is this gem, as well as throwing down some "I'm an expert with media-wiki, peasant". Ed Poor, what a guy. Acei9 23:56, 25 August 2012 (UTC)
- Isn't Ed on record (I think it's somewhere on Wikipedia) as saying that he can't write for shit? Didn't he say that's why he writes for free on wikis instead of being a published author? I guess that private school in New York didn't read that. It's also nice to see that Ed is still living in a parallel universe where Conservapedia is not a YEC site and respects all points of view.--Spud (talk) 04:44, 26 August 2012 (UTC)
- So, he's been hired to teach writing? Sounds like our great scholar was unemployed. I wonder whatever happened to his computer programming exploits?
Генгисevolving
08:04, 26 August 2012 (UTC)
- I'm guessing that by "private school" he means some Moonie kiddie indoctrination camp. Then again, it could also exist in his mind, like his non-existent wiki skills. Last I heard, Ed was working for customer services for some company that made some sort of eco-friendly scooter. --PsyGremlinSprich! 08:22, 26 August 2012 (UTC)
- Here we go. It's electric bikes. Although I see he's not listed on their website anymore, so maybe he quit. Maybe he didn't want to work for a bunch of global-warming advocates. --PsyGremlinSprich! 08:28, 26 August 2012 (UTC)
- Just looking at the original Ed post that created this thread, I'm counting at least 3 errors I'm 100% sure of (Misused colon, misused comma and poor sentence structure). There are a few more that if they aren't true errors, they certainly muddy up the writing..... The irony is strong in this one. SirChuckBI brake for Schukky 08:36, 26 August 2012 (UTC)
- Andy, Ken, and now Ed. Those who can, do. Those who can't, teach.
ГенгисIs the Pope a Catholic?
09:52, 26 August 2012 (UTC)
- Psy, that didn't look too much like Ed in the photo. Maybe this was just someone else with the same name? Phiwum (talk) 12:49, 26 August 2012 (UTC)
Conservapedia down for 64.180.243.0/x?[edit]
I still can't get to CP, but with a proxy, everything loads fine. Did Andy block me on a server level?RandonGeneration (talk) 18:02, 25 August 2012 (UTC)
- I had problems a couple of days ago (as did others) but it works fine for me now. However, Andy has implemented server side blocks in the past on IPs that have been clickbotting.
Генгисunbelieving
18:55, 25 August 2012 (UTC)
- Oh so you're brenden. Nice editing, comrade. 108.166.185.165 (talk) 21:01, 25 August 2012 (UTC)
- Well, my IP address is certainly blocked, and I doubt that it's due to anything that I've done. I don't clickbot, nor register accounts on CP, but only read the madness and discuss it here. Maybe someone in my IP neighborhood pissed off Karajou or whoever has gone off the deep end. (Since my home IP address is static, not much to do aside from viewing the site from the phone.) Phiwum (talk) 21:09, 25 August 2012 (UTC)
No mention of Armstrong?[edit]
I first heard about it about 5 or 6 hours ago and I had to wake up to find out about it. It is a pretty glaring omission. I suppose it is result of chasing all editors away no one is around to update the place. - π 04:34, 26 August 2012 (UTC)
- What would you expect them to say? Something about overated astronauts? Peter Rapidly running out of marmite 04:49, 26 August 2012 (UTC)
- I'd say that Andy has not yet made up his mind if Armstrong was a great Conservative Christian hero or a filthy godless liberal. No doubt he'll
do some researchflip a coin and decide.--Spud (talk) 04:54, 26 August 2012 (UTC)
- Considering all the other batshit craziness CP endorses, I wouldn't be terribly surprised to see them embrace the moon landing hoax conspiracy. I guess the fact that it sort of diminishes an American accomplishment makes them balk. If it had been the Soviets who made it to the moon they'd dismiss it in a heartbeat. DickTurpis (talk) 04:58, 26 August 2012 (UTC)
- Apollo 11 wasn't just a huge leap for mankind, it was a very nationalistic moment, so this is strange.
- What's their opinion on NASA again? Osaka Sun (talk) 05:15, 26 August 2012 (UTC)
- ]."[1] Armstrong is clearly part of the AGW hoax, smear him! Nebuchadnezzar (talk) 05:22, 26 August 2012 (UTC)
- (EC)At the moment Conservatives love NASA and blame Obama that there is no replacement for Space Shuttle and the US has to rely on foreign countries to get astronauts into space. CP I don't knoe their particular position. @PeterL, I would expect them to say something, at least an RIP. - π 05:23, 26 August 2012 (UTC)
- I see that in the past 24 hours the Wikipedia article about Neil Armstrong has had well over 500 edits (getting on for a thousand, I'd say) but the Conservapedia article has only had one. It looks like the Conservapedia regulars still neither love nor hate Neil but couldn't give a toss about him either way. I've been hearing all day that Armstrong gave very few interviews and I'm sure that he was quite careful not to reveal his views on politics or religion, to avoid becoming a divisive figure instead of a representative of all humanity.--Spud (talk) 12:31, 26 August 2012 (UTC)
- Last time I looked the WP article didn't mention his religion but a generic Goggle search suggested that he was "protestant".
ГенгисIs the Pope a Catholic?
14:09, 26 August 2012 (UTC)
- Oh, and very surprisingly there's been no mention of the other Armstrong either.
ГенгисOur ignorance is God; what we know is science.
14:10, 26 August 2012 (UTC)
- Or the other other Armstrong. C®ackeЯ 17:59, 26 August 2012 (UTC)
- Or the other other other Armstrong. --Night Jaguar (talk) 19:54, 26 August 2012 (UTC)
The Unhinged, starring CP sysops.[edit]
So just looking at recent changes...
- Conservative reverted and oversighted in the community portal, a fantastic example of abuse to hide abuse.
- Karajou's blocks are becoming more volatile, being freely able to call users idiots and morons (SamCoulter's really getting under his skin, teehee).
- Ed Poor keeps returning after several days/weeks of inactivity just to push people around, and AugustO appears to have given up on Andy's lengthy "review".
- With their support of Todd Akin, CP throws even the most right-winged fools under the bus. They have little to support, but everyone else to hate.
At this point, all users would do is ask "what would you do if Obama wins?" and expect them to go off like that Texas judge did, calling for arms or something. You'd usually see one of these things happening at CP, but it's all colliding at once like a 8-way train junction.
NorsemanCyser Melomel 13:40, 26 August 2012 (UTC)
- ...I'm actually kinda surprised that the Community Portal still exists. --Sid (talk) 16:26, 26 August 2012 (UTC)
- I'd love to see Andy and his Get Along Gang mounting up for the civil war. It'd be like a LARP, minus costumes, weapons and any kind of connection with reality. I suspect as well that this could be Ken's first view of sunlight in quite some time, and welcome relief from his bed sores and frenzied masturbation. Concernedresident omg!!! ponies!!! 16:44, 26 August 2012 (UTC)
Media Bullying[edit]
A term allegedly coined by Andy and in use exactly nowhere else is suddenly a Best New Conservative Word. --PsyGremlinTal! 14:46, 26 August 2012 (UTC)
- Hilariously, the closest cousin to this term/usage that I personally have seen actually comes from tweenagers crying on fanfiction forums, "IF YOU DON'T HAVE PRAISE FOR MY STORY DON'T SAY ANYTHING AT ALL." The thing is that when one presents an idea 'in public' it's like putting one's best foot forward. It's like stepping on stage. If you step on stage covered in fish guts and garbage, no critic should be blamed for saying that you stink. That's not bullying; asking special privileges to be accepted and not judged doesn't fly in a reality where people are constantly evaluating ideas. It's not done with some kind of LIBERAL GOAL. If something stinks, then people will comment on it.±
KnightOfTL;DRlavishly loquacious 14:55, 26 August 2012 (UTC)
- Coined by CP in 2008? I'll be generous and not count "social media bullying", but still, a quick search gives me for example this site from 2007, this one from 2002 (using the Waybackmachine to prove the date), and let's add this 2003 piece for good measure. Yep, FIRST COINED BY CONSERVAPEDIA! --Sid (talk) 16:23, 26 August 2012 (UTC)
- Things like this make me sort of wish Rommney would win. If Obama (likely) wins, It's four years of Andy ranting about how the RINOs doomed the US to whatever boogie man he comes up for a given week. If Mittens pulls it out, and he does purge the Tea Party from the Republican Core like I have to suspect he will, Andy will have NOTHING left. --Revolverman (talk) 18:03, 26 August 2012 (UTC)
- And did you know that the postponement of the Republican Convention is the result of media bullying, not because some clot arranged to hold it in Florida in the hurricane season? The Real James Brown (talk) 20:43, 26 August 2012 (UTC)
- Andy can't even get that right, he keep saying that the first 36 hours have been cancelled even though his source says postponed. Lying? Or does he really not know the difference?--BMcP - Just an astronomy guy 03:04, 27 August 2012 (UTC)
- That gives me an idea for a new SCP23.16.216.193 (talk) 04:02, 27 August 2012 (UTC)
- Do tell, dear anon. ±
KnightOfTL;DRmore at 11 21:44, 27 August 2012 (UTC)
Huh?[edit]
Can somebody explain to me what Conservative is on about here? I'm not sure if he is trying to get a point across of if this is a bot putting random sentences with words from the news together. There'as digital cheese at the end of this labyrinth of words! --K. (talk) 12:24, 27 August 2012 (UTC)
- It's basically Ken on one of his anti-science rants. Private companies can expect to bring in plenty of money by ferrying people with too much money into space, but NASA just does science and that doesn't turn a profit (and shows a love for evolutionism and a hatred of God), so therefore their budget needs to be slashed and given to the Creation Museum.
- Or something.
- Conservapedia - where the illiterate main page is enough to scare away prospective browsers. --PsyGremlinPrata! 12:40, 27 August 2012 (UTC)
- I think he's pissed because someone on the talk page said something about how the "In the news" section is full of stupid blog links instead of, say, something abou the passing of Neil Armstrong, so he figured he should dance on his grave out of spite. Seriously Ken, get some help. Carlaugust (talk) 12:44, 27 August 2012 (UTC)
- Oh, so it's basically "Kill them! They are libruls!". I guess I was looking for reasoning were there was none to expect. --K. (talk) 12:47, 27 August 2012 (UTC)
- Just wait till John Glenn passes. He had the colossal nerve to be a Democrat. MDB (the MD is for Maryland, the B is for Bear) 13:34, 27 August 2012 (UTC)
- Aaaannndddd.... it's gone.img --PsyGremlinSprich! 14:58, 27 August 2012 (UTC)
- I had this debate with him interestingly. NASA actually paid back the entire cost of all previous programs, plus a lot of interest, somewhere around 1980. Not to mention that a great deal of the money was actually paid to contractors such as Boeing. He doesn't listen to anything. Ayzmo (talk) 16:39, 27 August 2012 (UTC)
- The links are so worth purusing. My fave is Unreasonableness of Young Earth Deniers. There are two theses put forward: 1) Young Earth Deniers don't object to Jesus's turning water into wine because it's unscientific, so they're inconsistent and hypocritical, and 2) YED's insist on repeating the myth that the Church persecuted Galileo, when it was really liberals. Whoover (talk) 21:35, 27 August 2012 (UTC)
- Ah yes, Europe was awash with atheistic scientists at the beginning of the 17th century.
ГенгисYou have the right to be offended; and I have the right to offend you.
22:14, 27 August 2012 (UTC)
- Not to mention the fact that those 17th century atheistic scientists have yet to answer the 15 questions and are being cowards by not debating Cockofgod. The 17th century lacked machismo! Ole! Hiphopopotamus (talk) 22:43, 27 August 2012 (UTC)
- There's a certain cleverness in adopting the term "Young Earth Deniers". It makes it sound as if believing in an old earth (i.e., doubting that the earth is young) is just as unscientific as doubting that the holocaust took place. It's a cute way to turn it around and pretend that science is on your side. Phiwum (talk) 02:37, 28 August 2012 (UTC)
- I love how he potshotted at "extraterrestrial life", which, just like evolutionary theory and the 13.7Byo universe sciences, have been accepted by the abortion-hating, contraception-despising RCC. -- Seth Peck (talk) 15:58, 28 August 2012 (UTC)
Ugh.[edit]
I thought it would be creepy Uncle Ed, but Popeye takes the crown of the most revolting man on CP by promoting the most revolting man in the universe. These fuckers revolt me. Scott Lively is frankly a murderer, and the people who promote him are hate-filled shitbags with no conscience or sense of decency. Fuck you, fuck you all at Conservapedia. Stop being fucking arseholes. Just stop. --JeevesMkII The gentleman's gentleman at the other site 08:22, 28 August 2012 (UTC)
- So, as opposed to the "Fuck off, I'm a senior editor" guy it's the one who just leaves it at "Fuck off". I'm not checking that WND page, because if I end up reading it out loud as I sometimes do, I fear my minor intestine will leap through my body and strangle me to death. The headline is enough for me. Now, is Scott Lively literally a muderer or am I missing something here? --جئت ورأيت أنا القرف gross, isn't it? 11:09, 28 August 2012 (UTC)
- We really need a term for the nutter train of thought that homosexuality is the only cause of anything bad in the universe... Pink-batting? --Revolverman (talk) 18:52, 28 August 2012 (UTC)
- I'll get to work thenRandonGeneration (talk) 19:03, 28 August 2012 (UTC)
Where to begin...[edit]
... when it comes to this entry of Ken's on MPR.
- Gannett presumably owns the News-Leader, but they do not "produce it's web site", at least not in the sense that they're directly responsible for it's content.
- The fact they published a letter to the editor does not mean they endorse it's content.
- Ken, are you so desperate to validate Conservapedia that you're quoting letters to the editor in small city newspapers?
MDB (the MD is for Maryland, the B is for Bear) 11:46, 28 August 2012 (UTC)
- Why did Ken finish his post by saying that liberals are unable to find a single factual error in the Conservapedia homosexuality article. Citation needed, Ken! Allen Kemper, who sent that letter to the Missouri newspaper, doesn't sound much like a liberal. After all, he says he has an open mind and all good Conservapedians know that liberals are incapable of opening their minds.--Spud (talk) 12:53, 28 August 2012 (UTC)
- Googling his name leads directly to his Facebook page, where how open his mind is is available for all to see. He appears associated with some outfit that describe themselves as a "Procalimer of Truth". MrChris (talk) 13:44, 28 August 2012 (UTC)
- The "About" section of the Facebook page is just plain creepy: 'I have been saved according to Romans 10:13 since I was 8. I was baptized, that same year, and since then I have sought to be baptized and filled with the Holy Spirit, again and again to be a useful, and faithful love-slave of the Master! ' Also 'My good friends, Wayne Terrill, and Zach Dyer (also on Facebook) have worked with me in creating. This is a site dedicated to displaying, and distributing "Crafts With A Message". These prayed-over crafts, like prayer cloths can then be tools to drive out demons, and bring His Healings & Miracles to Bless, and Convert Unsuspecting People! Perhaps you know some godly, believing crafters who would greatly benefit?'. So, the ideal kind of person to give an unbiased assessment of Conservapedia's articles.. Cantabrigian (talk) 14:14, 28 August 2012 (UTC)
- I wonder if he's AK who has posted on the Homosexuality page and created a category Dutch People, Kemper is a Dutch name.
ГенгисIs the Pope a Catholic?
14:51, 28 August 2012 (UTC)
- I've been praying over the macaroni and glitter crafts I make on paper plates for years while I huff model airplane glue. Nothing.
14:56, 28 August 2012 (UTC)
Oh, so that's what God's realm on Earth will look like?[edit]
You know, like Russia! Yes, god's realm will give such wonderful things like restriction of free speech, beating of protests by police officials, murder of journalists for political reasons, mindless imperialism, protecting dictatorships, bribery of officials, patriotic conditioning of soldiers and of course punishment of the lazy! That's the spirit of the American constitution and what the founding fathers wanted! --K. (talk) 09:36, 29 August 2012 (UTC)
Launchbooty's Grand Plan[edit]
First found this on Pharyngula. It would appear that Terry is the secretary/treasurer of a group who wants to create a "museum" called Creation Science Hall of Fame near Cincinnati based on this website, (which is as far as the project has currently gone). The website itself rides the coattails of legitimate scientists such as Issac Newton, Johannes Kepler, and Sir Francis Bacon in an attempt to link Creationism to prominent scientists in the centuries before evolution, or even modern chemistry and geology existed, in order to attempt to tie science to their religious dogma. Hey Newton was also into alchemy and occultism, so I guess that means these also must be legitimate branches of science, amirite? The mind boggles. --BMcP - Just an astronomy guy 16:54, 28 August 2012 (UTC)
- I'd go. Just to see crap like this in 3-D -- from a Terry comment on the Galileo page (remember that Galileo had no disagreement with the Church, only with Aristotelian liberals) --
-.
- He's big on the Milky Way being "the Galaxy" because it's the one God cares about. Cue the Twilight Zone theme. Whoover (talk) 17:14, 28 August 2012 (UTC)
- This has been around for a while without going very far. Largely it seems like some sort of vanity project.
ГенгисRationalWiki GOLD member
18:37, 28 August 2012 (UTC)
- "We know now that the entire universe rotates about an axis that is not only parallel to but coincident with the axis of rotation of the Galaxy, and in the same direction." We do? From what I can tell, this notion of the universe spinning is an idea in physics but it is far from seen as definitive in any way. It was thought that such rotation explained the "Pioneer Anomaly" (until we found out it is just thermal radiation off the Pioneers themselves). The reason it is thought to be possible is due to the fact the majority of galaxies observed in the night sky towards the "galactic north pole" spin counterclockwise, (research is still being conducted to see if galaxies in the direction of the galactic south pole are spinning clockwise, in either case it still be on a small portion of the observable universe). An interesting idea, however even if it were true, it still wouldn't suggest the universe spins around the Milky Way, which is contrary to Hubble's law.--BMcP - Just an astronomy guy 18:49, 28 August 2012 (UTC)
- Wait. When they claim we're in "the galaxy", are we talking young-earth creationists here? I'm just trying to wrap my head around how they could reconcile our measurements of the universe, and how we make those measurements, with the belief that it's all only a few thousand years old. I guess it explains the hatred for relativity, at least... Q0 (talk) 01:12, 29 August 2012 (UTC)
- Creationists have been trying to reconcile the immense distances of the universe with their 6,000 year time frame for quite a while now, it is commonly called the Starlight Problem. Well most creations try to reconcile. Andy though will simply baulk at any distance written that is greater than 6000 light years from the Earth. That was my main argument with him when I wrote any astronomy article there, whether it be the Crab Nebula or the Andromeda Galaxy, anything that was listed as >6,000 light years was automatically suspect by Il Duce; who than proceed to edit out such distances.--BMcP - Just an astronomy guy 04:04, 29 August 2012 (UTC)
- You got to hand it to Andy. Most would twist, turn, spin, but not Andy, he'll just ram head first into the wall until it finally gives way. --Revolverman (talk) 04:26, 29 August 2012 (UTC)
- According to Andy the Starlight Problem is "a bigger problem for atheistic views, because those views cannot accommodate the explanation that some of the light in the sky is show for people on earth."img Also, the >6,000 light years is possibly the "distance artwork" of Godimg. Oh Andy, you're a gem. --Night Jaguar (talk) 05:59, 29 August 2012 (UTC)
- This is the same guy who believe the fact that leaves turn various warm colors in the autumn is sure proof that evolution is wrong because they are aesthetically pleasing for people to look at, which serves no evolutionary purpose; ergo the night sky is beautiful and such beauty would serve no purpose other than to be pleasing to the human eye, so why should those stars and galaxies really be those great distances instead of simply "painted" onto a huge 6000 light year radius black dome for our pleasure?--BMcP - Just an astronomy guy 13:24, 29 August 2012 (UTC)
- I'm sure you really meant to type (a)esthetically (beautiful) pleasing and not ascetically (avoiding physical pleasure).
ГенгисYou have the right to be offended; and I have the right to offend you.
14:16, 29 August 2012 (UTC)
- Yes, thank you. Stupid auto-correct :P --BMcP - Just an astronomy guy 15:53, 29 August 2012 (UTC)
- It's the religious basis for "truthiness." Once you accept that reality is comprised of tricks to test your faith or provide distance artwork, it's a small step to finding valuable alternate realities on your own. Like building a presidential campaign on Obama's elimination of a welfare work requirement, contrary to any evidence whatsoever. Or making a convention theme out of, "
If your business uses roads or other public infrastructureIf you have a business, you didn't build that." Reality is a canvas on which to paint righteous lessons. Whoover (talk) 20:28, 29 August 2012 (UTC)
- The existing Creation Museum is already near Cincinnati (as well as the Answers in Genesis office/sacrificial altar/mother's basement), so the location is probably not coincidental. -- Seth Peck (talk) 20:03, 28 August 2012 (UTC)
- So he wants to be California Adventure to AiG's Disneyland? --Revolverman (talk) 21:06, 28 August 2012 (UTC)
- Probably more like Adventure City. -- Seth Peck (talk) 21:14, 28 August 2012 (UTC)
- WOW, between Disneyland/CA, Universal, and even Knots Berry Farm on the outside... how is that place still running? --Revolverman (talk) 21:38, 28 August 2012 (UTC)
- Well, it is only $14.95... -- Seth Peck (talk) 21:43, 28 August 2012 (UTC)
- Well, budget prices is something you won't find in any of the big three, thats for fucking sure... --Revolverman (talk) 21:45, 28 August 2012 (UTC)
- Last time I saw the creation science hall of fame site it looked pretty much like it was abandoned, is this actually still a current thing or is this just Chuckarse's operation flying fortresses? --JeevesMkII The gentleman's gentleman at the other site 22:38, 28 August 2012 (UTC)
Someone noticed CP[edit]
Here. Nebuchadnezzar (talk) 01:11, 31 August 2012 (UTC)
Hey, Karajou[edit]
Do you realize that you're siding with the ACLU?
The linked Fox News story mentions the ACLU has gotten involved. Isn't that conservative kryptonite (conservanite?) MDB (the MD is for Maryland, the B is for Bear) 15:53, 29 August 2012 (UTC)
- ACLU also fights for gun rights. Conservatives don't like hearing this because it causes their faces to seize up, which can be inconvenient. ONE / TALK 16:04, 29 August 2012 (UTC)
- Do they? I don't remember that. Doesn't seem too consistent with their stated position either, depending on what you call gun rights. Have you any particular case in mind? Phiwum (talk) 17:41, 29 August 2012 (UTC)
- The ACLU says the right to bear arms is for militias not individuals. They do not fight for gun rights. How could you when Northwest Indiana and Chicago alone have more gun murders in a few weeks than all of Canada and Western Europe in a few years. Murder is not a conservative value but then again Conservapedia doesn't seem to have a problem with Catholics being called "pagans" so I guess I'm not conservative or Christian after all. Nate Keaton (talk) 12:56, 30 August 2012 (UTC)
- Their stated position is interesting; I hadn't read that. It seems the national organisation acts differently to state chapters of the ACLU, which regularly defend gun rights. In Texas they defended the right of gun owners to keep guns in their cars without being prosecuted for unlawfully carrying guns. In Florida they defended the rights of a gun-owner who had his guns taken away from his home by the police. A similar thing in Rhode Island. Here's one in Nevada. ONE / TALK 15:39, 30 August 2012 (UTC)
- I suspect the ACLU are concerned about these laws more for how they will be policed, enforced, and prosecuted. That is they will be used disproportionately against blacks, similar to the selective prosecution for drug posession. Pi 3:14 (talk) 22:51, 30 August 2012 (UTC)
- Well, in the examples I give, the first and last are general lawsuits/statements, the second is on behalf of a Jewish guy, and the third is on behalf of a Hispanic guy. So I would say your suspicion is unlikely, though certainly possible given my small data set. ONE / TALK 17:08, 31 August 2012 (UTC)
- Addendum: apologies for the sources; some are clearly biased and I haven't checked them out. But since they're conservatively biased, I assume they're pretty reliable when describing the ACLU doing something they actually agree with, so I assume they check out. ONE / TALK 15:42, 30 August 2012 (UTC)
- Er, Nate, I understand that Chicago is a pretty violent place, but could you really back up your claim? Do you mean that there was one particularly "few week" period in which the number of gun murders there was more than a few years that of Western Europe and Canada combined? Do you mean that this regularly happens? HuffPo reports 228 homicides in Chicago from 1/1 to 6/16/2012. Supposing that double that occurred in the area you're speaking of, the average per week would be roughly 456 / 27 \approx 17. Is it really the case that Canada + Western Europe produces fewer than 60 gun murders per year? (Hint: Canada's recent very low figure for 2010 was 554 murders. I'll bet the bulk of them occurred with a gun.
- No offense intended, but I sincerely doubt your claim. I'd be interested if you can back it up. Phiwum (talk) 16:30, 30 August 2012 (UTC)
- I was wrong about the several weeks remark. For some reason I thought I heard on the radio that Chicago had that astonishing number of murders. August was a record month but nowhere near what I said. There were 346 murders through the beginning of August this year and the estimate is that 75% were gun murders. So that's 242 and the year isn't up. Just back of the envelope calculations here: for Canada all I could find looking quickly was there were 598 homicides in 2011 and the estimate is that 30%, or 179, were gun murders. So I think over in Chicago they've got about as murders per year as in Canada and Western Europe. Sorry for the mistake there. I don't why I thought I heard that silly number. Nate Nate Keaton (talk) 18:34, 30 August 2012 (UTC)
- Okay, fair enough. I'm stunned that only 30% of Canadian murders were gun murders. Well, so we're more efficient than Canadians. You surely can't fault us for that. Phiwum (talk) 19:08, 30 August 2012 (UTC)
- I wanna take a quick sidebar here and note that one of the reasons why Europe has low homicide rates (and numbers) is not just that we have stricter gun control laws, but also that we don't have street gangs and with that no gangbanging or territorial conflicts between those (although there are small pockets of Latin American gangs expanding to Spain). --K. (talk) 21:59, 30 August 2012 (UTC)
- I wanna tell you that you're talking total bullshit if you think there aren't gangs in Europe. FFS, what kind of peril-sensitive sunglasses are you wearing? rpeh •T•C•E• 22:05, 30 August 2012 (UTC)
- I laughed out loud Rpeh. Had those before Blueblockers back in the day. Nate Nate Keaton (talk) 03:15, 31 August 2012 (UTC)
- Do you know the difference between gang and street gang or should I explain that? --K. (talk) 10:59, 31 August 2012 (UTC)
- Yes, you should explain that. ONE / TALK 17:03, 31 August 2012 (UTC)
- A gang is any kind of criminal organization, while a street gang is a gang in an urban setting. Street gangs are dominated by by younger criminals (in contrast to example mafia organisation or biker gangs). Apart from that the difference is largely in style, mafias and biker gangs try to stay under the radar of the police, they don't drive around other neighbourhoods and randomly shoot people they think might be from another gang.
- Of course saying that there are no gangs in Europe is BS, that's the reason I didn't say that. --K. (talk) 17:30, 31 August 2012 (UTC)
- Oh I *see*. The problem is simply that you don't know what the fuck you're talking about. Now I realise that I can ignore you with a clear conscience. rpeh •T•C•E• 23:24, 31 August 2012 (UTC)
- I ought to clarify that a bit. You're basically saying we have no freeway crime in Europe because we don't have freeways. Excluding the Mafia from gang-related crime is fucking stupid and introducing "street" as a prefix changes nothing. rpeh •T•C•E• 23:26, 31 August 2012 (UTC)
So Canadian murderers are ice-hockey-mask-wearing, knife-wielding maniacs? That country all of the sudden sounds way worse now that I know it's filled with Jason Voorhees's. Carlaugust (talk) 19:35, 30 August 2012 (UTC)
- If I recall correctly, most of the non-gang related murders were carried out with poisoning in Canada.
- Enjoy your Molsons buddy. --Revolverman (talk) 20:35, 30 August 2012 (UTC)
Breaking news![edit]
Kendoll got a follower on twitter! That's the whole thing. I'm not kidding. Conservapedia just redefined pathetic. --JeevesMkII The gentleman's gentleman at the other site 10:52, 30 August 2012 (UTC)
- Great grief, that's bad. Oh, and BTW Ken, please learn the difference between "Your" and "You're". rpeh •T•C•E• 11:00, 30 August 2012 (UTC)
- My belief that Kenny is the type who screams at the emmental in Wal Mart has just been torn down. It has got to be the stilton. --جئت ورأيت أنا القرف gross, isn't it? 12:15, 30 August 2012 (UTC)
- Nah, Venezuelan beaver cheese. MDB (the MD is for Maryland, the B is for Bear) 12:38, 30 August 2012 (UTC)
- My schizophrenic cousin does this word-salad stuff when he doesn't take his medication. This usually happens a few days before someone has to go bail him out of county lockup. I know how my cousin's illness affects our family, sometimes being very suddenly disruptive, and that's with 22 cousins nearby giving as much support as we can. It doesn't look like "Conservative" has a very good support network to help him with whatever his problems are and he does have serious problems. It is simply astonishing to me that nobody as Conservapedia wishes to help him by at least by cutting him off from embarrassing himself and Conservapedia on the front page blog. Nate Nate Keaton (talk) 12:40, 30 August 2012 (UTC)
- Three thoughts:
- I've never been sure Ken is truly mentally ill, or just weird.
- Andy et al could just view Ken as zealous, not mentally ill.
- Andy trying to get Ken to seek help would require Andy to admit he was seriously wrong about Ken, and we know that won't happen.
- MDB (the MD is for Maryland, the B is for Bear) 12:59, 30 August 2012 (UTC)
- There is evidence for 1. But you need to be a crazy-ass creepy stalker-fuck to find it. So it's not discussed or documented.
d hominem
13:03, 30 August 2012 (UTC)
- Am I missing something? Ken posted something in the news section that is most definitely not news. Not the first time he's done that. Remember when he posted the "news" that he got a near perfect score on a vocabulary testing website? It's not as if he wrote something random like "Cluck cluck cluck jabber jabber jabber. My old man's a mushroom" on the main page. In short, it would be strange behaviour for most wiki users but it's nothing spectacularly unusual for Ken. --Spud (talk) 13:45, 30 August 2012 (UTC)
- Oh god.... how the fuck is it that even now, Ken finds new ways to blow my mind as to how utterly pathetic he really is. If Andy lets this stay up on the main page he may as well get a sex change and formally rename himself as Mrs Demeyer. Judge HoldenThe Judge Smiles 17:46, 30 August 2012 (UTC)
- On the subject of the administration's opinion on Conservative, check out the leaks. Before he was admitted into the group, the other administrators questioned Conservative's "Jekyll and Hyde complex."
- The quote in question , for reference:
- "Ken DeMyer is 45 and from Buffalo, New York. Remember troll and user KDBuffalo? Was KDBuffalo trolling against us before or after the Ratwikians claimed he was Ken DeMyer?
- If the above is true, then we got someone with a clear Jekyll/Hyde personality. If it's not true, then we've got one hell of an elaborate ruse going on. Either way, I am of the opinion that Conservapedia should not have to suffer this. Any thoughts on this?"WilliamR (talk) 18:03, 30 August 2012 (UTC)
- Jesus wept. It's like Ed's live blogging of every vapid thought that strays through his mind. Coming next to the front page: a guy in the queue at Safeway tells Ken that he's not entirely sure about this whole evolution thing and that he needs to think it over. Concernedresident omg!!! ponies!!! 17:57, 30 August 2012 (UTC)
- How can you expect Andy or the other sysops to decide that Ken is mentally ill when they're all bonkers as well? Lily Inspirate me. 18:08, 30 August 2012 (UTC)
- A homicide detective and former atheist? Where does he come up with this crap?--"Shut up, Brx." 18:28, 30 August 2012 (UTC)
- Are you suggesting that an alleged homicide detective is any less an authority on evolution than a random dentist or an electrical engineer? Concernedresident omg!!! ponies!!! 21:20, 30 August 2012 (UTC)
- "Kendoll got a follower on twitter..." A whole one? You sure? Maybe it's a sock. Nebuchadnezzar (talk) 01:15, 31 August 2012 (UTC)
- I know what you really mean, but I'm just picturing a literal sock. Probably argyle. It's still only following him for the schadenfreude, though. --YossarianSpeak, Memory 18:48, 31 August 2012 (UTC)
I love Andy. He wears his heart on his sleeve.[edit]
Andy improves the Karl Rove article, now that Karl Rove is an unperson. Phiwum (talk) 02:05, 1 September 2012 (UTC)
- By the way, it's official now. George Bush's two term administration was "ultimately unsuccessful" (see above diff). Phiwum (talk) 02:06, 1 September 2012 (UTC)
- As I understand it, even Todd Akin has issued a half-arsed apology for what he said but Andy's still banging on about the RINOs who decided to gang up against a saintly defender of the unborn for no reason at all. Andy's determined to be the mad rabid right-winger who's too mad for other rabid right-wingers to go anywhere near, just in case he really has got rabies.--Spud (talk) 02:29, 1 September 2012 (UTC)
- If he's throwing Bush and co. under the bus now, what the hell is he even supporting anymore? Will he get so far gone that it becomes Andy VS Ever other group, idea, human on earth? --Revolverman (talk) 03:17, 1 September 2012 (UTC)
- Did anyone notice if Aschlafly (or Hurlbut) went to the RNC? --PringleMan 03:50. 1 September 2012 (UTC)
- Hmmm... Were the names of the guys throwing nuts at the black speaker ever released? --Revolverman (talk) 03:53, 1 September 2012 (UTC)
- I don't think so. Still, that doesn't seem like Andy's or Terry's M.O. Their racism is subtle, as in "anyone can join the country club, provided they meet the eligibility requirements...is it OUR fault no blacks meet these requirements?" --PringleMan 04:00. 1 September 2012 (UTC)
- Credit to Andy, I don't believe he is racist at all. ( one for, many, many against) Terry.... well Terry is a much different story. --Revolverman (talk) 04:02, 1 September 2012 (UTC)
- Yeah, from what I have seen, Andy may have many flaws, but racism isn't one of them. As nutty as Ken is, he doesn't appear to be the least bit racist as well. JPatt makes up the slack though.--BMcP - Just an astronomy guy 05:28, 1 September 2012 (UTC)
- Maybe you see racism to be a black and white issue. Just because Andy is not overtly racist doesn't mean that he isn't a little bit racist. But then how many of us are truly unbiased when it comes to people who are different from ourselves; it's just a question of degree. Lily Inspirate me. 08:25, 1 September 2012 (UTC)
- Spot on, Lily. London Grump (talk) 11:48, 1 September 2012 (UTC)
I remember reading a quote from David Byrne where he admitted to feeling racist because he felt a certain way around certain people. He said that he felt like it was ultimately not something he could control, just something he would hopefully grow out of. Big daddy A just has some growin up to do is all. AdrianC (talk) 16:57, 1 September 2012 (UTC)
Andy is insightful![edit]
I know that this is a very old edit, but honestly what made Andy think that "foul play" had a damned thing to do with baseball? Has anyone ever heard a sports announcer say, "Gee, Bob, that was a foul play?" What the heck? Phiwum (talk) 02:58, 1 September 2012 (UTC)
- I guess he thought everyone thought that the word "foul" was invented to describe a foul ball? --Revolverman (talk) 03:54, 1 September 2012 (UTC)
- Oh this page is a gem. Such wonderous insights such as:
- "worldwide - 1632: Did people really think in terms of the entire world nearly 400 years ago? Apparently so" -- Given the Magellan 's ships circumnavigated the globe in 1522, over a hundred years earlier, why wouldn't people think in such terms?
- "fission - 1617: Looks like nuclear fission is not a new idea after all!" -- I love how he implies that people in the 17th century thought about atomic fission and not the general definition of simply splitting anything into two parts.
- "dinosaur - 1841: surprisingly late date of origin, the term means "terrifying lizard," which raises the question of why its real name of lizard is not used today" - Because dinosaurs are not lizards; thanks for pointing out once again why you should never be taken seriously on the subjects of evolution and biology.
- Fun stuff; I really hope they expand this.--BMcP - Just an astronomy guy 05:43, 1 September 2012 (UTC)
- And for "landmark" we have "Land was much more important in culture and the economy before the Information Age." That's nothing more than taking part of the word and writing an Ed Poor pseudo factoid. He's an imbicile, in the original meaning of the word. Concernedresident omg!!! ponies!!! 08:06, 1 September 2012 (UTC)
- I think you mean that he's insightful. Who among us has noticed that land and labor is less valuable in an information economy? No one but Andy, man. No one but Andy. Phiwum (talk) 12:54, 1 September 2012 (UTC)
- Landmarks are definitely old news. None of this "see you at the pub by the courthouse". I'll see you the agreed coordinates. Concernedresident omg!!! ponies!!! 15:16, 1 September 2012 (UTC)
Oi, fuckers![edit]
Since Karajou is so fucking petrified of being called on his bullshit on this page, it'd be really nice if you all followed the note at the top of the page and manually screencapped the crap over there for those of us that can't see it. Using proxies is a ball ache, and doesn't help if Ken's religiously using the memory hole. -- Iscariot Andy Schlafly for Congress 2012! 02:36, 31 August 2012 (UTC)
- Aye Aye, your lordship23.16.216.193 (talk) 03:09, 31 August 2012 (UTC)
- Zug Zug! -GTac (talk) 15:08, 31 August 2012 (UTC)
- Did they re-up on server-side blocks? Occasionaluse (talk) 21:17, 31 August 2012 (UTC)
mmhmmnRandonGeneration (talk) 23:27, 1 September 2012 (UTC)
Redundant, but true.[edit]
I'm an avid fan of Conservapedia (for humor-related purposes), and I've read on here, and on the Wikipedia talk pages about the IP blackouts. I linked the Lenski Dialogue to my facebook last week, and since then I have not been able to view Conservapedia from my work computer. I know it's not breaking news or anything, but I'm still baffled. Ah well.. AdrianC (talk) 16:31, 31 August 2012 (UTC)
- Your work computer eh? I hope your IP can't be traced to a particular company, otherwise Karajou will phone up your boss (actually he's too coward to do that, he'll just email your boss) ONE / TALK 16:38, 31 August 2012 (UTC)
- I would say no one's that idiotic. Then I read the article on Atheism and Obesity.AdrianC (talk) 17:01, 31 August 2012 (UTC)
- Karajou has a track record of doing exactly that. I think - I may be confusing him with TK. ONE / TALK 17:19, 31 August 2012 (UTC)
- This is only a half memory, but I think it was TK who actually got in contact with employers, and Karajou who talked about some kind of legal action (companies letting employees use computers to harass conservapedia or whatever the fuck he thinks is a crime in his crazy head). X Stickman (talk) 21:29, 31 August 2012 (UTC)
- Oh yeh, those legal action fantasies of Karajou which he expanded upon on their internal thing were hilarious! You got the impression he thought he would just surprise the court with an "OBJECTION! I actually have here evidence that this person used our wiki to edit information in a trolling fashion!" and the entire court would be shocked and sentence that person to 50 years in guantanamo bay, and Karajou would be hailed as the hero and savior of all. I for one would actually really want to see what would've actually happen.. -GTac (talk) 13:07, 1 September 2012 (UTC)
Been meaning to insert this for sometime because it is revealing. When Ken first announced his Homosexuality and obesity article, he signed the email to the private sysop group, "Ken". So, unless he is a liar (which can get you desysoped and banned at CP), all the sysops know User:Conservative at CP is "Ken".:
[see below]
Sincerely,
Ken
Here's the link (deleted) which doesn't work with quotebox template. nobsCorporations are people, too 21:38, 1 September 2012 (UTC)
Are you still here Knob? London Grump (talk) 06:20, 2 September 2012 (UTC)
I see the president is officially a satanist atheist muslim now.[edit]
"I see no protestants!" sayeth the Arsefly. Does he have a vision defect that prevents him seeing black people? --JeevesMkII The gentleman's gentleman at the other site 18:54, 1 September 2012 (UTC)
- Why is Catholic Andy so concerned about that anyway? Vulpius (talk) 19:00, 1 September 2012 (UTC)
- I think because his interests are so wrapped up with the largely evangelical wingnutosphere, and that doubtless he never actually goes to church anyway, he's got to thinking of himself as de facto protestant. --JeevesMkII The gentleman's gentleman at the other site 19:10, 1 September 2012 (UTC)
- I hope someone there asks what Obama's religion or religious denomination is. I know he looked at the non-denominational Everfree Church but doesn't regularly attend any church. Of course that doesn't mean he isn't Christian; in fact given by the churches he had visited (Baptist, Episcopal), I would have to say he holds most to Protestant traditions. Still for Catholic Andy, this is odd (since he could support Catholic Ryan), but I suspect Andy is Catholic only because of family, and not that he really believes Catholic dogma and views; instead I suspect he is much more enamored with Calvinism.--BMcP - Just an astronomy guy 21:14, 1 September 2012 (UTC)
- If "conservatism is winning", it's a secular brand. Just another example of how comfortable Andy is holding views outside the mainstream and swimming against the tide of demographics. nobsCorporations are people, too 21:22, 1 September 2012 (UTC)
- I honestly have not understood any post you've made. Not once. Weird, huh? Phiwum (talk) 21:34, 1 September 2012 (UTC)
Ok, so you're stupid. BFD. nobsCorporations are people, too 21:45, 1 September 2012 (UTC)
- The price of fish. What's that got to do with? --YossarianSpeak, Memory 22:45, 1 September 2012 (UTC)
- Yeah, I'm stupid. That's probably it. Phiwum (talk) 23:22, 1 September 2012 (UTC)
- That is interesting, but what does that have to do with the price of fish? --Sasayaki (talk) 23:25, 1 September 2012 (UTC)
JPratt in fantasy land[edit]
A real, actual Tory writes a column in the Torygraph, and that's apparently "leftwingers". What planet are these morons from, and when are they going back there? --JeevesMkII The gentleman's gentleman at the other site 23:56, 1 September 2012 (UTC)
- Anyone not American is Leftwing/Liberal in Jpatt world. --Revolverman (talk) 00:03, 2 September 2012 (UTC)
So Jpatt understands British politics about as much as Brits and imperial colonialist morons here understand about American politics. Does that make it WIGO worthy? nobsCorporations are people, too 00:16, 2 September 2012 (UTC)
- Cool Story, Bro --Revolverman (talk) 00:16, 2 September 2012 (UTC)
- Fuck off Rob, you don't even understand what's going on in your immediate vicinity. Just fuck off already. Stop trolling us and fuck off. --JeevesMkII The gentleman's gentleman at the other site 00:17, 2 September 2012 (UTC)
- Actually i believe "Trolling" is classed as successfully managing to cause serious annoyance, offence, or confusion, of to start a flamewar between different users. Nob has done none of these, and the only reaction users have to him is a bored "fuck off, your not wanted". He is far, far below trolls in the overall hierarchy of abject patheticness (and yes I know thats not a a word). Judge HoldenThe Judge Smiles 10:09, 2 September 2012 (UTC)
- That is interesting, but what does that have to do with the price of fish? --Sasayaki (talk) 02:58, 2 September 2012 (UTC)
It's the most wonderful time of the year[edit]
Yes, it's September. Which means it can't be long before the undeniable, objectively beautiful fall foliage appears outside Andy's window and, hopefully, all over Conservapedia once again. Hooray!-- Kriss AkabusiAAAWOOOGAAAR!!1 10:46, 3 September 2012 (UTC)
- And in a couple of months, if we're good little boys and girls, we'll get the dissonant tut-tut about how Halloween is secularized language.--"Shut up, Brx." 12:26, 3 September 2012 (UTC)
CP Admins Don't Read the Linked Articles - Part Some Really Huge Number[edit]
Kara: "Will CBS believe the fake email about Gingrich forcing his wife to get an abortion?img"
Headline from article Kara links from CBSNews: Phony e-mails say Gingrich forced abortion on ex-wife (emphasis mine).
We know they don't read the articles, but do they even read the headlines for the articles they link before spouting off?--BMcP - Just an astronomy guy 00:55, 4 September 2012 (UTC)
- I saw that that a bit ago. I assumed I must just not be reading it right because how could he claim that they might believe the fake E-mails, when they themselves reported it was fake. --Revolverman (talk) 00:57, 4 September 2012 (UTC)
- Wow. It's not only the headline: they quote a press release calling the email a fake and also have "fake press release", "fake release" and "false email" in the first three paragraphs. Plus the whole thing is dated Jan 20 and Karajerk didn't realise. rpeh •T•C•E• 04:34, 4 September 2012 (UTC)
- It's also Kara actual post that's just plain stupid: "CBS reports that a fake email is circulating [...] will CBS believe this email?" That's what happens when you start writing a post and come up with propaganda piece after typing the actual news. --K. (talk) 12:23, 4 September 2012 (UTC)
- Even by CP standards, this shows cognitive dissonance at an insane level, well beyond the usual "why isn't the liberal mainstream media covering <this story from a mainstream media news source>?" MDB (the MD is for Maryland, the B is for Bear) 12:30, 4 September 2012 (UTC)
Yes, Kendoll. Many differences.[edit]
Kendoll helpfully lists three of the many differences his pathetic existence and the Vietnam war. Who wants to help add to the list? I'll go first.
- Charlie don't surf. Kendoll spends all day surfing the internet.
- Many Americans were "too beaucoup" for Saigon's many prostitutes. This is not a problem for Kendoll.
- The Viet Cong had a policy of "talking and fighting", Kendoll only does the talking.
- The Vietnamese were led to victory by Uncle Ho. Kendoll was led to a blacked out panel van by Uncle Ed.
Add more! --JeevesMkII The gentleman's gentleman at the other site 04:14, 4 September 2012 (UTC)
- Kenny boy sure loves using violent imagery. I wonder if there's any connection between that and an interest in video games. Shouldn't Andy being investigating that? We don't want another "young' mass murderer on our hands, do we?--Spud (talk) 04:57, 4 September 2012 (UTC)
- Ken's safe enough. He'd never actually go on a murder spree - he'd only ever blog about how a prominent creationist from Buffalo was about to start killing people at some unspecified date in the future. rpeh •T•C•E• 05:23, 4 September 2012 (UTC)
- Why is that picture a sample of something from A Song of Ice and Fire? --YossarianSpeak, Memory 06:08, 4 September 2012 (UTC)
- Because George R. R. Martin outsells the Bible on e-readers? The worst thing about that image is, of course, the lack of spoiler warning on it. It's an excerpt from A Dance with Dragons, book five for those who are reading the series, and about five years in the future for those morons who can't read and are only watching the TV show. -- Iscariot Andy Schlafly for Congress 2012! 3:18 pm, Today (UTC−5)
- It's from Wiki Commons Worm (talk) 13:57, 5 September 2012 (UTC)
I was going to post a comment asking him if he thought creationists need to take "Broken Arrow-like measures" because they feel in danger of being over-run by a numerically superior and better organised force, but the pointless coward seems to have blocked me from commenting on his blog after the last time I tore him a new hoop.--Fergus Mason Thruppence I got for selling my coat, tuppence for selling my blanket. If ever I 'list for a soldier again, the Devil shall be my Sergeant. 07:13, 4 September 2012 (UTC)
- I just love his belief that translating an entire book (assumedly into Mandarin) is "far easier" than writing one. Having spent the last 4 years of my life doing little else besides precisely this, I beg to differ. I challenge Ken to prove me wrong by taking his beloved "15 questions" and translating it - properly - into Mandarin. Oh, and one last thing: Marcel Proust --
08:52, 4 September 2012 (UTC)
- It's like you've never heard of Google translate. Geez. Phiwum (talk) 13:39, 4 September 2012 (UTC)
- Proust, in his first book wrote about... fa la la... Proust in his first book wrote about... He wrote about... Proust in his first book wrote about the... (gong sounds) rpeh •T•C•E• 13:48, 4 September 2012 (UTC)
- And Marcel Proust was baptized a Catholic! So, if you're calling the author of A La Recherche du Temps Perdu an evolutionist, I shall have to ask you to step outside! MDB (the MD is for Maryland, the B is for Bear) 13:53, 4 September 2012 (UTC)
- Okay, I get MDB's reference, but not Rpeh's. Phiwum (talk) 13:59, 4 September 2012 (UTC)
- Text. Video. You're welcome. rpeh •T•C•E• 14:01, 4 September 2012 (UTC)
- An actual "Summarize Proust" competition, though sadly without evening wear or swimsuits. MDB (the MD is for Maryland, the B is for Bear) 14:07, 4 September 2012 (UTC)
- A churlish, little-minded man would say, "Oh yes, I remember that skit, but you didn't do it right." A more honest man would say, "Wow, I plumb forgot about that skit." Now, you guess which one I'll go for. Phiwum (talk) 14:13, 4 September 2012 (UTC)
Any athlete who disses Tebow is overrated[edit]
Andy is so darnedcute. Phiwum (talk) 14:51, 4 September 2012 (UTC)
- Note that he doesn't even bother to spell the Esiason's name correctly, even though it's in the article to which he links.
- I will grant that Tebow's response was classy. MDB (the MD is for Maryland, the B is for Bear) 14:58, 4 September 2012 (UTC)
- I actually lol'd at "openly Christian".... --Andynot Schlafly 17:14, 4 September 2012 (UTC)
- Haha, oh Andy. I can just imagine Tebow, back when he was in the closet, bringing a Bible home for Thanksgiving, and telling his parents that it is his "roommate". Carlaugust (talk) 18:37, 4 September 2012 (UTC)
- I guess that makes ESPN's Skip Bayless the greatest sports reporter who ever existed, because he is the biggest Tebow apologist. And knows jack shit about sports. Aboriginal Noise What the ... 19:07, 5 September 2012 (UTC)
Abd[edit]
Is anyone interested in helping me counter Abd's various claims on cold fusion?64.180.243.158 (talk) 00:20, 5 September 2012 (UTC)
- You mean on CP? If so, why? Doctor Dark (talk) 02:00, 5 September 2012 (UTC)
Hmmm...[edit]
After perusing some archives about CP "in the news", and hearing reactions from Republicans, I have been led to make the following assertion: Conservapedia is the new NAMBLA. Now I don't mean that Conservapedians want man-boy love, I simply mean that if they tried to publicly donate funds to presidential campaign, they'd probably get the envelope returned unopened. No public figure wants anything to do with them, they operate in secret behind closed doors, and they pretty much all around are dispicable. LGBT groups shun NAMBLA as a fringe homosexual group that is not on the same page. NAMBLA's goal was to rewrite the "gay agenda" to have people fighting for abolishing age of consent laws...who else do we know of that wants to rewrite a book of laws...hmmmmmmm
AdrianC (talk) 14:21, 5 September 2012 (UTC)
- I sincerely doubt that many public figures are aware enough of CP to refuse its contributions. Phiwum (talk) 14:26, 5 September 2012 (UTC)
- That was my thought. Politicians who receive donations from Conservapedia wouldn't recoil in horror at the potential association but instead simply go "who"? Other than Cracked, Encyclopedia Dramatica, Wikipedia (cuz' they cover everything), PZ Myers, and us, who has any idea who Conservapedia is? Maybe Joseph "Obama is a homosexual Kenyan" Farah when he thinks about groups on the Right too crazy even for him ("At least I don't try to rewrite the Bible!"); but other than that? Certainly no one who has actually achieved office at the state or federal level. --BMcP - Just an astronomy guy 17:17, 5 September 2012 (UTC)
- It seems you know an awful many things about homosexuality BMcP. Maybe a listing from the Southern Poverty Law would be the better route. operate in secret— Unsigned, by: some BoN / talk / contribs
Rev. Moon is Dead[edit]
Anyone wanna take bets on how Uncle Ed reacts? --transResident Transfanform! 20:10, 2 September 2012 (UTC)
- Best part, someone already put it on Main Page Talk. Which one of you bastards was it? RachelW (talk) 21:16, 2 September 2012 (UTC)
- I think that this may qualify as grave-dancing. Actually, I'm more interested in what happens to the position of "messiah" within his church--"Shut up, Brx." 00:08, 3 September 2012 (UTC)
- His son has been running everything for years. I'm sure it all passes to him, ala North Korea. --Revolverman (talk) 00:24, 3 September 2012 (UTC)
- Oh, oh. Am I too late to write his epitaph? I'm going with '"God is dead" - Nietzsche'. --JeevesMkII The gentleman's gentleman at the other site 01:21, 3 September 2012 (UTC)
I've got to say, for a man whose god just snuffed it, Ed's taking it awfully calmly. It's almost like being Korean Jesus doesn't mean a damn thing. --JeevesMkII The gentleman's gentleman at the other site 04:05, 3 September 2012 (UTC)
- Nah, he took the literal translation of messiah, anointed one, and just sees that as "extra-special-not-quite-prophet-preacher-which-deserves-all-our-money"--"Shut up, Brx." 04:13, 3 September 2012 (UTC)
- Uncle Ed will know how to react appropriately since, in his own words: "I have been a member the Unification Church my entire adult life and am the Internet's leading authority on it. (My emphasis) I have access to the same public information as everyone else, of course, as well as inside information."[2] I guess we just have to wait for him to reveal to us the "inside information". Mick McT (talk) 11:08, 3 September 2012 (UTC)
I was a moonie cult leader - The Gruniad. CS Miller (talk) 20:02, 5 September 2012 (UTC)
Close encounters[edit]
So, I was over at the Shock of Goat chat room today when I was startled by an approach from an individual calling him/her/themselves John316. "John", having pegged me as an atheist in need of salvation, asked me if I was familiar with a particular website. It dawned on me soon after that I might well be communicating with the great man himself! As if to confirm my suspicions he melted away as soon as I asked him if he was in fact Ken.
I feel like I've just seen the rare Night Parrot or a Tasmanian Tiger. --Horace (talk) 01:32, 5 September 2012 (UTC)
- THAT is where these debates atheists keep ducking out on are supposed to happen? I'm laughing out loud! Shockofgod is surrounded by morons. Nate Keaton (talk) 03:49, 5 September 2012 (UTC)
- Unimaginative handle, pimping his own drivel, epic cowardice? Yep, that's our Kendoll. He really needs to go back to international man of mystery school. --JeevesMkII The gentleman's gentleman at the other site 04:06, 5 September 2012 (UTC)
- "I know you're sweating in Australia... I can see you... I can see your sweaty body oh god i'm gonna-- UGHN *logs off*" ONE / TALK 08:26, 5 September 2012 (UTC)
- Er, no. Ken, the self-proclaimed, college English-writing tutor said "I know your sweating".
ГенгисOur ignorance is God; what we know is science.
12:43, 5 September 2012 (UTC)
- Glad I am not the only one creeped out by the "sweating in Australia" comment.
- As for Shock, as mentioned by Kenny, the former is demanding a debate with Penn Jillette within 30 days or Penn will be deemed as a chicken. I love it when nobodies on the Internet feel that significant people with actual busy lives should give them the time of day; how self-important can you get?--BMcP - Just an astronomy guy 12:07, 5 September 2012 (UTC)
- Maybe Penn will get tired of fame and fortune and find his new calling debating nobodies. Occasionaluse (talk) 13:25, 5 September 2012 (UTC)
- I never got a reply from the Archbishop of Canterbury when I challenged him to a debate on the divinity of Christ. I guess I shall have to declare the divinity of Christ refuted, and the Catholic Church nothing but a coop of chickens. DickTurpis (talk) 13:34, 5 September 2012 (UTC
- Well, you could, but the Archbishop of Canterbury hasn't had much to do with the Catholic Church for a few years. Something to do with a silly spat about moving out and not being appreciative of where he had been raised. I'm not really sure of the details, but it's something like that.--
Jabba de Chops 15:22, 5 September 2012 (UTC)
- Ya, the Archbishop of Canterbury is a big deal in the Church of England, and as a result in the wider Anglican Church. The Anglican Church is a catholic church (it claims to be a successor to the original Christian church and that's the relevant meaning of "catholic" in this context), but when people say "the Catholic Church" they usually mean the Roman Catholic Church which doesn't much care what the Archbishop of Canterbury thinks about stuff. 82.69.171.94 (talk) 17:02, 5 September 2012 (UTC)
- Mea culpa. Teach me to post on RW before I'm fully awake. Yes, I meant the Anglican Church. Either way, BMOC in major religion who obviously should be taking the time to debate random internet people if they don't want to be chickens hiding in a rabbit hole or some other mixed metaphor. I did actually send him an email though, and got a "we've received your email and will give it all due attention" form letter response form his office. But yes, no debate, therefore coward, and divinity of Christ disproved. Yay. I win. DickTurpis (talk) 23:54, 5 September 2012 (UTC)
- I think Penn Jillette should take time off from doing 15 shows a month at the Rio, a TV show, a daily radio show and podcasts, and his other businesses to debate a rude nobody with no qualifications who has a record of shouting people down and turning their mics off. This is exactly how atheists will prove they are not chickens. It is exactly how Christianity Will Once Again Be Triumphant On The Internet. Ole Ole Ole. Wow. Nate Keaton (talk) 13:55, 5 September 2012 (UTC)
- I'm looking at this chat room right now. I don't understand the point of this. Nate Keaton (talk) 14:08, 5 September 2012 (UTC)
John316 is Ken, he immediately recognized my SN from CP...Umichcynic (talk) 05:43, 6 September 2012 (UTC)
"I love the smell of Napalm in the morning."[edit]
"Christianity is spreading in Vietnam." How? Napalm, mother fucker. If there's one way to endear yourself to the Vietnamese, it HAS to be Napalm imagery. I'm sure they love it. Idiot. Hiphopopotamus (talk) 23:50, 5 September 2012 (UTC)
- I'm sure that next we'll be hearing about how the atomic bomb of Christianity will irradiate Japanese atheists--"Shut up, Brx." 23:53, 5 September 2012 (UTC)
- The Christian Gojira crushing the infrastructure of atheist Tokyo! -- Iscariot Andy Schlafly for Congress 2012! 00:38, 6 September 2012 (UTC)
- Dear Ken, maybe you could talk about throwing Polish evolutionary beliefs into a concentration camp. Or genociding Rwandan atheist dogma. Really, I know you are ill buddy, but c'mon. Either get some help, or think through your ideas. Carlaugust (talk) 01:16, 6 September 2012 (UTC)
- This is an interesting game.
- Starving the malnourished atheism of Ukraine
- Christians raping atheistic Nanking
- Mark David Chapman shoots the atheism out of John Lennon
- --"Shut up, Brx." 01:25, 6 September 2012 (UTC)
- You forgot Cordoba.
Генгисunbelieving
01:51, 6 September 2012 (UTC)
- Brx has lynched the fun out of this thread. Acei9 01:53, 6 September 2012 (UTC)
- Next Tuesday, Christianity will fly airplanes into the towers of atheism. You're right Ace. This isn't fun anymore. But we can still all agree that Ken is an asshole. Hiphopopotamus (talk) 01:57, 6 September 2012 (UTC)
- AMERICAN ATHEISM COMES CRASHING DOWN LIKE THE WORLD TRADE CENTER AFTER IT WAS HIT BY THE QUESTION EVOLUTION AIRPLANES! 9/11 9/11 OLE! --GTac (talk) 10:00, 6 September 2012 (UTC)
- I know the last two comments are supposed to be jokes but didn't Ken do exactly that??? ONE / TALK 10:58, 6 September 2012 (UTC)
- That's the joke -GTac (talk) 11:56, 6 September 2012 (UTC)
- We've done these parodies before. MDB (the MD is for Maryland, the B is for Bear) 12:03, 6 September 2012 (UTC)
The US at the Paralympics[edit]
Should someone ask Andy why the US is currently sixth in the medal tally at the Paralympics? I mean, why the huge difference as between Olympics and Paralympics? In the latter the US is even below "increasingly atheistic" Australia. Are all the US Paralympic athletes gay or something? I'm sure Andy has a genuinely amusing answer. --Horace (talk) 02:02, 6 September 2012 (UTC)
- That's easy, if god liked Paralympions then they wouldn't be disabled. Acei9 02:04, 6 September 2012 (UTC)
- Well obviously, but I'm not sure that explains why the US, in particular, has not managed to produce a result anywhere near its Olympic result. After all, surely America is God's favourite country (even if he doesn't much like its paralympians). --Horace (talk) 02:23, 6 September 2012 (UTC)
- None of them are Tim Tebow so....Acei9 02:27, 6 September 2012 (UTC)
- I'm sure he would just say it has something to do with Title IX or whatever. The US rewards achievement, not equality. You know, something very Christian of him. Hiphopopotamus (talk) 02:51, 6 September 2012 (UTC)
deja-vu all over again: idou and no end[edit]
Idou againimg:I hope that AugustO realizes that when Andy says: You make some good points, what he really means is: I'll ignore your points without arguing against them... larron (talk) 13:19, 6 September 2012 (UTC)
RW and CP in August 2012[edit]
Some Observations:
- The numbers of editors at both wikis are comparable: 396 at RationalWiki, 322 at Conservapedia
- However, there are 2.5 as many edits here as over there
- the number of edits in the main namespace is less than 3,000 at Conservapedia, but nearly 4,500 at RationalWiki - though there is much more vandalism and reverting going on at CP.
- This August is the August with the fewest edits in the history of Conservapedia, but still - according to Andy Schlafly - the August with the greatest number of unique visitors.
larron (talk) 17:51, 6 September 2012 (UTC)
- I don't even know what "unique visitors" is supposed to mean, or what it means to Andy. --جئت ورأيت أنا القرف gross, isn't it? 18:01, 6 September 2012 (UTC)
"Sandra Fluke sees freedom as having others pay for the condoms her dozens of weekly lovers use to please her."[edit]
This Bresciani is certifiable--"Shut up, Brx." 18:28, 6 September 2012 (UTC)
Its times like these that I suspect all the other "contributors" on Lobanus's site are really just his schizophrenia manifesting in multiple personalities, all of which are even more hatefully stupid than the last Judge HoldenThe Judge Smiles 18:43, 6 September 2012 (UTC)
- What a prick. What do you think the odds are the Michael was taking a trip to Palmsdale when he wrote that. But really...that man is a priest??? Do you think he sat their and thought "What would Jesus do?...yup, he'd call her a filthy sl*t" Carlaugust (talk) 20:12, 6 September 2012 (UTC)
- I'd be curious to
be involved inknow more about her sex life, even though it's nobody's business but hers...I don't understand why the pundits are so curious and so against having to "pay for her sex life"...after all, they probably have to pay for their own (zing!). My guess? Fluke probably has several dozen fewer encounters per week than the conservative cuckolds would like to suggest, and with as busy as she is, it's more likely to be zero. [Insert text here about how the idiots are against birth control medication that are used for treating severe acne, depression, PPMD, ovarian cysts, etc.] -- Seth Peck (talk) 20:53, 6 September 2012 (UTC)
- Yeah man, that's fucked up. Acei9 21:35, 6 September 2012 (UTC)
- I think even Terry knows that that sentence really crosses the line, given the way he tries to paint it as the author's inference. Can someone grab a full page capture of that before it disappears down the memory hole? My screen cap plug-in seems to have died like CaptureBot. Make sure the comments are included if you can. Do we have a US lawyer in the community? I'd be interested in asking a few questions about this. -- Iscariot Andy Schlafly for Congress 2012! 22:36, 6 September 2012 (UTC)
- I don't have screen-cap but snipped the relevent section. Acei9
- Nutty Roux is a US lawyer.
03:49, 7 September 2012 (UTC)
- And Fergus Mason is a Brit. As I've read the article and been suitably scandalised by the allegations about Ms Fluke's industrial-scale fornication, does that mean she can make use of the UK's famously demented libel laws to reduce Bresciani to penury?-Fergus Mason Thruppence I got for selling my coat, tuppence for selling my blanket. If ever I 'list for a soldier again, the Devil shall be my Sergeant. 03:55, 7 September 2012 (UTC)
- "Statements falsely suggesting that a person is sexually promiscuous or sexually licentious are generally actionable as defamation.[11] Restatement (Second) of Torts § 569, comment f ("It is actionable per se to accuse in libelous form either a man or woman of any sexual misconduct ..."); King v. Northeastern Publishing Co., 294 Mass. 369, 370-371, 2 N.E.2d 486 (1936) (upholding verdict for plaintiff because the challenged publication could be reasonably understood as charging her with unchastity or fornication)" Stanton v. Metro Corp., 357 F. Supp. 2d 369 (D. Mass. 2005).
04:33, 7 September 2012 (UTC)
- Thanks Nutty. A couple of questions if I may. Who holds liability if it's deemed defamation? This idiot vicar? Terry? Both? Which courts would it go to, state or federal? This might be obvious to Yanks, but I'm clueless apart from the excellent education I've had watching imported courtroom dramas. Is there a statute of limitations for beginning action? -- Iscariot Andy Schlafly for Congress 2012! 10:13, 7 September 2012 (UTC)
- Oh sorry somehow the other questions didn't register. The speaker is liable. I don't know whether someone publishing and then ratifying would be liable. State courts are courts of "general jurisdiction," meaning they'll hear most any controversy subject to the limits set by statute or the state constitution. Federal courts are courts of "limited jurisdiction," meaning they'll only hear cases of a few types. The relevant one would be "diversity of citizenship," in which parties are from different states and the amount in controversy is greater than $75,000. Got me on whether the amount in controversy requirement would be met in a case like this. So who knows whether this could be in state or federal court. I'd be happy to lecture on subject matter jurisdiction but somehow that seems like too much to peck into this silver fucker when I'm this drunk and nobody really asked.
04:24, 8 September 2012 (UTC)
- All that said, Terry Hurlbut says some absolutely horrible things about public and private figures. I'd very much appreciate someone taking him to school for that. That Fluke statement is only marginally less creepy than the horrible lies he tells about President Obama. That "kingly power" article completely misrepresenting a statute reorganizing advise and consent, with the balance being toward preserving it, was appalling. When a commenter called him out he refused to edit or withdraw the article. That's dishonest.
04:28, 8 September 2012 (UTC)
- In case anyone's interested, this isn't a huge mystery under New Jersey law. I admittedly didn't spend a lot of time on this research, but it's reasonably on point.
- In the New Jersey case of Too Much Media, LLC v. Hale, 413 N.J.Super. 135, 993 A.2d 845 (N.J. Super., 2010), a blogger was alleged to have made a number of defamatory statements imputing criminal and fraudulent conduct on individual plaintiffs.
- There are two separate discussions in the case. The first is largely irrelevant, though sort of interesting in this context since Terry continues asserting that he is a "journalist." The question was whether a blogger is a journalist and can therefore avail herself of New Jersey's state Shield Law to prevent disclosure of her alleged sources. The court noted a number of tests employed around the country and concluded that the defendant was not a "newsperson" for purposes of invoking the Shield Law. Whoever the person is who wrote that vile essay on Terry's site may or may not be a journalist. I don't know how a New Jersey court would hold.
- The more relevant question was whether imputing criminal and fraudulent conduct on someone in writing, rather than orally, is defamation per se, for which there is no requirement of showing actual pecuniary loss to be able to proceed with suit, or whether the plaintiff must show some actual harm. NJ law considers orally imputing "serious sexual misconduct," as of a kind with the misconduct alleged in Too Much Media under the Restatement (Second) of Torts. The court noted that only certain specifically listed slanderous statements are susceptible of being considered defamation per se. A plaintiff alleging libel statements of exactly the same nature must show some actual harm. Even if she can't show pecuniary loss, she may nevertheless show some other actual harm, such as "impairment of reputation and standing in the community, personal humiliation, and mental anguish and suffering." Id. at 168. Showing damage to reputation in the context of Too Much Media might take the form of third party testimony showing an existing relationship had been seriously disrupted.
- Note that Massachusetts law considers written defamatory statements accusing someone of serious sexual misconduct as defamation per se for which damages would be presumed. Differences among state law like this are obviously potentially a big deal.
- It's also important to note that if the plaintiff is a public figure, he must prove that the defendant was motived by "actual malice" and knew the statement was false or recklessly disregarded its falsity. See, Gertz v. Robert Welch, Inc., 418 U.S. 323, 350, 94 S.Ct. 2997, 3012 (1974). Sandra Fluke is probably a "public figure" subject to Gertz because she "thrust [herself] into the vortex" of an existing public controversy.
- In any event, stating "Sandra Fluke sees freedom as having others pay for the condoms her dozens of weekly lovers use to please her" may be an "opinion" subject to some other privilege. I've only dealt with commercial defamation cases in which nobody asserted that a statement was an opinion so I'm not up on that law.
- @Iscariot: I have no idea what the New Jersey statute of limitations for personal actions like this or whether New Jersey law would even apply. It's a choice of law problem I have no interest in spending any time researching.
16:00, 7 September 2012 (UTC)
- Terry A. Hurlbut: For your information, I practice abstinence. I have had no relations of that kind with any woman since my wife died. No kidding, Chucky?
ГенгисOur ignorance is God; what we know is science.
22:45, 6 September 2012 (UTC)
- Thanks, Terry. Glad to hear it. Acei9 22:50, 6 September 2012 (UTC)
- Notice he only denied having sexual relations with woman..... Judge HoldenThe Judge Smiles 22:55, 6 September 2012 (UTC)
- ...And Bresciani sees freedom as a threat to his control over his congregation. TheLateGatsby (talk) 23:06, 6 September 2012 (UTC)
- "I have had no relations of that kind with any woman since my wife died." So, when he says, "I have had no relations", he means no woman will let him go P in V, obviously. But, when he says, "no relations of that kind", that's legalese for "I have, unsuccessfully, attempted to jerk off to Japanese-scat-porn", right? Two additional questions; 1) Isn't masturbation a sin? 2)Are PED drugs a socialist conspiracy allowing for dozens of lovers per week? Hiphopopotamus (talk) 07:18, 7 September 2012 (UTC)
- I like the fact that Lobarse has no problem claiming Ms Fluke has dozens of lovers but was so upset that someone called him inconsistent he called on god to damn them. I guess he really is inconsistent. rpeh •T•C•E• 11:57, 7 September 2012 (UTC)
- "Inconsistent" is probably the worse thing you can call a conservative, worse even than homosexual. They pride themselves on sticking to their guns more than anything--"Shut up, Brx." 12:11, 7 September 2012 (UTC)
I wish conservatives were consistent; then they'd be arguing for all the weirdo laws in the Old Testament. "Corn subsidies encourage the harvesting of the corners of one's field, which is a sin! I refuse to pay taxes for it! Why are these farmers using my tax dollars to stick crops into their orifices??" Carlaugust (talk) 13:24, 7 September 2012 (UTC)
- Whenever something like this happens it always leaves a bad taste of, 'I am angry that she is having sex! I should be having sex!' in my mouth. It's a very specific flavor of slut-shaming that always makes me uncomfortable about the people angry at the girl.±
KnightOfTL;DRgoing galt: the literal crazy train 14:34, 7 September 2012 (UTC)
- sex in your mouth, eh? Line forms to the left, folks...--Martin Arrowsmith (talk) 19:12, 7 September 2012 (UTC)
Slingcolon flavour humour, Kara officially declaring war on facts and the racist, babykilling DNC[edit]
Does anyone else suspect andy and his joyboys are getting a wee bit panicky over the DNC being less facepalmworthy than the Republican one? (forgetting of course the fact they are all supposedly RINOs now)
First of all we have Kara, who is now deciding that facts are liberal, and also condemns the democrats for being racist, and for refering to Jesus and Jerusalem at one point (despite Terry whining about them not having it in their platform barely 2 days beforehand) before pontificating how this will be the deciding factor in the election
Similarly andy lets forth his rage over the DNC allowing planned parenthood to speak there
And finally we have this wonderful example of christian wit as Peltshitter fumes over a single throwaway bit of snark from obama, and links to his boytoy's rant over how family unfriendly the DNC was and how offensive and insulting democrats are being (in an article which happily tries to slutshame Sandra fluke for her evil whorishness among other things)
I wonder what has rattled their cages? Judge HoldenThe Judge Smiles 18:43, 6 September 2012 (UTC)
- If I had to guess, I would say they realize that Romney has a very real chance of getting completely blown out in this election and they are worried that they will be subjected to four more years of Obama's style of hard-left-wing communism (by which, of course, I mean moderate-to-right-leaning free market capitalism). Carlaugust (talk) 20:06, 6 September 2012 (UTC)
- It's not quite so simple. The link in question specifically questions the fact-checking of political beliefs, as opposed to assertions (as in, the free market is good vs. free market policies have improved life for everybody in the past 20 years). One is a little more difficult to assess as a fact, while the other is more straightforward. --"Shut up, Brx." 20:32, 6 September 2012 (UTC)
-
- you forget that God personally steered that cyclone around Florida and aimed it at the sinful city of New Orleans. God must be a republican and favors Mitt Romney, a follower of the angel ? and the Gold tablets of mormonism. Hamster (talk) 20:47, 6 September 2012 (UTC)
"Slingcolon?" Really? We're moving up the digestive tract now? 66.45.252.90 (talk) 19:56, 7 September 2012 (UTC)
- I do not like any of the "euphemisms" for Dr Hurlbut with the exception of Lobarse, (which I found slightly amusing), since it speaks ill of those engaging in such juvenile name-calling. Matzosphere (talk) 14:50, 8 September 2012 (UTC)
Classic Andy[edit]
And oldie but a goodie, all of Andy's best arguments....despite for some reason being badly formatted for some reason. Acei9 02:28, 7 September 2012 (UTC)
Conservative ungrammatics[edit]
Can a representative of the "Society for Eliminating Greengrocer's Apostorphe's'" please deal with [3] and finish off the sentence after Alexa; and rearrange the misdirection on Conspiracy theories. 212.85.6.26 (talk) 14:54, 7 September 2012 (UTC)
- I'm not sure who this is directed towards. Good-faith users on CP -poor bastards- don't read this page, right? Anyone who corrects this error now will get banned. --TheLateGatsby (talk) 16:17, 7 September 2012 (UTC)
- Apostorphe's?
ГенгисYou have the right to be offended; and I have the right to offend you.
16:51, 7 September 2012 (UTC)
- Tangentially related, considering Kendoll's new obsession with Quora, any bets that there'll be a certain number of "I'm an atheist, but I can't answer these 15 question for evolutionists! What denomination of Christian should I become?" type questions posted there? --JeevesMkII The gentleman's gentleman at the other site 18:26, 7 September 2012 (UTC)
- The "hilarious" troll has made more errors than Ken did. Pathetic. Sphincter (talk) 20:34, 7 September 2012 (UTC)
- I'm assuming the use of the Greengrocer's apostrophe in the name of the society for eliminating it is intentional snark, a joke some i guess didn't get. DickTurpis (talk) 01:20, 8 September 2012 (UTC)
- Something to do with the tradition of British greengrocers adding the unnecessary apostrophe before the 's' in plurals on their chalk price boards, such as "Apple's - £1/lb". Ajkgordon (talk) 12:53, 8 September 2012 (UTC)
- It's a worldwide phenomenon. And not limited to transitory signs. Just up the road is a place that sells "Used Harley's". That said, the example in question is not a GGA. It's confusion over how "its" works. ħuman
00:18, 9 September 2012 (UTC)
- And don't forget the clothing company, Lands' End.
ГенгисRationalWiki GOLD member
04:12, 9 September 2012 (UTC)
Irony alert: Kendoll sez talk is cheap.[edit]
o rly, Kendoll? Considering your question evolution group (Or, you and your imaginary international friends as it is otherwise known) is currently about 0 for 10 or 20 when it comes to actually doing things you've announced you're going to do, I wouldn't be bandying that bit of hackneyed wisdom around quite so freely. Perhaps you ought to release that 100 page booklet you've been wittering on about for months. We could use a good laugh. --JeevesMkII The gentleman's gentleman at the other site 03:27, 9 September 2012 (UTC)
- Maybe I should help him on some of his pages? (I have a lovely word salad generator sitting on my hard drive somewhere..)64.180.242.74 (talk) 03:48, 9 September 2012 (UTC)
- Ken, you tosser. Just because something is stale and boring doesn't mean it's not true.Spud (talk) 03:59, 9 September 2012 (UTC)
- The hipster teaching one of my new computer classes uses this for word salad. I imagine it's more interesting than whatever these QE pamphlets are supposed to be but nobody's seen one yet so who knows? Nate Keaton (talk) 13:26, 9 September 2012 (UTC)
- Most amusing.
BrendenGregG pasted the link to Talk:Origins, and of course Conservative, who kept asking for evidence and to answer the retarded 15 questions, probably didn't even read the link and called it stale and boring evobabble. So to cement this, he makes a blog post about it, and then plasters it on the main page. Dance for us, Ken, for the puppet strings command it.
NorsemanCyser Melomel 15:12, 9 September 2012 (UTC)
"Talk is cheap. Now pay $20,000 to debate me." DickTurpis (talk) 16:06, 9 September 2012 (UTC)
|
https://rationalwiki.org/wiki/Conservapedia_talk:What_is_going_on_at_CP%3F/Archive298
|
CC-MAIN-2019-13
|
refinedweb
| 19,540
| 71.04
|
You may have seen this CompDocError before if you used python xlrd library to read the older version of the excel file (.xls). When directly opening the same file from Microsoft Excel, it is able to show the data properly without any issue.
This usually happens if the excel file is generated from 3rd party application, the program did not follow strictly on the Microsoft Excel standard format, although the file is readable by Excel but it fails when opening it with xlrd library due to the non-standard format or missing some meta data. As you may have no control on how the 3rd party application generate the file, you will need to find a way to handle this CompDocError in your code.
SOLUTIONS FOR COMPDOCERROR
Option 1:
If you look at the error message, the error raised from the line 427 in the compdoc.py in your xlrd package. Since you confirm there is no problem with the data in your excel file except the minor format issue, you can open the compdoc.py and comment out the lines for raising CompDocError exception.
while s >= 0: if self.seen[s]: pass #print("_locate_stream(%s): seen" % qname, file=self.logfile); dump_list(self.seen, 20, self.logfile) #raise CompDocError("%s corruption: seen[%d] == %d" % (qname, s, self.seen[s]))
Option 2:
You may notice if you open your file in Microsoft Excel and save it, you will be able to use xlrd to read and no exception will be raised. This is because Excel already fixed the issues for you when saving the file. You can use the same approach in your code to fix this problem.
To do that, you can use the pywin32 library to open the native Excel application and re-save the file.
import win32com.client as win32 excel_app = win32.Dispatch('Excel.Application') wb = excel_app.Workbooks.open("test.xls") excel_app.DisplayAlerts = False #do not show any alert when closing the excel wb.Save() excel_app.quit()
Conclusion
For option 1, it is good if your program only reads the files generated from the same source. If your program needs to read different excel files from different sources, it may not be a good to always assume the “CompDocError” can be ignored.
For option 2, when calling the excel_app.quit(), the entire Excel application will be closed without any alert. If you have other excel files opening at the time, it will be all closed together. So this solution is good if your program will run in a standalone environment or you confirm no other process/people will be using excel when running your code.
If you would like to understand more about how to read & write excel file with xlrd, please check this article.
|
https://www.codeforests.com/category/resources/page/7/
|
CC-MAIN-2022-21
|
refinedweb
| 457
| 63.29
|
Multi Tenancy
What Is Multi Tenancy?
"Software Multitenancy refers to a software architecture in which a single instance of a software runs on a server and serves multiple tenants. A tenant is a group of users who share a common access with specific privileges to the software instance." (Wikipedia)
In brief, seperated database, we can serve to multiple tenants in a single server. We just make sure that multiple instance of the application don't conflict with each other in same server environment.
This can be possible also for an existing application which is not designed as multitenant. It's easier to create such an application since the application has not aware of multitenancy. But there are setup, utilization and maintenance problems in this approach.
Single Deployment - Multiple Database
ln this approach, we may run a single instance of the application in a server. We have a master (host) database to store tenant metadata (like tenant name and subdomain) and a seperated database for each tenant. Once we identify the current tenant (for example; from subdomain or from a user login form), then we can switch to that tenant's database to perform operations.
In this approach, application should be designed as multi-tenant in some level. But most of the application can remain independed from multi-tenancy.
We should create and maintain a seperated database for each tenant, this includes database migrations. If we have many customers with dedicated databases, it may take long time to migrate database schema in an application update. Since we have seperated database for a tenant, we can backup it's database seperately from other tenants. Also, we can move the tenant database to a stronger server if that tenant needs it.
Single Deployment - Single Database
This is the most real multi-tenancy architecture: We only deploy single instance of the application with a single database into a single server. We have a TenantId (or similar) field in each table (for a RDBMS) which is used to isolate a tenant's data from others.
This is easy to setup and maintain. But harder to create such an application. Because, we must prevent a Tenant to read or write other tenant data. We may add TenantId filter for each database read (select) operation. Also, we may check it every write, if this entity is related to the current tenant. This is tedious and error-prone. But ASP.NET Boilerplate helps us here by using automatic data filtering.
This approach may have performance problems if we have many tenants with huge data. We may use table partitioning or other database features to overcome this problem.
Single Deployment - Hybrid Databases
We may want to store tenants in single databases normally, but want to create seperated databases for desired tenants. For example, we can store tenants with big data in their own databases, but store all other tenants in a single database.
Multiple Deployment - Single/Multiple/Hybrid Database
Finally, we may want to deploy our application to more than one server (like web farms) for a better application performance, high availability, and/or scalability. This is independent from the database approach.
Multi-Tenancy in ASP.NET Boilerplate
ASP.NET Boilerplate can work with all scenarios described above.
Enabling Multi Tenancy
Multi-tenancy is disabled by default. We can enable it in PreInitialize of our module as shown below:
Configuration.MultiTenancy.IsEnabled = true;
Host vs Tenant
First, we should define two terms used in a multi-tenant system:
- Tenant: A customer which have it's own users, roles, permissions, settings... and uses the application completely isolated from other tenants. A multi-tenant application will have one or more tenants. If this is a CRM application, different tenants have also thier own accounts, contacts, products and orders. So, when we say a 'tenant user', we mean a user owned by a tenant.
- Host: Host is singleton (there is a single host). The Host is responsible to create and manage tenants. So, a 'host user' is higher level and independent from all tenants and can control they.
Session
ASP.NET Boilerplate defines IAbpSession interface to obtain current user and tenant ids. This interface is used in multi-tenancy to get current tenant's id by default. Thus, it can filter data based on current tenant's id. We can say these rules:
- If both of UserId and TenantId is null, then current user is not logged in to the system. So, we can not know if it's a host user or tenant user. In this case, user can not access to authorized content.
- If UserId is not null and TenantId is null, then we can know that current user is a host user.
- If UserId is not null and also TenantId is not null, we can know that current user is a tenant user.
- If UserId is null but TenantId is not null, that means we can know the current tenant, but current request is not authorized (user did not login). See the next section to understand how current tenant is determined.
See session documentation for more information on the session.
Determining Current Tenant
Since all tenant users use the same application, we should have a way of distinguishing the tenant of the current request. Default session implementation (ClaimsAbpSession) uses different approaches to find the tenant related to the current request with the given order:
- If user has logged in, then gets TenantId from current claims. Claim name is and should contain an integer value. If it's not found in claims then the user is assumed as a host user.
- If user has not logged in, then it tries to resolve TenantId from tenant resolve contributors. There are 3 pre-defined tenant contributors and runs in given order (first success resolver wins):
- DomainTenantResolveContributer: Tries to resolve tenancy name from url, generally from domain or subdomain. You can configure domain format in PreInitialize method of your module (like Configuration.Modules.AbpWebCommon().MultiTenancy.DomainFormat = "{0}.mydomain.com";). If domain format is "{0}.mydomain.com" and current host of the request is acme.mydomain.com, then tenancy name is resolved as "acme". Then next step is to query ITenantStore to find the TenantId by given tenancy name. If a tenant is found, then it's resolved as the current TenantId.
- HttpHeaderTenantResolveContributer: Tries to resolve TenantId from "Abp.TenantId" header value, if present (This is a constant defined in Abp.MultiTenancy.MultiTenancyConsts.TenantIdResolveKey).
- HttpCookieTenantResolveContributer: Tries to resolve TenantId from "Abp.TenantId" cookie value, if present (uses the same constant explained above).
If none of these attemtps can resolve a TenantId, then current requester is considered as the host. Tenant resolvers are extensible. You can add resolvers to Configuration.MultiTenancy.Resolvers collection, or remove an existing resolver.
One last thing on resolvers is that; resolved tenant id is cached during the same request for performance reasons. So, resolvers are executed once in a request (and only if current user has not already logged in).
Tenant Store
DomainTenantResolveContributer uses ITenantStore to find tenant id by tenancy name. Default implementation of ITenantStore is NullTenantStore which does not contain any tenant and returns null for queries. You can implement and replace it to query tenants from any data source. Module zero properly implements it to get from it's tenant manager. So, if you are using module zero, don't care about the tenant store.
Data Filters
For multi tenant single database approach, we must add a TenantId filter to get only current tenant's entities while retrieving entities from database. ASP.NET Boilerplate automatically does it when you implement one of two interfaces for your entity: IMustHaveTenant and IMayHaveTenant.
IMustHaveTenant Interface
This interface is used to distinguish entities of different tenants by defining TenantId property. An example entitiy that implements IMustHaveTenant:
public class Product : Entity, IMustHaveTenant { public int TenantId { get; set; } public string Name { get; set; } //...other properties }
Thus, ASP.NET Boilerplate knows that this is a tenant-specific entity and automatically isolates entities of a tenant from other tenants.
IMayHaveTenant interface
We may need to share an entity type between host and tenants. So, an entity may be owned by a tenant or the host. IMayHaveTenant interface also defines TenantId (similar to IMustHaveTenant), but nullable in this case. An example entitiy that implements IMayHaveTenant:
public class Role : Entity, IMayHaveTenant { public int? TenantId { get; set; } public string RoleName { get; set; } //...other properties }
We may use same Role class to store Host roles and Tenant roles. In this case, TenantId property says if this is an host entity or tenant entitiy. A null value means this is a host entity, a non-null value means this entity owned by a tenant which's Id is the TenantId.
Additional Notes
IMayHaveTenant is not common as IMustHaveTenant. For example, a Product class can not be IMayHaveTenant since a Product is related to actual application functionality, not related to managing tenants. So, use IMayHaveTenant interface carefully since it's harder to maintain a code shared by host and tenants.
When you define an entity type as IMustHaveTenant or IMayHaveTenant, always set TenantId when you create a new entity (While ASP.NET Boilerplate tries to set it from current TenantId, it may not be possible in some cases, especially for IMayHaveTenant entities). Most of times, this will be the only point you deal with TenantId properties. You don't need to explicitly write TenantId filter in Where conditions while writing LINQ, since it will be automatically filtered.
Switching Between Host and Tenants
While working on a multitenant application database, we should know the current tenant. By default, it's obtained from IAbpSession (as described before). We can change this behaviour and switch to other given tenant data, independent from database architecture:
- If given tenant has a dedicated database, it switches to that database and gets products from it.
- If given tenant has not a dedicated database (single database approach, for example), it adds automatic TenantId filter to query get only that tenant's products.
If we don't use SetTenantId, it gets tenantId from session, as said before. There are some notes and best practices here:
- Use SetTenantId(null) to switch to the host.
- Use SetTenantId within a using block as in the example if there is not a special case. Thus, it automatically restore tenantId at the end of the using block and the code calls GetProducts method works as before.
- You can use SetTenantId in nested blocks if it's needed.
- Since _unitOfWorkManager.Current only available in a unit of work, be sure that your code runs in a UOW.
|
http://aspnetboilerplate.com/Pages/Documents/Multi-Tenancy
|
CC-MAIN-2017-09
|
refinedweb
| 1,761
| 56.35
|
.
Workaround″:Task task = new Task {
Id = 5,
Priority = new PriorityWrapper {EnumValue = Priority.High },
Title = “Write Tip 23”
};.
GREAT! I did the exact same thing in a billing project where the int value didn’t say much of the status. Never though of doing it for the entity framework.
Nice solution, that should shut the critics up for a while
Will this code supported in this version of EF?
var products = from p in db.Products
select new Product
{
Id = n.Id,
Name = n.Name
};
I tried it with VS2010 Beta1 and this exception still occured (same in the previous version of EF) while it is valid in LINQ To SQL:
"The entity or complex type ‘Demo.Product’ cannot be constructed in a LINQ to Entities query."
Ngoc,
That code isn’t supported but this is:
var anonproducts =
from p in db.Products
select new {Id = n.Id, Name = n.Name};
var products =
from p in anonproducts.AsEnumerable<T>()
select new Product {Id = p.Id, Name = p.Name};
Alex
EF doesn’t support enums? What? That’s… wierd. Even Linq-to-Sql does.
add the support, how hard can it be!!
is PriorityWrapper missing a constructor?
Phil,
No, I’m using the default constructor everywhere, along with a Object Initializer syntax.
I.e.
new Customer {Name = "ACME"};
rather than
new Customer("ACME");
Hope this helps
Alex
@Keith and Michael,
I hear you.
Alex
Many thanks. Got my EF 4.0 pseudo enums working now.
Can’t see why Microsoft aren’t implementing Enum mapping with ability to switch map to be either the int index or the string value.
I wanted to pass the string section through to the database so my code is a little different. If anyone is interested here’s my code for an organization type enum:
public enum OrganizationTypeEnum
{
Company,
Subsidiary,
Division,
Department,
Team
}
public class OrganizationTypeEnumWrapper
{
private OrganizationTypeEnum _organizationType;
public OrganizationTypeEnum OrganizationType
{
get { return _organizationType; }
set { _organizationType = value; }
}
public string StringValue
{
get { return _organizationType.ToString(); }
set { _organizationType = (OrganizationTypeEnum)Enum.Parse(typeof(OrganizationTypeEnum), StringValue, true); }
}
public static implicit operator OrganizationTypeEnumWrapper(OrganizationTypeEnum p)
{
return new OrganizationTypeEnumWrapper { OrganizationType = p };
}
public static implicit operator OrganizationTypeEnum(OrganizationTypeEnumWrapper pw)
{
if (pw == null) return OrganizationTypeEnum.Company;
else return pw._organizationType;
}
}
Does anyone know whether EF 4.0 supports multiple model diagrams? My database will have circa 200 tables and i do not want 1 diagram.
@Phil,
Nice solution, I was meaning to talk about that too, but it’s good to see you worked it out!
As for your question about multiple diagrams. Unfortunately the answer is no, there was talk of implementing something like that, but I think it got left on the cutting room floor, so to speak.
Alex
Any ideas why Microsoft have not implemented Enums. My guess is that because behind the scenes they are instantiated as structs derived from base System.Enum then they do not support inheritance and that the EF4.0 implementation of change tracking will therefore not work with them? (EF 4.0 creates derived proxy objects from your POCO classes). Then again I may be talking fluff?
I wonder whether its possible to somehow use extension methods on string type to perform implicit casts?
Phil,
No I don’t think there are any major technical issues. We don’t need to create proxies for your Enums, because they are simply a property of your POCO class.
The only reason they aren’t in the product is we were focusing on other things, like POCO, Model First etc.
There is still some time to react to your and other peoples feedback so you never know.
As for you question about extension methods and implicit casts, not sure, it would be nice wouldn’t it
Alex
It has been a source of constant annoyance with EF that it does not support enums. I could live with it being limited to only support mapping to int columns, but all we’re talking about here is the ability to make a few casts. It’ll take you an hour to implement but waste a million hours for all the EF users if you don’t..
@Morten,
I hear you. Unfortunately no piece of code takes an hour at Microsoft. Not that I’m making excuses.
I really want to see this get in too.
Alex
Hi,
Nice but too bad it’s not in EF4. We even got this running in EF1 with Int and Char support. Just give it a week and make EF a real professsional ORM
Roger,
I hear you. I wish it was just a week. While this from Eric Lippert is tongue in cheek there is a big element of truth too:
How many Microsoft employees does it take to change a lightbulb…
Alex — yes, I understand how much work MS has to do to ship features. But MS is so far behind in this space in general. I was really hoping that EF4 might be something I could drop NHibernate for. But it doesn’t look that way :(. It’s not just this one feature, but it’s that if this one little tiny thing doesn’t work right, then I can only imagine there must be all sorts of things all over the place that won’t work right once we get into it.
In fact, on a new project, we decided to simply not bother even looking at EF4 because of the high probability that we might run into problems at some point, even if we don’t know what the problems are now. With NHibernate, it’s a safe choice, and we know we’re not gonna hit anything too strange that we can’t quickly find a fix/workaround for.
<i>The only reason they aren’t in the product is we were focusing on other things, like POCO, Model First etc.</i>
ok, someone is either joking here or I am being a dumb EF user…
either way, why all that feedback then?
finger crossed for enums support in EF 4.0
I appreciate your work Alex, but I’ve dealt with other commercial ORM companies and (believe it or not) any request was made during the first 24 hours /and/or week (depending on the problem to deliver it)
I hope EF won’t have a FREE (you get what you payed for) moniker, because, strangely, Microsoft is on the right way
in the history you aren’t remembered by the good things you’ve done but by the few bad you’ve deployed, don’t destroy its name
thanks (and I am not trolling here)
Is there a similar way of getting this working in 3.5 SP1 or is this a 4.0 only trick?
I’ve very new to EF and I’m trying to migrate from LINQ2SQL to EF and this is a real headache (and we can’t use 2010 as its not rtm afaik)
thanks
You can tidy this example up with generics, a bit:
public class EnumType<T>
{
private T enumType;
public int Value
{
get { return (int)(object)enumType; }
set { enumType = (T)(object)value; }
}
public T EnumValue
{
get { return enumType; }
set { enumType = value; }
}
public static implicit operator EnumType<T>(T p)
{
return new EnumType<T>{ EnumValue = p };
}
public static implicit operator T(EnumType<T> pw)
{
if (pw == null) return default(T);
else return pw.EnumValue;
}
}
public enum wah
{
something,
boo,
legs
}
public class bum
{
public bum()
{
EnumType<wah> www = wah.legs;
}
}
@Dave,
Unfortunately I suspect your example won’t work in Beta2 because of a limitation in the EF, that means properties have to be declared at the same level in the CLR type hierarchy as they do in the EDM. Which I think means that the EF won’t be able to map classes derived from your Generic Base class to the corresponding EDM ComplexType.
We’ve made some changes post Beta2 that might fix the problem. Basically this sort of generic base type trick will work for Entities post Beta2, not sure about ComplexTypes though.
Alex
How can we make this work with the "Code Only" approach where you don’t have the edmx file to define the complex type?
Well you need to register the wrapper as a ComplexType something like this:
builder.ComplexType<PriorityWrapper>()
Code-Only ‘should’ pick up the int / string properties but ignore the enum property. I haven’t tested this yet myself, but I think it should work.
Keen to hear how you go.
Cheers
Alex
I tried using the ComplexType() method and it sort of worked. The only way I could get it to work was if the actual database column name was in the form: <PropertyName>_Value (e.g., "Priority_Value"). I can’t figure a way to make it work if I want my DB column named to be called something else.
Incidentally, I created a generic class to wrap this the same way Dave suggest above and it works fine (although suffers from the same problem where I can’t control the DB column name).
If you have any suggestions for how I can specify the DB column name, I’d appreciate it.
Sorry the belabor the point everyone else has made on the comments above, but if Microsoft doesn’t simply support enums the way LINQ to SQL has done for a number of years, it will be quite disappointing.
@Steve,
To specify the column name you need to specify a mapping explicitly.
So for example if you have this:
public class Task{
public int ID {get;set;}
public string Name {get;set;}
…
public PriorityWrapper Priority {get;set;}
}
You would need something like this:
builder.ComplexType<PriorityWrapper>();
builder.MapSingleType<Task>(
t => new {
id = t.ID,
name = t.Name,
…
priority = t.Priority.Value
}
);
As you see you simply ‘.’ through to the property of the ComplexType you want to map.
Re: not supporting Enum’s properly – I absolutely agree – it is a real shame.
Hope this helps
Alex
Alex – Thanks for your response. It looks like this sort of worked. A couple of interesting points that I’m observing:
When I switched to using this, the generic Wrapper<T> no longer worked. I had to switch back to the non-generic wrapper which means it’s not a very re-usable situation (and hence, not very developer-friendly) for enums.
When I don’t use the MapSingleType() method, I can’t control the column name (unfortunate) but I’m able to use the generic Wrapper<T> which make the lack of enum support slightly more palatable. But in the end, I can’t use that column name so my only choice would be to use MapSingleType().
Again, thx for your responses.
Is this workaround still possible with the final release of EF4? I keep getting an error: "The Type 'xx.PriorityWrapper' already contains a definition for 'Value'" Please let me know… I'm pulling my hair out trying to get this to work. Thanks.
@Steve
Could you paste your code first mapping for Wrapper<T>
builder.ComplexType<Wrapper<wah>>()
.Property(a => a.Value);
EF 4.0 release say that "The Type 'EnumType`1[wah]' is not a valid complex type. Generic types are not supported.
Thanks
How do you write queries when storing the enum value as a string. I have tried:
entities.Where(x => x.Status.Value == StatusEnum.Future.ToString());
but get the following exception:
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
Is this still the best approach for Enums? I am just getting started and quickly ran into this.
Is this still the best approach for Enums? I am just getting started and quickly ran into this.
@Daniel
You need to get the string before you use it:
string enumValue = StatusEnum.Future.ToString();
entities.Where(x => x.Status.Value == enumValue);
@Scott
Not sure if this is the 'Best' approach – all approaches have tradeoffs – it is however one we know works.
I've been trying to implementing this but am not sure where I create the public class PriorityWrapper as the codegen already creates a partial one and therefore I get an abiguity conflict
Please make this work. Its absolutly a must.
I like what i am seeing with the code first and convention based mapping/configuration just like Fluent NHibernate, but i wont change if something as simple as mapping to an enum doesnt work.
What modifications are needed to make this work in the final release (as the post was written for beta)? PriorityWrapper must be in a different namespace since it is not marked as partial.
Is that supposed to be the case? If so , the assigning and linq statements will not work as posted.
If PriorityWrapper is supposed to be in the same namespace, when it is marked as partial the Value property is defined in two places.
I feel I'm missing something very important or this example does not apply in its current from to the current EF release.
Any thoughts?
Please vote: connect.microsoft.com/…/support-enums-as-property-types-on-entities
@Anthony Main
This sample is for POCO only. So, default code generator must be turned off.
@Anthony Main
This sample is for POCO only. So, default code generation must be turned off.
This approach doesn't work for self-tracking entities as well.
@Dennis and author,
Yes, sample is for POCO, but it doesn't seem to work to well with POCO Entity templates. My problem, the complex type the author says to create is generated by the T4 templates, especially the property ("Value"), in which we need to add implementation too (per author). Thus, how do we add our special wrapper implementation for our complex type, when the POCO Entity T4 templates will overwrite it ?
Do we have to define the complex type by using 'code-first', b/c I am missing something trying 'design-first' with T4 POCO Entity templates ?
Please help/
@Daniel, @AlexJ
You don't need to get the string before you use it. Just add third implicit conversion – to string, like this:
and you can use it like this:
It works by immediately converting enumValue to OrganizationTypeEnumWrapper, and later, where strings are to be compared, converts it to string by the implicit operator newly added.
The minus of this is casting, but it's like casting to (int) in original solution, and far way better than getting string before creating query.
A simpler version:
public class Participant
{
public int ParticipantId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username { get; set; }
[Column(Name="Gender")]
public int InternalGender { get; set; }
[NotMapped]
public Gender Gender
{
get { return (Gender)this.InternalGender; }
set { this.InternalGender = (int)value; }
}
public DateTime DateOfBirth { get; set; }
} tomorrow the ADO.NET team comes with more new advanced framework. How I can use my current business model in that case. Do you expect me to remove all the virtual keywords from my properties and other nasty things. if the ADO.NET team comes with a new advanced framework tomorrow. How I can use my business model in that case? Do I need to remove all the virtual keywords from the properties and other nasty things??
@Darren
I couldn't get your example to work.The property
' public Gender Gender' won't compile…
Got any suggestions?
Hi Alex,
As of today, is Enum supported in EF for .NET 4(I mean VS2010)? I could'nt find clear documentation for this. Can you help with a small example in case it's available?
Thanks
Is there an example project I can download from you Alex? I've been trying hard to get this thing to work and feel rather stupid in the process. I can't get it to work with WCF. When I set my wrapper object to the enum value it says I can't implicitly convert. Here is my wrapper:
public partial class AddressTypeWrapper
{
#region Primitive Properties
private AddressType _a;
public int Value
{
get
{
return (int)_a;
}
set
{
_a = (AddressType)value;
}
}
public AddressType EnumValue
{
get
{
return _a;
}
set
{
_a = value;
}
}
public static implicit operator AddressTypeWrapper(AddressType addressType)
{
return new AddressTypeWrapper { EnumValue = addressType };
}
public static implicit operator AddressType(AddressTypeWrapper addressTypeWrapper)
{
return addressTypeWrapper.EnumValue;
}
#endregion
}
I changed my entity property to be the wrapper type:
[DataMember]
public AddressTypeWrapper AddressTypeID
{
get;
set;
}
The above is good, but it could be cleaned up a bit with generics and a little black magic, if you want to reuse the Value and EnumValue properties (can't do anything with the conversion operators). And maybe someone could suggest better black magic for my EnumValue property?
namespace DataTest.Model
{
}
By the way, Mr. Microsoft, we sure would like Enum type parameter constraints (seriously, why can't I do this:
[where EnumType : Enum]? Why is that explicitly forbidden?
Oops…I posted old version. This better:
All this code to make EF support enums ? No, thanks.
Is there a way of enum support via entity designer (db first) via generated DbContext entities?
|
https://blogs.msdn.microsoft.com/alexj/2009/06/05/tip-23-how-to-fake-enums-in-ef-4/
|
CC-MAIN-2016-30
|
refinedweb
| 2,839
| 64.3
|
Lock a mutex
#include <pthread.h> int pthread_mutex_lock( pthread_mutex_t* mutex );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically. this function's name stands for "non-POSIX." <stdlib.h> #include <pthread.h> #include <unistd.h> #include <errno.h> #include <string.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int count = 0; void* function 1 second */ sleep( 1 ); } return 0; } void* function 2 seconds */ sleep( 2 ); } return 0; } int main( void ) { int ret_code; ret_code = pthread_create( NULL, NULL, &function1, NULL ); if (ret_code != EOK) { printf ("Couldn't create first thread: %s\n", strerror (ret_code)); } ret_code = pthread_create( NULL, NULL, &function2, NULL ); if (ret_code != EOK) { printf ("Couldn't create second thread: %s\n", strerror (ret_code)); } /* Let the threads run for 60 seconds. */ sleep( 60 ); return EXIT_SUCCESS; }
|
http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.neutrino.lib_ref/topic/p/pthread_mutex_lock.html
|
CC-MAIN-2018-26
|
refinedweb
| 127
| 61.73
|
Hi, today I spend some time learning pthreads ( ~ multithreading) programming.
I would rewrite my plugins for this capability, but basic question is if such plugin can be compiled for windows. So this is question for peoples like samj, who tend to compile plugins for windows.
Specifically, It needs to include following into .c file:
#include <pthread.h>
#include <semaphore.h>
I read that these libraries are not common/supported/whatever on windows.
So, may I go on with this job? Thanks
pthreads (win)
Bonjour,
I can not compile plugins for a while.
I'll wait for the release of Gimp 2.8 for build new environments to compile on Windows.
I failed to find out when
I failed to find out when gimp 2.8 is due to be released.
In theory, it would be too much work to maintain two versions - threaded and non-threaded, so I will not do this, but will go on with threaded version. Anyway, I have no new features in mind to implement (talking about aumask)....
There are threads in glib,
There are threads in glib, and your plug-iuns already depends on that library:
You can also consider to implement GEGL ops and make your plug-in use them:
And finally, the GIMP 2.8 release date:
This a list of tasks that have to be finished before GIMP 2.8 can be released. Obviously, instead of a fixed date, we get a moving target (i.e. if you publish the currently displayed date anywhere, if will already invalid tomorrow), but previous experience has shown that fixed dates aren't a useful approach.
fine, glib threading would do
fine, glib threading would do as well, I just looked at it and see there are no semaphores - this is a little complication, but...
as for gegl - with my programming knowledge about plugins and how plugins get and return data from and to drawable, I dont understand where would the gegl fit in this scheme. Simple tutorial would be nice - to understand basic concepts. But threading is my priority now...
threaded plugins pthread gthread
tibor95: have you made any more progress? If you have any references or examples, I would appreciate it.
I have been trying to thread a plugin. It seems to work fine using POSIX pthreads. Then I switched to glib GThread. Now it crashes sometimes. I could be mistaken, they both might be flawed and only one manifests itself. (Once you start using threads, there is randomness i.e. chance i.e. luck involved.)
The documentation on gtheads seems sparse. What concerns me most is needing to call g_thread_init(NULL) early in the program. This link also points out the need to wrap calls to gdk in gdk_threads_enter();" and "gdk_threads_leave()".-...
I understand that glib itself is threadsafe once you call g_thread_init. I suppose you must tell gdk and gtk functions that threads are calling them, if the called functions keep internal state in global variables.
The plugin I am threading does mostly computation in the threads, with few calls to glib, gdk, or gtk. It does use many glib types. but I think those are mostly macros. My best guess at the moment is that the progress functions like gimp_progress_update(), which are called from the threads, are at fault.
Hi bootchk, indeed
Hi bootchk,
indeed documentation is sparse and also it is hard to find somebody who is competent enough and willing to share his knowledge.
I have currently two multithreading plugins (saturation equalizer and advanced unsharp mask), if you want to look into code, look at first one, this one is simplier. Though both sources might be ugly.
I went with glib threading and I believe it is rock solid. In my code I use only these related calls:
g_thread_init
g_thread_create (for each thread)
g_thread_join (to wait untill all thread exits)
So Im not able to advice in relation to "gdk_threads_enter();" and "gdk_threads_leave()".
I also run into problem (my fault) when threads kept overwriting the same variables, it is up to programmer to prevent it.
My technique is to split image (let say it has 1000 rows) into equal parts according to number of threads - 3 in my case.
So first thread processes rows 0-333, second: 334-667 and the third thread remaining part of image.
As for progres indicator, only the first one thread is allowed to upgrade it.
Feel free to ask more questions :)
threads
Thanks,
An update on my plugin: I found that the problem indeed *SEEMS* to be the call to gimp_progress_update. My solution was to put a mutex on the call to it. So each thread can update progress. As you say, another solution is to have the threads communicate with the main thread and let it be the only thread that updates progress.
How exactly did you update progress? Do you just update progress as each thread completes, in your case, in thirds? Or did the threads update a mutexed global variable which the main thread spun on?
Your original post said you needed semaphores, but you latest response says you didn't? In my case, I used mutexes, because threads are reading pixels another thread is writing.
How did you decide how many threads to start? There doesn't seem to be any support in glib or elsewhere to determine how many threads can actually execute concurrently on the hardware. I am going to use 8. I don't think that hurts performance to have more threads than actual hardware cores or hyperthreads. My computer only has two.
Are you releasing your plugin in only the threaded version? I suppose if as you say glib is rock solid and it compiles on other platforms, there is no reason not to have just a single version. Could there be users out there wanting plugins running on older distros where glib possibly was NOT rock solid for threading?
What was your perfomance improvement? I found that with two cores, the plugin was at best 3/4 the time of unthreaded performance.
As for my original question,
As for my original question, you must understand that I was just learning multithreding and did not have exact idea what I want. At the end I ended with very simple dizajn, where I dont need mutexes nor semaphores.
As I said I run only three threads and run them once. In some early version I run new thread for every single pixel (it was with posix threads) and overhead was huge.
By my opinion at least linux/unix kernels are able to cope with many more threads than cores and are able to distribute CPU time evenly. I have two computers – single core and dual core. I decided for three threads because it seemed good compromise. But I would not afraid of 8 threads neither but I belive there are few peoples who has more than 4 cores. Anyway, in source you can easily increase number of threads. (search for #define THREADS 3)
In theory you can set „1“ there, but of course it would not avoid multithreading but just run one thread only instead. I believe multithreading in glib is old thing so no need to care for peoples would have old version of glib...
As for updating progress, this is the code:
if (data->id ==0 && x % 10 == 0 && !data->preview)
gimp_progress_update ((gdouble) x / (gdouble) data->endline);
That say, if the id of current thread is 0 and number of current row(x) can be divided by 10 and it is not preview, progress bar is updated by:
curent line / number of lines in first section of image
first section is section to be processed by first thread.
I dont have exact number of CPU utilization on dualcore, but It would be very close to 2x100%.
Feel free to ask more, I am not sure I answered all your questions.
threads
Intel quad cores with hyperthreading can have eight threads, and newer cpu's have six cores, and the trend is more cores.
Remember, main is a thread too. So if you create three threads, you actually have four threads. But probably the main thread is just waiting on the others, and on a quad core, main wouldn't be using its core fully.
The way you implemented progress, if the first thread completes first, progress bar says 100% but two thirds of the work is yet to be done. You can't guarantee that the threads will get equal CPU time. But usually they do, so probably it doesn't matter.
Many image algorithms are moving to the GPU, so threading could be a dead end. I think that is why one poster suggested GEGL. But that is a whole other topic. I think you would need to learn GL (OpenGL), not GEGL, to make a plugin using the GPU. I think GEGL uses the GPU via GL, but doesn't expose the GPU to plugins. I could be wrong.
Thanks again. You have given me an idea I need to use threads differently to get more speed up.
On my single core PC I did
On my single core PC I did not noticed any discrepancies between progress bar (based on first thread) and actual (visual) completion of work. But mainly - this is just image processing application, so it just doesnt matter much. Even one second inaccuracy would not be very noticeable. Remember also that after threads completion plugin does also other work which might not be reflected in progress bar altogether..
I was looking also at GEGL but found it not usable (for me), first there is absolute lack of tutorials on beginners level and second I found that I have to hand-code my algorithms anyway...
As for GL/openGL - Im comletely unamiliar with this topic, but I can agree that it has some potential in future....
And that you for your interest, you are first person ever I could discuss this topic :)
|
http://registry.gimp.org/comment/12774
|
CC-MAIN-2013-48
|
refinedweb
| 1,661
| 72.66
|
#include <search.h> void *tsearch(const void )); #define _GNU_SOURCE
#include <search.h> void tdestroy(void *root, void (*free_node)(void *nodep)); <search.h>.) The third argument is the depth of the node, with zero being the root. You should not modify the tree while traversing it as the the results would be undefined.
(More commonly, preorder, postorder, and endorder are known as preorder, inorder, and postorder: before visiting the children, after the first and before the second, and after visiting the children. Thus, the choice of name postorder is rather confusing.)delete() returns a pointer to the parent of the item deleted, or NULL if the item was not found.
tsearch(), tfind(), and tdelete() also return NULL if rootp was NULL on entry.
twalk() uses postorder to mean "after the left subtree, but before the right subtree". Some authorities would call this "inorder", and reserve "postorder" to mean "after both subtrees"..
#define _GNU_SOURCE /* Expose declaration of tdestroy() */ #include <search.h> #include <stdlib.h> #include <stdio.h> #include <time = (int *) xmalloc(sizeof(int)); *ptr = rand() & 0xff; val = tsearch((void *) ptr, &root, compare); if (val == NULL) exit(EXIT_FAILURE); else if ((*(int **) val) != ptr) free(ptr); } twalk(root, action); tdestroy(root, free); exit(EXIT_SUCCESS); }
|
http://www.makelinux.net/man/3/T/tsearch
|
CC-MAIN-2014-52
|
refinedweb
| 200
| 67.65
|
It's not clear to me how to set response.content_length in my CGI functions.
The MQX_RTCS User Guide says in section 8.2.14:
content_length
Length of the response entity from CGI script.
If you look at the web_hvac example there are conflicting examples of how to set the content_length field.
Example 1 - content_length is set to data_length
In cgi_index.c there is this code:
/* Calculate content length while saving it to buffer */ length = snprintf(str, BUFF_SIZE, "%ld\n%ld\n%ld\n", hour, min, sec); response.data = str; response.data_length = length; response.content_length = response.data_length; /* Send response */ HTTPSRV_cgi_write(&response); return (response.content_length);
This seems to match what it says in the MQX RTCS User Guide.
Example 2 - content_length is set to zero
In cgi_hvac.c there is this code:
response.ses_handle = param->ses_handle; response.content_type = HTTPSRV_CONTENT_TYPE_HTML; response.status_code = 200; response." "<html><head><title>HVAC Settings response</title>" "<meta http-equiv=\"REFRESH\" content=\"0;url=hvac.shtml\"></head>\n<body>\n"; response.data_length = strlen(response.data); response.content_length = 0; HTTPSRV_cgi_write(&response); if (!bParams) { response.data = "No parameters received.<br>\n"; response.data_length = strlen(response.data); HTTPSRV_cgi_write(&response); } response.data = "<br><br>\n</body></html>"; response.data_length = strlen(response.data); HTTPSRV_cgi_write(&response); return (response.content_length);
In this case there are multiple calls to HTTPSRV_cgi_write() and content_length is set to zero on line 8. It is never set to non-zero.
My question:
1. When should content_length be set to data_length and when should it be set to zero?
Thanks,
Paul
Hi Paul,
If content_length is set to zero in first call of HTTPSRV_cgi_write(), The server will signalize end of response entity by closing the connection and thus ignoring keep-alive flag of session. If you set content_length to non-zero value it is send to client to inform him about length of response entity and thus it is not required to close the connection and keep-alive can be used. Variable data_length is used for storing length of data to be written in one specific call of HTTPSRV_cgi_write().
So in short:
I hope this answered your question.
P.S: In MQX 4.2 there will be support for chunked transmission encoding so you will not have to worry about content length.
Best regards,
Karel
|
https://community.nxp.com/thread/332422
|
CC-MAIN-2018-22
|
refinedweb
| 374
| 61.93
|
(This post is a part of a tutorial series on Building REST APIs in Django)
In our last post about Building APIs in Django, we explained why using Django REST Framework would be a good idea. In this post, we will start writing our APIs using this awesome framework. DRF itself works on top of Django and provides many useful functionality that can help with rapid API development.
Installing Django REST Framework
We have to install DRF first. We can install it using
pip as usual.
pip install djangorestframework
Once the installation succeeds, add
rest_framework to the
INSTALLED_APPS list in
settings.py.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api' ]
Now we are ready to start building our awesome APIs!
Using APIView
APIView class is quite similar to Django’s
View class except it is more REST-y! The
APIView class can be considered as quite similar to the Flask Resource class from our Flask Tutorial. An
APIView has methods for the HTTP verbs. We can implement our own methods to handle those requests the way we want.
Let’s modify the function we wrote in our first post to use
APIView instead.
from rest_framework.views import APIView from rest_framework.response import Response class HelloWorldView(APIView): def get(self, request): return Response({"message": "Hello World!"})
We have done two things –
- Our
HelloWorldViewextends
APIViewand overrides the
getmethod. So now DRF knows how to handle a
GETrequest to the API.
- We return an instance of the
Responseclass. DRF will do the content negotiation for us and it will render the response in the correct format. We don’t have to worry about rendering JSON / XML any more.
Since we are now using a class based view, let’s update the urlconf and make the following change:
url(r'^hello', HelloWorldView.as_view(), name="hello_world")
That’s all the change that is necessary – we import the class based view and call the
as_view method on it to return a view that Django can deal with. Under the hood, the
as_view class method works as an entry point for the request. The class inspects the request and properly dispatches to the
get,
put etc methods to process the request. It then takes the result and sends back like a normal function based view would do. In short, the
as_view method kind of works as a bridge between the class based view and the function based views commonly used with Django.
The Web Browsable API
If you visit `` you will now see a nice html view with our json response displayed along with other useful information (response headers). This html view is an excellent feature of DRF – it’s called the web browsable API. The APIs we create, DRF automagically generates a web view for us from where we can interact with our API, testing / debugging things. No need for swagger or any other external clients for testing. Awesome, no?
Function Based APIView
We can also use a function based form of APIView where we write a function and wrap it using the
api_view decorator. An example would look like this:
from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(["GET", "POST"]) def hello_world(request): if request.method == "GET": return Response({"message": "Hello World!"}) else: name = request.data.get("name") if not name: return Response({"error": "No name passed"}) return Response({"message": "Hello {}!".format(name)})
And in the
urls.py, the entry will look like this:
url(r'^hello', hello_world, name="hello_world")
I mostly use function based views when things are really simple and I have to handle just one type of request (say,
POST or
GET). But in case I have to handle multiple type of requests, I will then have to check
request.method to determine the type and handle accordingly. I find the class based view cleaner and well organized than writing a bunch of if else blocks.
You can read more about the function based APIView in the docs.
Accepting Input
We have seen how to write a simple end point to say “hello world!” – that is great. But now we must learn how we can handle inputs from our user. For this demonstration, on our
/api/hello endpoint, we would accept a
name in a POST request. If the name is passed, we will show a customized greeting. Let’s get to work!
class HelloWorldView(APIView): def get(self, request): return Response({"message": "Hello World!"}) def post(self, request): name = request.data.get("name") if not name: return Response({"error": "No name passed"}) return Response({"message": "Hello {}!".format(name)})
We have added a
post method that should handle the
POST requests. Instead of
request.POST, we would use
request.data which works across
PUT,
PATCH – all other methods too. If the name is not passed we send error message. Otherwise we send a hello world message.
With that code written, let’s try it out –
$ curl -H "Content-Type: application/json" -X POST -d '{"name":"masnun"}' {"message":"Hello masnun!"}
Aha, things worked as expected! Cool! What if we don’t pass the
name?
$ curl -H "Content-Type: application/json" -X POST {"error":"No name passed"}
It works exactly like we wanted it to! Fantastic!
What’s next?
In this post, we saw how the APIView works and how we can accept inputs and send responses for different http verbs. In the next post, we will discuss about serializers and how they can be useful.
If you would like to get notified when we post new content, please subscribe to our mailing list. We will email you when there’s something new here 🙂
|
http://polyglot.ninja/page/3/
|
CC-MAIN-2021-17
|
refinedweb
| 946
| 74.69
|
Hi,
I wrote a program to convert decimal numbers 0 -254 to characters and write it in a file. The program reads the characters back and gives the corresponding decimal numbers. But when I write corresponding characters of numbers 10,11,12, and 13, the program reads them back as 204. I cannot figure out how to get 10,11, 12 and 13 back. Any help will be appreciated. Here's the code:
Code:#include <iostream> #include <fstream> using namespace std; int main () { int x = 11; ofstream outfile ("output.dat", ios::out); if (!outfile) { exit (1); } outfile<<( unsigned char)(x); outfile.close(); int p; char ch; unsigned char ch1; ifstream infile; infile.open("output.dat"); if (!infile) { exit (1); } while ((ch= infile.peek()) !=EOF ) { infile >> ch1; p = int (ch1); cout<<p<<endl; } infile.close(); return 0; }
|
http://cboard.cprogramming.com/cplusplus-programming/84096-problem-writing-ascii-characters-file.html
|
CC-MAIN-2014-15
|
refinedweb
| 136
| 69.79
|
function formatDocs($filename, $title='') {
$content = file_get_contents($filename);
$content = str_replace("\n",'[\n]', $content);
// Fix links to man pages.
$content = preg_replace('/([^<]+)<\/a>/',
'$3', $content);
$content = preg_replace('/([^<]+)<\/a>/',
'$3',$content);
// External modules -- link to search.cpan.org: they WILL have it!
// Note that this is not perfect. There's some complication because we don't know how many / to replace with ::. My REGEX-fu is probably not up to snuff.
// It assumes that starting the URL with ../ means that it is out of the PDL namespace, and therefore an external module. But if the current doc is (say) PDL::IO::FITS and we want to link to PDL::Core, then there will be some leading ../ but still within the namespace. There's only so much DAL can do with PHP--I think the problem is with pod2html, honestly. Anyway, it's no worse than the previous solution (kept, but commented, below). Note that this way there is no way to specifically go to any anchored section on the page, because of the CPAN redirect, so we just drop it. Ultimately we should just link to metacpan, but they have no docs for modules that come from .pd files, so we're stuck for now.
if (preg_match_all('//',$content,$matches,PREG_SET_ORDER)) {
// print "
I matched " . count($matches) . " times!\n";
for ($i=0; $i";
// This was the original version, which was also not perfect.
// External modules -- link to perldoc.perl.org and hope they have it.
// $content = preg_replace('//',
// '', $content);
// Remove body tags.
$content = preg_replace('/^.*]*>/', '', $content);
$content = preg_replace('/<\/body>.*$/', '', $content);
// Finished.
$content = str_replace('[\n]', "\n", $content);
$content = preg_replace('/\n+/', "\n", $content);
return "
See also: How do I search for a function?
|
http://sourceforge.net/p/pdl/pdl-www/ci/master/tree/index.php?format=raw
|
CC-MAIN-2015-27
|
refinedweb
| 273
| 68.77
|
Including My Own Folder Of Components In The Namespace Which is the best practice ?
#1
Posted 30 April 2014 - 09:04 AM
I need this folder to be added to the namespaces that Yii autoloads for them to work well.
Any recomendations ?
MSc. Cristian Tala Sánchez
#2
Posted 30 April 2014 - 09:33 AM
CTala, on 30 April 2014 - 09:04 AM, said:
I need this folder to be added to the namespaces that Yii autoloads for them to work well.
Any recomendations ?
I usually put extended components in "components" folder: \common\components (in advanced application template)
#3
Posted 30 April 2014 - 11:40 AM
MSc. Cristian Tala Sánchez
#4
Posted 02 May 2014 - 02:42 PM
#5
Posted 02 May 2014 - 04:26 PM
CTala, on 30 April 2014 - 11:40 AM, said:
You don't need to do anything special. Just create/use a folder and set the appropriate namespace.
For example,
// app\libraries\MyLibrary.php <?php namespace app\libraries; class MyLibrary{ }
Then call it with the following:
$myLibrary = new \app\libraries\MyLibrary();
#6
Posted 03 May 2014 - 08:21 AM
So if I have something inside ( a class ) and I create a namespace for it, it does not work.
I can "Include it" the old way, but I wanted to know if there is a proper way to do it.
MSc. Cristian Tala Sánchez
#7
Posted 03 May 2014 - 08:26 AM
CTala, on 03 May 2014 - 08:21 AM, said:
Can you post the code - how are you defining and calling the class?
#8
Posted 06 May 2014 - 11:27 AM
I have a class called "MyDbManager" that actually I created under the rbac folder of yii, due that I could not make it work from an other folder. This class should be called in the config file of Yii under components:
'authManager' => [ 'class' => 'yii\rbac\MyDbManager', ],
If I have a folder in the root directory called components and my components I can not access that Class. This class is not being loaded due that I think that this folder is not in the path that Yii loads by default.
So the question, which is the best way to create a folder where I will keep my component and they will be loaded by Yii ?
MSc. Cristian Tala Sánchez
#9
Posted 06 May 2014 - 11:35 AM
CTala, on 06 May 2014 - 11:27 AM, said:
I recommend to create this class in a separate folder and not touch the core yii folders as that may get overwritten. For example you could create it under app/components or common/components and extend any yii classes in here.
namespace common\components; class MyDbManager extends yii\rbac\DbManager { //your code }
You can then set this in your config like:
'authManager' => [ 'class' => 'common\components\MyDbManager', ],
#10
Posted 06 May 2014 - 11:37 AM
- Create the folder
I created my folder under the root directory and is called components.
- Creating the namespace as the folder', ],
I think that now I understand a little bit better namespaces. I will write a wiki with this information in case someone has the same trouble that I had.
MSc. Cristian Tala Sánchez
#11
Posted 06 May 2014 - 12:57 PM
CTala, on 06 May 2014 - 11:27 AM, said:
Wait, what? Are you referring to the vendor/yiisoft/yii2 folder? You shouldn't be touching anything inside the vendor folder! That is for composer to manage properly. (It's dangerous because it "updates" by deleting/reinstalling the packages, meaning any changes you make will disappear.)
CTala, on 06 May 2014 - 11:37 AM, said:
I think that now I understand a little bit better namespaces. I will write a wiki with this information in case someone has the same trouble that I had.
That's exactly how I described it in my first post here. What did you do differently that made it not work the first time but then did work the second time? Perhaps you should put that in the wiki as well.
|
http://www.yiiframework.com/forum/index.php/topic/53853-including-my-own-folder-of-components-in-the-namespace/
|
CC-MAIN-2016-36
|
refinedweb
| 671
| 66.37
|
A Python module for creating Excel XLSX files.
Project/BMP/WMF/EMF images.
- Rich multi-format strings.
- Cell comments.
- Integration with Pandas.
- Textboxes.
- Support for adding Macros.
- Memory optimization mode for writing large files.
It supports Python 2.7, 3.4+ and PyPy and uses standard libraries only.
Here is a simple example:
import xlsxwriter # Create an new Excel file and add a worksheet. workbook = xlsxwriter.Workbook('demo) # Insert an image. worksheet.insert_image('B5', 'logo.png') workbook.close()
See the full documentation at:
Release notes:
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
XlsxWriter-1.2.2.tar.gz (257.1 kB view hashes)
Built Distribution
XlsxWriter-1.2.2-py2.py3-none-any.whl (140.6 kB view hashes)
|
https://pypi.org/project/XlsxWriter/1.2.2/
|
CC-MAIN-2022-27
|
refinedweb
| 143
| 54.69
|
2. TPBot Samples for Python
2.1. Add Python File
Download to unzip it: EF_Produce_MicroPython-master Go to Python editor
We need to add TPBot.py for programming. Click “Load/Save” and then click “Show Files (1)” to see more choices, click “Add file” to add TPBot.py from the unzipped package of EF_Produce_MicroPython-master.
2.2. Samples
Sample 1: Drive the car at a full speed.
from microbit import * from TPBot import * tp = TPBOT() tp.set_motors_speed(100,100)
Result
The speed of the left and right wheels is at 100, the car moves forward at the full speed.
Sample 2: Turn the headlights on in random colors
from microbit import * from TPBot import * import random tp = TPBOT() while True: R = random.randint(0,255); G = random.randint(0,255); B = random.randint(0,255); tp.set_car_light(R,G,B) sleep(500)
Result
The headlights light up in different colours at random.
Sample 3: Obstacles avoidance
from microbit import * from TPBot import * tp = TPBOT() while True: i = tp.get_distance(0) if i>3 and i<30: tp.set_motors_speed(-50, 50) sleep(500) else: tp.set_motors_speed(50, 50)
Result
The TPBot turns its direction once it detects any obstacle ahead of it.
Sample 4: Link-tracking
from microbit import * from TPBot import * tp = TPBOT() while True: i = tp.get_tracking() if i == 10: tp.set_motors_speed(10, 50) if i == 1: tp.set_motors_speed(50, 10) if i == 11: tp.set_motors_speed(25, 25)
Result
The TPBot drives along with the black line.
Sample 5: Control the servo
from microbit import * from TPBot import * tp = TPBOT() while True: tp.set_servo(1,180) sleep(1000) tp.set_servo(1,0) sleep(1000)
Result
The servo connecting to S1 continues driving back and forth.
|
https://www.elecfreaks.com/learn-en/microbitKit/TPbot_tianpeng/TPbot-python.html
|
CC-MAIN-2022-27
|
refinedweb
| 286
| 61.43
|
NOTE: There is a better text-to-speech package that I would recommend for Python. It supports espeak, but also supports native Windows and Mac speech APIs. Check out my Text-to-speech in Python with pyttsx3 tutorial. It also covers how to use English and Russian voices but works in Windows.
Install espeak and the python-espeak package in Ubuntu with apt-get.
sudo apt-get install espeak python-espeak
Next, download the Russian dictionary pack from. Download the version that matches your installed version. If you need to check what version you have installed use apt-cache.
apt-cache show espeak
After downloading the zip file, unzip it to get the dictionary file. Move it in to the espeak-data folder and overwrite the existing # and unzip it and replace the existing ru_dict file.
wget
unzip ru_dict-48.zip
sudo mv ru_dict-48 /usr/lib/x86_64-linux-gnu/espeak-data/ru_dict
In Python 2, You must specify the encoding in the first or second line to allow Cyrillic Characters.
# -*- coding: utf-8 -*-
from espeak import espeak
espeak.set_voice("ru")
espeak.synth("где хакер")
while espeak.is_playing:
pass
|
https://www.devdungeon.com/content/text-speech-python-espeak
|
CC-MAIN-2020-16
|
refinedweb
| 189
| 59.7
|
Im working on a project where i want to use the UART Pins. Therefore I want to use the "pigpio"-library.
I am just not able to receive bytes from the UART device.
For trying out I "shortcutet" the TxD and RxD of one Raspberry (3B+), wrote that little code to send letters
and with minicom I could verify that those letters where sent and received.
Code: Select all
#include<iostream> #include<pigpio.h> using namespace std; int x = gpioInitialise(); int main() { char p[] = "/dev/ttyS0"; int port = serOpen(p, 9600, 0); char buf[] = {'a','b','c'}; serWrite(pot, buf, 3); serClose(port); return 0;
Same thing with another Raspberry (Zero WH). So this worked fine.
But now if I connect the TxD of one Raspberry with the RxD of another, run the code on one and minicom on the other Pi, this doesn't work anymore. And I just can't get my head around why this wouldn't work.
Maybe someone can give me a little hint. Thanks!
|
https://www.raspberrypi.org/forums/viewtopic.php?f=33&t=250524&p=1529598
|
CC-MAIN-2019-43
|
refinedweb
| 170
| 80.92
|
New features and enhancements to spring 4.0
Spring is initially released in 2004 years later, with a few significant modifications, spring 2.0 provides xml namespaces and aspectj, spring 2.5 includes configuration.
4. 0 ve ion is the last significan not modification, and a new feature for the fi t time full support for java 8. You can still continue to use older versions of java, but the minimum requirements are promoted to java se 6. We also take advantage of this significant modification to remove many outdated classes and methods.
Upgrade to spring 4.0 guide manual see spring framework gighub wiki.
3. 1 improved getting started experience.
The new spring. Io web site provides a complete introduction to you to learn spring. More guides refer to the 1. Spring getting started for this document. The new web site also provides in-depth understanding of many projects published under spring.
If you're a maven user, you might be interested in the material listing pom file that's now published in each spring version.
3. 2 removes the obsolete packages and methods.
4. 0 versions remove all obsolete packages and many obsolete classes and methods. If you're upgrading from previous releases, you need to ensure that all calls to obsolete apis are fixed.
Full change please refer to the api differences report.
Note that optional third-party dependencies have been upgraded to the version of 2010/2011 ( that's, spring 4 only supports releases after 2010 years ), especially for hibernate 3.6 +, ehcache. For an exception, spring 4 requires hibernate validator 4.3 + and jackson2. 0 + ( spring 3.2 keeps support for jackson1, 8/1, 9, but now obsolete ).
3. 3 java 8 ( and 6 and 7 ).
Spring 4.0 provides support for several new features of java 8, allowing use of lambda expressions, using method references in spring callback interfaces. A good support for java. Time ( JSR-310 ) is to transform several existing annotatio & into @ repeatable, and you can use the parameter name of java 8 to build the code that enables debugging information ( based on the compiler flags of parameters ). ( compiler flags, translators note: Parameter name discovery is the name of the parameter through reflection, not the type.
Spring has retained compatibility with older versions of java and jdk, specifically for java se 6 and higher versions ( lowest jdk6. 18, released in 2010 ). Nevertheless, we recommend that new projects based on spring 4 use java 7 or 8.
3. 4 java ee 6 and 7.
Java ee 6 + and its associated jpa 2.0 and servlet 3.0 are considered the baseline of spring 4. For compatibility with google app engine and old application server, you might want to deploy spring 4 in the servlet 2.5 environment. However, servlet 3.0 + is highly recommended, and it's also a prerequisite for spring testing, as well as a prerequisite for simulation package testing development environment settings.
If you're a websphere 7 user, be sure to install jpa 2.0 packages, if you're weblogic 10.3.4 or later, install the jpa 2.0 patch so that spring 4 can compatibility.
More, spring 4.0 now supports specifications applicable to java ee 7, especially jms 2.0, jta 1.2, jpa 2.1, bean validation fso, and jsr 236 concurrency utilities. Like normal, this support is only intended for a person, such as in tomcat or standalone environments only. However, when spring applications are deployed on a server that's deployed in java ee 7.
Note that hibernate 4.3 is a provider of jpa 2.1, so it's only supported in spring 4.0. Likewise, hibernate validator 5.0 is a provider of bean validation 1.1. As a result, both aren't supported by spring 3.2.
3. 5 groovy bean definition dsl.
From spring 4.0, you can define external beans using groovy dsl. In concept, this is similar to using xml configuration beans, but you can use a simpler syntax. Using groovy also makes it easy to embed bean definitions directly into the boot } } }
Learn more about groovybeandefinitionreader 's java docs.
Improvement of 3. 6 core container.
The core container has several improvements:
Improvements to 3. 7 web.
The deployment of servlet 2.5 servers is retained, but spring 4.0 is now focused on deployment of servlet 3.0 + environments. If you use the spring mvc test framework, you need to ensure that a compatible jar package with servlet 3.0 is included on the test classpath.
In addition to the support for the following, in spring web modules, the following improvements are also included:
3. 8 websocket, sockjs and stomp messaging.
The new spring web socket module is fully supported by the client and server based on web socket. It's compatible with jsr 356, java websocket apis, and also provides a back option ( for example, web socket emulation ) for browsers that don't support sockjs.
The new spring messaging module supports stomp as a child of a web socket used with an annotation program model to be used by the path from and processed. As a result, a @ controller can contain both @ requestmapping and @ MessageMapping methods to handle http requests and messages from the client. New spring messaging modules also contain key abstractions extracted from the previous spring integration project as the basis for applications, such as message, MessageChannel, mesaagehandler, and so on.
For more details, refer to the 25 web socket support section.
Improvements to 3. 9 tests.
In addition to removing code that's obsolete in the spring test module, spring 4.0 introduces several new features for unit tests and integration tests:
Almost all annotations of the spring test module ( for example, @ ContextConfiguration, @ WebAppConfiguration, @ ContextHierarchy, @ activeProfiles, etc. ) can be used as a meta annotation to create custom annotations and reduce duplicate configuration in test suites.
A valid bean definition profile can be parsed programmatically, as long as you simply implement custom activeprofilesresolver and register the @ activeProfiles resolver property.
The spring core module introduces a new socketutils class for scanning locally idle tcp and udp server ports. This feature isn't specific to testing, but it's useful when writing integrated tests that require sockets, for example, to start the smtp server, ftp server, servlet container.
From spring 4.0, org, springframework, mock, web package simulation collection is based on servlet 3.0. In addition, some servlet api emulation ( for example, MockHttpServletRequest, MockServletContext, etc. ) has a few enhancements and can be improved by configuration.. Csdn. net/tangtong1/article/details/51326887.
|
https://www.dowemo.com/article/46309/spring-official-document-translation-(-chapter-3-)
|
CC-MAIN-2018-26
|
refinedweb
| 1,097
| 59.6
|
My new post for beginners and learners. So here We'll learn about Import and Export in a very very easy way. Let's go
Import and Export
- In JavaScript ES6, we can import and export functionalities from modules.
- These can be functions, classes, components, constants, essentially anything assign to a JavaScript variable.
- Modules can be single files or a whole folder with one index file as an entry point.
Why to use Import and Export
- The import and export statements in JavaScript help you to share code across multiple files to keep it reusable and maintainable.
- Encapsulation : Since not every function needs to be exported from a file. Some of these functionalities should only be used in files where they have been defined. File exports are a public API to a file, where only the exported functionalities are available to be reused elsewhere. This follows the best practice of encapsulation.
Export before declaration
export const name = Rahul; export function sayHi(user) { alert(`Hello, ${user}!`); } // no; at the end
And import them in another file with a relative path to the first file.
import { name } from './firstfile.js'; console.log(name); // Rahul sayHi(name); // Hello, Rahul! import * as person from './firstfile.js'; console.log(person.name); // Rahul
Imports can have aliases, which are necessary when we import functionalities from multiple files that have the same-named export.
import { name as firstName, sayHi } from './firstfile.js'; console.log(firstName); // Rahul
There is also default statement, which can be used for a few cases:
- To export and import a single functionality
- To highlight the main funuctionality of the exported API o a module To have a fallback import functionality
const person = { firstName: 'Rahul', lastName: 'Singh', }; export default person;
We can leave out the curly braces to import the default export.
import developer from './firstfile.js'; console.log(developer); // { firstName: 'Rahul', lastName: 'Singh' }
That was it explaining the
import and
export in JavaScript. Hope you have found it useful.
Need Help
Need help in raising funds to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.
😎Happy Coding | Thanks For Reading⚡
Discussion (1)
You need to enclose (name = "Rahul") or define Rahul as a variable. Otherwise it'll be misleading to beginners.
|
https://dev.to/rahxuls/what-is-export-and-import-in-javascript-3p6o
|
CC-MAIN-2021-10
|
refinedweb
| 382
| 57.37
|
This example will illustrate the propogation delay through the off-the-shelf NOT gates provided in libLCS. Two NOT gates with the clock pulse as inputs are set up. One of the NOT gates has a propogation delay which is more than the clock pulse width, and the other has a propogation delay which is less than clock pulse width.
#include <lcs/not.h> #include <lcs/clock.h> #include <lcs/simul.h> #include <lcs/changeMonitor.h> using namespace lcs; int main() { Bus<> s1, s2; Clock clk = Clock::getClock(); Clock::setPulseWidth(5); // Initialising an NOT gate with a propogation delay of // three system time units. This delay is less than the // pulse width of the clock signal. Not<3> n1(s1, clk); // Initialising an NOT gate with a propogation delay of // seven system time units. This delay is more than the // pulse width of the clock signal. Not<7> n2(s2, clk); // Initialising change monitors to monitor the output of // the two AND gates. ChangeMonitor<> s1m(s1, "Output1", DUMP_ON), s2m(s2, "Output2", DUMP_ON); Simulation::setStopTime(50); Simulation::start(); return 0; }
The output when the above program is compiled and run is as follows.
At time: 3, Output1: 1 At time: 7, Output2: 1 At time: 8, Output1: 0 At time: 12, Output2: 0 At time: 13, Output1: 1 At time: 17, Output2: 1 At time: 18, Output1: 0 At time: 22, Output2: 0 At time: 23, Output1: 1 At time: 27, Output2: 1 At time: 28, Output1: 0 At time: 32, Output2: 0 At time: 33, Output1: 1 At time: 37, Output2: 1 At time: 38, Output1: 0 At time: 42, Output2: 0 At time: 43, Output1: 1 At time: 47, Output2: 1 At time: 48, Output1: 0
Below is the screenshot of the gtkwave plot of the generated VCD file.
|
http://liblcs.sourceforge.net/delay_example_1.html
|
CC-MAIN-2017-22
|
refinedweb
| 300
| 66.67
|
25 February 2011 18:43 [Source: ICIS news]
LONDON (ICIS)--Lubricants demand in India, which is expected to overtake China as the world’s fastest growing major economy, could expand by more than 19% from 2009 to 2.23m tonnes in five years, said an industry expert on Friday.
Industrial lubricants are likely to be the fastest growing segment, followed by the consumer and commercial sectors, said Kline & Co’s Geeta Agashe.
Agashe spoke at the 15th ICIS World Base Oils & Lubricants Conference in ?xml:namespace>
Industrial oils and fluids, which accounted for slightly over half of India’s total lubricants demand in 2009, was projected to grow at 4.5% per year to 1.18m tonnes in 2014, according to Agashe. The country’s total lubricants consumption was at an estimated 1.86m tonnes in 2009.
A sizeable portion of the growth in industrial lubricants demand would come from the power generation plants, as well as the automotive and auto-component industries, she added.
Consumer lubricants consumption, driven mainly by rising car and motorcycle population, could expand to 214,000 tonnes by 2014, based on a projected annual growth rate of 3.3% per year, Agashe said.
The market is also expected to shift towards better quality and lighter viscosity engine oils, partly because of higher emission standards and stricter requirements by the original equipment manufacturers (OEM).
By 2014, 5W and 0W lower viscosity engine oils are expected to make up around 10% of the market in
Growth in the commercial automotive lubricants sector, which includes heavy duty engine oil for buses and trucks, as well as lubricants for agricultural equipment such as tractors, is expected to increase at a yearly rate of 2.6% to 834,000 tonnes in 2014, she said..
|
http://www.icis.com/Articles/2011/02/25/9439042/indias-lubricants-demand-predicted-to-see-strong-growth.html
|
CC-MAIN-2013-20
|
refinedweb
| 294
| 52.7
|
Please also note what I mean by "migration" (from the comments):.
Original post follows…
I just upgraded a simple app I wrote yesterday from an earlier version of Flex 4 (Gumbo) to the latest SDK and I got hit with the Fx prefix to namespace changes. Needless to say, I'm not impressed at all.
With the Fx prefix, I could easily layer Gumbo functionality into my existing apps and easily mix Spark and Halo without changing existing code or libraries. This ability is now gone.
I had to go through both my code and third-party libraries to add namespaces and I even had to alter the CSS. Previously, I had no such headaches and everything Just Worked (tm). Mixing Flex 3 and 4 was a joy. Not any longer.
This is a huge step backwards for anyone wanting to migrate existing Flex 3 apps to Flex 4 or reuse components. It makes the transition to Flex 4 and the creation of hybrid Flex 3/4 apps a real pain. It’s the triumph of formalism over pragmatism and the platform will suffer as a result.
And this namespace soup is going to make it all the more confusing for people new to the Flex platform to make sense of things.
Flex and similar technologies are commodities and compete in a supply market. The simpler things are, the more people will use them, and the higher the chances of the platform surviving and flourishing. Simplicity, user experience (yeah, even for a framework/platform) are key.
This namespace change adds lots of complexity for very little gain. It may satisfy the formalists who are probably as we speak trying to find a way to incorporate XSLT into the Flex workflow somehow and whose wet dreams would be a shift from ActionScript to Java for the platform but I hope that everyone involved understands the ramifications this move will have on developers who are new to the platform (so is that mx: again? No? fx: ... oh but that tag is s: and oh, that’s the language namespace but that’s a library... what again? huh? Just a sec, I think SilverLight was easier...) as well as for people migrating and transitioning existing Flex 3 applications.
Flex gods, please reconsider.
Update: As some of you have pointed out, my experience was exacerbated because I was porting from a previous version of Flex 4 to the latest Flex 4 SDK. You're right that this made my porting experience more difficult than a straight Flex 3 to Flex 4 port would have been since I had removed namespaces on all mx and Spark (previously Fx) components. However, I stand by my core point which is that the introduction of these language and library namespaces, along with namespaces in CSS makes it more difficult than necessary to port apps and will be more confusing for developers who are new to the platform.
A number of you have pointed out that the Fx prefix was not a long-term solution and that we would be faced with a similar choice for Flex 5. I don't feel that that's accurate. Flex 5 could keep using the Fx prefix for new components as I don't see such a radical overhaul of the component system occurring in the next version.
And while it's true that we already have namespaces, we've now introduced two framework-level namespaces and separated library namespaces and also introduced namespaces into CSS. Basically, we've introduced a lot of complexity for what I would argue is very little gain.
I'm sure tooling will take care of some of this complexity (and that should work in Adobe's favor and translate to more Flex Builder licenses sold even though they were not the ones to instigate this change). However, when you have to rely on tooling perhaps the problem is that the underlying technology is too complex. There is something sublimely beautiful about not needing any tooling whatsoever in Python, for example, that speaks volumes about the elegance of the language. Let's just say that I don't believe Flex would be in this namespace soup if Guido were calling the shots.
That said, Flex is still the most elegant rich-client technology I know. Yes, I love the tools in Cocoa and Objective-C is quite a marvelous achievement when you consider the limitations of C that they had to work with but there are also up-and-coming contenders ranging from Nokia's Qt to Unity 3D that are vying for the limited attentions of developers in a supply market. Simplicity is a key factor in differentiating your platform and wooing developers.
Simplicity is not something to be ashamed of. It does not make your Code Fu any less if you have simple tools and languages to work with. It just makes you all the more productive and lets you concentrate on crafting that most important part of your application: the user experience.
Flex is simple. We should try our utmost to at least preserve this simplicity, if not to take it a step further in each release.
Flex Fail Whale from Twitter Fail Whale by Yiying Lu
I was/am doing the same yesterday and today and you’re completely right.
At first sight I thought it was not so bad and that I just couldn’t see the tree trough the forest, but with this namespace soup (jummie) it’s like not seeing a forest trough another forest in a swamp (or something like that, you get what I’m saying right?)
Surely someone can (and will) write a tool or a plugin to automate this.
Unfortunatly, this is the pain that we will suffer when we use beta, or in this case, alpha level software in our projects. The Flex4 SDK is not complete yet, and won’t be for quite some time. The SDK you used earler was even doubly so. To move from alpha to alpha is not really a supported workflow they are targeting (people will be moving from Flex 3 -> Flex 4 once it’s complete).
The beauty about the way they are doing things right now is that you can take your Flex 3 code, and with a handful of tweaks, compile it right in Flex 4. This is because the mx namespace from 2006 /WILL NOT BE CHANGING/ as it would have if they introduced the Fx prefix. I don’t expect it to be much more of a pain to port a 3.0 to a 4.0 app than a 2.0 to a 3.0.
Just give it a few more months to bake out. They had a target to have everything switched from the FxButton to Fx:Button model by beta one, and I feel that they will be close. The builds in between are rough.
I think this has nothing to do about the state of a application Nick. Its a basic thing that by adding this “feature” Aral as tester felt it was a big step backwards to the former releases.
As I worked with namespaces in the past I thought: Why do we need them in first place? Packages are namespaces already: why to indulge two ways of them? The code ain’t getting more useful or better to read.
Its been used for overloading where actually real overloading would be a lot more appropriate feature. Its been used for unit testing where annotation would have been a lot nicer.
Well lets see, maybe they found some nice reason but it looks like its just some typing exercise.
So I’m confused.
Is it purely Flex 4.olderalpha to Flex 4.neweralpha porting that is causing these problems. Or is it Flex 3 to Flex 4 porting that is causing these problems?
I haven’t looked into Flex 4 extensively, could someone give a small example?
I think this was done under great pressure of community.
Surely this is going to be better in the long run though?
And doesn’t Flex Builder autocomplete your code, so you won’t have to worry about the namespaces? I guess it would suck to change all your existing code, but won’t it be a better model for the future?
[...] prefix in Gumbo revisited May 26th, 2009 Goto comments Leave a comment Aral Balkan blogged about what he called an epic FAIL of removing the Fx prefix from [...]
humm the FX prefix change to a fx: namespace
have been discussed few months ago here
the change was driven by the community of Flex developers
see the votes (100+) on JIRA
if you’re not happy with the change, you’ll have to convince not only Adobe but also the whole community who voted for this particular change
Blogged my thoughts on the Fx prefix issue here:
As zwetan also wrote, it got reported on the public Flex bugbase October 30th last year, 117 votes to drop the Fx prefix in favor of namespaces and has been extensive debate about it in the community. I think there’s little chance of turning that decision back now.
bugger. all the code formating is lost so that post isn’t going to make much sense ;(
I haven’t played with Flex 4 at all yet, but I am making production Flex 3 apps and still consider myself just a tinkerer in it. However, from the very beginning of learning Flex I was introduced into namespaces beyond mx — custom components for instance.
I want a Flex 4 component? I’ll use fx namespace. Flex 3 component: mx namespace. I don’t really see the confusion though my view is admittedly from the sidelines.
I’m pointing out my own real-world experience in porting a Flex 3 app to Flex 4 (and, as pointed out, from a previous version of the Flex 4 SDK to the latest). The “handful of tweaks” pointed out earlier _were not_ necessary when going from Flex 3 to the earlier Flex 4 SDK (before the namespaces “feature”).
Unfortunately, we’ve seen all this before with the additional complexities introduced into AS3 at the behest of a couple of extremely niche players whose needs are not mirrored in the majority (e.g., Google, etc.) The JavaScript community abandoned AS3/ECMAScript 4 for a reason. (I love a lot about AS3 but it could have been simpler).
Looks like we’re introducing some similarly unnecessary complexity into Flex now with this move to language/library namespaces.
@thebouv: No offense, but part of the problem is that there’s a lot of commentary and “me too” comments from the sidelines on this issue. I’d like to hear from people who are _actually porting stuff to Flex 4 from Flex 3_ and also the thoughts of developers taking up Flex 4 for the first time.
i.e., less theory, more empirical evidence please. My own _experience_ has been less than stellar. The _experience_ I had porting a different (larger) Flex 3 app to Gumbo with the previous Fx prefix was much simpler.
Looking forward to hearing about your _experiences_ with this.
Hey Peter, just replied to your post on your blog; here’s a proof-read version: developers .
@nouba: I wouldn’t call 100 votes “great pressure”, especially since quite a number of those were probably “me too” votes without a firm grasp of the ramifications. The real impact of this will become apparent months, if not years after the release of Flex 4 when people actually start migrating their applications to it.
@Marc Hughes: The issues will hit people migrating from Flex 3 to Flex 4. The previous workflow required absolutely no changes to existing code. This update requires that you update your existing code, even third party libraries and CSS. That’s a big step backwards and will affect adoption of and migration to Flex 4.
@zwetan: The original conversation only briefly registered on my radar as I was working on other stuff (still am, but gave a short break this week to churn out a couple of little AIR apps). So yeah, I’m late to the game but that doesn’t make the core issue any less relevant. :)
Going back to iPhone dev in the afternoon so, unfortunately, this is all the “convincing” I’m going to be doing on the subject. I do hope that those in the community supporting this change have actually tried porting Flex 3 stuff and mixing Flex 3/4 and working with Flex 3 skins, etc. If not, please do.
That’s all, Aral is over-and-out on this subject. Good hunting!
Thanks Aral, I don’t quite see how namespaces is making things so much more complex — but I’ll give it a shot myself tonight and see how I get along.
I’m happy to stand corrected if it turns out to be a real pain to port ;)
Flex 4 is a complicated release. It is complicated because you need to use parts of Flex 3 long with parts of Flex 4. That has nothing to do with namespaces. We have never had a version of Flex before where we needed to use pieces from Flex 1.5 and Flex 2 all at once. Flex was always a full major version revision before now.
Namespaces were a decision on how to deal with *that* complexity in a way that was sustainable into future releases. Yes, fxButton sounds like a nice simple solution, but it is not sustainable as future releases occur and we have new and interesting buttons. This is not a new solution though. Namespaces were already used for all custom components and custom libraries. So, a namespace is a logical extension of this concept.
Yes, it will require more work to move code from version 3 to version 4. Yes, new users will need to understand a bit more to write code that effectively uses components across (n) versions of Flex.
Again though, I don’t believe this is actually a namespace issue, the issue is just that 4 is more complex because it is composed of multiple component frameworks.
Michael: The Fx prefix doesn’t just “sound like a nice simple solution” it *was*. I ported my Flex 3 app to the previous Flex 4 SDK with absolutely no headache whatsoever. Heck, initially, I didn’t even change anything because I didn’t need to.
Then, as I needed to add Gumbo functionality, I simply layered it in and — to my surprise at the time — it just worked. I was even telling some Adobe folks recently how cool that was. It was an awesome experience.
If Flex 4 is a “complicated release”, it has failed. An iPod is a complicated piece of machinery and yet you don’t get to see any of that complication. Google is a very complicated system and yet you don’t even get a whiff of that complexity. Complexity of the system and complexity of the interface are two hugely different things. Make the system as complicated or complex as you like (that’s your problem as the developer of the system) but make the interface as simple as possible for yours users. In this case, the interface is the grammar and semantics of the framework. And this change reflects the complexity there. It places the complexity on the shoulders of the user (the Flex developer).
It basically boils down to this:
We had a system that was trivial to implement and required no changes to existing code.
We now have a system that requires extensive changes to existing code and is non-trivial to learn.
That’s a loss.
Aral, I think your issue is more with the old SDK vs. the new SDK. After this post, for “fun” I ported one of my medium sized apps from Flex 3 to the 4.0.0.6992 SDK. Minus some fun messing with the States updating and some CSS updates, I was able to take an app that had about 35 screens/windows and have it workable for the most part. Now, mind you there are still some bugs in the SDK, and I am OK with that (this is STILL ALPHA).
Also, please remember, very early on with the Flex 4 SDK, it was based on the Flex 3 SDK, which means that of course you could just compile it in the new one — you didn’t get any of the forward movement or benifits! Namespace aside, you got some new gumbonents and that was it, none of the new state management or other great things that are happening with Flex 4.
And also, please remember, this is still in ALPHA. things are not all fleshed out, and not complete. The directions are there, but it’s not all done. Things will get faster/easier/better as it progresses through the software lifecycle.
I don’t understand why you had to modify existing code, other than stuff you had written in an earlier version of Flex 4. A Halo button is still a Halo button and still uses the mx prefix. Like others have pointed out, if you have ever written or used a custom component you are used to multiple namespaces. If you have used Flex for more than 60 minutes or so, chances are you’ve done that.
Can you elaborate on what code you had to change?
Great post as always Aral, but on behalf of sound logic, I’d argue that to prove that A out-weights B it’s not sufficient to argue that A is very very heavy. It turns out that be B has to be proven not to be heavier than A.
Ok, call us Formalists. ;-)
I haven’t played at all with Flex4 yet, so I may be missing something here, but how would using the Fx prefix scale in subsequent releases? Would we be forced to deal with Fx2Button, Fx3Button, etc?
It beleive using namespaces is the correct way to go here. Perhaps the prefix is feels to some as more user-friendly or pragmatic, but it seems to me to be a short-sighted solution.
Sounds like nobody learned from the palaver with XML namespaces. During a large project a couple of years back, we wrote “It’s a namespace problem” at the top of the whiteboard. It was accurate about 90% of the time.
I’ve had a look in Flex 4 SDK already and wrote ten blog posts about it.
I can’t say that I find the new namespace solution difficult. I like it more than the previous way. Why should there be two different way to create a Button (“mx:Button” and “FxButton”)? “mx:Button” and “s:Button” sounds better to me.
Please, would (once) shup up ! … and maybe don’t try to market your name on all hot topics ?!
[...] got pinged several times this morning in response to Aral Balkin’s post on the use of namespaces in Flex 4. I can’t get his site to load so I can not comment on his post there. But I feel strongly [...]
@flo, I’d hate to point out the obvious but regardless of which solution you pick, there will always be two ways to create a button as long as there are two different buttons to create. i.e., (1) mx:Button and (2) s:Button.
@aral,
Great discussion. It’s about 2 months too late, but still cool of you to chime in. I’m a fan of following the namespace convention. Seems like the fx prefix was trying to solve a problem that the language already had a solution to. As the framework grows adding random prefixes seems awkward and unmanageable.
I liked Flo’s comment about scalability–Fx2Button, etc. Also, really, this ship sailed so long ago and is already docked in Bermuda. But beyond that, I too would like to understand a bit more about the difficulty you’re having. Were you relying on default namespaces rather than explicit ones? Because I use distinct namespaces all the time (in fact I’m unsure how you’d get by in MXML without them), including for my own component libraries.
I had a few ideas I wanted to contribute to the discussion, but your blog decided my post looked “spammy” (because of some ‘xmlns’ code?) and rejected it without any option to make edits. Seems a little harsh…
Aral –
I’m not going to weigh in on the pros and cons of prefixes vs. namespaces here. I just wanted to point out one clarifying point, to make sure it’s clear to anyone reading this discussion. Modulo the kind of (minor) incompatibilities that creep into any rev of software, Flex 3 MXML will simply work in Flex 4. You can continue to use the 2006 namespace as you wish. You can create new 2009 MXML files and use them in the same project as 2006. You still have to update your CSS, and it doesn’t address the learnability problem you, among others, see in using segmented namespaces in general, of course. But I wanted to make sure the point was clear.
Ely Greenfield
Adobe, Flex SDK
Aral, you’re kidding, right? First, that ship sailed like, three months ago.
Second, the alpha of Flex 4 broke with best practises in establishing the prefixing convention, which admittedly was in the good old spirit of hackiness for which Flash component frameworks used to be famous for, but would have created a precendent in the future direction of the Flex framework making it difficult if not impossible to correct or get away from later on, in say Flex 5 onwards (Fx2Button, GXButton, anyone?). The community rebelled, Adobe saw the light, and that nasty nasty hack in the framework was put to rest.
And in having that discussion Adobe realized that if it was to live up to Flex being open source, that it would have to take input from the community and not arbitrarily decide things which may break with future compatibility. So that’s a good thing. Dis the votes on JIRA if you want Aral, but the noise that generated made a difference. (Now if only they could listen to the votes on FP-444…)
If you’re having migration issues, my suggestion would be to write an ant task to speed up the process of adding in the extra namespaces.
Namespaces are needed, of course, so that URI definition files can be accessed for a particular framework, or we’d all be adding a gazillion import statements at the start of each file. Messy, messy. By making the rule that all coding libraries must reference a declared namespace for MXML components, the language has become a lot more uniform. And I would argue, easier to understand, because there are no tricky exceptions to the rule to remember, like, “every library uses its own namespace, except the Flex 4 components, because they’re special.” So using namespaces actually makes it easier for beginners to learn (and yes, I have taught Flex to beginners).
This move actually makes it possible for the first time to use different versions of the framework simultaneously. Now tell me, which is easier: namespaces instead of prefixing, or The Marshal Plan?
re: ipod
Aral, an IPod and Flex are not the same thing. Yes, an IPod is a complicated piece of machinery, which, through a fantastic interface allows you to do 20-40 unique functions very well. It does not try to do everything.
Flex is a langage/sdk that is intended to be infinitely flexible and tries to allow anyone to create anything they might want to create. Those two things warrant a very different level of of complexity.
If you want to compare the IPod source versus the source to a music-playing application in Flex, that would be a fair comparison.
I still disagree with one of your statements “However, I stand by my core point which is that the introduction of these language and library namespaces, along with namespaces in CSS makes it more difficult than necessary to port apps and will be more confusing for developers who are new to the platform.”
The point i can’t get past is that this isn’t a new concept. If you create a custom component or you use a custom library in Flex today (version 3 and before) you create a new namespace to reference those classes. That is today’s metaphor, not a new one. So, yes, there are more namespaces you have to deal with by default, and, that sucks.
However, to my original point, I don’t think the issue has to do as much with namespaces as it does with missing pieces in the SDK. When moving from 2 to 3, there was complete parity, so, even if you did have to change a namespace, it would have been minor. I think the issue here comes from the fact that you need to mix pieces from 3 and 4 on virtually e
As far as the rest, I still believe the real issue exists because there isn’t 100% parity between 4 and 3. If we could simply change a namespace and everything still existed, this would be less of an issue.
Cheers,
Mike
[...] I documented the trouble I had in porting my Flex 3 app to Flex 4 and I blamed the move from the Fx prefix to namespaces for my woes. As some of you have pointed [...]
Thank you all again for your comments and insight.
Let’s see if we can’t do something to make this better: The Flex 4 One-Step Migration Challenge –
[...] I documented the trouble I had in porting my Flex 3 app to Flex 4 and I blamed the move from the Fx prefix to namespaces for my woes. As some of you have pointed [...]
While I do find:
Better than
I do have an issue that in trying to experiment with Flex 4 “Gumbo”, I have not been able to find a current example that works.
Finally I stumbled on the following, which at least doesn’t generate an error:
Adobe needs to update it’s examples. Everything seems like it’s stuck in 2008.
My bad…let’s see if this shows up:
EXAMPLE:
<s:Application xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:fx=”″
xmlns:mx=”library://ns.adobe.com/flex/halo”
creationComplete=”">
</s:Application>
[...] the impact of this change recently hit Aral Balkan, a prominent Flash community member, and suddenly the controversy was reborn. In Aral’s [...]
In the update to your post you state that folks pointed out that the real crux of your problems were all due to the *removal* of namespaces in your Flex 4 Alpha codebase, issues that wouldn’t arise in the far more common scenario of a Flex 3 to 4 migration. Yet, you argue that your point still stands. How so? You made your argument based on headaches you attributed to the namespace changes, when in fact those headaches were due to issues far more particular to your specific scenario.
Given everything outlined, and in particular given the migration post Ben Stucki just made (Flex 3 to 4), what are your specific issues? What example can your provide of migration being difficult?
I think the issue here is the definition of migration. Ben made the point that a trivial five-line app will run with the addition of a single CSS namespace definition. While true for the simplistic, contrived example,.
I agree with the apparent misnomer of the term “migration” in this regard. Similarly, my brain has been struggling over whether or not the use of namespaces in Flex 4 is technically “correct”, or if it is instead a clever “work-around” to a much larger architectural problem. Naturally, this sort of conceptual brain-busting would easily be debated for days on end if you locked a group of architects in a room and left for the weekend.
In regard to my recent comment, it seems my thinking is on track with Dominic’s (see comment #22).
I also just remembered hearing Matt Chotin acknowledge the overall problem in the architecture and why namespaces had to be used as a solution, even if it is not technically correct; it is the most painless for now. As I understand, a separate team was recently compiled, separate from the Flex SDK/Flash Builder release time line, with the goal of re-architecting the Flex framework from the ground up. The project is largely experimental at this point though I believe.
Aral, instead of blazing your frustration to the community like this, can you give us some concrete examples to your problem? What do you file under “extensive namespace changes”? Really, I think you’re making this way bigger than it is :).
Note: article updated, “EPIC FAIL” retracted; let’s move on and address the core issue here which is that making Flex 3 to Flex 4 migration seamless is in all our interests. As such, please read the note at the top of the post and also my follow-up post. Thanks!
Seems to me that one of your big points is that this is going to be difficult for people to figure out and “all the more confusing for people new to the Flex platform”. But people have shown that it’s trivial to compile a Flex 3 app in Flex 4, and not too hard to migrate a relatively simple Flex 3 app to Flex 4. Isn’t this most likely the kind of thing “people new to the Flex platform” are going to be doing? Or, if they are really new, they are just going to be starting straight from Flex 4.
Yes, I guess a hugely complex app will be more difficult to port over, but give people some credit. They had the smarts to create a hugely complex app. I’m sure they will be able to grasp the concept of multiple name spaces.
Aral, your points are all completely legitimate in both the original and updated posts. I agree that its time to move on as well, and focus on whats really going on… Moreover, I agree that there is a core underlying issue architecturally, and it has been made clear to me personally that the product managers are aware of this “Epic Fail” – and by the way, exaggeration or not, I like the extreme nature of that verbiage. For petes sake, that little 2-word phrase attracted more attention than any blog titles I’ve seen in a hell of a long time! (lol).
More importantly, the attention is warranted. Based on my studies, it is questionable as to whether or not the use of namespaces in this context is consistent with the original intent of namespaces in the first place, and I have yet to hear any disagreement from anyone on that. Generally, a namespace is an architectural tool to be used during application development in order to avoid conflict with the naming conventions of the framework. They’re not meant to separate code libraries within the framework itself. Like I said though, I’m pretty sure everyone involved with the Flex SDK team is aware of this, and I would not be surprised if Flex 5 is a complete overhaul of the framework.
@Keith: Please read my note regarding the definition of migration. Simply compiling a Flex 3 app with the Flex 4 SDK is not migration. Refactoring your Flex 3 application so that you can enhance it with Spark components is not trivial and that’s the definition of migration that we need to adopt as that’s the real-world use case for migration (it doesn’t matter whether or not you can compile your Flex 3 app with the Flex 4 SDK if the first Flex 4 feature you’re going to use is going to require a far more extensive refactoring of your codebase to migrate it to a Flex 4 project utilizing both libraries.)
> Simplicity is not something to be ashamed of. It does not make your Code Fu any less
> if you have simple tools and languages to work with.
Simplicity is what everyone wants and aims for, but speak for yourself Aral. I don’t know what you are working and you certainly don’t know what we’re working on. In terms of natural language, speaking like a caveman may be simple, but it doesn’t make it easy to communicate. A language like English is highly complex, but if you know it communicating becomes easy. Simplicity doesn’t necessarily = easy and complexity doesn’t necessarily = difficult.
Many computer language features evolved to solve real-world problems. Faced with simple tools, people can and will do the most incredible things, in spite of their tools. But because I can hand-wash my clothes and would do just as good a job as the machine, would I want to? If someone else doesn’t understand how to use the machine, my heart bleeds for them, but I’ve got better things to do with my time and the complex tools I have evolved in order to free me to get on with something meaningful.
Complexity is nothing to be ashamed of either. With complexity I can build my own simplicity. That’s what object oriented programming gave us. Or I can buy someone else’s complexity to simplify my life. As the complexity of Actionscript has grown, our productivity has shot through the roof.
> It [simplicity] just makes you all the more productive and lets you concentrate on crafting that
> most important part of your application: the user experience.
Kind of like building the space shuttle using stone age hammers and clubs would let them concentrate on the visual design?
Sorry Aral. I respect you but this is all populist nonsense.
[...] use all the cool new features and components, but I didn’t go into a lot of details. However Aral’s blog does have information on what I might expect when I start to use spark components. Simply compiling [...]
I need to disagree with the main point of your argument Aral. I think that refactoring a Flex 3 application to Flex 4 (with the use of Spark components) *is* trivial.
I’m very comfortable with the use of namespaces, after all that’s what I’m used to as a Flex developer. Heck I can even migrate one class a day and my app will still compile and run just fine. How much simpler can it get?
The decision was right to to use namespaces
The decision was wrong to decide to release an unfinished product with missing components.
I’d rather wait a bit longer for a complete release. But adobe needs to make money too…
but it is nice that we can migrate one screen at the time as Stefan points out. I wonder how much migration
i’ll be doing anyway, There must be a really good reasons for it that canot be solved in flex3, otherwise flex3 will do.
ah well, at least your blog post became EPIC, he he
[...] about Fx prefix versus namespaces in Flex [...]
|
http://aralbalkan.com/2202
|
crawl-003
|
refinedweb
| 5,904
| 69.82
|
Post your Comment
Array copy
Array copy Hello all.
could someone telle me how to copy an array (holding random numbers)
to a new array...( then make randomnumbers on this new array ) but without changing the excisting array ?
last . possibility
JavaScript Copy Array
JavaScript Copy Array
... useful in
complex applications. In this section, you will study how to copy an array... using JavaScript..
<html>
<head>
<h2>Copy
Copy char array into string
Description:
This tutorial demonstrate how to convert char array into a string...) return and
creates new array of string and copies the specified characters into it and the
String.valueOf(charArray) copy the content of character
Java array copy example
Java array copy example
In this section we will discuss about the arrayCopy.... To copy
the elements of an existing array I have created a new empty integer... to copy the elements
to the specified array. Since array indexing is started from
C Array copy example
C Array copy example
In this section, you will learn how to copy an array in C.
The example... the size of an array states its
capacity to hold maximum number of values.
Copying an array to another
Copying an array to another
Java Copy Array Example:In this tutorial, you will learn how to copy data from one array to another.
Here, providing you an example with code
Circular array implementation
Circular array implementation i have 2 arrays of strings with size 7 and 9 respectively. I want my array with size 7 to be circular and copy the strings from other array of size 9 to the array of size 7. When i copy the strings
Posting Copy and Paste HTML
Posting Copy and Paste HTML Posting Copy and Paste HTML
cut,copy,paste
cut,copy,paste plz... give me the coding of cut,copy and paste in Java (Netbeans
array example - Java Beginners
array example hi!!!!! can you help me with this question... dependents to Employee that is an array of Dependent objects, and instantiate a five-element array
* while this isn't the best practice, there isn't a much better
copy() example
Copying a file in PHP
In this example, you will learn 'how to copy a file in PHP programming language?'
For copying a file, we use copy command from source to destination within PHP code tag like
copy ($source,$destination);
Lets
in_array
in_array in_array in php
copy file - Java Beginners
copy file i want to copy file from one folder to another
Hi Friend,
Try the following code:
import java.io.*;
public class CopyFile{
public void copy(File src, File dst) throws IOException
data copy - SQL
data copy
how to copy values of one column from one table into another column of another table? Hi
INSERT INTO table_name (column_name)
AS SELECT DISTINCT VALUES FROM table_name (column_name
Copy Files - Java Beginners
Copy Files I saw the post on copying multiple files () and I have something... and then copy it to the folder I need.
Does anyone have a similar program
ARRAY SIZE!!! - Java Beginners
ARRAY SIZE!!! Hi,
My Question is to:
"Read integers from the keyboard until zero is read, storing them in input order in an array A. Then copy them to another array B doubling each integer.Then print B."
Which seems
Copy and pasting - Java Beginners
Copy and pasting hi all, I am copying some cells from excell... JPopupMenu popup; JTable table; public BasicAction cut, copy, paste, selectAll...); copy = new CopyAction("Copy", null); paste = new PasteAction("Paste",null)
Merge Sort String Array in Java
of the list. i then copy my list in the array. the method call inside the main...Merge Sort String Array in Java Hello,
I am trying to implement a merge sort algorithm that sorts an array of Strings. I have seen numerous
Copy Mails to Xl sheet - JavaMail
Copy Mails to Xl sheet Can somebody give me the Java code to copy outlook mails into an Xl sheet
Post your Comment
|
http://roseindia.net/discussion/32176-JavaScript-Copy-Array.html
|
CC-MAIN-2015-35
|
refinedweb
| 663
| 61.77
|
Dear all,
I am all new to Rhino / Grasshopper and would like to know how to improve the speed of a Python script.
I am particularly interested in 2 options:
- using Numba and its
@jitoperator for parallelization
- replacing all the
forloops by matrix operations with Numpy
I haven’t tested the first option yet since I can’t seem to install “GH_CPython” on Rhino 6. I don’t know whether it is a compatibility issue or not, and if by chance @Mahmoud_Mohamed_Ouf reads this message, I would really appreciate to have some information regarding that matter.
I should also mention that the “GH_PythonRemote” component that I am currently testing instead doesn’t work with jit operators.
Now, the problem that I have with Numpy is when I need to convert numpy arrays of vectors to Rhino Geometry objects like
Point3d. It takes forever.
In the example below I have a simple line growth algorithm where positions, distances and forces computation is entirely vectorized with numpy. Without converting the vectors array to Point3d the script runs faster than the regular
for loop version and computes the position of about 2000 points under 100 ms per iteration (without RTrees or KDTrees). However, when I iterate over the numpy array to convert the vectors to Point3D the script slows down drastically (23 times slower in this example) and becomes much slower than the
for loop version.
definition: Line Growth (numpy).gh (8.7 KB)
script
import Rhino.Geometry as rg import ghpythonremote import scriptcontext np = scriptcontext.sticky['numpy'] sp = scriptcontext.sticky['scipy.spatial'] distance = sp.distance def setup(): global arr #Take every consecutive pair of points on a curve and insert a new one in between pts = np.array([[p.X, p.Y, p.Z] for p in iPoints]) avg = (pts[:-1] + pts[1:]) * .5 arr = np.insert(avg, range(pts.shape[0]), pts, 0) print "loaded" if iDraw: push() subdivide() #Convert numpy vectors array to Point3d oPoints = [rg.Point3d(p[0], p[1], p[2]) for p in arr] else: setup() def subdivide(): global arr #Check distances between each consecutive pair of points #insert a new point if distance is below the specified threshold d = np.sqrt(np.sum(np.diff(arr, axis=0)**2,1)) idc = np.nonzero(d>iDiameter)[0] means = (arr[idc] + arr[idc+1]) * .5 arr = np.insert(arr, idc+1, means, 0) def push(): global arr #Computes distances matrix and set self-comparisons to NaN d = distance.cdist(arr, arr) np.fill_diagonal(d, None) #Find pairs of vectors whose separation distance is < iDiameter id1, id2 = np.nonzero(d<iDiameter) #Count (number of "too close" vectors for each vector) count = np.vstack(np.bincount(id1)) #Difference between pairs of selected vectors dif = arr[id2] - arr[id1] #Distances between pairs of selected vectors dis = np.vstack(d[id1, id2]) #Normalized differences dif /= dis #Scaled differences dif *= .5 * (iDiameter - dis) #Average of differences (0 at start) avg = np.zeros([arr.shape[0], 3]) #Indicates where to sum (indices) idx = np.flatnonzero(np.concatenate(([1], np.diff(id1)))) #Average sums of differences avg[np.unique(id1)] = np.add.reduceat(dif, idx, axis = 0) / count #Push arr -= avg
Questions:
- Is there a faster way to convert the numpy array to Point3d ?
- If not, how would you use numpy to speed-up this script ?
- Do you know another / better way to improve the speed of this script ?
Any help, guidelines or hints, would be greatly appreciated.
If something isn’t clear about my question, please let me know.
|
https://discourse.mcneel.com/t/best-way-to-improve-the-speed-of-a-python-script/91044
|
CC-MAIN-2020-34
|
refinedweb
| 585
| 57.37
|
VS2005 Linking problem std::_String_base::_Xran
- Friday, August 26, 2005 9:45 PMHello,
I trying to build my project in VS8 (it was building fine in VS2003).
I get these linking error :
engine.lib(ECMFileHandler.obj) : error LNK2001: unresolved external symbol "public: void __thiscall std::_String_base::_Xran(void)const " (?_Xran@_String_base@std@@QBEXXZ)
engine.lib(ECMFileHandler.obj) : error LNK2001: unresolved external symbol "public: void __thiscall std::_String_base::_Xlen(void)const " (?_Xlen@_String_base@std@@QBEXXZ)
engine.lib(ECMFileHandler.obj) : error LNK2001: unresolved external symbol "public: void __thiscall std::ios_base::_Addstd(void)" (?_Addstd@ios_base@std@@QAEXXZ)
I checked to make sure all my projects are compiled in MT debug.
Here are the command line of the linker for my projects:
Dodgeball:
/OUT:"D:\SVN_Dev\build\dodgeball\Debug\DodgeBall.exe" /NOLOGO /LIBPATH:"D:\SVN_Dev\libs\NewtonSDK\sdk\dll" /MANIFEST /MANIFESTFILE:"Debug\DodgeBall.exe.intermediate.manifest" /DEBUG /PDB:"d:\SVN_Dev\build\dodgeball\Debug\DodgeBall.pdb" /ERRORREPORT:PROMPT d3dx9d.lib d3d9.lib comctl32.lib d3dxof.lib dinput.lib libcmtd.lib libcpmtd.lib dinput8.lib dsound.lib dsetup.lib dplayx.lib dxguid.lib dxtrans.lib dxErr9.lib winmm.lib newton\engin\debug\engine.lib" "..\..\build\dx9utils\debug\dx9utils.lib" "..\..\build\math\debug\math.lib" "..\..\build\utils\debug\utils.lib"
dx9utils:
/OUT:"D:\SVN_Dev\build\dx9utils\Debug\DX9Utils.dll" /NOLOGO /DLL /MANIFEST /MANIFESTFILE:"D:\SVN_Dev\build\dx9utils\Debug\DX9Utils.dll.intermediate.manifest" /DEBUG /PDB:"d:\SVN_Dev\build\dx9utils\Debug\DX9Utils
engine:
/OUT:"D:\SVN_Dev\build\Engin\Debug\Engine.dll" /NOLOGO /LIBPATH:"D:\SVN_Dev\libs\NewtonSDK\sdk\dll" /DLL /MANIFEST /MANIFESTFILE:"D:\SVN_Dev\build\Engin\Debug\Engine.dll.intermediate.manifest" /DEBUG /PDB:"d:\SVN_Dev\build\Engin\Debug\Engine newton" "..\..\build\math\debug\math.lib" "..\..\build\utils\debug\utils.lib"
math:
/OUT:"D:\SVN_Dev\build\Math\Debug\Math.dll" /NOLOGO /DLL /MANIFEST /MANIFESTFILE:"D:\SVN_Dev\build\Math\Debug\Math.dll.intermediate.manifest" /DEBUG /PDB:"d:\SVN_Dev\build\math\Debug\Math
utils:
/OUT:"D:\SVN_Dev\build\utils\Debug\Utils.dll" /NOLOGO /DLL /MANIFEST /MANIFESTFILE:"D:\SVN_Dev\build\utils\Debug\Utils.dll.intermediate.manifest" /DEBUG /PDB:"d:\SVN_Dev\build\utils\Debug\Utils
I have been adding different libs to the configuration and searching on google with no success...
I hope someone can tell me what is going on !
Thanks
All Replies
- Friday, August 26, 2005 11:55 PMModeratorHmm: I think I might know what is going on here. A dump of the symbols in the libcpmtd.lib that ships with Visual C++ 2005 show the following definition for Xran
131 00000000 SECT62 notype () External | ?_Xran@_String_base@std@@SAXXZ (public: static void __cdecl std::_String_base::_Xran(void))
Notice how it is a __cdecl function and the error message you are seeing states that it is a __thiscall function.
Also if I look at the current definition of _String_base (which is in the xstring header file) I see the following:();
};
For a native compilation __CLRCALL_PURE_OR_CDECL should map to __cdecl.
If I was you I would take a look at your definition of _String_base and check that the member function declarations use the __CLRCALL_PURE_OR_CDECL macro and if they don't then you might want to make them explicitly __cdecl as I note that you do not appear to be compiling for the CLR.
- Tuesday, March 14, 2006 6:56 PMI had the same problem when convertin Crypto51/523 library from VS2003 to VS2005. I figured out that newly built cryptolib.lib went to different folder and the main app was trying to link to old .lib file. As soon as paths were fixed the issue resolved.
- Friday, July 21, 2006 2:03 PMI'm having this same problem. The linker output says __thiscall instead of __cdecl. If the linker is showing __thiscall, but it should be __cdecl, why is the linker doing this? Which library should Xran be found in?
- Friday, July 06, 2007 10:11 PMDid you ever figure this out? I'm encountering the same issue...
- Monday, July 23, 2007 5:15 PMI got rid of this problem by just doing a "Rebuild All" of my project.
- Tuesday, August 28, 2007 2:16 PM
Hi,
I have the same problem...I am new to VC++...Here are the errors
dSSTSDKsul.lib(hex.obj) : error LNK2001: unresolved external symbol "public: void __thiscall std::_String_base::_Xran(void)const " (?_Xran@_String_base@std@@QBEXXZ)
1>dSSTSDKsul.lib(oaep.obj) : error LNK2001: unresolved external symbol "public: void __thiscall std::_String_base::_Xran(void)const " (?_Xran@_String_base@std@@QBEXXZ)
From your explanation above i see that the function call should be _cdecl instead of _thiscall.But i don't know how to change it...
Pls help me out.
Thanks
Thilak Raj S
- Friday, October 19, 2007 7:42 PMI face the same problem
I got a solution , i followed the steps .
Go to the Tools Menu ,click on the Options
a dialogbox will appear ,
Go to the Projects->vc++Directories->click
In the dropdonw box select " Show directories for : " select " Library files "
check the order of the path it should be somethin like
$(VCInstallDir)lib
$(VCInstallDir)atlmfc\lib
$(VCInstallDir)PlatformSDK\lib\prerelease
$(VCInstallDir)PlatformSDK\lib
$(FrameworkSDKDir)lib
Note : This might change for different project , ther might be additional paths .( but it works me )
- Saturday, January 26, 2008 2:46 PM
Hi everybody,
I'm facing quite the same problem when tried to port one of apps from VC6.0 to
VC2005.
In two words: my program links additional 3-rd party libs (gx*.lib - see
logs) that were developed probably in VC6.0. The conflict seems to
appear exactly as said - at function decoration - old style is __thiscall while new VC2005
style is __stdcall (courtesy of google).
My problem seems to be little more complicated - I can't rebuild these 3-rd party
libs against correct decoration.
My questions are:
1. Does attached compiler output mean that I refer to improper PSDK
libs? Are VC2005 default libs not proper? I'm not an expert when facing
such fat output from compiler...
2. Is VC2005 and/or PSDK installation self-contained when facing this
sort of problems with different versions of stdc++ library? Or do I have
to download some additional stuff?
3. How to configure project options to correct this situation? I tried
hints met across different forums (reordering lib dir order in VC
options, /MT option, excluding particular lib files, ect.), rather 0%
accuracy in my case (or improperly applied).
If someone could explain me step by step an actual mechanism of this error, I would
appreciate it a lot.
---------------------------------------------------
Here is compiler error log:
Here is compiler error log (verbose):
Compiler options:
/Od /I "D:\MK Local Exchange\eXcite\include" /I "/include" /D "WIN32" /D
"_DEBUG" /D "_CONSOLE" /D "USE_GXCAM" /D "_WIN32_WINNT=0x500" /D "_MBCS"
/Gm /EHsc /RTC1 /MTd /Fo"Debug\\" /Fd"Debug\vc80.pdb" /W3 /nologo /c /ZI
/TP /errorReport
rompt
Linker options:
/OUT:"F:\Projects\VS2005\eXcite\src\bin/simplegrab_d.exe" /INCREMENTAL
/NOLOGO /LIBPATH:"D:\Program Files\Microsoft SDK\Lib"
/LIBPATH:"F:\Projects\VS2005\eXcite\src\../lib" /MANIFEST
/MANIFESTFILE:"Debug\simplegrab_d.exe.intermediate.manifest" /DEBUG
/PDB:"Debug/simplegrab_d.pdb" /SUBSYSTEM:CONSOLE /MACHINE:X86
/ERRORREPORT
ROMPT baslercam_md.lib gxdevice_mt.lib xcam_md.lib
gtrans.lib gxpp_md.lib kernel32.lib user32.lib gdi32.lib winspool.lib
comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib
odbc32.lib odbccp32.lib
---------------------------------------------------
Any response greatly welcome...
Greetings
mk
- Friday, August 22, 2008 1:30 PM
Hi aberazioon,
I faced the same problem but in my case, the external libraries were compiled using Studio 2003 and I only had 2 unresolved external symbols: Xran and Xlen.
This problem hapens because the library libcpmt.lib (libcpmtd.lib) in MS Visual 2003 and MS Visual 2008 has different prototype definitions for xRan and xLen (MS Visual 200* + command prompt + type the command "dumpbin /ALL libcpmtd.lib" )
In 2003:
// 00000018 REL32 00000000 34C ?_Xran@_String_base@std@@QBEXXZ (public: void __thiscall std::_String_base::_Xran(void)const )
// 0000001E REL32 00000000 2DF ?_Xlen@_String_base@std@@QBEXXZ (public: void __thiscall std::_String_base::_Xlen(void)const )
In 2008:
// 00000019 REL32 00000000 5CC ?_Xran@_String_base@std@@SAXXZ (public: static void __cdecl std::_String_base::_Xran(void))
// 0000001D REL32 00000000 5C6 ?_Xlen@_String_base@std@@SAXXZ (public: static void __cdecl std::_String_base::_Xlen(void))
To solve the problem I did the following... a bit bizarre but it works for me:
(The general idea here is to create a dll / library that exports the unknown symbols and these new methods in the dll will call the new methods behaviour in libcpmt.lib @ 2008)
1) I used MS Visual 2003 pre-processor (type the command "cl /EP <source code_1.cpp>") to get the "String_base" class definition.
// Source code_1.cpp
#include <string>
// end of code_1.cpp
In MS Visual 2003, class definition is:
class _String_base
{
public:
void _Xlen() const;
void _Xran() const;
};
2) According with _Xran and _Xlen definition in 2008, both methods are static.
3) Compile the following source code in 2008. Type the command "cl /D_DLL_EXPORT /EHsc /LD libvisual2003_visual2008.cpp /link".
// Source libvisual2003_visual2008.cpp
#include <string>
namespace std2003_2008
{
class _String_base2003_2008
{
public:
__declspec(dllexport) void _Xlen2003_2008(void) const;
__declspec(dllexport) void _Xran2003_2008(void) const;
};
};
void std2003_2008::_String_base2003_2008::_Xran2003_2008 () const
{
std::_String_base::_Xran ();
}
void std2003_2008::_String_base2003_2008::_Xlen2003_2008 () const
{
std::_String_base::_Xlen ();
}
// end of libvisual2003_visual2008.cpp
4) Type the command "dumpbin /ALL libvisual2003_visual2008.dll" (MS Visual 2008) to get the public symbols of _Xran2003_2008 and _Xlen2003_2008.
// ?_Xlen2003_2008@_String_base2003_2008@std2003_2008@@QBEXXZ
// ?_Xran2003_2008@_String_base2003_2008@std2003_2008@@QBEXXZ
5) Re-compile again libvisual2003_visual2008.cpp with following command "cl /D_DLL_EXPORT /EHsc /LD libvisual2003_visual2008.cpp /link /export:?_Xran@_String_base@std@@QBEXXZ=?_Xran2003_2008@_String_base2003_2008@std2003_2008@@QBEXXZ /export:?_Xlen@_String_base@std@@QBEXXZ=?_Xlen2003_2008@_String_base2003_2008@std2003_2008@@QBEXXZ"
Here, the new dll will export 2 new symbols (the ones that were unknown in initial compilation) and they will map to the methods _Xlen2003_2008 and _Xran2003_2008.
6) If you dump the public symbols of the new dll (step 5), you will get the following:
// 1 0 00001010 ?_Xlen2003_2008@_String_base2003_2008@std2003_2008@@QBEXXZ
// 2 1 00001010 ?_Xlen@_String_base@std@@QBEXXZ
// 3 2 00001000 ?_Xran2003_2008@_String_base2003_2008@std2003_2008@@QBEXXZ
// 4 3 00001000 ?_Xran@_String_base@std@@QBEXXZ
7) Re-compile the program again with the new "libvisual2003_visual2008.lib" library.
8) To run the application don't forget the "libvisual2003_visual2008.dll".
Greetings
JN123 @ Portugal
- Thursday, March 11, 2010 9:55 AMI had the same problem.
Solved.
Solution: Ignore all default libraries was set to yes under linker options. Set to no !
EugenWiebe1
- Friday, February 25, 2011 11:58 AMI too faced the same problem and found that platform sdk path was on the top of the list of lib path. After moving it to the last and it worked fine.
- Tuesday, April 05, 2011 2:31 PM
i have the same problem and found that i build some library (smartwin++) from make bat file with VS 9.0 and tryied to build sample with VS 10.0 from devend and got unresolved links.
building library with appropriate VS version (10.0) solved problem.
|
http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/5ac28a31-3339-4db1-90f4-68edad360309
|
CC-MAIN-2013-20
|
refinedweb
| 1,801
| 50.02
|
#include <i_filter.h>
This class represents an image filter. It is meant to be used to convolve with other filters and with images. The reason I made this class (as opposed to simply using a Matrix) is to be able to overload the * operator to use as a convolution. More generally, a filter is not really a matrix, but a signal, so it should not have the functionality of a matrix.
Construct filter of specified size, defaults to zero by zero.
Construct filter from matrix.
Read filter from a named file.
Read filter from a named file.
Copy ctor, performs a deep copy.
Destroy filter's memory.
Access value lvalue at row, column coordinates.
Access value rvalue at row, column coordinates.
Test whether row, column coordinates are valid.
Return the number of columns in the filter.
Return the number of rows in the filter.
Lvalue value access at given row & column, no bounds-checking.
Rvalue value access at given row & column, no bounds-checking.
Assignment of a matrix to a filter.
Deep copy assignment.
Swap the implementation of two filters.
Write to a file.
Convolve an image with a filter.
|
http://kobus.ca/research/resources/doc/doxygen/classkjb_1_1Filter.html
|
CC-MAIN-2022-21
|
refinedweb
| 190
| 62.85
|
#include <LOCA_Utils.H>
#include <LOCA_Utils.H>
List of all members.
The following parameters are used by this class and should be defined in the "Utilities" sublist of the main loca parameter list.
The public variables should never be modified directly.
Message types for printing.
Note that each message type if a power of two - this is very important. They can be added together to specify which messages you wish to receive.
[static]
Indicate whether or not the message should be printed.
Returns true if the specifed message type should be printed.
Returns true if the specifed message type should be printed and this is the print process.
'*'.
Returns a sublist of the paramter list given by name.
Note that this hard-codes the parameter list structure and does not do a search to find the sublist
Returns true if the current processor is designated as the processor send output to screen and/or file.
This is used to prevent each processor from printing the same information.
-1
Creates a Sci object which can be used in an output stream for printing a double precision number in scientific format with an arbitrary precision. The default precision is that specificed by the Utils static object.
cout << Utils::sci(d) << "or" << Utils::sci(d,2);
Set the parameters in the utilities class.
Valid parameters are:
|
http://trilinos.sandia.gov/packages/docs/r4.0/packages/nox/doc/html/classLOCA_1_1Utils.html
|
crawl-003
|
refinedweb
| 222
| 67.25
|
Answered
Hi,
i use one library - with name Joost for streaming xml transformations and it allows scripting.
The config for this library looks like XSLT, but has it's own name spaces.
And the scripting tag has usual name <script>, but the name space is joost:
<?xml version="1.0"?>
<!-- test for recursive stx:process-siblings -->
<stx:transform xmlns:stx=""
xmlns:
<joost:script
// some script
</joost:script>
</stx:transform>
And there is dilemma - i can remove the namespace - but specifying it like this:
xmlns=""
But this breaks output, however allowing me to use Javascript code completion.
Or i can use it as is is supposed to be - but Idea treats content as usual text - no JS completion.
Is there any way to specify idea that this is JS script - ignoring the namespace of the tag?
You can add this tag to language injection settings, just like the default one:
Thanks,
That's amazing!
|
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206608469-XHTML-file-type-script-tag-namespace
|
CC-MAIN-2020-16
|
refinedweb
| 153
| 67.79
|
PySpark Usage Guide for Pandas with Apache Arrow
- Apache Arrow in Spark
- Enabling for Conversion to/from Pandas
- Pandas UDFs (a.k.a. Vectorized UDFs)
- Usage Notes
Apache Arrow in Spark.enabled to
true. This is disabled by default.
In addition, optimizations enabled by
spark.sql.execution.arrow.enabled could fallback automatically
to non-Arrow optimization implementation if an error occurs before the actual computation within Spark.
This can be controlled by
spark.sql.execution.arrow.fallback.enabled.
import numpy as np import pandas as pd # Enable Arrow-based columnar data transfers spark.conf.set("spark.sql.execution.arrow.
Pandas UDFs (a.k.a. Vectorized UDFs)
Pandas UDFs are user defined functions that are executed by Spark using Arrow to transfer data and
Pandas to work with the data. A Pandas UDF is defined using the keyword
pandas_udf as a decorator
or to wrap the function, no additional configuration is required. Currently, there are two types of
Pandas UDF: Scalar and Grouped Map.
Scalar
Scalar Pandas UDFs are used for vectorizing scalar operations. They can be used with functions such
as
select and
withColumn. The Python function should take
pandas.Series as inputs and return
a
pandas.Series of the same length. Internally, Spark will execute a Pandas UDF by splitting
columns into batches and calling the function for each batch as a subset of the data, then
concatenating the results together.
The following example shows how to create a scal, b):| # +-------------------+
Grouped Map
Grouped map Pandas UDFs are used with
groupBy().apply() which implements the “split-apply-combine” pattern.
Split-apply-combine
DataFrame.
To use
groupBy().apply(), the user needs to define the following:
- A Python function that defines the computation for each group.
- A
StructTypeobject or a string that defines the schema of the output
groupby().apply() to subtract the mean from each value in the group.
from pyspark.sql.functions import pandas_udf, PandasUDFType df = spark.createDataFrame( [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)], ("id", "v")) @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP) def subtract_mean(pdf): # pdf is a pandas.DataFrame v = pdf.v return pdf.assign(v=v - v.mean()) df.groupby("id").apply(subtract_mean).show() # +---+----+ # | id| v| # +---+----+ # | 1|-0.5| # | 1| 0.5| # | 2|-3.0| # | 2|-1.0| # | 2| 4.0| # +---+----+
For detailed usage, please see
pyspark.sql.functions.pandas_udf and
pyspark.sql.GroupedData.apply.
Grouped Aggregate
Grouped aggregate Pandas UDFs are similar to Spark aggregate functions. Grouped aggregate Pandas UDFs are used with
groupBy().agg() and
pyspark.sql groupBy and window operations:
from pyspark.sql.functions import pandas_udf, PandasUDFType from pyspark.sql import Window df = spark.createDataFrame( [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)], ("id", "v")) @pandas_udf("double", PandasUDFType.GROUPED_AGG) def mean_udf(v): return v.mean()
pyspark.sql.functions.pandas_udf
Usage Notes
Supported SQL Types
Currently, all Spark SQL data types are supported by Arrow-based conversion except
MapType,
ArrayType of
TimestampType, and nested
StructType.
BinaryType is supported only when
installed PyArrow is equal to or higher then 0.10.0.
Setting Arrow Batch Size
For usage with pyspark.sql, the supported versions of Pandas is 0.19.2 and PyArrow is 0.8.0. Higher versions may be used, however, compatibility and data correctness can not be guaranteed and should be verified by the user.
Compatibiliy Setting for PyArrow >= 0.15.0 and Spark 2.3.x, 2.4.x blog.
|
http://spark.apache.org/docs/2.4.7/sql-pyspark-pandas-with-arrow.html
|
CC-MAIN-2021-43
|
refinedweb
| 574
| 55
|
mbstowcs (3) - Linux Man Pages
mbstowcs: convert a multibyte string to a wide-character string
NAME
mb.
ATTRIBUTESFor an explanation of the terms used in this section, see attributes(7).
CONFORMING TOPOSIX.1-2001, POSIX.1-2008, C99.
NOTESThe behavior of mbstowcs() depends on the LC_CTYPE category of the current locale.
The function mbsrtowcs(3) provides a better interface to the same functionality.
EXAMPLEThe program below illustrates the use of mbstowcs(), as well as some of the wide character classification functions. An example run is the following:
$ ./t_mbstowcs de_DE.UTF-8 Grüße!
Length of source string (excluding terminator):
Wide character string is: Grüße! (6 characters)
int
main(int argc, char *argv[])
{
Program source
#include <wctype.h>
#include <locale.h>
#include <wchar.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
Wide character string is: Grüße! (6 characters)
int
main(int argc, char *argv[])
{
int
main(int argc, char *argv[])
{
|
https://www.systutorials.com/docs/linux/man/3-mbstowcs/
|
CC-MAIN-2020-29
|
refinedweb
| 150
| 62.54
|
Hi everyone,
I’m working on a project that requires me to have access to each step of backward propagation during the training process. Say I have a 10 layer fully connected neural net (input->fc1->fc2->…->fc10->output), and during the backward process I want something like output.backward()->fc10.backward()->fc9->backward()->…->fc1.backward() in separate steps so that I can get gradient of each layer and check how much time it costs for computing gradient of each layer.
However, for now, when I call loss.backward() using this backward function ( ), then only the loss variable is contained in the variables, and pushed into the execution engine.
loss.backward()
backward
loss
variables
execution engine
How can I get access to gradient computation process of each parameters (layers) in the network? I really want something like
for layers in reversed(network):
layer_grad=layers.backward()
# and at here I can check the time cost of gradient computing of a single layer
layers.update(layer_grad) # based on certain optimizer
Any information will be appreciate.
you can use backward hooks for:
Hi @smth,
Thanks a lot for the pointers you provide. I also have other questions related, hope you can provide some information.
My project involve solving some straggler (slow worker) issues in distributed cluster. So, I want to “skip” backward calculation (gradient computing) for some layers in the network.
Say if I run the training code on a certain node in a cluster, and after I do the backward process at a certain layer(layer_10.backward -> layer_9.backward -> layer_8.backward), at this time I decided this node is too slow and I want to just simply skip calling backward step of remaining layers to avoid more time costs (e.g. by simply assign a certain value to gradients of those remaining layers rather than actually calculate the gradients) .
Is this possible in current pytorch API? Or I need to customize modules (say convolutional layer)?
What you are asking for is not strictly possible without writing custom autograd.Function functions to insert these custom nodes. Either that, or you do some book-keeping and manage the graph yourself.
For example:
model = nn.ModuleList(nn.Linear(100, 200), nn.ReLU(), nn.Linear(200, 300))
x = Variable(torch.randn(10, 100), requires_grad=True)
def model_forward(model, x):
for m in model:
x = model(x)
x.detach_()
return x
def model_backward(model, grad_output):
for m in reversed(model):
if TOO_LATE:
return # shortcut outside of backward
grad_output = m.backward(grad_output)
return grad_output
Something of this order. It’s super hacky, and you have to do all model book-keeping yourself.
I tried this method you provided with following code when defining my customized module list (a simple LeNet example here) and forward, backward operation:
forward
class LeNetLayerSplit(nn.Module):
def __init__(self):
super(LeNetLayerSplit, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5, 1)
self.conv2 = nn.Conv2d(20, 50, 5, 1)
self.fc1 = nn.Linear(4*4*50, 500)
self.fc2 = nn.Linear(500, 10)
self.ceriation = nn.CrossEntropyLoss()
self.module_list_0 = nn.ModuleList([self.conv1, nn.MaxPool2d(2, stride=2), nn.ReLU(),
self.conv2, nn.MaxPool2d(2, stride=2), nn.ReLU()])
self.module_list_1 = nn.ModuleList([self.fc1, self.fc2])
self._name = "LeNet_layer_split"
def forward(self, x, target):
for sub_module in self.module_list_0:
x = sub_module(x)
x.detach_()
x = x.view(-1, 4*4*50)
for sub_module in self.module_list_1:
x = sub_module(x)
x.detach_()
loss = self.ceriation(x, target)
return x, loss
def backward(self, grad_output):
for m in reversed(self.module_list_1):
grad_output = m.backward(grad_output)
grad_output.view(-1, 50, 4, 4)
for n in reversed(self.module_list_0):
grad_output = n.backward(grad_output)
return grad_output
When calling this model, I used the following code:
def build_model(self):
self.network = LeNetLayerSplit()
# this is only used for test
self.optimizer = torch.optim.SGD(self.network.parameters(), lr=self.lr, momentum=self.momentum)
def train(self, train_loader=None):
self.network.train()
# iterate of epochs
for i in range(self.max_num_epochs):
for batch_idx, (data, y_batch) in enumerate(train_loader):
iter_start_time = time.time()
data, target = Variable(data, requires_grad=True), Variable(y_batch)
self.optimizer.zero_grad()
logits, loss = self.network(data, target)
print("Trial Loss: {}".format(loss.data[0]))
print("Start Backward Prop Process: ")
loss.backward()
But I get the error of RuntimeError: there are no graph nodes that require computing gradients. I guess I call the backward function in a wrong way, and simple search returns no related issue.
But when I read the original code of autograd variable, I found that in this line results generated during the forward process are set to requires_grad=False when calling detach_, is this issue caused by that? If so, how can I solve it? Please provide me more details about this.
RuntimeError: there are no graph nodes that require computing gradients
autograd
requires_grad=False
detach_
Thanks a lot!
@zazzyy if you call detach_() then there is no node in the graph that requires_grad=True, so autograd is complaining that it has no work to do.
detach_()
What you might want to do is (maybe), instead of x.detach_(), call x = Variable(x.data, requires_grad=True) (or some form of this, that will compute gradients).
x.detach_()
x = Variable(x.data, requires_grad=True)
Hi, @smth thanks a lot for your response. Based on your suggestions, I tried the following things bellow:
backward()
def backward(self, grad_output):
for m in reversed(self.module_list_1):
grad_output = m.backward(grad_output)
grad_output.view(-1, 50, 4, 4)
for n in reversed(self.module_list_0):
grad_output = n.backward(grad_output)
return grad_output
self.network.backward(grad_output=${RANDOM_VARIABLE})
grad_output = m.backward(grad_output)
File "/home/usr/anaconda2/lib/python2.7/site-packages/torch/nn/modules/module.py", line 262, in __getattr__
type(self).__name__, name))
AttributeError: 'Linear' object has no attribute 'backward'
Dose this mean I need to overwrite the corresponding nn.Module by myself with a backward function, or there is a way that the current Module will do that for me? So, in general, I only want to call the backward process layer by layer, after getting the gradient of each layer, I just want to do a simple check (e.g. the value of a certain variable) and to determine if I need to do or just skip the remaining backward process.
nn.Module
Module
in your backward function, you are calling .backward on m which is the Module. what you need to do is to call backward on the Variable that is the output from the module.
.backward
m
Hi, @smth. Thanks a lot for this pointer.
I already tried what you suggest that call the .backward() on the output Variable that is output from the module. The case is, if I do the normal forward() manner like this way:
.backward()
forward()
def forward(self, x, target):
for sub_module in self.module_list_0:
x = sub_module(x)
x = x.view(-1, 4*4*50)
for sub_module in self.module_list_1:
x = sub_module(x)
loss = self.ceriation(x, target)
return x, loss
Then once I call the variable.backward() on the last variable, say loss.backward() then the whole backward process will be executed. But if I call anything like x = Variable(x.data, requires_grad=True) after each forward step as you mentioned, then it seems no grad will be calculated if I check param.grad in module.parameters().
After checking this topic Assign manual assigned "grad_output", it seems call variable.backward(grad_output) can be helpful, but when I calling loss.backward(grad_output) under normal forward manner, the behavior is nothing different from loss.backward().
What tricks do I need in the forward/backward process to achieve executing backward process layer by layer (e.g. get output from last layer and use it to do backward for next layer, like doing the chain rule manually )?
variable.backward()
param.grad
module.parameters()
variable.backward(grad_output)
loss.backward(grad_output)
here’s a more precise and fuller example. What you are doing in my example is to completely avoid autograd’s automatic backward computation and manually reverse-computing the backward graph.
For anyone coming here with a search, my solution is a hack, it is not good practice. it is given as an illustration just to showcase to @zazzyy how to shortcut these things
import torch
import torch.nn as nn
from torch.autograd import Variable
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.layers = nn.ModuleList([
nn.Linear(10, 10),
nn.Linear(10, 10),
nn.Linear(10, 10),
nn.Linear(10, 10),
])
def forward(self, x):
self.output = []
self.input = []
for layer in self.layers:
# detach from previous history
x = Variable(x.data, requires_grad=True)
self.input.append(x)
# compute output
x = layer(x)
# add to list of outputs
self.output.append(x)
return x
def backward(self, g):
for i, output in reversed(list(enumerate(self.output))):
if i == (len(self.output) - 1):
# for last node, use g
output.backward(g)
else:
output.backward(self.input[i+1].grad.data)
print(i, self.input[i+1].grad.data.sum())
model = Net()
inp = Variable(torch.randn(4, 10))
output = model(inp)
gradients = torch.randn(*output.size())
model.backward(gradients)
Hi, @smth. I deeply appreciate this working snippet, it is basically what I asked.
I have one further question about this. It seems the grad_output we provide in this line
grad_output
gradients = torch.randn(*output.size())
are never used to compute anything during the backward process since when I tried to print every self.output[i+1].grad.data, they’re all equal to the random gradient generated by torch.randn(*output.size()). And everything in self.output has grad_fn=None. That make sense because as you mentioned this hack “ompletely avoid autograd’s automatic backward computation and manually reverse-computing the backward graph”.
self.output[i+1].grad.data
torch.randn(*output.size())
self.output
grad_fn=None
My question is if I want to make this net works “normally”, do I need to manually handle the entire backward process (e.g. write all backward functions for all layers, manually compute gradients, and etc.)? Is there any way to make this less hacky or any function (e.g. backward function of Conv layer) to borrow?
I’m sorry the example had a bug. I’ve fixed it now (see my example again) and it correctly computes gradients.
|
https://discuss.pytorch.org/t/how-to-split-backward-process-wrt-each-layer-of-neural-network/7190
|
CC-MAIN-2017-47
|
refinedweb
| 1,712
| 52.87
|
I have a problem getting PyDev on eclipse to recognize already installed modules. Here is my detailed approach. The machine is a Mac (Snow Leopard).
In terminal the command
python --version
import unidecode
from unidecode import unidecode
Traceback (most recent call last):
File "/Users/me/Documents/workspace/myproject/python/pythontest.py", line 12, in <module>
from unidecode import unidecode
ImportError: No module named unidecode
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
from unidecode import unidecode
def main():
print unidecode(u"Ågot Aakra")
if __name__ == '__main__':
main()
#!/usr/bin/env python
This is the solution to my problem:
../site-packages/of your corresponding python version. ( For me it was
/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/for python 2.6 on my Mac with Snoe Leopard.)
../site-packages/of your corresponding python version.
And you should be good to go. =)
Thanks @all particionts, who provided hints into the right direction in the comments.
|
https://codedump.io/share/Tmi8p92U3wEd/1/adding-python-modules-to-pydev-in-eclipse-results-in-import-error
|
CC-MAIN-2017-04
|
refinedweb
| 163
| 53.58
|
Before Production Configuration was introduced in Eclipse V3.1, RCP developers confronted the problem of how to effectively and efficiently package, and deliver their RCP projects with the required plug-ins. This problem, in fact, is a consumption issue because it essentially determines the distribution and usability of their software. Thanks to Eclipse V3.1's new Production Configuration feature, you can now wrap their applications with dependencies and branding elements easily. This article details how to leverage Eclipse Product Configuration with a sample RCP application: a game called Frog Across River.
To get the most out of this article, you need an Eclipse development environment and the sample code. If you don't have Eclipse already, download the following:
- JRE V1.5.0 or later; Eclipse requires the Java Runtime Environment to operate
- Eclipse Platform or IBM Rational Software Development Platform V7.X
- The sample code in the Download section
Prerequisite: An RCP application
The prerequisite of Eclipse Product Configuration is an existing RCP application. You will need it as the bootstrap entry of your product. In this section, you will develop a game of Frog Across River as an RCP application using the following instructions. This RCP application is a plug-in project that will extend the
org.eclipse.core.runtime.applications extension and play the entry role of your product. Alternately, you can skip through this section by importing the whole project by downloading the attached (see Download) to get a sample RCP application for later scenarios.
Create a sample RCP plug-in
First, we generate a plug-in project following these steps. Launch Eclipse, shift to the plug-in development perspective by selecting Window > Open Perspective > Other... > Plug-in Development.
- From the Eclipse menu, select File > New > Project... > Plug-in Development > Plug-in Project and click Next.
- In the Plug-in Project wizard page, input
com.example.zyxas project name and click Next.
- In the Plug-in Content wizard page, accept all default settings and click Yes for the "Would you like to create a rich client application?" option, then click Next.
- In the Templates wizard page, select Hello RCP template and click Finish. Afterward, you will find a project named
com.example.zyxin the workspace.
Import the RCP game source code
Copy all Java source files (.java files) from
com.example.zyx.zip to the workspace, replacing the existing ones:
- Application.java
- ApplicationActionBarAdvisor.java
- ApplicationworkbenchAdvisor.java
- ApplicationWorkbenchWindowAdvisor.java
- Perspective.java
- GameView.java
This RCP project will create the Frog Across River game in a GUI view that enables mouse and keyboard input on the menu bar and canvas. Its design architecture is shown in Figure 1.
Figure 1. Class diagram of RCP application
Among them,
Application.java must implement the IPlatformRunnable interface because the plugin.xml file has extended the extension point of
org.eclipse.core.runtime.applications. That means you should implement the
run() method of IPlatformRunnable, which is responsible for creating the SWT display and starting up a workbench.
Listing 1. Application.java
public class Application implements IPlatformRunnable { public Object run(Object args) throws Exception { ... int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); ... } }
ApplicationActionBarAdvisor.java is used to create and display menu bar.
Listing 2. ApplicationActionBarAdvisor.java
public class ApplicationActionBarAdvisor extends ActionBarAdvisor { ... private IWorkbenchAction exitAction; private IAction gameAction; ... protected void fillMenuBar(IMenuManager menuBar) { IMenuManager viewMenu = new MenuManager("&Game","Game"); menuBar.add(viewMenu); viewMenu.add(gameAction); viewMenu.add(exitAction); } }
GameView.java is the core of this RCP game. It loads images, renders the display, responds to user actions (mouse and keyboard events), and controls the whole process of the game.
Double-buffer technology is applied to avert screen flicker and flash during animation. Why? When you instruct JVM to display an animation, JVM will clear the screen, show the window, paint the screen, and show it again. That degrades your application's appearance. Double-buffering boosts performance by painting an off-screen image, then dumping it to the display.
Listing 3. GameView.java
public class GameView extends ViewPart { ... public void createPartControl(final Composite parent) { ... canvas.addMouseListener(new MouseAdapter() { public void mouseDoubleClick(MouseEvent e) { } }); canvas.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { ... } canvas.addPaintListener(new PaintListener() { public void paintControl(PaintEvent event) { final Image image = new Image(parent.getDisplay(), canvas.getBounds()); final GC gcImage = new GC(image); ... event.gc.drawImage(image, 0, 0); ... }
Copy the code list below into
plugin.xml file because your RCP game will show up a view as the GUI to interact with users.
Listing 4. plugin.xml
<extension point="org.eclipse.ui.views"> <category id="com.example.zyx.browser" name="Browser Example"/> <view id="com.example.zyx.GameView" name="Browser" icon="icons/window16x16.gif" class="com.example.zyx.GameView" category="com.example.zyx.browser"/> </extension>
Launch the RCP game in Eclipse
To execute the RCP game application in Eclipse, switch to the Overview tab of
plugin.xml and click Launch an Eclipse application. A new Eclipse application launch configuration will be created for you, and you will find the execution result of your RCP game, as shown in Figure 2.
Figure 2. Execution of the sample RCP application
Create your product configuration
You will create a Product Configuration file (
.product) to wrap up the Frog Across River RCP application as a product. You can locate it in any project or folder.
To generate a Product Configuration file, select File > New > Other > Plug-in Development > Product Configuration, then click Next. When the Product Configuration wizard page appears, select
com.example.zyx plug-in project as its parent folder, input
myProduct.product as its file name, select "Create a configuration file with basic settings" and click Finish (see Figure 3).
Figure 3. Wizard to create new Product Configuration
Configure
In this section, we introduce how to define and customize the product published with your RCP application after you create your .product file. You need to import some files and folders into your plug-in project from
com.example.zyx.zip before you set up the Product Configuration. They are listed in Figure 4.
Figure 4. Imported resources
The following table provides the description of these resources.
Table 1. Resource description
Overview tab
First, click the Overview tab (see Figure 5). You will set up the Product Definition here. The product definition consists of Product Name, Product ID, and an Application associate with the Product ID. What's more, it is specified whether the product configuration unit is based on plug-in or feature.
Figure 5. Overview tab
Product Name defines the name of the product, which will be shown in the title bar. Input
%productName in the Product Name text field, which will automatically refer to the values in plugin.properties file according to the locale. Product ID defines the product ID and it associates with the Application ID. Click New... to the right of Product ID. When the Product Definition window pops up, choose com.example.zyx as the Defining Plug-in, then select com.example.zyx.application as its associated application, and use
product as its product ID. Click Finish to return to the Overview tab. Select plug-ins radio button in the "The product configuration is based on" section.
You can see the product name in the title bar when you launch the product, as shown below.
Figure 6. Product name in title bar of my product
Configuration tab
Click the Configuration tab. You will define the elements in you product and the configuration file. The "Plug-ins and Fragments section" lists all plug-ins and fragments that will be packaged in your product.
Figure 7. Configuration tab
Click Add... to the right of the Plug-ins and Fragments list, then select the com.example.zyx plug-in, and click OK. Click the Add Required Plug-ins button, then all required plug-ins and fragments are added. The "Configuration File" section is used to set up the product runtime information. This file must be named config.ini. You can accept its default setting, which will generate a default config.ini file in configuration folder when the product is exported. The following gives a sample of the file's content.
Listing 5. Content of config.ini
#Product Runtime Configuration File osgi.splashPath=platform:/base/plugins/com.example.zyx eclipse.product=com.example.zyx.product osgi.bundles=org.eclipse.equinox.common@2:start,org.eclipse.update.configurator@3:start, org.eclipse.core.runtime@start osgi.bundles.defaultStartLevel=4
The first line determines the location of splash screen, which will be displayed when product launches. The second line defines the product name.
In the last two lines,
StartLevel is used by the product to launch plug-ins after they have been successfully installed and resolved. In other words,
StartLevel defines the startup sequence of these core plug-ins. A start level is defined as a non-negative integer. The products will launch plug-ins with Start Level 0. Afterward, it's the turn of all plug-ins with start level 1. This progress won't end until it reaches its designated start level: the
defaultStartLevel or the
osgi.startLevel. In this sample config.ini file, the
defaultStartLevel is 4. The default value for the
osgi.startLevel property is 6.
Launcher tab
Click the Launcher tab, where you will set the Program Launcher and Launching Arguments.
Figure 8. Launcher tab
Program Launcher is used to specify launcher name and launcher icons, in the form of an .exe file for Windows® to launch your product after you have exported it. Input FrogAcrossRiver in the Launcher Name text field. Click the radio button Use a single ICO file containing 7 images as specified above, then click Browse... and navigate to select the 7Images.ico file in the icons folder. You can generate and use your own icon file or just leverage BMP images by clicking Specify separate BMP images.
An .ico file is a container that includes required image files with different size and color modes for its host application. Windows selects the image it needs to use, based on the user's display settings. If the icon does not contain the appropriate size or color mode, Windows will take the closest size and resolution, and render the icon to suit.
Table 2. Icon properties
Launching arguments provides the product with the default program arguments and VM arguments. In its way, an .ini file with the same name as the launcher mame will be generated in the root of the exported folder to record these arguments. Input -console in the Program Arguments text field, which will open a console window when your product is launched. After you export the product, go to the exported folder, you can find the .exe and .ini files as shown below.
Figure 9. Executable file and config file
Splash screen
A splash screen will appear when the product launches. This file must be located in the root folder and be named splash.bmp. Otherwise, the product will not find it at runtime.
Figure 10. Splash screen configuration in Branding tab
Click Browse... on the right of Plug-in test field and select the plug-in project where the splash file resides. Progress bar and Progress message are used to indicate the process status on the splash screen. Add the following value into the plugin_customization.ini file.
org.eclipse.ui/SHOW_PROGRESS_ON_STARTUP=true
Next, add the following property to the product extension section of the plugin.xml file.
<property name="preferenceCustomization" value="plugin_customization.ini"> </property>
Then select Add a progress bar. Input
0 and
280 for x-offset and y-offset, and input
455 and
15 for width and height. Then select Add a progress message. Input
7 and
220 for x-offset and y-offset, and input
441 and
20 for width and height. Select your favorite color in Text Color for the progress message. When you launch the product, you can see the splash screen come up, and the progress bar and progress message appear.
Figure 11. Progress bar and progress message at the product's start up
Window images
Images for your application window are configured in this section (see Figure 12). These images must be in GIF format. An image with a size of 16x16 appears in the upper-left corner of the window and task bar. A 32x32 image appears in the Alt+Tab application switcher.
Figure 12. Window image configuration in Branding tab
With the Browse... button, define the 16x16 and 32x32 images you want from your project's icon folder. Then go to the plugin.xml file to verify your configuration with following declaration:
<property name="windowImages" value="icons/alt_window_16.gif,icons/alt_window_32.gif"> </property>
After you launch the product, you will see the images is displayed in Figure 13.
Figure 13. 32x32 image in Alt+Tab application switcher
About dialog
The About dialog consists of the about image rendered on the left and the about text briefly introducing your product. You will manage these two items in this section.
Figure 14. About dialog configuration in Branding tab
Click Browse... to the right of Image text field and select a GIF file from the icon folder.
There are two ways to define the about text. One is to directly input the text in the Text field; the other is to define a key and value pair in the plugin.properties file and refer to the key in the Text field. As you will leverage the second one, just input
%productBlurb in the Text field as shown in Figure 14.
productBlurb is the key defined in the plugin.properties file, as shown below.
Listing 6. plugin.properties
pluginName=Frog Across River providerName=Xing Xing Li and Ying Xi Zhao productName=My Product productBlurb=My Product based on Eclipse Platform\n\ \n\ Version: 1.0.0\n\ Build id: M20061124-1422 \n\ \n\ Welcome to my Product based on Eclipse Product Configuration. \n\ A RCP game is encapsulated in it with customized branding elements.\n\ \n\ This product is developed by Xing Xing Li and Ying Xi Zhao \n\ (c) Copyright by authors. All rights reserved\n\
You need to add an action so that the menu item for the About dialog will appear in the menu bar of your product, such as Help > About. Open the ApplicationActionBarAdvisor.java file and remove the comment tags to activate the following code.
Listing 7. ApplicationActionBarAdvisor.java
public class ApplicationActionBarAdvisor extends ActionBarAdvisor { ... private IWorkbenchAction aboutAction; protected void makeActions(final IWorkbenchWindow window) { ... aboutAction = ActionFactory.ABOUT.create(window); register(aboutAction); ... } protected void fillMenuBar(IMenuManager menuBar) { //Help MenuManager helpMenu = new MenuManager("&Help",IWorkbenchActionConstants.M_HELP); menuBar.add(helpMenu); // About > Help helpMenu.add(new Separator()); helpMenu.add(aboutAction); ... } }
After you launch your product and select Help > About, the About dialog will appear.
Figure 15. About dialog sample
Welcome page
A welcome page is used to introduce the product information, which is especially helpful for new users. You can depict all features, usage, and tips of your product via the welcome page.
Figure 16. Welcome page configuration in Branding tab
To enable a welcome page in your product, you will extend two extensions:
org.eclipse.ui.intro and
org.eclipse.ui.intro.config. Add the following code into the plugin.xml file.
Listing 8. Intro configuration in plugin.xml
<extension point="org.eclipse.ui.intro"> <intro class="org.eclipse.ui.intro.config.CustomizableIntroPart" icon="icons/alt_window_16.gif" id="com.example.zyx.intro"> </intro> <introProductBinding introId="com.example.zyx.intro" productId="com.example.zyx.product"> </introProductBinding> </extension> <extension point="org.eclipse.ui.intro.config"> <config content="introContent.xml" id="com.example.zyx.configId" introId="com.example.zyx.intro"> <presentation home- <implementation kind="html" os="win32,linux,macosx"> </implementation> </presentation> </config> </extension>
Next, add an action in menu bar by selecting Help > Welcome. Open the
ApplicationActionBarAdvisor.java file again and remove the comment tag of the following code.
Listing 9. ApplicationActionBarAdvisor.java
public class ApplicationActionBarAdvisor extends ActionBarAdvisor { ... private IWorkbenchAction introAction; protected void makeActions(final IWorkbenchWindow window) { ... introAction = ActionFactory.INTRO.create(window); register(introAction); } protected void fillMenuBar(IMenuManager menuBar) { ... helpMenu.add(introAction); ... } }
You will see the following welcome page when you launch your product.
Figure 17. Welcome page sample
Publish Your RCP product
Test before publishing
Go back to the Overview tab and find the Testing section. When you have changed the product name, window images, about image and about text, etc., click Synchronize link to reflect your changes to plugin.xml to ensure that the plug-in manifest is up to date. Click Launch the product to test your product before it's exported.
There is an example of how the Synchronize link works. Change the product name from
%productName to
my product, then click Synchronize. Go to the plugin.xml file and verify whether the product name value ws changed to
my product. After that, change it back to
%productName and click Synchronize, then click Launch the product, and your product will launch.
Export product
Go to the find Exporting section of the Overview tab, where there is a link to export your product. Click the Eclipse Product export wizard. In the export dialog that pops up, specify MyProduct as the Root directory and C:\export as the destination directory.
After clicking Finish, verify the export result by navigating to the C:\export\MyProduct directory. You will find the FrogAcrossRiver.exe and FrogAcrossRiver.ini files in which your launching arguments are recorded. You will also verify that the icon of the FrogAcrossRiver.exe file is what you desire.
Figure 18. Exported RCP product in file system
If you have installed JRE, double-click the
FrogAcrossRiver.exe to launch your product.
Congratulations! You configured and published your RCP application as a product successfully.
JRE
This tip can help you publish your product on a non-JRE OS: Just find a platform with JRE installed, copy its JRE directory into the root folder of your exported product, as shown below.
Figure 19. JRE added to exported RCP product
Double-click FrogAcrossRiver.exe and it launches your RCP product successfully.
Troubleshooting
- You will be notified if your .ico file doesn't include the required image files in the specified sizes or color depths with the error message: [Program Launcher] The launcher may not get branded correctly, .ico file is missing its image. Similarly, you will get the following warning message if you specified an invalid image in the .product file: [About Dialog] Image: path/ImageName — is not a path to a valid file.
- If you add
-cleanin Program Arguments and launch the product from an exported folder, you will not see the splash screen. However, you can see it when launched from the Launch the product link.
Summary
This article has shown how to create and pack your branded Eclipse product by leveraging Eclipse's Product Configuration and PDE. Although you can do this using a script, we have demonstrated a more effective and efficient way to produce the product where you can configure and manage all branding information and elements. Most importantly, this article has shown the possibilities of an RCP world with the aid of the Eclipse Production Configuration feature.
Download
Resources
Learn
- The "Rich Client Tutorial Part 1" introduces basic instructions of RCP development.
- "PDE Does Plug-ins" gives a background description on how to develop in Eclipse's PDE.
- Read "How to Build an Eclipse Product" to learn more about Eclipse product primary principles.
- "Creating product branding" describes some elements (such as icon and splash screen) in product banding.
- Browse all the Eclipse content on developerWorks.
- Users new to Eclipse should look at the Eclipse start here.
- latest Eclipse SDK and try its Product Configuration feature with your RCP projects.
-
- Learn more about RCP from the Eclipse Foundation's Official Eclipse FAQs.
-.
|
http://www.ibm.com/developerworks/library/os-eclipse-brand/index.html
|
CC-MAIN-2014-35
|
refinedweb
| 3,275
| 50.63
|
Hi,I found a bug in Sublime Text2. Shortly, create new file, write something in it. Then paste this at the beggining of file
/**
*******************************************************************************
* some text
* sdsada ome text2
* some tedsa sdad xt3
* some text4
*
* some text5
*
*******************************************************************************/
And now you are unable to delete characters in this file by pressing backspace. Only way is to select text and then press backspace.
If you can provide some workaround I will be grateful
sublimetext.com/docs/2/revert.html
It does not change anything. Problem still exists. Freshly installed sublime text has the same issue (for new linux user)
Are you sure you removed your data folder ? This look like a plugin problem.Reinstalling ST is no enough.
Yes I'm sure. I moved .config/sublime-text-2 somewhere else. Even created new user and do a fresh installation.I run FindKeyConflicts, but it looks fine. The problem disappears when I remove mentioned comment header (but I cant work this way, such header is mandatory for my job).
Work fine for me on Windows.What's the syntax of your new file, PlainText ?
I've checked plain text and c++.I'm working on Linux Mint, maybe it causes the problem. I'm going to switch to Fedora today.
Everything works on Fedora 18 O.o
Hello everybody, i have the same problem with backspace and also with del key with plain text, C file, SQL file, at least !
I tried to rename sublime folder as mentioned but without effect.
My installation is a fresh installation without plugins installed by myself.
I'm on Ubuntu 12.10.
Linux Mint 14 XFCE 64 bit - no problems at all!
I'm running a Linux desktop with Ubuntu 10.04, it have the same bug, a laptop with Ubuntu 12.04 with the same bug, tested on windows 7, no problem and MacOs no problem.Sublime backs to normal when you removes the comment.
Problem occurs on Xubuntu 12.04 32bit. Pretty frustrating bug.
Could you please describe the problems you're having and how to reproduce them? Otherwise we cannot provide any help.
The problem has already been described but here it is outlined along with some sample code which produces the problem on my machine.
ProblemThe backspace and delete key do not work on all occasions. There does seem to be a workaround whereby selecting the text and pressing backspace or delete will work.
Sample
#ifndef TEST_H
#define TEST_H
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/erase.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/predicate.hpp>
namespace Test
{
}
#endif //TEST_H
In this code snippet the problem seems a bit sporadic. Anything below line 7 the backspace won't work but everything above it does seem to work. I'm beginning to think the problem has nothing to do with comments but perhaps it's related to line endings or something else.
BUMP! how is this huge bug not solved yet?!
|
https://forum.sublimetext.com/t/backspace-does-not-work-when-file-starts-with-comment-header/9358/8
|
CC-MAIN-2016-18
|
refinedweb
| 506
| 70.19
|
Elixir v1.8.2 Enumerable protocol View Source(enumerable, fun) do reducer = fn x, acc -> {:cont, [fun.(x) | acc]} end Enumerable.reduce(enumerable, {:cont, []}, reducer) |> elem(1) |> :lists.reverse() end
Notice the user-supplied function is wrapped into a
reducer/0 function.
The
reducer/0 function must return a tagged tuple after each step,
as described in the
acc/0 type. At the end,
Enumerable.reduce/3
returns
result/0.
This protocol uses tagged tuples to exchange information between the
reducer function and the data type that implements the protocol. This
allows enumeration of resources, such as files, to be done efficiently
while also guaranteeing the resource will be closed at the end of the
enumeration. This protocol also allows suspension of the enumeration,
which is useful when interleaving between many enumerables is required
(as in the
zip/1 and
zip/2 functions).
This protocol requires four functions to be implemented,
reduce/3,
count/1,
member?/2, and
slice/1. The core of the protocol is the
reduce/3 function. All other functions exist as optimizations paths
for data structures that can implement certain properties in better
than linear time.
Link to this section Summary
Types
A partially applied reduce function.
A slicing function that receives the initial position and the number of elements in the slice.
Functions
Retrieves the number of elements in the
enumerable.
Checks if an
element exists within the
enumerable.
Reduces the
enumerable into an element.
Returns a function that slices the data structure contiguously.
Link to this section Types
acc() View Source.
continuation() View Source
A partially applied reduce function.
The continuation is the closure returned as a result when the enumeration is suspended. When invoked, it expects a new accumulator and it returns the result.
A continuation can be trivially implemented as long as the reduce function is defined in a tail recursive fashion. If the function is tail recursive, all the state is passed as arguments, so the continuation is the reducing function partially applied.
reducer() View Source
The reducer function.
Should be called with the
enumerable element and the
accumulator contents.
Returns the accumulator for the next enumeration step.
result()
View Source
result() ::
{:done, term()} | {:halted, term()} | {:suspended, term(), continuation()}.
slicing_fun()
View Source
slicing_fun() ::
(start :: non_neg_integer(), length :: pos_integer() -> [term()])
slicing_fun() :: (start :: non_neg_integer(), length :: pos_integer() -> [term()])
A slicing function that receives the initial position and the number of elements in the slice.
The
start position is a number
>= 0 and guaranteed to
exist in the
enumerable. The length is a number
>= 1 in a way
that
start + length <= count, where
count is the maximum
amount of elements in the enumerable.
The function should return a non empty list where
the amount of elements is equal to
length.
t() View Source
Link to this section Functions
count(enumerable) View Source
Retrieves the number of elements in the
enumerable.
It should return
{:ok, count} if you can count the number of elements
in the
enumerable.
Otherwise it should return
{:error, __MODULE__} and a default algorithm
built on top of
reduce/3 that runs in linear time will be used.
member?(enumerable, element) View Source
Checks if an
element exists within the
enumerable.
It should return
{:ok, boolean} if you can check the membership of a
given element in the
enumerable with
===/2 without traversing the whole
enumerable.
Otherwise it should return
{:error, __MODULE__} and a default algorithm
built on top of
reduce/3 that runs in linear time will be used.
reduce(enumerable, acc, fun) View Source
Reduces the
enumerable into an element.
Most of the operations in
Enum are implemented in terms of reduce.
This function should apply the given
reducer/0 function to each
item in the
enumerable and proceed as expected by the returned
accumulator.
See the documentation of the types
result/0 and
acc/0 for
more information.
Examples
As an example, here is the implementation of
reduce for lists:
def reduce(_list, {:halt, acc}, _fun), do: {:halted, acc} def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)} def reduce([], {:cont, acc}, _fun), do: {:done, acc} def reduce([head | tail], {:cont, acc}, fun), do: reduce(tail, fun.(head, acc), fun)
slice(enumerable) View Source
Returns a function that slices the data structure contiguously.
It should return
{:ok, size, slicing_fun} if the
enumerable has
a known bound and can access a position in the
enumerable without
traversing all previous elements.
Otherwise it should return
{:error, __MODULE__} and a default
algorithm built on top of
reduce/3 that runs in linear time will be
used.
Differences to
count/1
The
size value returned by this function is used for boundary checks,
therefore it is extremely important that this function only returns
:ok
if retrieving the
size of the
enumerable is cheap, fast and takes constant
time. Otherwise the simplest of operations, such as
Enum.at(enumerable, 0),
will become too expensive.
On the other hand, the
count/1 function in this protocol should be
implemented whenever you can count the number of elements in the collection.
|
https://hexdocs.pm/elixir/Enumerable.html
|
CC-MAIN-2019-26
|
refinedweb
| 837
| 55.95
|
On 9/25/07, Joe Perches <joe@perches.com> wrote:
> On Tue, 2007-09-25 at 00:58 -0400, linux@horizon.com wrote:
> > Even the "kp_" prefix is actually pretty unnecessary. It's "info"
> > and a human-readable string that make it recognizable as a log message.
>
> While I agree a prefix isn't necessary, info, warn, err
> are already frequently #define'd and used.
>
> kp_<level> isn't currently in use.
>
> $ egrep -r -l --include=*.[ch] "^[[:space:]]*#[[:space:]]*define[[:space:]]+(info|err|warn)\b" * | wc -l
> 29
Yes, this is a very good point, they're already used. If they hadn't
been, everything would have been perfect. Actually, I'd have preferred
info/warn/err over kprint_<level> if it wasn't for the fact that
they're used (and in slightly different ways too).
As I wrote initially, one of the absolute requirements of a new API is
to retain full backwards compatibility with printk(). Which means that
using simply err()/info()/warn() is out of the question *for now*.
That is not to say we can't change this at a later time.
I think it would be good to have a base layer containing the functions
kprint_<level>(), just to have something that 1) has a meaningful
name, and 2) doesn't disturb anybody else's names. err/info/warn or
kp_err/info/warn() (in order to have shorter names) can then be
implemented in terms of this.
I suppose that another goal of a new API would be to unify the
somewhat-a-mess of API that is now, i.e. many alternatives that do the
same thing is also not good. But this can be changed with patches (to
convert to new API) later.
If you look closer at the current definitions of erro/warn/info, it
turns out that most of them also do this to automatically prefix all
messages with the driver name. This makes me realize that there really
is a need for a way to automatically prefix messages or store a
per-message "subsystem" field. I propose the following solution:
The kprint.h header file looks like this:
/* This is a back-up string to be used if the source file doesn't
define this as a macro. */
const char *SUBSYSTEM = "";
/* Call this macro whatever you want, it's just an example anyway. */
#define info(msg, ...) printf("%s: " msg, SUBSYSTEM, ## __VA_ARGS__)
Then you can have a C file that overrides SUBSYSTEM by defining it as a macro:
#include <linux/kprint.h>
#define SUBSYSTEM "usb"
info("test");
--> results in printf("%s: " "test", "usb");
Or, a C file that doesn't:
#include <linux/kprint.h>
info("test");
--> results in printf("%s: " "test", SYBSYSTEM);
--> output is ": test"
Though, instead of actually incorporating this SUBSYSTEM name into the
string, I suggest passing it off as an argument into the real kprint()
machinery, to be stored along (but seperately) with timestamp, etc.
Hm, that's a digression. But thanks for the idea :)
Vegard
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at
Please read the FAQ at
|
http://lkml.org/lkml/2007/9/25/62
|
crawl-002
|
refinedweb
| 530
| 63.7
|
yasnippets for jasp, ase and python
Posted February 17, 2014 at 09:03 AM | categories: ase, emacs, jasp | tags: | View Comments
Table of Contents
In using [[ for calculations, I find there are lots of small python phrases I use over and over. Today I will examine using yasnippet to save time and keystrokes. yasnippet is a template expansion module, where you type a small set of characters, press
Tab, and the
characters "expand" to the full text. It is pretty sophisticated, and allows you to define "tab-stops" which you interactively fill in, and tab between like filling in a form.
All the snippets are defined in the
*Appendix.
1 Tangle the snippets, and add them to yasnippet
Each snippet definition belongs in a file in a directory. The main directory is called "snippets". Since I anticipate using these snippets in org-mode, each snippet is defined in a directory within snippets called "org-mode". First, we make the directory here. I also want to use the snippets in python mode, so we also create a python-mode directory here. We do not have to duplicate the snippets. We can create a file called .yas-parents , with one line in it containing "org-mode".
mkdir -p snippets/org-mode mkdir -p snippets/python-mode echo "org-mode" > snippets/python-mode/.yas-parents
Each snippet is defined in a src block with a
:tangle header. So, we can extract them all in one command here.
(org-babel-tangle)
We also need to add our new directory to yasnippets. This is done by adding the directory to the
yas-snippet-dirs variable. You could add this to your init.el file to permanently add these snippets.
(add-to-list 'yas-snippet-dirs "c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/snippets")
Finally, we reload all the snippet definitions, so our new definitions are ready to use.
(yas-reload-all)
[yas] Reloaded everything (snippets will load just-in-time)... (some errors, check *Messages*).
Alternatively, you might just load this directory.
(yas-load-directory "./snippets")
2 Using the snippets
Each of these snippets is for a python phrase, but I usually write my python blocks in org-mode. You would use these by typing the shortcut name, and then pressing tab. Below I show what each shortcut expands to.
wjl →
with jasp('') as calc:
wjn →
with jasp('',) as calc:
calc.calculate(atoms)
cc →
calc.calculate(atoms)
cga →
atoms = calc.get_atoms()
atm →
Atom('', )
atms →
atoms = Atoms([], cell)=
ape →
atoms.get_potential_energy()
agf →
atoms.get_forces()
avw →
from ase.visualize import view
view(atoms)
awt →
from ase.io import write
write('.png', atoms, show_unit_cell=2)
npa →
np.array()
pp →
plt.plot(, )
pxl →
plt.xlabel()
pyl →
plt.ylabel()
pl →
plt.legend()
ij →
from jasp import *
inp →
import numpy as np
imp →
import matplotlib.pyplot as plt
iase →
from ase import Atom, Atoms
What other snippets would be handy?
3 Appendix
3.1 jasp snippets
# -*- mode: snippet -*- # -- with jasp('$1') as calc: $0
# -*- mode: snippet -*- # -- with jasp('$1',$0) as calc: calc.calculate(atoms)
# -*- mode: snippet -*- # -- calc.calculate(atoms)
# -*- mode: snippet -*- # -- atoms = calc.get_atoms()
3.2 ase snippets
Template for an ase.Atom
# -*- mode: snippet -*- # -- Atom('$1', $2)
# -*- mode: snippet -*- # -- atoms = Atoms([$1], cell=$2)
# -*- mode: snippet -*- # -- atoms.get_potential_energy()
# -*- mode: snippet -*- # -- atoms.get_forces()
# -*- mode: snippet -*- # -- from ase.visualize import view view(${1:atoms})
# -*- mode: snippet -*- # -- from ase.io import write write('$1.png', ${2:atoms}, show_unit_cell=${3:2})
3.3 python snippets
# -*- mode: snippet -*- # -- import numpy as np
# -*- mode: snippet -*- # -- import matplotlib.pyplot as plt
# -*- mode: snippet -*- # -- from ase import Atom, Atoms
# -*- mode: snippet -*- # -- np.array($0)
# -*- mode: snippet -*- # -- plt.plot($1, $2)
# -*- mode: snippet -*- # -- plt.xlabel($1)
# -*- mode: snippet -*- # -- plt.ylabel($1)
# -*- mode: snippet -*- # -- plt.legend($1)
# -*- mode: snippet -*- # -- from jasp import *
Copyright (C) 2014 by John Kitchin. See the License for information about copying.
Org-mode version = 8.2.5h
|
http://kitchingroup.cheme.cmu.edu/blog/2014/02/17/yasnippets-for-jasp-ase-and-python/
|
CC-MAIN-2018-30
|
refinedweb
| 643
| 62.75
|
Hello all,
I really hope you could help me with that. I have an exercise in my 'Financial modelling' module and am quite lost to be honest.
Let's explain the situation: I am dealing with the Dow Jones index.
-The first question of this exercise is to test for unit root. I do that using Perron's procedure and the log of the index and find a unit root. So far so good.
-The second question, and that's where I'm not sure, is to identify an ARMA model for the purpose of estimating the series of equity market returns.
The first problem is that I'm not sure if I have to use the Log Dow Jones which contains a unit-root or the return which does not. I think I have read somewhere that you have to use stationary variables to identify an ARMA model so I used the return (log and difference) and not the log. But obviously, the first difference of my log Dow Jones looks exactly like a pure white-noise process.
So when I estimate my ARMA model, I regress with maximum likelihood a pure white noise which is a bit silly I guess. Then I do the overfitting procedure and actually find that for an ARMA (4,4), all my coefficients are significant and the 'white-noise' test of my residuals is perfect.
So I'm tempted to say that my 'white-noise'-like returns can be modelled by an ARMA (4,4) but I feel like I've done something wrong here.
-Can you really estimate stock returns with an ARMA model?
-Does the lecturer actually asked us to identify the ARMA model on the log and not the return of the index? (but it contains a unit-root so don't think you can do it)
-Does the lecturer actually want us to say that it is not possible?
Ok, sorry with all these questions. I really do hope I've been clear. Let me know if you want me to shed light on a certain point.
Thank you in advance for your help.
Have a good evening
|
http://mathhelpforum.com/business-math/83690-arma-models.html
|
CC-MAIN-2017-09
|
refinedweb
| 359
| 71.85
|
Hi Richard,
Thanks for looking into this. The structure itself is not vitally important other than that it upset my script. I'm certainly happy with a system that gives rubbish for rubbish structures but I think that rather than produce a pentavalent carbon, as the kekulize function does in this case, it should produce an error. Pentavalent carbons are quite unequivocally wrong, after all, and producing one is a clear sign that something's badly awry.
Regards,
Dave
Hi,
I've had a problem with the structure AFUWEE, as shown in the attached script. If I do standardise_aromatic_bonds(), standardise_delocalised_bonds(), kekulize(), I get a structure with a pentavalent carbon (atom 3), a C-H with 2 double bonds off it. If I run the same three functions on _that_ molecule, I get aromatic (type 4) bonds for those two bonds, which is a bit odd for a kekulised structure. Granted, the bonding for this molecule is a mess (possibly there should be a double bond to the phosporus?) but the inconsistent behaviour isn't great, either. Mercury shows AFUWEE with a fully-aromatic 6,5 carbon system, which is also unexpected.
This is the case in the latest production version (1.0.0) and the 2017 beta version.
Regards,
Dave
Hi Richard,
Sorry not to reply sooner, I've been on holiday. I'm happy to report that the script now runs using the beta version of the 1.3 API. Thanks for squeezing it in so close to the wire.
Dave
Hi,
If I run the script below, with testmol.sdf as attached, the first remove_hydrogens() gives no complaint, the second gives the error
File "test_ccdc_h.py", line 17, in <module>
mol1.remove_hydrogens()
File "/home/davidc/anaconda2/envs/TwoD2ThreeD/lib/python2.7/site-packages/ccdc/molecule.py", line 1454, in remove_hydrogens
ChemistryLib.remove_hydrogens(self._molecule)
TypeError: in method 'remove_hydrogens', argument 1 of type 'EditableMolecule &'
I can't find any documentation about editable or non-editable molecules. Can someone please help me understand what the difference is between the two cases and how I go about removing hydrogens from a molecule read from a string? My real use case is with SDF records POSTed to a webservice, so I don't want to have to go through a file.
Thanks,
Dave
-------------------------------------------------------------------------------------------------
Script:
#!/usr/bin/env python
from ccdc import io
from ccdc.molecule import Molecule
mol_reader = io.MoleculeReader( 'testmol.sdf' )
mol = mol_reader[0]
mol.remove_hydrogens() # works fine
f = open( 'testmol.sdf' , 'r' )
fc = f.read()
mol1 = Molecule.from_string( fc , 'sdf' )
mol1.remove_hydrogens() # generates error
Hi Ilenia,
Thanks for the reply. I had stumbled upon the standardise_aromatic_bonds() bit some time after posting, but not the delocalised_bonds() equivalent. I'll amend my script accordingly. If this step isn't in the documentation examples, can I suggest it's added? It seems to be quite important!
Thanks for the tip about the databases, I'll add that, too, though clearly in this case it was a secondary effect.
Cheers,
Dave
Hi,
I'm getting odd results with the attached structure. It seems I can only attach one file, so I've attached the structure. The script I'm running is at the bottom. When I run it, I get:
Num atoms in Test Mol : 36
Unusual bonds : 1
[u'C17', u'N16'] [16, 15] 1.35176561208 1.30825121262 1.30575835705 3.46603009836 False 17
When I analyse the structure in Mogul, the z score is 0.628 for that bond, based on 7599 hits, whereas here it's 3.466 and 17 respectively. It's very odd, too, that it only complains about 1 of the C-N bonds in the pyridine, not the other!
Any hints as to what I'm going on will be gratefully received!
Thanks,
Dave
PS the indentation in the script is obviously mangled by this text box.
----------------------------------------------------------------------------------------------------------------------------
#!/usr/bin/env python
from ccdc import io
from ccdc.conformer import GeometryAnalyser
from ccdc.molecule import Molecule
import sys
engine = GeometryAnalyser()
mol_reader = io.MoleculeReader( sys.argv[1] )
mol = mol_reader[0]
print 'Num atoms in %s : %d' % ( mol.identifier , len( mol.atoms ) )
mol_checked = engine.analyse_molecule( mol )
print 'Unusual bonds : %d' % len([b for b in mol_checked.analysed_bonds if b.unusual])
for b in mol_checked.analysed_bonds :
if b.unusual :
print b.atom_labels , b.atom_indices , b.value , b.mean , b.median , b.z_score , b.generalised , b.nhits
After some more persistence and patience, I seem to have it running ok on Ubuntu 16.04. I installed it into a fresh anaconda environment using
conda install ~/Downloads/csd-python-api-1.0.0-linux-64-py2.7-conda.tar.bz2
and some simple things work. My initial thought that it wasn't working was because
mol_checked = engine.analyse_molecule( mol )
seemed to hang - that's where the patience came in. It just takes quite a bit longer than I thought it would.
My experience is that using pip install and setting LD_LIBRARY_PATH as suggested in the installation instructions is a mistake. On my machine, at any rate, this left me with incompatible libraries in my the search path, which had been built with an older glibc than the system libraries, so I got a lot of shared library errors. Installing with anaconda didn't show this effect, for reasons that I can't fathom.
Hi,
I'm attempting to install the API on Ubuntu 16.04. The run_test.sh script gives the attached output:
I have tried using anaconda for the installation, and pip. Attached is the output from the pip installation, the anaconda was the same although the installation tarball for the latter didn't seem to have the tests directory in it, so I had to unpack the pip tarball anyway!
The output from the tests looks a bit worrying to me. Why are some tests skipped? The Segmentation faults look particularly iffy. Is there any way of knowing which tests were failing? It may be that these are for things we're not licensed for or won't be using (we have licenses for CSD-System only).
I realise that ubuntu isn't on your list of known successes. That seems a bit odd, given its popularity. I can probably switch to Suse if needed, though that would be disappointing.
Thanks,
Dave
|
https://www.ccdc.cam.ac.uk/public/55e9912a-6b1b-e611-a350-00505686f06e/forum-posts
|
CC-MAIN-2018-47
|
refinedweb
| 1,041
| 67.86
|
SETUID(3V) SETUID(3V)
NAME
setuid, seteuid, setruid, setgid, setegid, setrgid - set user and group
ID
SYNOPSIS
#include <<sys/types.h>>
int setuid(uid)
uid_t uid;
int seteuid(euid)
uid_t euid;
int setruid(ruid)
uid_t ruid;
int setgid(gid)
gid_t gid;
int setegid(egid)
gid_t egid;
int setrgid(rgid)
gid_t rgid;
DESCRIPTION
setuid() (setgid()) sets both the real and effective user ID (group ID)
of the current process as specified by uid (gid) (see NOTES).
seteuid() (setegid()) sets the effective user ID (group ID) of the cur-
rent process.
setruid() (setrgid()) sets the real user ID (group ID) of the current
process.
These calls are only permitted to the super-user or if the argument is
the real or effective user (group) ID of the calling process.
SYSTEM V DESCRIPTION
If the effective user ID of the calling process is not super-user, but
if its real user (group) ID is equal to uid (gid), or if the saved set-
user (group) ID from execve(2V) is equal to uid (gid), then the effec-
tive user (group) ID is set to uid (gid).
RETURN VALUES
These functions return:
0 on success.
-1 on failure and set errno to indicate the error as for
setreuid(2) (setregid(2)).
ERRORS
EINVAL The value of uid (gid) is invalid (less than 0 or
greater than 65535).
EPERM The process does not have super-user privileges and uid
(gid) does not matches neither the real user (group) ID
of the process nor the saved set-user-ID (set-group-ID)
of the process.
SEE ALSO
execve(2V), getgid(2V), getuid(2V), setregid(2), setreuid(2)
NOTES
For setuid() to behave as described above, {_POSIX_SAVED_IDS} must be
in effect (see sysconf(2V)). {_POSIX_SAVED_IDS} is always in effect on
SunOS systems, but for portability, applications should call sysconf()
to determine whether {_POSIX_SAVED_IDS} is in effect for the current
system.
21 January 1990 SETUID(3V)
|
http://modman.unixdev.net/?sektion=3&page=setruid&manpath=SunOS-4.1.3
|
CC-MAIN-2017-17
|
refinedweb
| 318
| 65.66
|
Collaboration Tutorial
From OLPC
This tutorial focuses on activity sharing. Read Activity sharing for an overview of the concepts. See also Presence Service and Tubes.
See Collaboration Central for all things relating to activity collaboration.
[edit] Introduction
Collaboration is implemented with Telepathy, a D-Bus framework for Instant Messaging protocols. The Presence Service provides functionality to Sugar to track shared Activities and Buddies (and show them on the Neighborhood View), and talks to Telepathy connection managers for XMPP via a Jabber server (telepathy-gabble), and Link Local XMPP (telepathy-salut).
XMPP is used to provide presence information about Buddies (other XOs you can collaborate with). The mesh view is like an instant messenger buddy list, represented in a more graphical way.
Not all the Buddies you see are on the same network as you. In particular, any of them could be behind a NAT firewall, and so you cannot simply open a TCP/IP socket to them to exchange data. Furthermore, while it is not yet implemented, Bitfrost's P_NET protection will restrict activities' use of networking, but not apply to collaboration via Telepathy.[1]
XMPP via the Jabber server on the school server allows you to exchange data with all the Buddies you can see, whether or not they are directly reachable from your XO.
[edit] Shared Activities
A shared activity is implemented using an XMPP MUC (multi user chat room). Buddies that are in the room, are in the shared activity.
Presence Service provides each shared activity with a Telepathy Text Channel by default. This text channel is a connection to the XMPP chat room, but is not useful for data sharing directly. You can see an example of this Text Channel in direct use in the Chat activity. In future, Sugar will provide "overlay chat" to activities, allowing you to do text chat with the participants of a shared activity.
On top of this Text Channel, PS provides a Tubes channel to exchange data with the other participants via Tubes.
[edit] Tubes
There are two types of Activity sharing#Tubes at present: D-Bus Tubes and Stream Tubes.
D-Bus Tubes provide D-Bus functionality to signal and call methods on everyone in the room.
Stream Tubes wrap TCP/IP sockets and are more suited to streaming data between two participants.
[edit] D-Bus Tubes
See the D-Bus tutorial and the dbus-python tutorial.
D-Bus provides signals and methods:
- Signals are multicast - they are sent to all participants in the shared activity (including the sender). They send data and have no return value.
- Method calls are called on a single participant, and they do have a return value.
It is important to design your Activity's D-Bus Tubes API well, to support the functionality that your collaboration will need.
More to come here...
[edit] Bus names, handles, Buddy objects
Signals and Methods use bus names to identify senders and recipients. Telepathy uses handles to identify participants. Sugar uses Buddy objects.
The TubeConnection object can convert between bus names and handles - see tubeconn.py for details.
More to come here...
[edit] Stream Tubes
See the Read activity's code for an example. It's in git://dev.laptop.org/projects/read-activity and is built by default in sugar-jhbuild.
More to come here...
[edit] Example Activity: HelloMesh
HelloMesh is a demo activity with sample code using a D-Bus Tube. The code is in git://dev.laptop.org/projects/hellomesh and can be built in sugar-jhbuild with ./sugar-jhbuild buildone hellomesh
First, let's look at HelloMesh's D-Bus Tubes API. There are two signals and one method:
@signal(dbus_interface=IFACE, signature=) def Hello(self): """Say Hello to whoever else is in the tube.""" self._logger.debug('I said Hello.')
@method(dbus_interface=IFACE, in_signature='s', out_signature=) def World(self, text): """To be called on the incoming XO after they Hello.""" if not self.text: self._logger.debug('Somebody called World and sent me %s', text) self._alert('World', 'Received %s' % text) self.text = text self.text_received_cb(text) # now I can World others self.add_hello_handler() else: self._logger.debug("I've already been welcomed, doing nothing")
@signal(dbus_interface=IFACE, signature='s') def SendText(self, text): """Send some text to all participants.""" self.text = text self._logger.debug('Sent text: %s', text) self._alert('SendText', 'Sent %s' % text)
When a new participant joins the shared activity, it sends the Hello signal. This goes to all existing participants. The Hello signal has an empty signature, since no actual parameters are being sent.When an (existing) participant receives the Hello signal, it calls the World method of the signal's sender. The World method takes a string parameter (text) represented by
in_signature='s'It doesn't return anything, hence
out_signature=''
Calling World when Hello is received is done in hello_cb:
def hello_cb(self, sender=None): """Somebody Helloed me. World them.""" if sender == self.tube.get_unique_name(): # sender is my bus name, so ignore my own signal return self._logger.debug('Newcomer %s has joined', sender) self._logger.debug('Welcoming newcomer and sending them the game state') self.tube.get_object(sender, PATH).World(self.text, dbus_interface=IFACE)
Note that signals go to all participants, including yourself - the above code shows how to ignore your own signals.
sender is a bus (as in D-Bus) name, like :2.OWI0MTk2MzNAdmFpbwAA. Signals and Methods use these to identify senders and recipients.
In order to receive the Hello signal, we need to add a signal receiver:
def add_hello_handler(self): self._logger.debug('Adding hello handler.') self.tube.add_signal_receiver(self.hello_cb, 'Hello', IFACE, path=PATH, sender_keyword='sender') self.tube.add_signal_receiver(self.sendtext_cb, 'SendText', IFACE, path=PATH, sender_keyword='sender')
You can see this called in the World method above, because in this example once we have had our World method called by an existing participant, we can then respond to somebody else's Hello signal.
This also adds a signal receiver for the SendText signal, defined above, which sends the text from the user interface.
[edit] See Also
Sugar_Almanac#Package:_sugar.presence
|
http://wiki.laptop.org/go/Tubes_Tutorial
|
CC-MAIN-2013-20
|
refinedweb
| 1,008
| 50.43
|
Using open source code from 6th sense and webpages, we have created a motor toy car that is controlled using 6th sense technology. A webcam picks up different hand movements from the user who has 4 colored finger gloves, and will send that data over to the car, which will move appropriately. From there the car will live stream a video feed to the Pi's webpage!
~~~~~
This project was made forWashington State University's 24hr Hardware Hackathon. We will be continuing to perfect this instructable and add more details / additions in the future! Please let us know if you have any questions!
Step 1: Gather Materials
General Materials:
- Toy R/C monster truck, large enough to fit a Raspberry Pi or Arduino on.
- Rasbperry Pi (or Arduino)
Pertaining to the Pi:
- Micro SD card (8GB or larger)
- Breadboard
- Jumper Wires
- USB Dongle (wifi adapter)
- Pi-Camera
- Power cord
- Monitor to connect to Pi
- Portable mouse / keyboard
Step 2: Install Raspbian Onto Your New Pi
We recommend using at least an 8 GB Micro USB for installing Raspbian. We went with a 16GB just to be safe. We also used the Raspberry Pi 2 body.
Step 3: Install Open Source Cam Web Interface
Install the web streaming software. We used RPi Cam Web Interface.
Follow the instructions here:
Make sure to run the install again after you install the software to run the configure options.
You need to "start" the camera and should set it to autorun if you want it to start automatically every time you boot your Pi
Step 4: Configure Open Source Code for 6th Sense Technology
Install the Sixth Sense Tech software
Open Source Code Here:
If you are using a 64 bit computer, you may need to make some modifications.
We recommend the following YouTube video for assistance:...
Step 5: Hacking the Toy Car Transmitter and Receiver: Testing
First we need to find a way to turn the physical buttons on the transmitter and make a micro-controller enable these contacts.
Instructions
1: Remove all four buttons.
2: Find what is the positive and negative contact of each of the switches.
3. Solder jumper cables to all of the switches' contacts.
4: If the contacts have been surface mounted then you might want to glue the transmitter board to a prototyping board. Rewire the jumpers to that prototyping board.
5: Once that is done, connect the jumpers to their respective transistors (NPN) as shown in the schematic.
6: Now connect the base of the transistors to their respective pins on the micro-controller.
7: Connect the power cables and double check the circuit.
8: Connect power to the reviving circuit board.
9: Upload the sketch onto the micro controller.
10: The car must start moving according to sketch completely wireless.
(this sketch is for an Arduino microcontroller, we used this for testing and later switched to Python on the Raspberry PI for control)
Arduino Sketch
/*
* Hardware Hackathon
* Test Code 1, this will control the R/C car, this code does not accept any user input
* 14/11/15
*/
int forwardPin = 2;
int backwardPin = 7;
int leftPin = 8;
int rightPin = 9;
void setup(){
pinMode(forwardPin, OUTPUT);
pinMode(backwardPin, OUTPUT);
pinMode(leftPin, OUTPUT);
pinMode(rightPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
// Move Forward
digitalWrite(forwardPin, HIGH);
Serial.println("Move Forward");
delay(750);
digitalWrite(forwardPin, LOW);
// Move Backward
digitalWrite(backwardPin, HIGH);
Serial.println("Move Backward");
delay(750);
digitalWrite(backwardPin, LOW);
// Turn Left
digitalWrite(forwardPin, HIGH);
digitalWrite(leftPin, HIGH);
Serial.println("Turn Left");
delay(750);
digitalWrite(forwardPin, LOW);
digitalWrite(leftPin, LOW);
// Turn Right
digitalWrite(forwardPin, HIGH);
digitalWrite(rightPin, HIGH);
Serial.println("Turn Right"); delay(750);
digitalWrite(forwardPin, LOW);
digitalWrite(rightPin, LOW);
}
Step 6: Assemble Final Code and Compile!
We had our Sixth Sense computer setup as a web server and modified the Sixth Sense program to write a single character to a text file that was on the web server and accessed that file from the Raspberry Pi to read the values as inputs for the car control.
The text file simply contained one of five characters based on the current position of each of the four colored markers:
1, 2, 3, 4, 0
The Python code on the Raspberry Pi (or C code on an Arduino) reads the character from the web file and decodes it into the appropriate action for the car.
Sixth Sense Code can be found at our git repository:
This is the Python code for the Raspberry Pi that ties everything together.
Paste this into a python file, and run.
#Hardware Hackathon
#Code 1
#14/11/15 #Ground -> pin 20 grey
#5V -> pin 2 #3.3 -> pin 1
#receive the data #!/usr/bin/env python
import urllib.request
print ("Pi Home server running!")
forwardPin = 17 # GPIO pin3 white
backwardPin = 23 # pin 5 purple
leftPin = 27 #pin 13 grey
rightPin = 22 #pin 15 red
from time import sleep from RPi import GPIO import time
# set our mode GPIO.setmode(GPIO.BCM)
def setup():
GPIO.setup(forwardPin, GPIO.OUT)
GPIO.setup(backwardPin, GPIO.OUT)
GPIO.setup(leftPin, GPIO.OUT)
GPIO.setup(rightPin, GPIO.OUT)
def loop():
response=urllib.request.urlopen('')
html=str(response.read())[2:-1]
html = html.split("\\r\\n")[:-1]
print(html)
print(html[0])
if (html[0]== "1"):
# Move Forwards
GPIO.output(forwardPin, True)
time.sleep(.75)
GPIO.output(forwardPin, False)
print("HTML 1")
elif (html[0]== "2"):
# Move Backward
GPIO.output(backwardPin, True)
time.sleep(.75)
GPIO.output(backwardPin, False)
print("HTML 2")
elif (html[0]== "3"):
#// Turn Left
GPIO.output(forwardPin, True)
GPIO.output(leftPin, True)
time.sleep(.75)
GPIO.output(forwardPin, False)
GPIO.output(leftPin, False)
print("HTML 3 left")
elif (html[0]== "4"):
#// Turn Right
GPIO.output(forwardPin, True)
GPIO.output(rightPin, True)
time.sleep(.75)
GPIO.output(forwardPin, False)
GPIO.output(rightPin, False)
print("HTML 4")
def main():
GPIO.setwarnings(False)
setup()
while(1):
loop()
time.sleep(.1)
main()
|
http://www.instructables.com/id/Camera-Equipped-RC-car-using-sixth-sense/
|
CC-MAIN-2017-17
|
refinedweb
| 981
| 56.66
|
Using Tableau to create word clouds with ease.
A Word cloud, also known as a Tag cloud, is a visual representation of text data, typically used to depict keyword metadata (tags) on websites or to visualize free form text[Wikipedia]. Word clouds are a popular type
of infographic with the help of which we can show the relative frequency of words in our data. This can be depicted either by the size or the color of the chosen fields in the data. They are a pretty powerful feature to draw attention to your presentation or story
Objective
Tableau is a data analytics and a visualization tool widely used in the industry today. Tableau provides a native feature to create Word Clouds with a few mouse clicks. This is going to be a pretty short article emphasizing on the steps required to create a word cloud in Tableau. In case you want a more detailed article to begin with Tableau, make sure you go through my article Data Visualisation with Tableau first.
Even though this article is focussed on word clouds, I would also be mentioning some visual best practices with respect to using word clouds. Word clouds look cool but there are some better substitutes that convey the same message but in a more clear and accurate way.
Data
The data pertains to the top 20 movies of 2018 in the US having been ranked by domestic box office earnings in billions of dollars. The data also contains the Metacritic scores for each movie. Metacritic is a website that aggregates reviews of media products including movies.
All the worksheets and Tableau Workbooks can be accessed from its associated repository here.
Creating a Word Cloud in Tableau
Movies as per their Domestic Gross Earnings
- Open the Tableau Desktop and connect to the data source. You can choose any data format but here we are using an excel file which has the desired data.
- Drag the desired dimension to Text on the Marks card. Here I am going to drag the Movie Title to the Text since I want to know which movie performed well in terms of the Box office collections.
- Drag the Domestic Gross earnings on to the Size on the Marks card.
- Now drag the Domestic Gross earnings on to the Color on the Marks card since we want the color to reflect the earning pattern.
- Change the Mark type from Automatic to Text.
- Next, you can hide the title, change the view and the background as per your likings and you have your word cloud ready.
Movies as per their Metacritic Score
The steps remain the same as above except that we use the Metacritic Score instead of the earnings.
Improving the Word Cloud
The above examples deal with a simple and refined dataset having limited fields. What if the data contained a paragraph or some passage from a book and we were required to create a word cloud for that. Let’s see an example of such an instance.
Dataset
For the demonstration purpose, I have taken the entire passage from one of my medium articles. I copied the entire text irrespective of the content and placed it in a
text.txt file. Then I ran a small python script to save the words and their frequencies into a CSV file. You can use any dataset of your choice.
from collections import Counter
def word(fname):
with open(fname) as f:
return Counter(f.read().split())
print(word_count("text.txt"))
import csv
my_dict = word_count("text.txt")
with open('test.csv', 'w') as f:
for key in my_dict.keys():
f.write("%s,%sn"%(key,my_dict[key]))
text.csv is the file that contains our dataset and will appear like this:
Now switch to Tableau.
- Create a word cloud as explained above using the words in the
text.csvfile.
- If you want to limit the number of entries, you can use the word count as a filter and show only the words with minimum frequency.
- Remove the most common words — Even after filtering by the word count, we see that there are words like ‘the’, ‘in’ etc which do not hold much significance but are appearing all over the worksheet. Let’s get rid of them. We will begin by creating a list of common words in English which can be accessed from here. The list contains words having a rank associated with them which we will use as a measure for filtering.
- Now let’s add this sheet into our workbook. The two sheets will be blended against the Words column since that is common to both sources.
- Create a new parameter and name it as “Words to be excluded” with the following settings:
- Show the Parameter Control and exclude the most common words from the cloud by filtering.
Now adjust the settings and you can have a better-looking word cloud with filter options.
When not to use a Word Cloud
Marti A. Hearst’s guest post “What’s up with Tag Clouds” is worth a read when discussing about word clouds. Word clouds are definitely eye-catching and provide a sort of overview or first insight and since they are quite popular, people usually have one or two in their presentations.
On the other hand, word clouds do not provide a clear differentiation between words of similar sizes, unlike a bar chart. Also, words belonging to the same category may lie far apart from each other and the smaller ones may be overlooked.
Alternatives to Word Cloud
- TreeMap
A Treemap may provide a better, but not the best, idea when compared to a word cloud. Treemaps are sometimes regarded as rectangular cousins of Pie Chart and may not be ideal when displaying detailed information.
- Bar Chart
A sorted Bar Chart definitely provides better and more accurate information since it gives a baseline for comparison.
Conclusion
Word Clouds are surely catchy and help the presentation to shine out but when it comes to serious data analysis there are better tools that can be tried out. However, the main aim of this article was to show how to create word clouds in Tableau with minimalistic effort. So you can try out building your own word clouds with data of your choice.
|
https://parulpandey.com/2019/02/21/word-clouds-in-tableau-quick-easy/
|
CC-MAIN-2022-21
|
refinedweb
| 1,043
| 70.02
|
?
Thank you anonymonk. The last post in the subthread you linked showed the use of _write) which does what fwrite() does, but takes a fileno rather than stream handle, and that works just fine. Presumably because the fileno gets used to look up the appropriate stream stuff internally, and thus gets to use the correct expansion of __iob_func().
This might not be of great help to you, but under Win32 strawberry-perl 5.16.3.1 #1 Tue Mar 12 12:12:07 2013 x64 the following code works:
use strict;
use Inline C => <<'__C__';
#include <stdio.h>
void test ( ) {
char buffer[] = { 'x' , 'y' , 'z' };
fwrite (buffer, 1, sizeof(buffer), stderr );
}
__C__
test( );
[download]
Reading your old thread, it looks to me that the root cause of the problem was a mismatch of compilers. So one solution could be to either change compilers or re-compile Perl with your preferred compiler.
the root cause of the problem was a mismatch of compilers.
Kinda. Sorta. But not really.
I::C code is compiled to a runtime linked dll. There is nothing fundamentally wrong with using multiple different CRTs within different dlls in the same process. (provided you don't try to mix'n'match by (say) mallocing with one and freeing with another.)
Indeed, this is (so far; but I've been doing it for a good many years) the only real problem I've encountered with using a different compiler for building modules and I::C stuff, than was used to build the AS perl I use.
The problem is that the Perl headers pull in a shitload of the PerlIO crap regardless of whether the code being compiled uses it or not. And it is that PerlIO crap that is screwing this up.
So one solution could be to either change compilers or re-compile Perl with your preferred compiler.
Neither of those is an option. It has to be AS perl. The compiler AS use is no longer available; neither is (their) source for the build of Perl I need for this.
But thanks for your reply.
#
|
http://www.perlmonks.org/?node_id=1034892
|
CC-MAIN-2014-23
|
refinedweb
| 349
| 80.01
|
Hi
I have the following bit of code, basically keeps getting a list of available Drives on a windows computer (every 2 seconds at the moment but it will be every 30secs).
Trouble is that when running this when watching the memory usage in Task Manager the memory keeps increasing, I have left this running for around 10 minutes and it still increasing.
Is there any reason why this is happening as it SHOULD be just replacing the contents of 'currentDrives' variable.
Thanks
Code :
import java.io.File; public class Main { public static void main(String[] args) { File[] currentDrives = File.listRoots(); while(true) { currentDrives = File.listRoots(); try { Thread.sleep(2000); } catch(Exception ex) { System.out.println("Error: " + ex.getMessage()); } } } }
|
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/16806-memory-usage-increasing-while-loop-memory-leak-printingthethread.html
|
CC-MAIN-2015-18
|
refinedweb
| 119
| 57.98
|
19 February 2010 12:17 [Source: ICIS news]
LONDON (ICIS news)--Major European polyvinyl chloride (PVC) producer SolVin’s Rheinberg facility in Germany is now back on stream following delays to its scheduled restart, a company source on Friday.
The site, which has the capacity to produce 240,000 tonnes/year of PVC, according to ICIS plants and projects data, had been due to restart on 8 February after a week-long outage.
However, technical issues had hampered the restart, delaying it until 15 February.
“Rheinberg came back onstream on Monday [15 February],” the source confirmed, before adding that its 300,000 tonne/year PVC facility at Tavaux in ?xml:namespace>
“We are completely sold out and have not been able to build any inventory [ahead of the scheduled maintenance at Tavaux] over this period,” the source said. “We have received numerous enquiries for volume but we did not have it and had to turn people away.”
For more on Solvin’s Rheinberg or Tavaux plant, visit ICIS plants and projects.
|
http://www.icis.com/Articles/2010/02/19/9336379/solvin-resumes-full-pvc-production-at-rheinberg-after-restart-delay.html
|
CC-MAIN-2013-20
|
refinedweb
| 171
| 56.59
|
FilePickerSortFlag
Since: BlackBerry 10.0.0
#include <bb/cascades/pickers/FilePickerSortFlag>
To link against this class, add the following line to your .pro file: LIBS += -lbbcascadespickers
Defines the attributes that the files can be sorted on in FilePicker.
By default, the files will be sorted based on type of files being displayed. For example, picture files will be sorted by date and documents will be sorted by name.
Overview
Public Types Index
Public Types
Various Sortflags associated with FilePicker.
BlackBerry 10.0.0
- Default
FilePicker will choose the appropriate sort type based on the type of files being displayed.
- Name
Sort by Name.Since:
BlackBerry 10.0.0
- Date
Sort by modification date.Since:
BlackBerry 10.0.0
- Suffix
Sort by file suffix.Since:
BlackBerry 10.0.0
- Size
Sort by file size.Since:
BlackBerry 10.0.0
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
|
https://developer.blackberry.com/native/reference/cascades/bb__cascades__pickers__filepickersortflag.html
|
CC-MAIN-2015-11
|
refinedweb
| 154
| 63.96
|
Dot Net 3.6 Years of Experience Interview Questions
Hai Friends, Recently i have attended one interview and i have share my interview experience very happily with you. This experience will use you for your future for many interviews. All the Best my Friends
These are first two questions in technical round
1. What are the technologies you are used ?
2 .How many projects you have worked on with client names on which technology?
after that the interviewer asked on these questions.
total Duration 1:40 mins. (Technical round only)
in Asp.Net
What is the use of session state and application state and difference between them?
ASP Page life cycle events ?
Use gloabl.asax file
How to handle sessions ?
How to handle application level errors?
How to handle method level errors?
Can i use more than one web.config file in solution?
Can i use more than one web.config file in project?
What is view state?
What is cookies ? use of cookiless session ?
Session modes ?
What is the use of rendering event ?
Diff between datagrid and gridview in asp.net ?
How to get values using javascript and jquery?
How to call client side functions using javascript and jquery
How to stop/ kill the session?
How to write ajax calling using jquery ?
Use of globalization and localization ?
Difference between user control and custom control ?
How to call Master Page methods in our web page ?
Diff between .ascx and .asmx ?
Diff types of validations ?
What is update panel ?
How to register user control in web page ?
in C#
Assembly types and how to create assembly and how to create strong name ?
Diff between interface and abstract and virtual?
static polymorphism and dynamic polymorphism?
Late binding and early binding ?
What is inheritance and types of inheritance?
When you used interface in your application ?
How t use abstract class in your application ?
What is function overloading and function overriding?
What is the use of new key word ?
Use of const, readonly ?
What is GAC ?
Diff between finalize and dispose ?
Use of stack and heap ?
How to create object to abstract class ?
How to write multiple inheritance ? \
Difference between string and stringBuilder ?
What is Delegate ?
What is anonymus Functions ?
in SQL Server
What is procedure and function . What is the difference ?
What is DDL and DML ?
Can we write nested procedures if yes how to write and execute?
How to write transactions?
What is the trigger and types? How to Write Triggers?
Use of triggers
What is the Courser and use?
What is the CTE ?
in WCF
How to consume WCFservice in our application?
How to get json data using WCF service ?
Different contracts in wcf
What is ABC?
What is mexhttp bindng?
Binding types in WCF?
Modes in WCF?
How many types of Hosting in WCF service ?
What is SOAP ?
Which namespace is used for XML Serialization ?
then next Round is Project Manager Round. in this round the interviewer focused not only on projects but also some real time questions . it took nearly (1:20 min Manager round only)
These are first two questions in project manager round
1. What are the technologies you are used ?
2 .How many projects you have worked on with client names on which technology and explain any two projects briefly ?
in Manager Round the interview asked these questions..
I have one WCF service with 5 methods ? how to give 2 methods to client 1 and remaining three to client 2 . How to restrict access the remaining 3 methods to client 1 and same as client 2 the remaining 2 methods ?
When we use Message Contract ?
How to use Shared assembly ?
How to show second 100 records to client ?
How to get data from web.config
Diff between web.confing and app.config ?
I have wrote one method with try catch block. in try block i have write int a = 100 / 0 ; , but there is no "dividebyzero exception" in catch block. how to throw that exception to catch block ?
what is Collections ? diff between List and IEnumarable ?
Previously i have worked on Silverlight technology with MVVM pattern. The interviewer asked me questions on that project and that MVVM pattern and also asked two to three questions on HTML and CSS. i can't remember these questions thats why i didn' write.
if you have any concerns please let me know.
Regards,
Nanda Kishore.CH
|
http://www.dotnetspider.com/resources/46019-Dot-Net-36-Years-of-Experience-Interview-Questions.aspx
|
CC-MAIN-2018-51
|
refinedweb
| 727
| 80.58
|
Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava
order. Lets take an example, Suppose you want to sort the data...;
Q 1. How can I get the full path of Explorer.exe.... : How do I limit the scope of a file
chooser?
Ans : Generally FileFilter is used
Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava
;
Q 1 : How should I create an immutable class ?
Ans... not be altered because they are declared as final,
all the variables must... is the method of
the PrintWriter class which is an example of
overloading
Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava
;
Q 1. When should I use the abstract class rather... a class
having all its methods abstract i.e. without any implementation. That means...
Methods
An
interface contains all the methods
i want code for these programs
i want code for these programs Advances in operating system
Laboratory Work:
(The following programs can be executed on any available and suitable platform)
Design, develop and execute a program using any
hi all - Java Beginners
hi all hi,
i need interview questions of the java asap can u please sendme to my mail
Hi,
Hope you didnt have this eBook. You.../Good_java_j2ee_interview_questions.html?s=1
Regards,
Prasanth HI
Hi
Hi Hi All,
I am new to roseindia. I want to learn struts. I do not know anything in struts. What exactly is struts and where do we use it. Please help me. Thanks in advance.
Regards,
Deepak
CoreJava Project
CoreJava Project Hi Sir,
I need a simple project(using core Java, Swings, JDBC) on core Java... If you have please send to my account
jsf f:parm value dynamical settings
jsf f:parm value dynamical settings Hi .
i have following query...;%
}
%>
</h:form>
i want to get value of x for each parm.../bb.jpg" onclick="fnChangeImage();">
<f:param name="selectValue
corejava - Java Interview Questions
corejava how to merge the arrays of sorting i want source code of this one plz--------------------------------------------- Hi Friend...(String a[]){
int i;
int array[] = {12,9,4,99,120,1,3,10
corejava - Java Interview Questions
;Hi friend,
date validation in javascript
var dtCh= "/";
var minYear=1900;
var maxYear=2100;
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Check that current character is number
Corejava - Java Interview Questions
having only numeric values by using Pattern class.
Hi Friend,
4...:
import java.util.*;
public class String_Example{
public static void main...);
}
for(int i=0;i
CoreJava
CoreJava Sir, What is the difference between pass by value and pass by reference. can u give an example!
hi! how can i write aprogram in java by using scanner when asking...();
System.out.println(i);
System.out.println(d);
System.out.println(f... to to enter, like(int,double,float,String,....)
thanx for answering....
Hi
online multiple choice examination hi i am developing online multiple choice examination for that i want to store questions,four options,correct answer in a xml file using jsp or java?can any one help me?
Please to develop a online bit by bit examination process as part of my project in this i am stuck at how to store multiple choice questions options and correct option for the question.this is the first project i am doing
hi..
hi.. I want upload the image using jsp. When i browse the file then pass that file to another jsp it was going on perfect. But when i read...);
for(int i=0;i<arr.length-1;i++) {
newstr=newstr
corejava - Java Beginners
corejava pass by value semantics Example of pass by value semantics in Core Java. Hi friend,Java passes parameters to methods using pass.... This is, for example, why you cannot mutate the (original, caller's) reference to the object
jsf f:parm value dynamical settings
jsf f:parm value dynamical settings <%for(int x=0;x<5;x++)
{
%>
// this is error inbinding
<%
}
%>
please share your thought how can i resolve this issue , i want to set value dynamically
Installing programs over a network
Installing programs over a network Hi, i want to write a java program that will allow me to install programs from a server to a client machine. Any help will be appreciated. Thanks
corejava - Java Beginners
Deadlock Core Java What is Deadlock in Core Java? Deadlock is nothing but accessing a same space by different by different programs...,Here is nice example of deadlock in Java.Please check at
corejava - Java Interview Questions
Core Java vs Advance Java Hi, I am new to Java programming and confuse around core and advance java Beginners
Tutorials for Core Java beginners Can anyone share their example of Encapsulation in java? I'm a core Java beginner. Hi,Here is the description of Encapsulation in java:Encapsulation is a process of binding
hi - SQL
hi hi sir,i want to insert a record in 1 table
for example
sno sname sno1
i want to insert the value of sno as 1,2,3,............
when the time of insertion i
java lab programs - Java Beginners
a multi-threaded Java program to print all numbers below 100,000 that are both...;Hi Friend,
1)StackExample
class Stack{
protected int st[];
protected int...;
}
public boolean isEmpty(){
return index == -1;
}
public void push(int i
hi - Date Calendar
hi sir,i am do the project on swings,i want a datepicker in java,how to use datepicker in my swings application,plz provide a example for to use...
ThanQ Hi Friend,
Try the following code
i want immediate code - Development process
i want immediate code Basic sales tax is applicable at a rate of 10% on all goods, except books,
food, and medical products that are exempt. Import duty is an additional
sales tax applicable on all imported goods at a rate
java programs - Java Beginners
; Hi Friend,
1)Prime Numbers:
import java.util.*;
class PrimeNumbers...+" and "+num2+" are:" );
for (int i = num1; i < num2; i++){ {
int j;
for (j = 2; j < i; j++)
{
if (i % j == 0) {
break;
}
}
if (i == j) {
primeNo
c++ programs
c++ programs i want the syntax for the following programs according...+.....n/n+2
3.1!/1+2!/2+3!/3+4!/4+...n!/n
i just want the main logic as i m nt getting it i m jss starter of this language i want it soon
programs - Java Magazine
;
You clarify which techlogy we want?
Applet swing or java2d
use... Ellipse2D.Double(50,50,80,80));
}
}
Thanks
Rajanikant Hi... :
Thanks
Amardeep
Programs - JMS
JMS Example Program Hi, can any one explain the JMS program with the help of an example
java programs
of a given number i need java programs for this category?
Hi Friend...");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = input.next
Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava
because they are declared as final,
all the variables must be assigned... interface is an abstract data type like a class
having all its methods abstract
Installing programs over a network using java
Installing programs over a network using java Hi, i want to write a java program that will allow me to install programs from a server to a client machine. Any help will be appreciated. sir, i am entering the 2 dates in the jtable,i want to difference between that dates,plz provide the suitable example sir
Hi.../beginners/DateDifferent.shtml
Programs in java - Java Interview Questions
Program in Java decimal to binary i need a java example to String... of an example? Hi friend,import java.io.*;import java.io.IOException;public...{ public static String reverseIt(String source) { int i, len = source.length sir,Thanks for ur coporation,
i am save the 1 image with customer data,when i am search that customer data,i want to see that image (already... that customer photo (image path) through customer data,
if i want
Hi... - Java Beginners
Hi... Hi friends
I want to make upload file module please help...please write the using mvc1 rule
I have three field emp_id,name,file
if i am click the browse button then open one dialog box and select any(.doc
how to execuite java programs???
how to execuite java programs??? I have jdk 1.6 installed in my pc.i want to execuite java programs in ms-dos for applet and without using applet.please tell
Hi da SAKTHI ..check thiz - Java Beginners
/
Thanks
Hi friend,
I saw your code and modified. What you want...Hi da SAKTHI ..check thiz package bio;//LEAVE IT
import java.lang....=new ImageIcon("f:\\2LEAVES.jpg");img2=new ImageIcon("f:\\Q1.jpg");img3=new
hi,
hi, print("code sample");how to display all elements in 2d array usin any one loop
Struts 1 Tutorial and example programs
-fledged practical example of each of the types presented in Part I namely...Struts 1 Tutorials and many example code to learn Struts 1 in detail.
Struts 1... we have listed all the tutorials published on our website
related
Hi
Hi Hi this is really good example to beginners who is learning struts2.0
thanks
Want Automatic No with Date - Development process
Want Automatic No with Date
Hi, I want the jsp code. i want serial no with date and month.For example
"240501" date is 24 and month is 05 and serial no 01 .Thanks Prakash
hi!
hi! public NewJFrame() {
initComponents();
try...();
String f=txtgen.getText();
String g=txtadd.getText...=st.executeUpdate("insert into railway values("+a+",'"+b+"','"+c+"','"+d+"','"+e+"','"+f?
Hi..
Hi.. what are the steps mandatory to develop a simple java program?
To develop a Java program following steps must be followed by a Java developer :
First of all the JDK (Java
Development Kit) must be available
hi
*
* *
* * *
* * * *print("code sample");
Hi Friend,
Try... num=4;
int p = num;
int q = 0;
for (int i = 0; i <= num; i++) {
for (int j = p; j>= 1; j-- )
System.out.print(" ");
p-=1;
for (int k = 1; k <= i; k
hi sc
hi
the total cost of the two items;otherwise,display the total for all three
|
http://www.roseindia.net/tutorialhelp/comment/3828
|
CC-MAIN-2014-49
|
refinedweb
| 1,685
| 55.54
|
# One Day from PVS-Studio User Support

We welcome any chatting on code quality. Our clients, students, and other users from all corners of the Internet write to us. Regardless of the country, time zone or language. Well, speaking language, not programming. Among programming languages, we are so far interested in a limited set. Right now, it's C, C++, C# and Java. There are many benefits from communication. We implement some users' suggestions immediately, because they are really useful. Often we just lend a hand with someone's project by explaining analyzer warnings, which end up being errors. This note is about such case.
About the analyzer
------------------
[PVS-Studio](https://www.viva64.com/en/pvs-studio-download/) is a tool designed to detect errors and potential vulnerabilities in the source code of programs, written in C, C++, C# and Java. It works in Windows, Linux and macOS environment.
There are three feedback forms to contact us:
1. [Feedback](https://www.viva64.com/en/about-feedback/)
2. [Trial request](https://www.viva64.com/en/pvs-studio-download/)
3. [Price request](https://www.viva64.com/en/order/)
Thursday night
--------------
One active user who tried the analyzer on his code actively started sending false warnings. Before I could answer, there were already 3 emails. It was the end of the working day and I was tired (speaking about the question of reliability of manual code review). Our team was actively preparing for a high-wrought release, which was a few days away.
I decided to answer on Friday or even during the next week:
*Hello Constantine.*
*We'll review your warnings. Next week I will comment on suspicious places:-)*
This note is about effectiveness of static code analysis. Manual code review will be inferior to automatic check in many cases, especially at the end of the day.
With the user's permission, I will cite you our mails:
**Email 1**
*False-positive V712 warnings:*
```
uint32_t StartUpCounter = 0, HSEStatus = 0;
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); // V712...
```
**Email 2**
*V715 false positive for the same fragment:*
```
{ // V715 ... lpmode.cpp 356
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
```
**Email 3**
*Holy cats, such a haunted place! The analyzer complains about the same fragment (see the code from the previous emails):*
*V560 A part of conditional expression is always true: (StartUpCounter != ((uint16\_t) 0x5000)). lpmode.cpp 356*
*V776 Potentially infinite loop. The variable in the loop exit condition 'HSEStatus == 0' does not change its value between iterations. lpmode.cpp 356*
*Maybe I don't get something? But in practice everything works, and if the quartz does not start, then we exit this fragment on timeout;-)*
**Email 4 (reply)**
*Hello Constantine.*
*We'll review your warnings. Next week I will comment on suspicious places:-)*
**Email 5**
*Damn it! Only after your email, I noticed that the statement «do» is missed… Finally, all fell into a groove! Seems like I completely lost my eye sharpness %)*
***do*** *{...} while (...);*
Conclusion
----------
As you may have noticed, there were 4 analyzer warnings for the same fragment, but it still took time to convince the user that there was an error. In such a situation, manual review would not even have a chance.
A similar story with happy ending: "[How PVS-Studio Proved to Be More Attentive Than Three and a Half Programmers](https://www.viva64.com/en/b/0587/)"
Use static analyzers in your project. They don't replace code review with colleagues, but add support to code quality control.
|
https://habr.com/ru/post/467561/
| null | null | 617
| 57.98
|
MongoDB is one of the popular NoSQL databases. It uses a document-oriented, JSON-like approach to represent data, making the integration of semi-structured data fairly easy.
This article is an introduction on how to use PyMongo, the package to interact with MongoDB in Python, for basic interactions with the database.
MongoDB Basics
As mentioned in the opening paragraph, MongoDB is a document-oriented database. The “document” is hence the main concept in this family of databases. This means that the database stores and retrieves records called documents.
If modelled in a sensible fashion, documents are usually self-describing and self-contained, so everything you need to know about the document is represented within the document. The data format used by mongo is JSON, which is a very convenient way to encapsulate data.
An example of document in MongoDB:
{ "title": "An article about MongoDB and Python", "content": "Some long discussion about MongoDB", "publication_date": "2015-09-07 10:00:00", "shares": { "twitter": 123, "facebook" 456, "linkedin": 789 }, "tags": ["python", "mongodb", "nosql"], "author": { "name": "Marco", "author_id": 1 } }
Documents are grouped into collections. In a comparison with the relational world, if a document is a row/record, a collection would be something similar to a table. A group of collections can be hosted on the same database, and the concept of database here is similar to the relational one (sometimes referred to as schema).
Being a JSON-style data store, MongoDB is often referred to as schemaless: fields can dynamically be added to documents without the need to define an explicit schema.
Note: schema design in complex applications is still a useful tool, and some careful thoughts should be spent when designing our document representation. Maybe it’s more helpful to think about it as dynamic schema rather than schemaless, as the word still conveys the idea of flexibility provided by document-oriented data stores, yet the importance of some sort of structure is not forgotten.
Quick Installation
MongoDB is available for most package managers (e.g. in rpm or deb format). You can also install the binary tarball by simply unzipping it and making it visible from your $PATH. From the official website, download the tarball for your operating system. At the time of this writing, the latest version is 3.0.6:
tar zxf mongodb-osx-x86_64-3.0.6 ln -s mongodb-osx-x86_64-3.0.6 mongodb
You can immediately run the server:
cd mongodb ./bin/mongod
The MongoDB daemon is now listening on localhost:27017, the default settings.
MongoDB + Python = PyMongo
PyMongo is the Python driver for MongoDB, and it can be installed via pip:
pip install pymongo
This should install the latest 3.0 version of PyMongo (the interface for previous 2.* versions could be slightly different, so pay attention to this detail).
The main component of PyMongo is the MongoClient class. In order to connect with the database, we’ll need an instance of the client:
from pymongo import MongoClient client = MongoClient()
Databases and collections are created automatically if they don’t exist. Let’s create a database called tutorial and a collection called articles:
db = client['tutorial'] coll = db['articles']
We can now define an a document an insert it in the collection:
from datetime import datetime doc = { "title": "An article about MongoDB and Python", "author": "Marco", "publication_date": datetime.utcnow(), # more fields } doc_id = coll.insert_one(doc).inserted_id
the insert_one() methods does exactly what its name says. The document is represented as a Python dictionary, which looks very similar to a JSON object. PyMongo handles the conversion between data types (e.g. a datetime object in Python will become an ISODate in MongoDB, booleans are converted from True to true, etc.).
We also append the inserted_id attribute, to capture the ID assigned by Mongo to the document. This sort of primary key is stored in the _id field:
print(doc_id) # ObjectId('55eb163d3661250ae4232ba6')
The _id of a document is an instance of ObjectId, rather than a simple string. This is important to keep in mind if we try to retrieve a document by its ID:
# query by ObjectId my_doc = coll.find_one('_id': doc_id) print(my_doc) # {'title': 'An article about MongoDB and Python', 'author': 'Marco', '_id': ObjectId('55eb163d3661250ae4232ba6'), ...} doc_id_str = str(doc_id) print(doc_id_str) # 55eb163d3661250ae4232ba6 # query by ID-string my_doc = coll.find_one('_id': doc_id_str) print(my_doc) # empty # Converting an ID-string to an ObjectId from bson.objectid import ObjectId my_doc = coll.find_one({'_id': ObjectId(doc_id_str)}) print(my_doc) # {'title': 'An article about MongoDB and Python', 'author': 'Marco', '_id': ObjectId('55eb163d3661250ae4232ba6'), ...}
The string-vs-ObjectId mismatch problem is one of the first encountered by MongoDB novices, so it’s something to keep in mind.
We have introduced the insert_one() and find_one() functions, which work for one document. Their counterparts, insert_many() and find() will work for many documents. Specifically, insert_many() takes a list of documents as argument, i.e. a list of dictionaries. On the other side, find() will return a cursor, which can be used like an iterable, e.g.:
many_docs = coll.find() # empty query means "retrieve all" for doc in many_docs: print(doc)
More Complex Queries
Given this data set:
doc1 = { "title": "Intro to MongoDB and Python", "publication_date": datetime(2015, 9, 7), "likes": 10 } doc2 = { "title": "Intro to Neo4J and Python", "publication_date": datetime(2015, 9, 1), "likes": 5 } doc3 = { "title": "Intro to Elasticsearch and Python", "publication_date": datetime(2015, 8, 1), "likes": 15 } coll.insert_many([doc1, doc2, doc3]) print(coll.count()) # 3
We can filter the results to find documents older than a given date
results = coll.find({"publication_date": {'$lt': datetime(2015, 9, 1)}}) for doc in results: print(doc) # {'title': 'Intro to Elasticsearch and Python', ...}
The $lt operator simply stands for less than, and of course it finds its counterpart in $gt. As expected, we also have $lte and $gte if we want to include also the limit (the date 2015-09-01 in the previous example):
results = coll.find({"publication_date": {'$lte': datetime(2015, 9, 1)}}) for doc in results: print(doc) # {'title': 'Intro to Neo4J and Python', ...} # {'title': 'Intro to Elasticsearch and Python', ...}
The results are in order of _id. If we need to sort the results according to a particular field, we can use the appropriate function:
from pymongo import ASCENDING, DESCENDING # get all docs, sort by number of likes high-to-low results = coll.find().sort("likes", DESCENDING) for doc in results: print(doc) # {'title': 'Intro to Elasticsearch and Python', "likes": 15, ...} # {'title': 'Intro to MongoDB and Python', "likes": 10, ...} # {'title': 'Intro to Neo4J and Python', "likes": 5, ...}
We can of course build more complex queries and combine them with the appropriate sorting. As the query itself is a Python dictionary, we can define it separately rather than in-line, just for readability:
query = { "publication_date": { "$gte": datetime(2015, 9, 1) }, "likes": { "$gt": 5 } } results = coll.find(query) for doc in results: print(doc) # {'title': 'Intro to MongoDB and Python', "likes": 10, ...}
Summary
This article has introduced PyMongo, the Python driver to interact with MongoDB. The interaction with MongoDB via Python is fairly straightforward, and we can be up and running with some basic queries quite quickly.
MongoDB is one of the popular NoSQL databases which uses a document-oriented data store. Its JSON-like format and its dynamic schema approach make the case for self-describing and self-contained documents.
|
https://marcobonzanini.com/category/mongodb/
|
CC-MAIN-2021-31
|
refinedweb
| 1,214
| 54.83
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.