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 |
|---|---|---|---|---|---|
Background I’m currently writing some code for a naughts and crosses machine learning program based on M.E.N.A.C.E, and I have finished the code for the actual machine learning and for playing against the computer, as well as another computer to play games against it to train it. The user can enter that they’d like to ..
Category : carriage-return
I want to display a progress bar however putting the printing code inside a separate function seems to invoke an std::flush as each time the progress bar is printing in a new line. This did not happen when the code was used inline The code: #include <iostream> #include <unistd.h> void load(int curr, int total) { ..
Surprisingly I didn’t find an answer to this seemingly very common problem. In Python when I print something to the CLion Console when the printed text is longer than 80 characters, an automatic line break is inserted. In hexadecimal I can see the inserted symbol is carriage return (0D 0A) on Windows. How can I ..
I have two dev machines, one Debian, the other Windows 10. I’m having trouble with the Debian laptop (hardware) so I’m temporarily trying to move my work to Windows. I’m far more comfortable with Debian. I’m running make docs on ReStructured Text files in my client’s repo. I should say here that I’m a newb ..
Assume I have the following code which is an infinit counter : #include <iostream> int main() { short int counter = 0; while(true) cout << "This is a counter: " << counter++ << " and I’ll keep counting!r"; return 0; } When you run the code with the carriage return, it will overwrite the existing ..
#include<cstdio> #include<iostream> #include<cstdlib> #include<conio.h> #include<cstring> using namespace std; int main(){ char *ptr; int n=1,i=0,value; ptr = (char*)calloc(n,sizeof(char)); while(1){ value = getch(); cout << char(value); if(char(value) == ‘$’) break; ptr[i] = char(value); n++; i++; ptr = (char *)realloc(ptr,n*sizeof(char)); } cout<<"nnYour text is…n"; for(i=0;i<n;++i) cout<<ptr[i]; cout<<strlen(ptr); return 0; } So everything works as expected until i hit ..
I have a function to print r (carriage return escape character) to overwrite the previously printed chars as shown below. // show the current time in military form. void show(Clock *ptr) { cout.fill(‘0’); cout << setw(2) << ptr->hr << ":" << setw(2) << ptr->min << ":" << setw(2) << ptr->sec << "r"; } It works ..
System.out.println(“Hello rWorld”); Output:- world why is the Hello missing, I am using Windows. How does /r,/n,/r/n differ ? Source: Sta..
Recent Comments | https://windowsquestions.com/category/carriage-return/ | CC-MAIN-2021-21 | refinedweb | 446 | 64.71 |
The QWidgetAction class extends QAction by an interface for inserting custom widgets into action based containers, such as toolbars. More...
#include <QWidgetAction>
This class was introduced in Qt 4.2.
The QWidgetAction class extends QComboBox in a QToolBar, presenting a range of different zoom levels. QToolBar provides QToolBar::insertWidget() as convenience function for inserting a single widget. However if you want to implement an action that uses custom widgets for visualization in multiple containers then you have to subclass QWidgetAction.
If a QWidgetAction is added for example to a setDefaultWidget(). That widget will then be used if the action is added to a QToolBar, or in general to an action container that supports QWidgetAction. If a QWidgetAction with only a default widget is added to two toolbars at the same time then the default widget is shown only in the first toolbar the action was added to.(). | http://doc.trolltech.com/main-snapshot/qwidgetaction.html#createWidget | crawl-003 | refinedweb | 147 | 53.1 |
shifting bitsHello, I want to make a function that shifts bits to the left and right and append them to the left ...
How to set a bit?Thank you for replying, my program works! thanks
How to set a bit?Hello,
I want to write a function that sets multiple bits.
Here is how it should look:
The user...
Change content/line of text in a FileHello, I want to change a line of text/content in a text file. There are many options, like copy the...
reverse a number of digits of the user input@LowestOne
Am I on the right track?
[code]#include <stdio.h>
#include <stdlib.h>
int main ()
{
... | http://www.cplusplus.com/user/dutchman/ | CC-MAIN-2016-07 | refinedweb | 112 | 87.21 |
import {local} from 'wix-storage';
import wixWindow from 'wix-window';
$w.onReady(function () { if(!local.getItem("firstTimePopupShown")) { wixWindow.openLightbox("Announcement");
local.setItem("firstTimePopupShown", "yes");
} } );
I used this code and followed all the instructions on the wix tutorial but it keeps popping up on the home page of my members profile. Which is where i stored the code because thats the site i want the member too see it for the first time.
The lightbo is linked to 4 other lightboxes through a button because it's a intro tutorial on the site. Could this be causing the continues pop-up every the member visits the site?
please help!
Be sure you set the lightbox trigger to "automatically display: no.
Also be sure not to test it in browser incognito/private mode
yes that was set. Already tried with 3 different accounts. Could it be because its a dynamic page and not a member page?
It doesn't depend on the user account but on the device and browser and site page (you store it in the browser cache).
(If you want to make it user-dependent it should be done completely different.)
I'm not sure what exactly you did there, but if the code runs on the current page and you're using the same browser on the same device, it shouldn't pop up. | https://www.wix.com/corvid/forum/community-discussion/one-time-pop-up-lightbox-code-not-working | CC-MAIN-2020-10 | refinedweb | 226 | 62.38 |
A Normal Accident In Python and mod_wsgi
I fixed a glitch in PyMongo last week, the result of a slapstick series of mishaps. It reminds me of the Three Mile Island nuclear accident, which inspired the "Normal Accidents" theory of failure in complex systems: one surprise leads to the next, to the next, to an outcome no one anticipated.
It started a couple months ago, when we got a minor bug report about PyMongo. The reporter was using PyMongo with Python 3.2, mod_wsgi, and Apache. Whenever he restarted his application, he saw this error message in his log:
Exception TypeError: "'NoneType' object is not callable" in <bound method Pool.__del__> ignored
The exception was ignored because it was raised from a "__del__" method, so it didn't affect his application. Still, I needed to understand what was going on. So I made a test environment, and I used Apache to run a Python script like the one in the bug report:
import pymongo class C: pass C.client = pymongo.MongoClient()
I could reproduce the bug: Whenever I restarted Apache, the PyMongo connection pool's destructor logged "TypeError: NoneType object is not callable."
The pool's destructor makes two method calls, and no function calls:
def __del__(self): # _thread_id_to_sock is a dict of sockets. for sock in self._thread_id_to_sock.values(): sock.close()
During interpreter shutdown, None is somehow being called as a function. I'm no expert on Python's shutdown sequence, but I've never heard of a method being set to None. And yet, the only calls in this code are the "values" method and the "close" method. What gives?
I put a "return" statement at the beginning of "__del__" and restarted Apache: the error disappeared. So I moved the "return" statement down a line, before "sock.close()". The next time I restarted Apache, I saw the error again.
While I was hacking directly on the installed PyMongo package, I noticed something funny. The installed code looked like:
def __del__(self): # _thread_id_to_sock is a dict of sockets. for sock in list(self._thread_id_to_sock.values()): sock.close()
Notice the call to "list"? When I installed PyMongo with Python 3.2, the installer ran 2to3 on PyMongo's code, which automatically translates Python 2 syntax to Python 3.
Why did 2to3 decide to wrap the "values" call in "list"? Well, in Python 2, "values" returns a copy, but in Python 3 it returns a dictionary view that's tied to the dict's underlying data. 2to3 worries that I might rely on the old, copying behavior, so in Python 3 it makes a copy of the values by calling "list".
So it must be the call to "list" that raises the TypeError. Sure enough, when I deleted the "list" call from the installed PyMongo code, the exception disappears. Fantastic!
Why don't we see this error all the time, though? Perhaps it has to do with the shutdown sequence. Normally, a pool is referred to by other objects, but not by a class. I hypothesized that the reporter saw the error because he'd made a reference from a class to the MongoClient to the pool, which delayed the pool's destruction until after the "list" builtin had been set to None:
To test this theory, I replaced this line:
C.client = pymongo.MongoClient()
...with this:
client = pymongo.MongoClient()
Now the pool is no longer referred to by a class, it's only referred to by a global variable in the module named "mod":
Sure enough the error disappeared.
So far, I understood that the connection pool's destructor ran too late, because it was being kept alive by a reference from a class, and it relied on the "list" builtin, because 2to3 had added a call to "list", so it raised a TypeError. Now, did it only happen with mod_wsgi? I wrote the simplest Python example I could, and I tried to reproduce the TypeError:
# mod.py class C(object): pass class Pool(object): def __del__(self): print('del') list() C.pool = Pool()
I could import this module into the Python shell, then quit, and I got no TypeError. Actually I didn't see it print "del" either—the pool's destructor never runs at all. Why not?
A class definition like "C" creates a reference cycle. It refers to itself as the first element in its method resolution order. You can see how "C" refers to itself by printing its method resolution order in the Python shell:
>>> import mod >>> mod.C.__mro__ (<class 'mod.C'>, <type 'object'>)
When the interpreter shuts down it runs the C function "Py_Finalize", which first does a round of garbage collection to destroy reference cycles, then destroys all modules:
void Py_Finalize(void) { /* Collect garbage. This may call finalizers; it's nice to call these * before all modules are destroyed. */ PyGC_Collect(); /* Destroy all modules */ PyImport_Cleanup(); }
When "PyGC_Collect" runs, the "mod" module still refers to class C, so the class isn't destroyed and neither is the Pool it refers to:
Next, "PyImport_Cleanup" sets all modules' global variables to None. Now class C is garbage: it's in a reference cycle and nothing else refers to it:
But the interpreter is dying and it will never call "PyGC_Collect" again, so class C is never destroyed and neither is the pool.
Great, I understand everything up to this point. But, if the pool is never destroyed when a regular Python interpreter shuts down, why is it destroyed when a mod_wsgi application restarts? I dove into mod_wsgi's source code to see how it manages Python interpreters. (This isn't my first rodeo: I examined mod_wsgi closely for my "Python C Extensions And mod_wsgi" article last year.) I wrote a little C program that runs Python in a sub interpreter, the same as mod_wsgi does:
int main() { Py_Initialize(); PyThreadState *tstate_enter = PyThreadState_Get(); PyThreadState *tstate = Py_NewInterpreter(); PyRun_SimpleString("import mod\n"); if (PyErr_Occurred()) { PyErr_Print(); } Py_EndInterpreter(tstate); PyThreadState_Swap(tstate_enter); printf("about to finalize\n"); Py_Finalize(); printf("done\n"); return 0; }
Just like mod_wsgi, my program creates a new Python sub interpreter and tells it to import my module, then it swaps out the sub interpreter and shuts it down with "Py_EndInterpreter". Its last act is "Py_Finalize". And behold! The script quoth:
about to finalize Exception TypeError: "'NoneType' object is not callable" in <bound method Pool.__del__> ignored done
My little C program acts just like the application in the bug report! What is it about this code that makes it throw the TypeError during shutdown, when a regular Python interpreter does not?
I stepped through my program in the debugger and solved the final mystery. What makes this code special is, it calls "Py_EndInterpreter". "Py_EndInterpreter" calls "PyImport_Cleanup", which sets all modules' global variables to None, thus turning class C into cyclic garbage:
"PyImport_Cleanup" even clears the "builtins" module, which includes functions like "list". Any code that tries to call "list" afterward is actually calling None.
Now "Py_Finalize" calls "PyGC_Collect". (It will then run "PyImport_Cleanup" for the second time, but that's not relevant now.) This is the difference between the regular interpreter's shutdown sequence and mod_wsgi's: In the mod_wsgi case, modules have been cleared before the final garbage collection, so class C is destroyed along with the pool. However, since the pool's destructor runs after "PyImport_Cleanup", its reference to "list" is now None, and it throws "TypeError: 'NoneType' object is not callable".
Success! I had traced the cause of the bug from start to finish. To recap: in the bug-reporter's code, he had made a reference from a class to a pool, which made the pool's destructor run very late. And he ran the code in mod_wsgi, which clears modules before the final garbage collection, otherwise the pool's destructor wouldn't have run at all. He was using Python 3, so 2to3 had inserted a call to "list" in the pool's destructor, and since the destructor ran after all modules were cleared, the call to "list" failed.
Luckily, this cascade of failures leads merely to an occasional log message, not to a Three Mile Island meltdown. My boss Bernie came up with an incredibly simple fix. I replace the call to "values":
def __del__(self): for sock in self._thread_id_to_sock.values(): sock.close()
... with a call to "itervalues":
def __del__(self): for sock in self._thread_id_to_sock.itervalues(): sock.close()
(You can view the whole commit here.)
Now that I'm using "itervalues", 2to3 now replaces it with "values" in Python 3 instead of "list(values)". Since I'm no longer relying on the "list" builtin to be available in the destructor, no TypeError is raised. | https://emptysqua.re/blog/a-normal-accident-in-python-and-mod-wsgi/ | CC-MAIN-2019-18 | refinedweb | 1,442 | 61.97 |
Search
Create
989 terms
MrCengiz
TEACHER
SAT Vocab (A-Z)
1000 Common SAT Words, SAT terms, SAT names, SAT English, SAT exam, SAT, SAT study
STUDY
PLAY (When he realized that the revolutionaries would surely win, the king abdicated his throne.)
abduct
(v.) to kidnap, take by force (The evildoers abducted the fairy princess from her happy home.)
aberration
(n.) something that differs from the norm (In 1918, the Boston Red Sox won the World Series, but the success turned out to be an aberration, and the Red Sox have not won a World Series since.)
abet
(v.) to aid, help, encourage (The spy succeeded only because he had a friend on the inside to abet him.)
abhor
(v.) to hate, detest (Because he always wound up kicking himself in the head when he tried to play soccer, Oswald began to abhor the sport.)
abide
1. (v.) to put up with (Though he did not agree with the decision, Chuck decided to abide by it.) 2. (v.) to remain (Despite the beating they've taken from the weather throughout the millennia, the mountains abide.)
abject
(adj.) wretched, pitiful (After losing all her money, falling into a puddle, and breaking her ankle, Eloise was abject.)
abjure
(v.) to reject, renounce (To prove his honesty, the President abjured the evil policies of his wicked predecessor.)
abnegation
(n.) denial of comfort to oneself (The holy man slept on the floor, took only cold showers, and generally followed other practices of abnegation.)
abort
(v.) to give up on a half-finished project or effort (After they ran out of food, the men, attempting to jump rope around the world, had to abort and go home.)
abridge
1. press.)
abscond
(v.) to sneak away and hide (In the confusion, the super-spy absconded into the night with the secret plans.)
absolution
(n.) freedom from blame, guilt, sin (Once all the facts were known, the jury gave Angela absolution by giving a verdict of not guilty.)
abstain
(v.) to freely choose not to commit an action (Everyone demanded that Angus put on the kilt, but he did not want to do it and abstained.)
abstruse
(adj.) hard to comprehend (Everyone else in the class understood geometry easily, but John found the subject abstruse.)
accede
(v.) to agree (When the class asked the teacher whether they could play baseball instead of learn grammar they expected him to refuse, but instead he acceded to their request.)
accentuate
(v.) to stress, highlight (Psychologists agree that those people who are happiest accentuate the positive in life.)
accessible
(adj.) obtainable, reachable (After studying with SparkNotes and getting a great score on the SAT, Marlena happily realized that her goal of getting into an Ivy-League college was accessible.)
acclaim
(n.) high praise (Greg's excellent poem won the acclaim of his friends.) accolade (n.) high praise, special distinction (Everyone offered accolades to Sam after he won the Noble Prize.)
accolade
(n.) high praise, special distinction (Everyone offered accolades to Sam after he won the Noble Prize.)
accommodating
(adj.) helpful, obliging, polite (Though the apartment was not big enough for three people, Arnold, Mark, and Zebulon were all friends and were accommodating to each other.)
accord
(n.) an agreement (After much negotiating, England and Iceland finally came to a mutually beneficial accord about fishing rights off the cost of Greenland.)
accost
(v.) to confront verbally (Though Antoinette was normally quite calm, when the waiter spilled soup on her for the fourth time in 15 minutes she stood up and accosted the man.)
accretion
(n.) slow growth in size or amount (Stalactites are formed by the accretion of minerals from the roofs of caves.)
acerbic
(adj.) biting, bitter in tone or taste (Jill became extremely acerbic and began to cruelly make fun of all her friends.)
acquiesce
(v.) to agree without protesting (Though Mr. Correlli wanted to stay outside and work in his garage, when his wife told him that he had better come in to dinner, he acquiesced to her demands.).).)
adept
(adj.) extremely skilled (Tarzan was adept at jumping from tree to tree like a monkey.)
adhere
1. (n.) to stick to something (We adhered the poster to the wall with tape.) 2. (n.) to follow devoutly (He adhered to the dictates of his religion without question.)
admonish
(v.) to caution, criticize, reprove (Joe's mother admonished him not to ruin his appetite by eating cookies before dinner.)
adorn
(v.) to decorate (We adorned the tree with ornaments.)
adroit
(adj.) skillful, dexterous (The adroit thief could pick someone's pocket without attracting notice.)
adulation
(n.) extreme praise (Though the book was pretty good, Marcy did not believe it deserved the adulation it received.)
adumbrate
(v.) to sketch out in a vague way (The coach adumbrated a game plan, but none of the players knew precisely what to do.)
adverse
(adj.) antagonistic, unfavorable, dangerous (Because of adverse conditions, the hikers decided to give up trying to climb the mountain.).)
aerial
(adj.) somehow related to the air (We watched as the fighter planes conducted aerial maneuvers.)
aesthetic
(adj.) artistic, related to the appreciation of beauty (We hired Susan as our interior decorator because she has such a fine aesthetic sense.)
affable
(adj.) friendly, amiable (People like to be around George because he is so affable and good-natured.)
affinity
(n.)a spontaneous feeling of closeness (Jerry didn't know why, but he felt an incredible affinity for Kramer the first time they met.)
affluent
(adj.) rich, wealthy (Mrs. Grebelski was affluent, owning a huge house, three cars, and an island near Maine.)
affront
(n.) an insult (Bernardo was very touchy, and took any slight as an affront to his honor.)
aggrandize
(v.) to increase or make greater (Joseph always dropped the names of the famous people his father knew as a way to aggrandize his personal stature.) aggrieved employees.)
agile
(adj.) quick, nimble (The dogs were too slow to catch the agile rabbit.) agnostic (adj.) believing that the existence of God cannot be proven or disproven (Joey's parents are very religious, but he is agnostic.)
agriculture
(n.) farming (It was a huge step in the progress of civilization when tribes left hunting and gathering and began to develop more sustainable methods of obtaining food, such as agriculture.)
aisle
(n.) a passageway between rows of seats (Once we got inside the stadium we walked down the aisle to our seats.)
alacrity
(n.) eagerness, speed (For some reason, Chuck loved to help his mother whenever he could, so when his mother asked him to set the table he did so with alacrity.)
alias
(n.) a false name or identity (He snuck past the guards by using an alias and fake ID.)
allay
(v.) to soothe, ease (The chairman of the Federal Reserve gave a speech to try to allay investors' fears about an economic downturn.)
allege
(v.) to assert, usually without proof (The policeman had alleged that Marshall committed the crime, but after the investigation turned up no evidence, Marshall was set free.)
alleviate
(v.) to relieve, make more bearable (This drug will alleviate the symptoms of the terrible disease, but only for a while.)
allocate
(v.) to distribute, set aside (The Mayor allocated 30 percent of the funds for improving the town's schools.)
aloof
(adj.) reserved, distant (The scientist could sometimes seem aloof, as if he didn't care about his friends or family, but really he was just thinking about quantum mechanics.)
altercation
(n.) a dispute, fight (Jason and Lionel blamed one another for the car accident, leading to an altercation.)
amalgamate
(v.) to bring together, unite (Because of his great charisma, the presidential candidate was able to amalgamate all democrats and republicans under his banner.)
ambiguous
(adj.) uncertain, variably interpretable (Some people think Caesar married Cleopatra for her power, others believe he was charmed by her beauty. His actual reasons are ambiguous.)
ambivalent
(adj.) having opposing feelings (My feelings about Calvin are ambivalent because on one hand he is a loyal friend, but on the other, he is a cruel and vicious thief.)
ameliorate
(v.) to improve (The tense situation was ameliorated when Sam proposed a solution everyone could agree upon.)
amenable
(adj.) willing, compliant (Our father was amenable when we asked him to drive us to the farm so we could go apple picking.)
amenity
(n.) an item that increases comfort (Bill Gates's house is stocked with so many amenities, he never has to do anything for himself.)
amiable
(adj.) friendly (An amiable fellow, Harry got along with just about everyone.) amicable (adj.) friendly (Claudia and Jimmy got divorced, but amicably and without hard feelings.)
amorous
(adj.) showing love, particularly sexual (Whenever Albert saw Mariah wear her slinky red dress, he began to feel quite amorous.)
amorphous
(adj.) without definite shape or type (The effort was doomed from the start, because the reasons behind it were so amorphous and hard to pin down.)
anachronistic
(adj.) being out of correct chronological order (In this book you're writing, you say that the Pyramids were built after the Titanic sank, which is anachronistic.)
analgesic
(n.) something that reduces pain (Put this analgesic on the wound so that the poor man at least feels a little better.)
analogous
(adj.) similar to, so that an analogy can be drawn (Though they are unrelated genetically, the bone structure of whales and fish is quite analogous.)
anarchist
(n.) one who wants to eliminate all government (An anarchist, Carmine wanted to dissolve every government everywhere.)
anathema
(n.) a cursed, detested person (I never want to see that murderer. He is an anathema to me.)
anecdote
(n.) a short, humorous account (After dinner, Marlon told an anecdote about the time he got his nose stuck in a toaster.)
anesthesia
(n.) loss of sensation (When the nerves in his spine were damaged, Mr. Hollins suffered anesthesia in his legs.)
anguish
(n.) extreme sadness, torment (Angelos suffered terrible anguish when he learned that Buffy had died while combating a strange mystical force of evil.)
animated
(adj.) lively (When he begins to talk about drama, which is his true passion, he becomes very animated.).)
annul
(v.) to make void or invalid (After seeing its unforeseen and catastrophic effects, Congress sought to annul the law.)
anomaly
(n.) something that does not fit into the normal order ("That rip in the space- time continuum is certainly a spatial anomaly," said Spock to Captain Kirk.)
anonymous
(adj.) being unknown, unrecognized (Mary received a love poem from an anonymous admirer.)
antagonism
(n.) hostility (Superman and Bizarro Superman shared a mutual antagonism, and often fought.)
antecedent
(n.) something that came before (The great tradition of Western culture had its antecedent in the culture of Ancient Greece.)
antediluvian
(adj.) ancient (The antediluvian man still believed that Eisenhower was president of the United States and that hot dogs cost a nickel.)
anthology
(n.) a selected collection of writings, songs, etc. (The new anthology of Bob Dylan songs contains all his greatest hits and a few songs that you might never have heard before.)
antipathy
(n.) a strong dislike, repugnance (I know you love me, but because you are a liar and a thief, I feel nothing but antipathy for you.)
antiquated
(adj.) old, out of date (That antiquated car has none of the features, like power windows and steering, that make modern cars so great.)
antiseptic
(adj.) clean, sterile (The antiseptic hospital was very bare, but its cleanliness helped to keep patients healthy.)
antithesis
(n.) the absolute opposite (Your values, which hold war and violence in the highest esteem, are the antithesis of my pacifist beliefs.)
anxiety
(n.) intense uneasiness (When he heard about the car crash, he felt anxiety because he knew that his girlfriend had been driving on the road where the accident occurred.)
apathetic
(adj.) lacking concern, emotion (Uninterested in politics, Bruno was apathetic about whether he lived under a capitalist or communist regime.)
apocryphal
(adj.) fictitious, false, wrong (Because I am standing before you, it seems obvious that the stories circulating about my demise were apocryphal.)
appalling
(adj.) inspiring shock, horror, disgust (The judge found the murderer's crimes and lack of remorse appalling.)
appease
(v.) to calm, satisfy (When the child cries, the mother gives him candy to appease him.)
appraise
(v.) to assess the worth or value of (A realtor will come over tonight to appraise our house.)
apprehend
1. (v.) to seize, arrest (The criminal was apprehended at the scene.) 2. (v.) to perceive, understand, grasp (The student has trouble apprehending concepts in math and science.)
approbation
(n.) praise (The crowd welcomed the heroes with approbation.)
appropriate
(v.) to take, make use of (The government appropriated the farmer's land without justification.)
aquatic
(adj.) relating to water (The marine biologist studies starfish and other aquatic creatures.)
arable
(adj.) suitable for growing crops (The farmer purchased a plot of arable land on which he will grow corn and sprouts.)
arbiter
(n.) one who can resolve a dispute, make a decision (The divorce court judge will serve as the arbiter between the estranged husband and wife.)
arbitrary
(adj.) based on factors that appear random (The boy's decision to choose one college over another seems arbitrary.)
arbitration
(n.) the process or act of resolving a dispute (The employee sought official arbitration when he could not resolve a disagreement with his supervisor.)
arboreal
(adj.) of or relating to trees (Leaves, roots, and bark are a few arboreal traits.)
arcane
(adj.) obscure, secret, known only by a few (The professor is an expert in arcane Lithuanian literature.)
archaic
(adj.) of or relating to an earlier period in time, outdated (In a few select regions of Western Mongolian, an archaic Chinese dialect is still spoken.)
archetypal
(adj.) the most representative or typical example of something (Some believe George Washington, with his flowing white hair and commanding stature, was the archetypal politician.)
ardor
(n.) extreme vigor, energy, enthusiasm (The soldiers conveyed their ardor with impassioned battle cries.)
arid
(adj.) excessively dry (Little other than palm trees and cacti grow successfully in arid environments.)
arrogate
(v.) to take without justification (The king arrogated the right to order executions to himself exclusively.)
artifact
(n.) a remaining piece from an extinct culture or place (The scientists spent all day searching the cave for artifacts from the ancient Mayan civilization.)
artisan
(n.) a craftsman (The artisan uses wood to make walking sticks.)
ascertain
(v.) to perceive, learn (With a bit of research, the student ascertained that some plants can live for weeks without water.)
ascetic
(adj.) practicing restraint as a means of self-discipline, usually religious (The priest lives an ascetic life devoid of television, savory foods, and other pleasures.)
ascribe
(v.) to assign, credit, attribute to (Some ascribe the invention of fireworks and dynamite to the Chinese.)
aspersion
(n.) a curse, expression of ill-will (The rival politicians repeatedly cast aspersions on each others' integrity.)
aspire
(v.) to long for, aim toward (The young poet aspires to publish a book of verse someday.)
assail
(v.) to attack (At dawn, the war planes assailed the boats in the harbor.)
assess
(v.) to evaluate (A crew arrived to assess the damage after the crash.)
assiduous
(adj.) hard-working, diligent (The construction workers erected the skyscraper during two years of assiduous labor.)
assuage
(v.) to ease, pacify (The mother held the baby to assuage its fears.)
astute
(adj.) very clever, crafty (Much of Roger's success in politics results from his ability to provide astute answers to reporters' questions.)
asylum
1. (n.) a place of refuge, protection, a sanctuary (For Thoreau, the forest served as an asylum from the pressures of urban life.) 2. (n.) an institution in which the insane are kept (Once diagnosed by a certified psychiatrist, the man was put in an asylum.)
atone
(v.) to repent, make amends (The man atoned for forgetting his wife's birthday by buying her five dozen roses.)
atrophy
(v.) to wither away, decay (If muscles do not receive enough blood, they will soon atrophy and die.)
attain
(v.) to achieve, arrive at (The athletes strived to attain their best times in competition.)
attribute
1. (v.) to credit, assign (He attributes all of his success to his mother's undying encouragement.) 2. (n.) a facet or trait (Among the beetle's most peculiar attributes is its thorny protruding eyes.)
atypical
(adj.) not typical, unusual (Screaming and crying is atypical adult behavior.) audacious (adj.) excessively bold (The security guard was shocked by the fan's
audacious
attempt to offer him a bribe.)
audible
(adj.) able to be heard (The missing person's shouts were unfortunately not audible.)
augment
(v.) to add to, expand (The eager student seeks to augment his knowledge of French vocabulary by reading French literature.)
auspicious
(adj.) favorable, indicative of good things (The tennis player considered the sunny forecast an auspicious sign that she would win her match.)
austere
(adj.) very bare, bleak (The austere furniture inside the abandoned house made the place feel haunted.)
avarice
(n.) excessive greed (The banker's avarice led him to amass a tremendous personal fortune.).)
balk
(v.) to stop, block abruptly (Edna's boss balked at her request for another raise.)
ballad
(n.) a love song (Greta's boyfriend played her a ballad on the guitar during their walk through the dark woods.)
banal
(adj.) dull, commonplace (The client rejected our proposal because they found our presentation banal and unimpressive.)
bane
(n.) a burden (Advanced physics is the bane of many students' academic lives.).)
battery
1.(n.) a device that supplies power (Most cars run on a combination of power from a battery and gasoline.) 2. (n.)assault, beating (Her husband was accused of assault and battery after he attacked a man on the sidewalk.)
beguile
(v.) to trick, deceive (The thief beguiled his partners into surrendering all of their money to him.)
behemoth
(n.) something of tremendous power or size (The new aircraft carrier is among several behemoths that the Air Force has added to its fleet.)
benevolent
(adj.) marked by goodness or doing good (Police officers should be commended for their benevolent service to the community.)
benign
(adj.) favorable, not threatening, mild (We were all relieved to hear that the medical tests determined her tumor to be benign.)
bequeath
(v.) to pass on, give (Jon's father bequeathed his entire estate to his mother.)
berate
(v.) to scold vehemently (The angry boss berated his employees for failing to meet their deadline.)
bereft
(adj.) devoid of, without (His family was bereft of food and shelter following the tornado.)
beseech
(v.) to beg, plead, implore (The servant beseeched the king for food to feed his starving family.)
bias
(n.) a tendency, inclination, prejudice (The judge's hidden bias against smokers led him to make an unfair decision.)
bilk
(v.) cheat, defraud (The lawyer discovered that this firm had bilked several clients out of thousands of dollars.)
blandish
(v.) to coax by using flattery (Rachel's assistant tried to blandish her into accepting the deal.)
blemish
(n.) an imperfection, flaw (The dealer agreed to lower the price because of the many blemishes on the surface of the wooden furniture.)
blight
1. (n.) a plague, disease (The potato blight destroyed the harvest and bankrupted many families.) 2. (n.) something that destroys hope (His bad morale is a blight upon this entire operation.)
boisterous
(adj.) loud and full of energy (The candidate won the vote after giving several boisterous speeches on television.)
bombastic
(adj.) excessively confident, pompous (The singer's bombastic performance disgusted the crowd.)
boon
(n.) a gift or blessing (The good weather has been a boon for many businesses located near the beach.)
bourgeois
(n.) a middle-class person, capitalist (Many businessmen receive criticism for their bourgeois approach to life.)
brazen
(adj.) excessively bold, brash (Critics condemned the novelist's brazen attempt to plagiarize Hemingway's story.).)
cacophony
(n.) tremendous noise, disharmonious sound (The elementary school orchestra created a cacophony at the recital.)
cadence
(n.) a rhythm, progression of sound (The pianist used the foot pedal to emphasize the cadence of the sonata.)
cajole
(v.) to urge, coax (Fred's buddies cajoled him into attending the bachelor party.)
calamity
(n.) an event with disastrous consequences (The earthquake in San Francisco was a calamity worse than any other natural disaster in history.)
calibrate
(v.) to set, standardize (The mechanic calibrated the car's transmission to make the motor run most efficiently.)
callous
(adj.) harsh, cold, unfeeling (The murderer's callous lack of remorse shocked the jury.)
calumny
(n.) an attempt to spoil someone else's reputation by spreading lies (The local official's calumny ended up ruining his opponent's prospect of winning the election.)
camaraderie
(n.) brotherhood, jovial unity (Camaraderie among employees usually leads to success in business.)
candor
(n.) honesty, frankness (We were surprised by the candor of the mayor's speech because he is usually rather evasive.)
canny
(adj.) shrewd, careful (The canny runner hung at the back of the pack through much of the race to watch the other runners, and then sprinted past them at the end.)
canvas
1. (n.) a piece of cloth on which an artist paints (Picasso liked to work on canvas rather than on bare cement.) 2. (v.) to cover, inspect (We canvassed the neighborhood looking for clues.)
capacious
(adj.) very spacious (The workers delighted in their new capacious office space.)
capitulate
(v.) to surrender (The army finally capitulated after fighting a long costly battle.)
capricious
(adj.) subject to whim, fickle (The young girl's capricious tendencies made it difficult for her to focus on achieving her goals.)
captivate
(v.) to get the attention of, hold (The fireworks captivated the young boy, who had never seen such things before.)
carouse
(v.) to party, celebrate (We caroused all night after getting married.)
carp
(v.) to annoy, pester (The husband divorced his wife after listening to her carping voice for decades.)
catalog
1. (v.) to list, enter into a list (The judge cataloged the victim's injuries before calculating how much money he would award.) 2. (n.) a list or collection (We received a catalog from J. Crew that displayed all of their new items.)
catalyze
(v.) to charge, inspire (The president's speech catalyzed the nation and resuscitated the economy.)
caucus
(n.) a meeting usually held by people working toward the same goal (The ironworkers held a caucus to determine how much of a pay increase they would request.)
caustic
(adj.) bitter, biting, acidic (The politicians exchanged caustic insults for over an hour during the debate.)
cavort
(v.) to leap about, behave boisterously (The adults ate their dinners on the patio, while the children cavorted around the pool.)
censure
1. (n.) harsh criticism (The frustrated teenager could not put up with anymore of her critical mother's censure.) 2. (v.) to rebuke formally (The principal censured the head of the English Department for forcing students to learn esoteric vocabulary.)
cerebral
(adj.) related to the intellect (The books we read in this class are too cerebral— they don't engage my emotions at all.)
chaos
(n.) absolute disorder (Mr. Thornton's sudden departure for the lavatory plunged his classroom into chaos.)
chastise
(v.) to criticize severely (After being chastised by her peers for mimicking Britney Spears, Miranda dyed her hair black and affected a Gothic style.)
cherish
(v.) to feel or show affection toward something (She continued to cherish her red plaid trousers, even though they had gone out of style and no longer fit her.)
chide
(v.) to voice disapproval (Lucy chided Russell for his vulgar habits and sloppy appearance.)
choreography
(n.) the arrangement of dances (The plot of the musical was banal, but the choreography was stunning.)
chronicle
1. (n.) a written history (The library featured the newly updated chronicle of World War II.) 2. (v.) to write a history (Albert's diary chronicled the day-to-day growth of his obsession with Cynthia.)
chronological
(adj.) arranged in order of time (Lionel carefully arranged the snapshots of his former girlfriends in chronological order, and then set fire to them.)
circuitous
(adj.) roundabout (The bus's circuitous route took us through numerous outlying suburbs.)
circumlocution
(n.) indirect and wordy language (The professor's habit of speaking in circumlocutions made it difficult to follow his lectures.)
circumscribed
(adj.) marked off, bounded (The children were permitted to play tag only within a carefully circumscribed area of the lawn.)
circumspect
(adj.) cautious (Though I promised Rachel's father I would bring her home promptly by midnight, it would have been more circumspect not to have specified a time.)
circumvent
(v.) to get around (The school's dress code forbidding navel-baring jeans was circumvented by the determined students, who were careful to cover up with long coats when administrators were nearby.)
clairvoyant
(adj.) able to perceive things that normal people cannot (Zelda's uncanny ability to detect my lies was nothing short of clairvoyant.).)
clandestine
(adj.) secret (Announcing to her boyfriend that she was going to the gym, Sophie actually went to meet Joseph for a clandestine liaison.).)
clemency
(n.) mercy (After he forgot their anniversary, Martin could only beg Maria for clemency.)
clergy
(n.) members of Christian holy orders (Though the villagers viewed the church rectory as quaint and charming, the clergy who lived there regarded it as a mildewy and dusty place that aggravated their allergies.)
cloying
(adj.) sickeningly sweet (Though Ronald was physically attractive, Maud found his constant compliments and solicitous remarks cloying.)
coagulate
(v.) to thicken, clot (The top layer of the pudding had coagulated into a thick skin.)
coalesce
(v.) to fuse into a whole (Gordon's ensemble of thrift-shop garments coalesced into a surprisingly handsome outfit.)
cobbler
(n.) a person who makes or repairs shoes (I had my neighborhood cobbler replace my worn-out leather soles with new ones.)
coerce
(v.) to make somebody do something by force or threat (The court decided that Vanilla Ice did not have to honor the contract because he had been coerced into signing it.)
cogent
(adj.) intellectually convincing (Irene's arguments in favor of abstinence were so cogent that I could not resist them.)
cognizant
(adj.) aware, mindful (Jake avoided speaking to women in bars because he was cognizant of the fact that drinking impairs his judgment.)
coherent
(adj.) logically consistent, intelligible (Renee could not figure out what Monroe had seen because he was too distraught to deliver a coherent statement.)
collateral
1. (adj.) secondary (Divorcing my wife had the collateral effect of making me poor, as she was the only one of us with a job or money.) 2. (n.) security for a debt (Jacob left his watch as collateral for the $500 loan.)
colloquial
(adj.) characteristic of informal conversation (Adam's essay on sexual response in primates was marked down because it contained too many colloquial expressions.)
collusion
(n.) secret agreement, conspiracy (The three law students worked in collusion to steal the final exam.)
colossus
(n.) a gigantic statue or thing (For 56 years, the ancient city of Rhodes featured a colossus standing astride its harbor.)
combustion
(n.) the act or process of burning (The unexpected combustion of the prosecution's evidence forced the judge to dismiss the case against Ramirez.)
commendation
(n.) a notice of approval or recognition (Jared received a commendation from Linda, his supervisor, for his stellar performance.)
commensurate
(adj.) corresponding in size or amount (Ahab selected a very long roll and proceeded to prepare a tuna salad sandwich commensurate with his enormous appetite.)
commodious
(adj.) roomy (Holden invited the three women to join him in the back seat of the taxicab, assuring them that the car was quite commodious.)
compelling
(adj.) forceful, demanding attention (Eliot's speech was so compelling that Lenore accepted his proposal on the spot.)
compensate
(v.) to make an appropriate payment for something (Reginald bought Sharona a new dress to compensate her for the one he'd spilled his ice cream on.)
complacency
(n.) self-satisfied ignorance of danger (Colin tried to shock his friends out of their complacency by painting a frightening picture of what might happen to them.)
complement
(v.) to complete, make perfect (Ann's scarf complements her blouse beautifully, making her seem fully dressed even though she isn't wearing a coat.)
compliant
(adj.) ready to adapt oneself to another's wishes (Sue had very strong opinions about what to do on a first date, and Ted was absolutely compliant.)
complicit
(adj.) being an accomplice in a wrongful act (By keeping her daughter's affair a secret, Maddie became complicit in it.)
compliment
(n.) an expression of esteem or approval (I blushed crimson when Emma gave me a compliment on my new haircut.)
compound
1. (v.) to combine parts (The difficulty of finding a fire fighting started, Joseph rushed into the family compound because it was safe and well defended.)
comprehensive
(adj.) including everything (She sent me a comprehensive list of the ingredients needed to cook rabbit soufflé.)
compress
(v.) to apply pressure, squeeze together (Lynn compressed her lips into a frown.)
compunction
(n.) distress caused by feeling guilty (He felt compunction for the shabby way he'd treated her.)
concede
(v.) to accept as valid (Andrew had to concede that what his mother said about Diana made sense.)
conciliatory
(adj.) friendly, agreeable (I took Amanda's invitation to dinner as a very conciliatory gesture.)
concise
(adj.) brief and direct in expression (Gordon did not like to waste time, and his instructions to Brenda were nothing if not concise.)
concoct
(v.) to fabricate, make up (She concocted the most ridiculous story to explain her absence.)
concomitant
(adj.) accompanying in a subordinate fashion (His dislike of hard work carried with it a concomitant lack of funds.)
concord
(n.) harmonious agreement (Julie and Harold began the evening with a disagreement, but ended it in a state of perfect concord.)
condolence
(n.) an expression of sympathy in sorrow (Brian lamely offered his condolences on the loss of his sister's roommate's cat.)
condone
(v.) to pardon, deliberately overlook (He refused to condone his brother's crime.)
conduit
(n.) a pipe or channel through which something passes (The water flowed through the conduit into the container.)
confection
(n.) a sweet, fancy food (We went to the mall food court and purchased a delicious confection.)
confidant
(n.) a person entrusted with secrets (Shortly after we met, she became my chief confidant.)
conflagration
(n.) great fire (The conflagration consumed the entire building.) (n.) a gathering together (A confluence of different factors made tonight the
confluence
(n.) a gathering together (A confluence of different factors made tonight the perfect night.)
conformist
(n.) one who behaves the same as others (Julian was such a conformist that he had to wait and see if his friends would do something before he would commit.)
confound
(v.) to frustrate, confuse (MacGuyver confounded the policemen pursuing him by covering his tracks.)
congeal
(v.) to thicken into a solid (The sauce had congealed into a thick paste.)
congenial
(adj.) pleasantly agreeable (His congenial manner made him popular wherever he went.)
congregation
(n.) a gathering of people, especially for religious services (The priest told the congregation that he would be retiring.)
congruity
(n.) the quality of being in agreement (Bill and Veronica achieved a perfect congruity of opinion.)
connive
(v.) to plot, scheme (She connived to get me to give up my vacation plans.)
consecrate
(v.) to dedicate something to a holy purpose (Arvin consecrated his spare bedroom as a shrine to Christina.)
consensus
(n.) an agreement of opinion (The jury was able to reach a consensus only after days of deliberation.)
consign
(v.) to give something over to another's care (Unwillingly, he consigned his mother to a nursing home.)
consolation
(n.) an act of comforting (Darren found Alexandra's presence to be a consolation for his suffering.)
consonant
(adj.) in harmony (The singers' consonant voices were beautiful.)
constituent
(n.) an essential part (The most important constituent of her perfume is something called ambergris.)
constrain
(v.)to forcibly restrict (His belief in nonviolence constrained him from taking revenge on his attackers.)
construe
(v.) to interpret (He construed her throwing his clothes out the window as a signal that she wanted him to leave.)
consummate
(v.) to complete a deal; to complete a marriage ceremony through sexual intercourse (Erica and Donald consummated their agreement in the executive boardroom.)
consumption
(n.) the act of consuming (Consumption of intoxicating beverages is not permitted on these premises.)
contemporaneous
(adj.) existing during the same time (Though her novels do not feature the themes of Romanticism, Jane Austen's work was contemporaneous with that of Wordsworth and Byron.)
contentious
(adj.) having a tendency to quarrel or dispute (George's contentious personality made him unpopular with his classmates.)
contravene
(v.) to contradict, oppose, violate (Edwidge contravened his landlady's rule against overnight guests.)
contrite
(adj.) penitent, eager to be forgiven (Blake's contrite behavior made it impossible to stay angry at him.)
contusion
(n.) bruise, injury (The contusions on his face suggested he'd been in a fight.)
conundrum
(n.) puzzle, problem (Interpreting Jane's behavior was a constant conundrum.)
convene
(v.) to call together (Jason convened his entire extended family for a discussion.)
convention
1. (n.) an assembly of people (The hotel was full because of the cattle- ranchers' convention.) 2. (n.) a rule, custom (The cattle-ranchers have a convention that you take off your boots before entering their houses.)
convivial
(adj.) characterized by feasting, drinking, merriment (The restaurant's convivial atmosphere put me immediately at ease.)
convoluted
(adj.) intricate, complicated (Grace's story was so convoluted that I couldn't follow it.)
copious
(adj.) profuse, abundant (Copious amounts of Snapple were imbibed in the cafeteria.)
cordial
(adj.) warm, affectionate (His cordial greeting melted my anger at once.)
coronation
(n.) the act of crowning (The new king's coronation occurred the day after his father's death.)
corpulence
(adj.)extreme fatness (Henry's corpulence did not make him any less attractive to his charming, svelte wife.)
corroborate
(v.) to support with evidence (Luke's seemingly outrageous claim was corroborated by witnesses.)
corrosive
(adj.) having the tendency to erode or eat away (The effect of the chemical was highly corrosive.)
cosmopolitan
(adj.) sophisticated, worldly (Lloyd's education and upbringing were cosmopolitan, so he felt right at home among the powerful and learned.)
counteract
(v.) to neutralize, make ineffective (The antidote counteracted the effect of the poison.).)
covet
(v.) to desire enviously (I coveted Moses's house, wife, and car.)
covert
(adj.) secretly engaged in (Nerwin waged a covert campaign against his enemies, while outwardly appearing to remain friendly.)
credulity
(n.) readiness to believe (His credulity made him an easy target for con men.)
crescendo
(n.) a steady increase in intensity or volume (The crescendo of the brass instruments gave the piece a patriotic feel.)
criteria
(n.) standards by which something is judged (Among Mrs. Fields's criteria for good cookies are that they be moist and chewy.)
culmination
(n.) the climax toward which something progresses (The culmination of the couple's argument was the decision to divorce.)
culpable
(adj.) deserving blame (He was culpable of the crime, and was sentenced to perform community service for 75 years.)
cultivate
(v.) to nurture, improve, refine (At the library, she cultivated her interest in spy novels.)
cumulative
(adj.) increasing, building upon itself (The cumulative effect of hours spent in the sun was a deep tan.)
cunning
(adj.) sly, clever at being deceitful (The general devised a cunning plan to surprise the enemy.)
cupidity
(n.) greed, strong desire (His cupidity made him enter the abandoned gold mine despite the obvious dangers.)
cursory
(adj.) brief to the point of being superficial (Late for the meeting, she cast a cursory glance at the agenda.)
curt
(adj.) abruptly and rudely short (Her curt reply to my question made me realize that she was upset at me.)
curtail
(v.) to lessen, reduce (Since losing his job, he had to curtail his spending.)
daunting
(adj.) intimidating, causing one to lose courage (He kept delaying the daunting act of asking for a promotion.)
dearth
(n.) a lack, scarcity (An eager reader, she was dismayed by the dearth of classic books at the library.)
debacle
(n.) a disastrous failure, disruption (The elaborately designed fireworks show turned into a debacle when the fireworks started firing in random directions.)
debase
(v.) to lower the quality or esteem of something (The large raise that he gave himself debased his motives for running the charity.)
debauch
(v.) to corrupt by means of sensual pleasures (An endless amount of good wine and cheese debauched the traveler.)
debunk
(v.) to expose the falseness of something (He debunked her claim to be the world's greatest chess player by defeating her in 18 consecutive matches.)
decorous
(adj.) socially proper, appropriate (The appreciative guest displayed decorous behavior toward his host.)
decry
(v.) to criticize openly (The kind video rental clerk decried the policy of charging customers late fees.)
deface
(v.) to ruin or injure something's appearance (The brothers used eggs and shaving cream to deface their neighbor's mailbox.)
defamatory
(adj.) harmful toward another's reputation (The defamatory gossip spreading about the actor made the public less willing to see the actor's new movie.)
defer
(v.) to postpone something; to yield to another's wisdom (Ron deferred to Diane, the expert on musical instruments, when he was asked about buying a piano.)
deferential
(adj.) showing respect for another's authority (His deferential attitude toward her made her more confident in her ability to run the company.)
defile
(v.) to make unclean, impure (She defiled the calm of the religious building by playing her banjo.)
deft
(adj.) skillful, capable (Having worked in a bakery for many years, Marcus was a deft bread maker.)
defunct
(adj.) no longer used or existing (They planned to turn the defunct schoolhouse into a community center.)
delegate
(v.) to hand over responsibility for something (The dean delegated the task of finding a new professor to a special hiring committee.)
deleterious
(adj.) harmful (She experienced the deleterious effects of running a marathon without stretching her muscles enough beforehand.)
deliberate
(adj.) intentional, reflecting careful consideration (Though Mary was quite upset, her actions to resolve the dispute were deliberate.)
delineate
(v.) to describe, outline, shed light on (She neatly delineated her reasons for canceling the project's funding.)
demagogue
(n.) a leader who appeals to a people's prejudices (The demagogue strengthened his hold over his people by blaming immigrants for the lack of jobs.)
demarcation
(n.) the marking of boundaries or categories (Different cultures have different demarcations of good and evil.)
demean
(v.) to lower the status or stature of something (She refused to demean her secretary by making him order her lunch.)
demure
(adj.) quiet, modest, reserved (Though everyone else at the party was dancing and going crazy, she remained demure.)
denigrate
(v.) to belittle, diminish the opinion of (The company decided that its advertisements would no longer denigrate the company's competitors.)
denounce
(v.) to criticize publicly (The senator denounced her opponent as a greedy politician.)
deplore
(v.) to feel or express sorrow, disapproval (We all deplored the miserable working conditions in the factory.)
depravity
(n.) wickedness (Rumors of the ogre's depravity made the children afraid to enter the forest.)
deprecate
(v.) to belittle, depreciate (Always over-modest, he deprecated his contribution to the local charity.)
derelict
(adj.) abandoned, run-down (Even though it was dangerous, the children enjoyed going to the deserted lot and playing in the derelict house.)
deride
(v.) to laugh at mockingly, scorn (The bullies derided the foreign student's accent.)
derivative
(adj.) taken directly from a source, unoriginal (She was bored by his music because she felt that it was derivative and that she had heard it before.).)
desolate
(adj.) deserted, dreary, lifeless (She found the desolate landscape quite a contrast to the hustle and bustle of the overcrowded city.)
despondent
(adj.) feeling depressed, discouraged, hopeless (Having failed the first math test, the despondent child saw no use in studying for the next and failed that one too.)
despot
(n.) one who has total power and rules brutally (The despot issued a death sentence for anyone who disobeyed his laws.)
destitute
(adj.) impoverished, utterly lacking (The hurricane destroyed many homes and left many families destitute.)
deter
(v.) to discourage, prevent from doing (Bob's description of scary snakes couldn't deter Marcia from traveling in the rainforests.)
devious
(adj.) not straightforward, deceitful (Not wanting to be punished, the devious girl blamed the broken vase on the cat.)
dialect
(n.) a variation of a language (In the country's remote, mountainous regions, the inhabitants spoke a dialect that the country's other inhabitants had difficulty understanding.)
diaphanous
(adj.) light, airy, transparent (Sunlight poured in through the diaphanous curtains, brightening the room.).)
diffident
(adj.) shy, quiet, modest (While eating dinner with the adults, the diffident youth did not speak for fear of seeming presumptuous.)
diffuse
1. (v.) to scatter, thin out, break up (He diffused the tension in the room by making in a joke.) 2. (adj.) not concentrated, scattered, disorganized (In her writings, she tried unsuccessfully to make others understand her diffuse thoughts.)
dilatory
(adj.) tending to delay, causing delay (The general's dilatory strategy enabled the enemy to regroup.)
diligent
(adj.) showing care in doing one's work (The diligent researcher made sure to check her measurements multiple times.)
diminutive
(adj.) small or miniature (The bullies, tall and strong, picked on the diminutive child.)
dirge
(n.) a mournful song, especially for a funeral (The bagpipers played a dirge as the casket was carried to the cemetery.)
disaffected
(adj.) rebellious, resentful of authority (Dismayed by Bobby's poor behavior, the parents sent their disaffected son to a military academy to be disciplined.)
disavow
(v.) to deny knowledge of or responsibility for (Not wanting others to criticize her, she disavowed any involvement in the company's hiring scandal.)
discern
(v.) to perceive, detect (Though he hid his emotions, she discerned from his body language that he was angry.)
disclose
(v.) to reveal, make public (The CEO disclosed to the press that the company would have to fire several employees.)
discomfit
(v.) to thwart, baffle (The normally cheery and playful children's sudden misery discomfited the teacher.)
discordant
(adj.) not agreeing, not in harmony with (The girls' sobs were a discordant sound amid the general laughter that filled the restaurant.)
discrepancy
(n.) difference, failure of things to correspond (He was troubled by the discrepancy between what he remembered paying for the appliance and what his receipt showed he paid for it.)
discretion
(n.) the quality of being reserved in speech or action; good judgment (Not wanting her patient to get overly anxious, the doctor used discretion in deciding how much to tell the patient about his condition.)
discursive
(adj.) rambling, lacking order (The professor's discursive lectures seemed to be about every subject except the one initially described.)
disdain
1. (v.) to scorn, hold in low esteem (Insecure about their jobs, the older employees disdained the recently hired ones, who were young and capable.) 2. (n.) scorn, low esteem (After learning of his immoral actions, Justine held Lawrence in disdain.)
disgruntled
(adj.) upset, not content (The child believed that his parents had unjustly grounded him, and remained disgruntled for a week.)
disheartened
(adj.) feeling a loss of spirit or morale (The team was disheartened after losing in the finals of the tournament.)
disparage
(v.) to criticize or speak ill of (The saleswoman disparaged the competitor's products to persuade her customers to buy what she was selling.)
disparate
(adj.) sharply differing, containing sharply contrasting elements (Having widely varying interests, the students had disparate responses toward the novel.)
dispatch
(v.) to send off to accomplish a duty (The carpenter dispatched his assistant to fetch wood.)
dispel
(v.) to drive away, scatter (She entered the office as usual on Monday, dispelling the rumor that she had been fired.)
disperse
(v.) to scatter, cause to scatter (When the rain began to pour, the crowd at the baseball game quickly dispersed.)
disrepute
(n.) a state of being held in low regard (The officer fell into disrepute after it was learned that he had disobeyed the orders he had given to his own soldiers.)
dissemble
(v.) to conceal, fake (Not wanting to appear heartlessly greedy, she dissembled and hid her intention to sell her ailing father's stamp collection.)
disseminate
(v.) to spread widely (The politician disseminated his ideas across the town before the election.).)
dissipate
1. (v.) to disappear, cause to disappear (The sun finally came out and dissipated the haze.) 2. (v.) to waste (She dissipated her fortune on a series of bad investments.)
dissonance
(n.) lack of harmony or consistency (Though the president of the company often spoke of the company as reliant solely upon its workers, her decision to increase her own salary rather than reward her employees revealed a striking dissonance between her alleged beliefs and her actions.)
dissuade
(v.) to persuade someone not to do something (Worried that he would catch a cold, she tried to dissuade him from going out on winter nights.)
distend
(v.) to swell out (Years of drinking beer caused his stomach to distend.)
dither
(v.) to be indecisive (Not wanting to offend either friend, he dithered about which of the two birthday parties he should attend.)
divine
(adj.) godly, exceedingly wonderful (Terribly fond of desserts, she found the rich chocolate cake to be divine.)
divisive
(adj.) causing dissent, discord (Her divisive tactics turned her two friends against each other.)
divulge
(v.) to reveal something secret (Pressured by the press, the government finally divulged the previously unknown information.)
docile
(adj.) easily taught or trained (She successfully taught the docile puppy several tricks.)
dogmatic
(adj.) aggressively and arrogantly certain about unproved principles (His dogmatic claim that men were better than women at fixing appliances angered everyone.)
dormant
(adj.) sleeping, temporarily inactive (Though she pretended everything was fine, her anger lay dormant throughout the dinner party and exploded in screams of rage after everyone had left.)
dour
(adj.)stern, joyless (The children feared their dour neighbor because the old man would take their toys if he believed they were being too loud.)
dubious
(adj.) doubtful, of uncertain quality (Suspicious that he was only trying to get a raise, she found his praise dubious.)
duplicity
(n.) crafty dishonesty (His duplicity involved convincing his employees to let him lower their salaries and increase their stock options, and then to steal the money he saved and run the company into the ground.)
duress
(n.) hardship, threat (It was only under intense duress that he, who was normally against killing, fired his gun.)
dynamic
(adj.) actively changing (The parents found it hard to keep up with the dynamic music scene with which their children had become very familiar.)
ebullient
(adj.) extremely lively, enthusiastic (She became ebullient upon receiving an acceptance letter from her first-choice college.)
eclectic
(adj.) consisting of a diverse variety of elements (That bar attracts an eclectic crowd: lawyers, artists, circus clowns, and investment bankers.)
ecstatic
(adj.) intensely and overpoweringly happy (The couple was ecstatic when they learned that they had won the lottery.)
edict
(n.) an order, decree (The ruler issued an edict requiring all of his subjects to bow down before him.)
efface
(v.) to wipe out, obliterate, rub away (The husband was so angry at his wife for leaving him that he effaced all evidence of her presence; he threw out pictures of her and gave away all her belongings.)
effervescent
(adj.) bubbly, lively (My friend is so effervescent that she makes everyone smile.)
efficacious
(adj.) effective (My doctor promised me that the cold medicine was efficacious, but I'm still sniffling.).)
elaborate
(adj.) complex, detailed, intricate (Dan always beats me at chess because he develops such an elaborate game plan that I can never predict his next move.)
elated
(adj.) overjoyed, thrilled (When she found out she had won the lottery, the writer was elated.)
elegy
(n.) a speech given in honor of a dead person (At the funeral, the widow gave a moving elegy describing her love for her husband.)
elicit
(v.) to bring forth, draw out, evoke (Although I asked several times where the exit was, I elicited no response from the stone-faced policeman.)
eloquent
(adj.) expressive, articulate, moving (The priest gave such an eloquent sermon that most churchgoers were crying.)
elucidate
(v.) to clarify, explain (I didn't understand why my friend was so angry with me, so I asked Janine to elucidate her feelings.)
elude
(v.) to evade, escape (Despite an intense search, the robber continues to elude the police.)
emaciated
(adj.) very thin, enfeebled looking (My sister eats a lot of pastries and chocolate but still looks emaciated.)
embellish
1. (v.) to decorate, adorn (My mom embellished the living room by adding lace curtains.) 2. (v.)to add details to, enhance (When Harry told me that he had "done stuff" on his vacation, I asked him to embellish upon his account.)
embezzle
(v.) to steal money by falsifying records (The accountant was fired for embezzling $10,000 of the company's funds.)
emend
(v.) to correct or revise a written text (If my sentence is incorrect, the editor will emend what I have written.)
eminent
1. (adj.) distinguished, prominent, famous (Mr. Phillips is such an eminent scholar that every professor on campus has come to hear him lecture.) 2. (adj.) conspicuous (There is an eminent stain on that shirt.)
emollient
(adj.) soothing (This emollient cream makes my skin very smooth.)
emote
(v.) to express emotion (The director told the actor he had to emote, or else the audience would have no idea what his character was going through.)
empathy
(n.) sensitivity to another's feelings as if they were one's own (I feel such empathy for my sister when she's in pain that I cry too.)
empirical
1. (adj.) based on observation or experience (The scientist gathered empirical data on the growth rate of dandelions by studying the dandelions behind his house.) 2. (adj.) capable of being proved or disproved by experiment (That all cats hate getting wet is an empirical statement: I can test it by bathing my cat, Trinket.)
emulate
(v.) to imitate (I idolize Britney Spears so much that I emulate everything she does: I wear her outfits, sing along to her songs, and date a boy named Justin.)
enamor
(v.) to fill with love, fascinate, usually used in passive form followed by "of" or "with" (I grew enamored of that boy when he quoted my favorite love poem.)
encore
(n.) the audience's demand for a repeat performance; also the artist's performance in response to that demand (At the end of the concert, all the fans yelled, "Encore! Encore!" but the band did not come out to play again.)
encumber
(v.) to weigh down, burden (At the airport, my friend was encumbered by her luggage, so I offered to carry two of her bags.)
enervate
(v.) to weaken, exhaust (Writing these sentences enervates me so much that I will have to take a nap after I finish.)
enfranchise
(v.) to grant the vote to (The Nineteenth Amendment enfranchised women.)
engender
(v.) to bring about, create, generate (During the Olympics, the victories of U.S. athletes engender a patriotic spirit among Americans.)
enigmatic
(adj.) mystifying, cryptic (That man wearing the dark suit and dark glasses is so enigmatic that no one even knows his name.)
enmity
(n.) ill will, hatred, hostility (Mark and Andy have clearly not forgiven each other, because the enmity between them is obvious to anyone in their presence.)
ennui
(n.) boredom, weariness (I feel such ennui that I don't look forward to anything, not even my birthday party.)
entail
(v.) to include as a necessary step (Building a new fence entails tearing down the old one.)
enthrall
(v.) to charm, hold spellbound (The sailor's stories of fighting off sharks and finding ancient treasures enthralled his young son.)
ephemeral
(adj.) short-lived, fleeting (She promised she'd love me forever, but her "forever" was only ephemeral: she left me after one week.)
epistolary
(adj.) relating to or contained in letters (Some people call me "Auntie's boy," because my aunt and I have such a close epistolary relationship that we write each other every day.)
epitome
(n.) a perfect example, embodiment (My mother, the epitome of good taste, always dresses more elegantly than I do.)
equanimity
(n.) composure (Even though he had just been fired, Mr. Simms showed great equanimity by neatly packing up his desk and wishing everyone in the office well.)
equivocal
(adj.) ambiguous, uncertain, undecided (His intentions were so equivocal that I didn't know whether he was being chivalrous or sleazy.)
erudite
(adj.) learned (My Latin teacher is such an erudite scholar that he has translated some of the most difficult and abstruse ancient poetry.)
eschew
(v.) to shun, avoid (George hates the color green so much that he eschews all green food.)
esoteric
(adj.) understood by only a select few (Even the most advanced students cannot understand the physicist's esoteric theories.)
espouse
(v.) to take up as a cause, support (I love animals so much that I espouse animal rights.)
ethereal
(adj.) heavenly, exceptionally delicate or refined (In her flowing silk gown and lace veil, the bride looked ethereal.)
etymology
(n.) the history of words, their origin and development (From the study of etymology, I know that the word "quixotic" derives from Don Quixote and the word "gaudy" refers to the Spanish architect Gaudí.)
euphoric
(adj.) elated, uplifted (I was euphoric when I found out that my sister had given birth to twins.).)
exacerbate
(v.) to make more violent, intense (The gruesome and scary movie I saw last night exacerbated my fears of the dark.)
exalt
(v.) to glorify, praise (Michael Jordan is the figure in basketball we exalt the most.)
exasperate
(v.) to irritate, irk (George's endless complaints exasperated his roomate.)
excavate
(v.) to dig out of the ground and remove (The pharaoh's treasures were excavated by archeologists in Egypt.)
exculpate
(v.) to free from guilt or blame, exonerate (My discovery of the ring behind the dresser exculpated me from the charge of having stolen it.)
excursion
(n.) a trip or outing (After taking an excursion to the Bronx Zoo, I dreamed about pandas and monkeys.)
execrable
(adj.) loathsome, detestable (Her pudding is so execrable that it makes me sick.)
exhort
(v.) to urge, prod, spur (Henry exhorted his colleagues to join him in protesting against the university's hiring policies.)
exigent
(adj.) urgent, critical (The patient has an exigent need for medication, or else he will lose his sight.)
exonerate
(v.) to free from guilt or blame, exculpate (The true thief's confession exonerated the man who had been held in custody for the crime.)
exorbitant
(adj.) excessive (Her exorbitant praise made me blush and squirm in my seat.)
expedient
(adj.) advisable, advantageous, serving one's self-interest (In his bid for reelection, the governor made an expedient move by tabling all controversial legislation.).)
expurgate
(v.) to remove offensive or incorrect parts, usually of a book (The history editors expurgated from the text all disparaging and inflammatory comments about the Republican Party.)
extant
(adj.) existing, not destroyed or lost (My mother's extant love letters to my father are in the attic trunk.)
extol
(v.) to praise, revere (Violet extolled the virtues of a vegetarian diet to her meat- loving brother.)
extraneous
(adj.) irrelevant, extra, not necessary (Personal political ambitions should always remain extraneous to legislative policy, but, unfortunately, they rarely are.)
extricate
(v.) to disentangle (Instead of trying to mediate between my brother and sister, I extricated myself from the family tension entirely and left the house for the day.)
exult
(v.) to rejoice (When she found out she won the literature prize, Mary exulted by dancing and singing through the school's halls.)
fabricate
(v.) to make up, invent (When I arrived an hour late to class, I fabricated some excuse about my car breaking down on the way to school.)
façade
1. (n.) the wall of a building (Meet me in front of the museum's main façade.) 2. (n.) a deceptive appearance or attitude (Despite my smiling façade, I am feeling melancholy.).).)
fathom
(v.) to understand, comprehend (I cannot fathom why you like that crabby and mean-spirited neighbor of ours.)
fatuous
(adj.) silly, foolish (He considers himself a serious poet, but in truth, he only writes fatuous limericks.)
fecund
(adj.) fruitful, fertile (The fecund tree bore enough apples to last us through the entire season.)
felicitous
1. (adj.) well suited, apt (While his comments were idiotic and rambling, mine were felicitous and helpful.) 2. (adj.) delightful, pleasing (I spent a felicitous afternoon visiting old friends.)
feral
(adj.) wild, savage (That beast looks so feral that I would fear being alone with it.)
fervent
(adj.) ardent, passionate (The fervent protestors chained themselves to the building and shouted all night long.)
fetid
(adj.) having a foul odor (I can tell from the fetid smell in your refrigerator that your milk has spoiled.)
fetter
(v.) to chain, restrain (The dog was fettered to the parking meter.)
fickle
(adj.) shifting in character, inconstant (In Greek dramas, the fickle gods help Achilles one day, and then harm him the next.)
fidelity
(n.) loyalty, devotion (Guard dogs are known for the great fidelity they show toward their masters.)
figurative
(adj.) symbolic (Using figurative language, Jane likened the storm to an angry bull.)
flabbergasted
(adj.) astounded (Whenever I read an Agatha Christie mystery novel, I am always flabbergasted when I learn the identity of the murderer.)
flaccid
(adj.) limp, not firm or strong (If a plant is not watered enough, its leaves become droopy and flaccid.)
flagrant
(adj.) offensive, egregious (The judge's decision to set the man free simply because that man was his brother was a flagrant abuse of power.)
florid
(adj.) flowery, ornate (The writer's florid prose belongs on a sentimental Hallmark card.)
flout
(v.) to disregard or disobey openly (I flouted the school's dress code by wearing a tie-dyed tank top and a pair of cut-off jeans.)
foil
(v.) to thwart, frustrate, defeat (Inspector Wilkens foiled the thieves by locking them in the bank along with their stolen money.)
forage
(v.) to graze, rummage for food (When we got lost on our hiking trip, we foraged for berries and nuts in order to survive.)
forbearance
(n.) patience, restraint, toleration (The doctor showed great forbearance in calming down the angry patient who shouted insults at him.)
forestall
(v.) to prevent, thwart, delay (I forestalled the cold I was getting by taking plenty of vitamin C pills and wearing a scarf.)
forlorn
(adj.) lonely, abandoned, hopeless (Even though I had the flu, my family decided to go skiing for the weekend and leave me home alone, feeling feverish and forlorn.)
forsake
(v.) to give up, renounce (My New Year's resolution is to forsake smoking and drinking.)
fortitude
(n.) strength, guts (Achilles' fortitude in battle is legendary.)
fortuitous
(adj.) happening by chance, often lucky or fortunate (After looking for Manuel and not finding him at home, Harriet had a fortuitous encounter with him at the post office.)
forum
(n.) a medium for lecture or discussion (Some radio talk-shows provide a good forum for political debate.)
foster
(v.) to stimulate, promote, encourage (To foster good health in the city, the mayor started a "Get out and exercise!" campaign.)
fractious
(adj.) troublesome or irritable (Although the child insisted he wasn't tired, his fractious behavior—especially his decision to crush his cheese and crackers all over the floor—convinced everyone present that it was time to put him to bed.)
fraught
(adj.) (usually used with "with") filled or accompanied with (Her glances in his direction were fraught with meaning, though precisely what meaning remained unclear.)
frenetic
(adj.) frenzied, hectic, frantic (In the hours between night and morning, the frenetic pace of city life slows to a lull.)
frivolous
(adj.) of little importance, trifling (Someday, all that anxiety about whether your zit will disappear before the prom will seem totally frivolous.)
frugal
(adj.) thrifty, economical (Richard is so frugal that his diet consists almost exclusively of catfish and chicken liver—the two most inexpensive foods in the store.)
furtive
(adj.) secretive, sly (Jane's placement of her drugs in her sock drawer was not as furtive as she thought, as the sock drawer is the first place most parents look.)
garish
(adj.) gaudy, in bad taste (Mrs. Watson has poor taste and covers every object in her house with a garish gold lamé.)
garrulous
(adj.) talkative, wordy (Some talk show hosts are so garrulous that their guests can't get a word in edgewise.)
genial
(adj.) friendly, affable (Although he's been known to behave like a real jerk, I would say that my brother is an overall genial guy.)
gluttony
(n.) overindulgence in food or drink (Ada's fried chicken tastes so divine, I don't know how anyone can call gluttony a sin.)
goad
(v.) to urge, spur, incite to action (Jim may think he's not going to fight Billy, but Billy will goad Jim on with insults until he throws a punch.)
gourmand
(n.) someone fond of eating and drinking (My parents, who used to eat little more than crackers and salad, have become real gourmands in their old age.)
grandiloquence
(n.) lofty, pompous language (The student thought her grandiloquence would make her sound smart, but neither the class nor the teacher bought it.)
grandiose
(adj.) on a magnificent or exaggerated scale (Margaret planned a grandiose party, replete with elephants, trapeze artists, and clowns.)
gratuitous
(adj.) uncalled for, unwarranted (Every morning the guy at the donut shop gives me a gratuitous helping of ketchup packets.).)
guile
(n.) deceitful, cunning, sly behavior (Because of his great guile, the politician was able to survive scandal after scandal.)
hackneyed
(adj.) unoriginal, trite (A girl can only hear "I love you" so many times before it begins to sound hackneyed and meaningless.)
hallowed
(adj.) revered, consecrated (In the hallowed corridors of the cathedral, the disturbed professor felt himself to be at peace.).)
hardy
(adj.) robust, capable of surviving through adverse conditions (I too would have expected the plants to be dead by mid-November, but apparently they're very hardy.)
harrowing
(adj.) greatly distressing, vexing (The car crash was a harrowing experience, but I have a feeling that the increase in my insurance premiums will be even more upsetting.)
haughty
(adj.) disdainfully proud (The superstar's haughty dismissal of her costars will backfire on her someday.)
hedonist
(n.) one who believes pleasure should be the primary pursuit of humans (Because he's such a hedonist, I knew Murray would appreciate the 11 cases of wine I bought him for his birthday.)
hegemony
(n.) domination over others (Britain's hegemony over its colonies was threatened once nationalist sentiment began to spread around the world.)
heinous
(adj.) shockingly wicked, repugnant (The killings were made all the more heinous by the fact that the murderer first tortured his victims for three days.)
heterogeneous
(adj.) varied, diverse in character (I hate having only one flavor so I always buy the swirled, or should I say heterogeneous, type of ice cream.)
hiatus
(n.) a break or gap in duration or continuity (The hiatus in service should last two or three months—until the cable lines are repaired .)
hierarchy
(n.) a system with ranked groups, usually according to social, economic, or professional class (Women found it very difficult to break into the upper ranks of the department's hierarchy.)
hypocrisy
(n.) pretending to believe what one does not (Once the politician began passing legislation that contradicted his campaign promises, his hypocrisy became apparent.)
hypothetical
(adj.) supposed or assumed true, but unproven (Even though it has been celebrated by seven major newspapers, that the drug will be a success when tested in humans is still hypothetical.)
iconoclast
(n.) one who attacks common beliefs or institutions (Jane goes to one protest after another, but she seems to be an iconoclast rather than an activist with a progressive agenda.)
idiosyncratic
(adj.) peculiar to one person; highly individualized (I know you had trouble with the last test, but because your mistakes were highly idiosyncratic, I'm going to deny your request that the class be given a new test.)
idolatrous
(adj.) excessively worshipping one object or person (Xena's idolatrous fawning over the band—following them on tour, starting their fan club, filming their documentary—is really beginning to get on my nerves.)
ignominious
(adj.) humiliating, disgracing (It was really ignominious to be kicked out of the dorm for having an illegal gas stove in my room.)
illicit
(adj.) forbidden, not permitted (The fourth-grader learned many illicit words from a pamphlet that was being passed around school.)
immerse
(v.) to absorb, deeply involve, engross (After breaking up with her boyfriend, Nancy decided to immerse herself in her work in order to avoid crying.)
immutable
(adj.) not changeable (The laws of physics are immutable and constant.)
impassive
(adj.) stoic, not susceptible to suffering (Stop being so impassive; it's healthy to cry every now and then.)
impeccable
(adj.) exemplary, flawless (If your grades were as impeccable as your sister's, then you too would receive a car for a graduation present.)
impecunious
(adj.) poor ("I fear he's too impecunious to take me out tonight," the bratty girl whined.)
imperative
1. (adj.) necessary, pressing (It is imperative that you have these folders organized by midday.) 2. (n.) a rule, command, or order (Her imperative to have the folders organized by midday was perceived as ridiculous by the others.).).)
implicate
(v.) to involve in an incriminating way, incriminate (Even though Tom wasn't present at the time of the shooting, he was implicated by the evidence suggesting that he had supplied the shooters with guns.)
implicit
(adj.) understood but not outwardly obvious, implied (I know Professor Smith didn't actually say not to write from personal experience, but I think such a message was implicit in her instruction to use scholarly sources.)
impregnable
(adj.) resistant to capture or penetration (Though the invaders used battering rams, catapults, and rain dances, the fortress proved impregnable and resisted all attacks.)
impudent
(adj.) casually rude, insolent, impertinent (The impudent young man looked the princess up and down and told her she was hot even though she hadn't asked him.)
impute
(v.) to ascribe, blame (The CEO imputed the many typos in the letter to his lazy secretary.)
inane
(adj.) silly and meaningless (Some films are so inane that the psychology of the characters makes absolutely no sense.)
inarticulate
(adj.) incapable of expressing oneself clearly through speech (Though he spoke for over an hour, the lecturer was completely inarticulate and the students had no idea what he was talking about.)
incarnate
1. (adj.) existing in the flesh, embodied (In the church pageant, I play the role of greed incarnate.) 2. (v.) to give human form to (The alien evaded detection by incarnating himself in a human form.).)
incessant
(adj.) unending (We wanted to go outside and play, but the incessant rain kept us indoors for two days.)
inchoate
(adj.) unformed or formless, in a beginning stage (The country's government is still inchoate and, because it has no great tradition, quite unstable.)
incisive
(adj.) clear, sharp, direct (The discussion wasn't going anywhere until her incisive comment allowed everyone to see what the true issues were.)
inclination
(n.) a tendency, propensity (Sarah has an inclination to see every foreign film she hears about, even when she's sure that she won't like it.)
incontrovertible
(adj.) indisputable (Only stubborn Tina would attempt to disprove the incontrovertible laws of physics.)
incorrigible
(adj.) incapable of correction, delinquent (You can buy Grandma nicotine gum all you want, but I think that after sixty-five years of smoking she's incorrigible.)
increment
(n.) an enlargement; the process of increasing(The workmen made the wall longer, increment by increment.)
incumbent
1. (n.) one who holds an office (The incumbent senator is already serving his fifth term.) 2. (adj.) obligatory (It is incumbent upon this organization to offer aid to all who seek it.)
indefatigable
(adj.) incapable of defeat, failure, decay (Even after traveling 62 miles, the indefatigable runner kept on moving.)
indigenous
(adj.) originating in a region (Some fear that these plants, which are not indigenous to the region, may choke out the vegetation that is native to the area.)
indigent
(adj.) very poor, impoverished (I would rather donate money to help the indigent population than to the park sculpture fund.)
indignation
(n.) anger sparked by something unjust or unfair (I resigned from the sorority because of my indignation at its hazing of new members.).)
inept
(adj.) not suitable or capable, unqualified (She proved how inept she was when she forgot three orders and spilled a beer in a customer's lap.)
inexorable
(adj.) incapable of being persuaded or placated (Although I begged for hours, Mom was inexorable and refused to let me stay out all night after the prom.)
inextricable
(adj.) hopelessly tangled or entangled (Unless I look at the solution manual, I have no way of solving this inextricable problem.)
infamy
(n.) notoriety, extreme ill repute (The infamy of his crime will not lessen as the decades pass.)
infusion
(n.) an injection of one substance into another; the permeation of one substance by another (The infusion of Eastern religion into Western philosophy created interesting new schools of thought.)
ingenious
(adj.) clever, resourceful (Her ingenious use of walnuts instead of the peanuts called for by the recipe was lauded by the other garden club members who found her cake delicious.)
ingenuous
(adj.) not devious; innocent and candid (He must have writers, but his speeches seem so ingenuous it's hard to believe he's not speaking from his own heart.)
inhibit
(v.) to prevent, restrain, stop (When I told you I needed the car last night, I certainly never meant to inhibit you from going out.)
inimical
(adj.) hostile, enemylike (I don't see how I could ever work for a company that was so cold and inimical to me during my interviews.).)
innate
(adj.) inborn, native, inherent (His incredible athletic talent is innate, he never trains, lifts weights, or practices.)
innocuous
(adj.) harmless, inoffensive (In spite of their innocuous appearance, these mushrooms are actually quite poisonous.)
innovate
(v.) to do something in an unprecedented way (Because of the stiff competition, the company knew it needed to pour a lot of energy into innovating new and better products.)
innuendo
(n.) an insinuation (During the debate, the politician made several innuendos about the sexual activities of his opponent.)
inoculate
(v.) to introduce a microorganism, serum, or vaccine into an organism in order to increase immunity to illness; to vaccinate (I've feared needles ever since I was inoculated against 37 diseases at age one; but I have also never been sick.)
inquisitor
(n.) one who inquires, especially in a hostile manner (The inquisitor was instructed to knock on every door in town in order to find the fugitive.)
insatiable
(adj.) incapable of being satisfied (My insatiable appetite for melons can be a real problem in the winter.).)
insipid
(adj.) dull, boring (The play was so insipid, I fell asleep halfway through.)
insolent
(adj.) rude, arrogant, overbearing (That celebrity is so insolent, making fun of his fans right to their faces.)
instigate
(v.) to urge, goad (The demagogue instigated the crowd into a fury by telling them that they had been cheated by the federal government.)
insular
(adj.) separated and narrow-minded; tight-knit, closed off (Because of the sensitive nature of their jobs, those who work for the CIA must remain insular and generally only spend time with each other.)
insurgent
(n.) one who rebels (The insurgent snuck into and defaced a different classroom each night until the administration agreed to meet his demands.)
integral
(adj.) necessary for completeness (Without the integral ingredient of flour, you wouldn't be able to make bread.)
interject
(v.) to insert between other things (During our conversation, the cab driver occasionally interjected his opinion.)
interlocutor
(n.) someone who participates in a dialogue or conversation (When the officials could not come to an agreement over the correct cover of the flags, the prime minister acted as an interlocutor.)
interminable
(adj.) without possibility of end (The fact that biology lectures came just before lunch made them seem interminable.)
intimation
(n.) an indirect suggestion (Mr. Brinford's intimation that he would soon pass away occurred when he began to discuss how to distribute his belongings among his children.)
intractable
(adj.) difficult to manipulate, unmanageable (There was no end in sight to the intractable conflict between the warring countries.)
intransigent
(adj.) refusing to compromise, often on an extreme opinion (The intransigent child said he would have 12 scoops of ice cream, or he would bang his head against the wall until his mother fainted from fear.)
intrepid
(adj.) brave in the face of danger (After scaling a live volcano prior to its eruption, the explorer was praised for his intrepid attitude.)
inundate
(v.) to flood with abundance (Because I am the star of a new sitcom, my fans are sure to inundate me with fan mail and praise.).)
inviolable
(adj.) secure from assault (Nobody was ever able to break into Batman's inviolable Batcave.)
irascible
(adj.) easily angered (At the smallest provocation, my irascible cat will begin scratching and clawing.)
iridescent
(adj.) showing rainbow colors (The bride's large diamond ring was iridescent in the afternoon sun.)
irreverence
(n.) disrespect (The irreverence displayed by the band that marched through the chapel disturbed many churchgoers.)
irrevocable
(adj.) incapable of being taken back (The Bill of Rights is an irrevocable part of American law.)
jubilant
(adj.) extremely joyful, happy (The crowd was jubilant when the firefighter carried the woman from the flaming building.)
judicious
(adj.) having or exercising sound judgment (When the judicious king decided to compromise rather than send his army to its certain death, he was applauded.)
juxtaposition
(n.) the act of placing two things next to each other for implicit comparison (The interior designer admired my juxtaposition of the yellow couch and green table.)
knell
(n.) the solemn sound of a bell, often indicating a death (Echoing throughout our village, the funeral knell made the stormy day even more grim.)
kudos
(n.) praise for an achievement (After the performance, the reviewers gave the opera singer kudos for a job well done.)
laceration
(n.) a cut, tear (Because he fell off his bike into a rosebush, the paperboy's skin was covered with lacerations.)
laconic
(adj.) terse in speech or writing (The author's laconic style has won him many followers who dislike wordiness.)
languid
(adj.) sluggish from fatigue or weakness (In the summer months, the great heat makes people languid and lazy.)
larceny
(n.) obtaining another's property by theft or trickery (When my car was not where I had left it, I realized that I was a victim of larceny.)
largess
(n.) the generous giving of lavish gifts (My boss demonstrated great largess by giving me a new car.)
latent
(adj.) hidden, but capable of being exposed (Sigmund's dream represented his latent paranoid obsession with other people's shoes.)
laudatory
(adj.) expressing admiration or praise (Such laudatory comments are unusual from someone who is usually so reserved in his opinions.)
lavish
1. (adj.) given without limits (Because they had worked very hard, the performers appreciated the critic's lavish praise.) 2. (v.) to give without limits (Because the performers had worked hard, they deserved the praise that the critic lavished on them.)
legerdemain
(n.) deception, slight-of-hand (Smuggling the French plants through customs by claiming that they were fake was a remarkable bit of legerdemain.)
lenient
(adj.) demonstrating tolerance or gentleness (Because Professor Oglethorpe allowed his students to choose their final grades, the other teachers believed that he was excessively lenient.)
lethargic
(adj.) in a state of sluggishness or apathy (When Jean Claude explained to his boss that he was lethargic and didn't feel like working that day, the boss fired him.).)
libertarian
(adj.) advocating principles of liberty and free will (The dissatisfied subjects overthrew the monarch and replaced him with a libertarian ruler who respected their democratic principles.)
licentious
(adj.) displaying a lack of moral or legal restraints (Marilee has always been fascinated by the licentious private lives of politicians.)
limpid
(adj.) clear, transparent (Mr. Johnson's limpid writing style greatly pleased readers who disliked complicated novels.)
linchpin
(n.) something that holds separate parts together (The linchpin in the prosecution's case was the hair from the defendant's head, which was found at the scene of the crime.)
lithe
(adj.) graceful, flexible, supple (Although the dancers were all outstanding, Jae Sun's control of her lithe body was particularly impressive.)
litigant
(n.) someone engaged in a lawsuit (When the litigants began screaming at each other, Judge Koch ordered them to be silent.)
lucid
(adj.) clear, easily understandable (Because Guenevere's essay was so lucid, I only had to read it once to understand her reasoning.)
luminous
(adj.) brightly shining (The light of the luminous moon graced the shoulders of the beautiful maiden.)
lurid
(adj.) ghastly, sensational (Gideon's story, in which he described a character torturing his sister's dolls, was judged too lurid to be printed in the school's literary magazine.).)
malleable
(adj.) capable of being shaped or transformed (Maximillian's political opinions were so malleable that anyone he talked to was able to change his mind instantly.)
mandate
(n.) an authoritative command (In the Old Testament, God mandates that no one should steal.)
manifest
1. (adj.) easily understandable, obvious (When I wrote the wrong sum on the chalkboard, my mistake was so manifest that the entire class burst into laughter.) 2. (v.) to show plainly (His illness first manifested itself with particularly violent hiccups.)
manifold
(adj.) diverse, varied (The popularity of Dante's Inferno is partly due to the fact that the work allows for manifold interpretations.)
maudlin
(adj.) weakly sentimental (Although many people enjoy romantic comedies, I usually find them maudlin and shallow.)
maverick
(n.) an independent, nonconformist person (Andreas is a real maverick and always does things his own way.)
mawkish
(adj.) characterized by sick sentimentality (Although some nineteenth- century critics viewed Dickens's writing as mawkish, contemporary readers have found great emotional depth in his works.)
maxim
(n.) a common saying expressing a principle of conduct (Miss Manners's etiquette maxims are both entertaining and instructional.)
meager
(adj.) deficient in size or quality (My meager portion of food did nothing to satisfy my appetite.)
medley
(n.) a mixture of differing things (Susannah's wardrobe contained an astonishing medley of colors, from olive green to fluorescent pink.).)
meritorious
(adj.) worthy of esteem or reward (Manfred was given the congressional medal of honor for his meritorious actions.)
metamorphosis
(n.) the change of form, shape, substance (Winnifred went to the gym every day for a year and underwent a metamorphosis from a waiflike girl to an athletic woman.)
meticulous
(adj.) extremely careful with details (The ornate needlework in the bride's gown was a product of meticulous handiwork.)
mitigate
(v.) to make less violent, alleviate (When I had an awful sore throat, only warm tea would mitigate the pain.)
moderate
1. (adj.) not extreme (Luckily, the restaurant we chose had moderate prices; none of us have any money.) 2. (n.) one who expresses moderate opinions (Because he found both the liberal and conservative proposals too excessive, Mr. Park sided with the moderates.)
modicum
(n.) a small amount of something (Refusing to display even a modicum of sensitivity, Henrietta announced her boss's affair in front of the entire office.)
modulate
(v.) to pass from one state to another, especially in music (The composer wrote a piece that modulated between minor and major keys.)
mollify
(v.) to soften in temper (The police officer mollified the angry woman by giving her a warning instead of a ticket.)
morass
(n.) a wet swampy bog; figuratively, something that traps and confuses (When Theresa lost her job, she could not get out of her financial morass.)
mores
(n.) the moral attitudes and fixed customs of a group of people. (Mores change over time; many things that were tolerated in 1975 are no longer seen as being socially acceptable.)
morose
(adj.) gloomy or sullen (Jason's morose nature made him very unpleasant to talk to.)
multifarious
(adj.) having great diversity or variety (This Swiss Army knife has multifarious functions and capabilities. Among other things, it can act as a knife, a saw, a toothpick, and a slingshot.)
mundane
(adj.) concerned with the world rather than with heaven, commonplace (He is more concerned with the mundane issues of day-to-day life than with spiritual topics.)
munificence
(n.) generosity in giving (The royal family's munificence made everyone else in their country rich.)
mutable
(adj.) able to change (Because fashion is so mutable, what is trendy today will look outdated in five years.)
myriad
(adj.) consisting of a very great number (It was difficult to decide what to do Friday night because the city presented us with myriad possibilities for fun.).)
nebulous
(adj.) vaguely defined, cloudy (The transition between governments meant that who was actually in charge was a nebulous matter.)
nefarious
(adj.) heinously villainous (Although Dr. Meanman's nefarious plot to melt the polar icecaps was terrifying, it was so impractical that nobody really worried about it.)
negligent
(adj.) habitually careless, neglectful (Jessie's grandfather called me a negligent fool after I left the door to his apartment unlocked even though there had been a recent string of robberies.)
neophyte
(n.) someone who is young or inexperienced (As a neophyte in the literary world, Malik had trouble finding a publisher for his first novel.)
nocturnal
(adj.) relating to or occurring during the night (Jackie was a nocturnal person; she would study until dawn and sleep until the evening.)
noisome
(adj.) unpleasant, offensive, especially to the sense of smell (Nobody would enter the stalls until the horse's noisome leavings were taken away.)
nomadic
(adj.) wandering from place to place (In the first six months after college, Jose led a nomadic life, living in New York, California, and Idaho.)
nominal
(adj.) trifling, insignificant (Because he was moving the following week and needed to get rid of his furniture more than he needed money, Jordan sold everything for a nominal fee.)
nonchalant
(adj.) having a lack of concern, indifference (Although deep down she was very angry, Marsha acted in a nonchalant manner when she found out that her best friend had used her clothing without asking.)
nondescript
(adj.) lacking a distinctive character (I was surprised when I saw the movie star in person because she looked nondescript.)
notorious
(adj.) widely and unfavorably known (Jacob was notorious for always arriving late at parties.)
novice
(n.) a beginner, someone without training or experience (Because we were all novices at yoga, our instructor decided to begin with the basics.)
noxious
(adj.) harmful, unwholesome (Environmentalists showed that the noxious weeds were destroying the insects' natural habitats.)
nuance
(n.) a slight variation in meaning, tone, expression (The nuances of the poem were not obvious to the casual reader, but the professor was able to point them out.)
nurture
(v.) to assist the development of (Although Serena had never watered the plant, which was about to die, Javier was able to nurture it back to life.)
obdurate
(adj.) unyielding to persuasion or moral influences (The obdurate old man refused to take pity on the kittens.)
obfuscate
(v.) to render incomprehensible (The detective did want to answer the newspaperman's questions, so he obfuscated the truth.)
oblique
(adj.) diverging from a straight line or course, not straightforward (Martin's oblique language confused those who listened to him.)
oblivious
(adj.) lacking consciousness or awareness of something (Oblivious to the burning smell emanating from the kitchen, my father did not notice that the rolls in the oven were burned until much too late.)
obscure
(adj.) unclear, partially hidden (Because he was standing in the shadows, his features were obscure.)
obsequious
(adj.) excessively compliant or submissive (Mark acted like Janet's servant, obeying her every request in an obsequious manner.)
obsolete
(adj.) no longer used, out of date (With the inventions of tape decks and CDs, which both have better sound and are easier to use, eight-track players are now entirely obsolete.)
obstinate
(adj.) not yielding easily, stubborn (The obstinate child refused to leave the store until his mother bought him a candy bar.).)
ominous
(adj.) foreboding or foreshadowing evil (The fortuneteller's ominous words flashed through my mind as the hooded figure approached me in the alley.)
onerous
(adj.) burdensome (My parents lamented that the pleasures of living in a beautiful country estate no longer outweighed the onerous mortgage payments.)
opulent
(adj.) characterized by rich abundance verging on ostentation (The opulent furnishings of the dictator's private compound contrasted harshly with the meager accommodations of her subjects.)
oration
(n.) a speech delivered in a formal or ceremonious manner (The prime minister was visibly shaken when the unruly parliament interrupted his oration about failed domestic policies.)
ornate
(adj.) highly elaborate, excessively decorated (The ornate styling of the new model of luxury car could not compensate for the poor quality of its motor.)
orthodox
(adj.) conventional, conforming to established protocol (The company's profits dwindled because the management pursued orthodox business policies that were incompatible with new industrial trends.)
oscillate
(v.) to sway from one side to the other (My uncle oscillated between buying a station wagon to transport his family and buying a sports car to satisfy his boyhood fantasies.)
ostensible
(adj.) appearing as such, seemingly (Jack's ostensible reason for driving was that airfare was too expensive, but in reality, he was afraid of flying.)
ostentatious
(adj.) excessively showy, glitzy (On the palace tour, the guide focused on the ostentatious decorations and spoke little of the royal family's history.)
ostracism
(n.) exclusion from a group (Beth risked ostracism if her roommates discovered her flatulence.)
pacific
(adj.) soothing (The chemistry professor's pacific demeanor helped the class remain calm after the experiment exploded.)
palatable
(adj.) agreeable to the taste or sensibilities (Despite the unpleasant smell, the exotic cheese was quite palatable.)
palette
(adj.) a range of colors or qualities (The palette of colors utilized in the painting was equaled only by the range of intense emotions the piece evoked.).)
paradigm
(n.) an example that is a perfect pattern or model (Because the new SUV was so popular, it became the paradigm upon which all others were modeled.)
paradox
(n.) an apparently contradictory statement that is perhaps true (The diplomat refused to acknowledge the paradox that negotiating a peace treaty would demand more resources than waging war.)
paragon
(n.) a model of excellence or perfection (The mythical Helen of Troy was considered a paragon of female beauty.)
paramount
(adj.) greatest in importance, rank, character (It was paramount that the bomb squad disconnect the blue wire before removing the fuse.)
pariah
(n.) an outcast (Following the discovery of his plagiarism, Professor Hurley was made a pariah in all academic circles.)
parody
(n.) a satirical imitation (A hush fell over the classroom when the teacher returned to find Deborah acting out a parody of his teaching style.)
parsimony
(n.) frugality, stinginess (Many relatives believed that my aunt's wealth resulted from her parsimony.)
partisan
(n.) a follower, adherent (The king did not believe that his rival could round up enough partisans to overthrow the monarchy.)
patent
(adj.) readily seen or understood, clear (The reason for Jim's abdominal pain was made patent after the doctor performed a sonogram.)
pathology
(n.) a deviation from the normal (Dr. Hastings had difficulty identifying the precise nature of Brian's pathology.).)
penchant
(n.) a tendency, partiality, preference (Jill's dinner parties quickly became monotonous on account of her penchant for Mexican dishes.)
penitent
(adj.) remorseful, regretful (The jury's verdict may have been more lenient if the criminal had appeared penitent for his gruesome crimes.)
penultimate
(adj.) next to last (Having smoked the penultimate cigarette remaining in the pack, Cybil discarded the last cigarette and resolved to quit smoking.).)
permeate
(v.) to spread throughout, saturate (Mrs. Huxtable was annoyed that the wet dog's odor had permeated the furniture's upholstery.)
pernicious
(adj.) extremely destructive or harmful (The new government feared that the Communist sympathizers would have a pernicious influence on the nation's stability.)
perplex
(v.) to confuse (Brad was perplexed by his girlfriend's suddenly distant manner.)
perspicacity
(adj.) shrewdness, perceptiveness (The detective was too humble to acknowledge that his perspicacity was the reason for his professional success.)
pert
(adj.) flippant, bold (My parents forgave Sandra's pert humor at the dinner table because it had been so long since they had last seen her.).)
pervasive
(adj.) having the tendency to spread throughout (Stepping off the plane in Havana, I recognized the pervasive odor of sugar cane fields on fire.)
petulance
(n.) rudeness, irritability (The Nanny resigned after she could no longer tolerate the child's petulance.)
philanthropic
(adj.) charitable, giving (Many people felt that the billionaire's decision to donate her fortune to house the homeless was the ultimate philanthropic act.)
phlegmatic
(adj.) uninterested, unresponsive (Monique feared her dog was ill after the animal's phlegmatic response to his favorite chew toy.)
pillage
(v.) to seize or plunder, especially in war (Invading enemy soldiers pillaged the homes scattered along the country's border.)
pinnacle
(n.) the highest point (Book reviewers declared that the author's new novel was extraordinary and probably the pinnacle of Western literature.)
pithy
(adj.) concisely meaningful (My father's long-winded explanation was a stark contrast to his usually pithy statements.)
pittance
(n.) a very small amount, especially relating to money (Josh complained that he was paid a pittance for the great amount of work he did at the firm.)
placate
(v.) to ease the anger of, soothe (The man purchased a lollipop to placate his irritable son.)
placid
(adj.) calm, peaceful (The placid lake surface was as smooth as glass.)
platitude
(n.) an uninspired remark, cliché (After reading over her paper, Helene concluded that what she thought were profound insights were actually just platitudes.)
plaudits
(n.) enthusiastic approval, applause (The controversial new film received plaudits from even the harshest critics.)
plausible
(adj.) believable, reasonable (He studied all the data and then came up with a plausible theory that took all factors into account.)
plenitude
(n.) an abundance (My grandmother was overwhelmed by the plenitude of tomatoes her garden yielded this season.)
plethora
(n.) an abundance, excess (The wedding banquet included a plethora of oysters piled almost three feet high.)
pliable
(adj.) flexible (Aircraft wings are designed to be somewhat pliable so they do not break in heavy turbulence.)
poignant
(adj.) deeply affecting, moving (My teacher actually cried after reading to us the poignant final chapter of the novel.).)
potable
(adj.) suitable for drinking (During sea voyages it is essential that ships carry a supply of potable water because salty ocean water makes anyone who drinks it sick.)
potentate
(n.) one who has great power, a ruler (All the villagers stood along the town's main road to observe as the potentate's procession headed towards the capital.)
pragmatic
(adj.) practical (The politician argued that while increased security measures might not fit with the lofty ideals of the nation, they were a pragmatic necessity to ensure everyone's safety.)
precipice
(n.) the face of a cliff, a steep or overhanging place (The mountain climber hung from a precipice before finding a handhold and pulling himself up.)
preclude
(v.) to prevent (My grandfather's large and vicious guard dog precluded anyone from entering the yard.)
precocious
(adj.) advanced, developing ahead of time (Derek was so academically precocious that by the time he was 10 years old, he was already in the ninth grade.)
predilection
(n.) a preference or inclination for something (Francois has a predilection for eating scrambled eggs with ketchup, though I prefer to eat eggs without any condiments.)
preponderance
(adj.) superiority in importance or quantity (Britain's preponderance of naval might secured the nation's role as a military power.)
prepossessing
(adj.) occupying the mind to the exclusion of other thoughts or feelings (His prepossessing appearance made it impossible for me to think of anything else.)
presage
(n.) an omen (When my uncle's old war injury ached, he interpreted it as a presage of bad weather approaching.)
prescient
(adj.) to have foreknowledge of events (Questioning the fortune cookie's prediction, Ray went in search of the old hermit who was rumored to be prescient.)
prescribe
(v.) to lay down a rule (The duke prescribed that from this point further all of the peasants living on his lands would have to pay higher taxes.)
presumptuous
(adj.) disrespectfully bold (The princess grew angry after the presumptuous noble tried to kiss her, even though he was far below her in social status.)
pretense
(n.)an appearance or action intended to deceive (Though he actually wanted to use his parents' car to go on a date, Nick borrowed his parents' car under the pretense of attending a group study session.)
primeval
(adj.) original, ancient (The first primates to walk on two legs, called Australopithecus, were the primeval descendants of modern man.)
privation
(n.) lacking basic necessities (After decades of rule by an oppressive government that saw nothing wrong with stealing from its citizens, the recent drought only increased the people's privation.).)
procure
(v.) to obtain, acquire (The FBI was unable to procure sufficient evidence to charge the gangster with racketeering.)
profane
(adj.) lewd, indecent (Jacob's profane act of dumping frogs in the holy water in the chapel at his boarding school resulted in his dismissal.)
profligate
(adj.) dissolute, extravagant (The profligate gambler loved to drink, spend money, steal, cheat, and hang out with prostitutes.)
profuse
(adj.) plentiful, abundant (The fans were profuse in their cheers for the star basketball player.)
promulgate
(v.) to proclaim, make known (The film professor promulgated that both in terms of sex appeal and political intrigue, Sean Connery's James Bond was superior to Roger Moore's.)
propagate
(v.) to multiply, spread out (Rumors of Paul McCartney's demise propagated like wildfire throughout the world.)
propensity
(n.) an inclination, preference (Dermit has a propensity for dangerous activities such as bungee jumping.)
propitious
(adj.) favorable (The dark storm clouds visible on the horizon suggested that the weather would not be propitious for sailing.)
propriety
(n.) the quality or state of being proper, decent (Erma's old-fashioned parents believed that her mini-skirt lacked the propriety expected of a "nice" girl.).)
prowess
(n.) extraordinary ability (The musician had never taken a guitar lesson in his life, making his prowess with the instrument even more incredible.)
prudence
(n.) cautious, circumspect (After losing a fortune in a stock market crash, my father vowed to practice greater prudence in future investments.).)
pungent
(adj.) having a pointed, sharp quality—often used to describe smells (The pungent odor in the classroom made Joseph lose his concentration during the test.)
punitive
(adj.) involving punishment (If caught smoking in the boys' room, the punitive result is immediate expulsion from school.)
putrid
(adj.) rotten, foul (Those rotten eggs smell putrid.) Q
quagmire
(n.) a difficult situation (We'd all like to avoid the kind of military quagmire characterized by the Vietnam War.)
quaint
(adj.) charmingly old-fashioned (Hilda was delighted by the quaint bonnets she saw in Amish country.).)
quixotic
(adj.) idealistic, impractical (Edward entertained a quixotic desire to fall in love at first sight in a laundromat.)
quotidian
(adj.) daily (Ambika's quotidian routines include drinking two cups of coffee in the morning.)
rail
(v.) to scold, protest (The professor railed against the injustice of the college's tenure policy.)
rancid
(adj.) having a terrible taste or smell (Rob was double-dog-dared to eat the rancid egg salad sandwich.)
rancor
(n.) deep, bitter resentment (When Eileen challenged me to a fight, I could see the rancor in her eyes.)
rapport
(n.) mutual understanding and harmony (When Margaret met her paramour, they felt an instant rapport.)
rash
(adj.) hasty, incautious (It's best to think things over calmly and thoroughly, rather than make rash decisions.)
raucous
(adj.) loud, boisterous (Sarah's neighbors called the cops when her house party got too raucous.)
raze
(v.) to demolish, level (The old tenement house was razed to make room for the large chain store.).)
recapitulate
(v.) to sum up, repeat (Before the final exam, the teacher recapitulated the semester's material.)
reciprocate
(v.) to give in return (When Steve gave Samantha a sweater for Christmas, she reciprocated by giving him a kiss.)
reclusive
(adj.) solitary, shunning society (Reclusive authors such as J.D. Salinger do not relish media attention and sometimes even enjoy holing up in remote cabins in the woods.)
reconcile
1. (v.) to return to harmony (The feuding neighbors finally reconciled when one brought the other a delicious tuna noodle casserole.) 2. (v.) to make consistent with existing ideas (Alou had to reconcile his skepticism about the existence of aliens with the fact that he was looking at a flying saucer.)
rectitude
(n.) uprightness, extreme morality (The priest's rectitude gave him the moral authority to counsel his parishioners.)
redoubtable
1. (adj.) formidable (The fortress looked redoubtable set against a stormy sky.) 2. (adj.) commanding respect (The audience greeted the redoubtable speaker with a standing ovation.)
refract
(v.) to distort, change (The light was refracted as it passed through the prism.)
refurbish
(v.) to restore, clean up (The dingy old chair, after being refurbished, commanded the handsome price of $200.)
refute
(v.) to prove wrong (Maria refuted the president's argument as she yelled and gesticulated at the TV.)
regurgitate
1. (v.) to vomit (Feeling sick, Chuck regurgitated his dinner.) 2. (v.) to throw back exactly (Margaret rushed through the test, regurgitating all of the facts she'd memorized an hour earlier.).)
relish
(v.) to enjoy (Pete always relished his bedtime snack.)
remedial
(adj.) intended to repair gaps in students' basic knowledge (After his teacher discovered he couldn't read, Alex was forced to enroll in remedial English.)
remiss
(adj.) negligent, failing to take care (The burglar gained entrance because the security guard, remiss in his duties, forgot to lock the door.)
renovate
1. (v.) restore, return to original state (The renovated antique candelabra looked as good as new.) 2. (v.) to enlarge and make prettier, especially a house (After getting renovated, the house was twice as big and much more attractive.)
renown
(n.) honor, acclaim (The young writer earned international renown by winning the Pulitzer Prize.)
renunciation
(n.) to reject (Fiona's renunciation of red meat resulted in weight loss, but confused those people who thought she'd been a vegetarian for years.)
repentant
(adj.) penitent, sorry (The repentant Dennis apologized profusely for breaking his mother's vase.)
replete
(adj.) full, abundant (The unedited version was replete with naughty words.)
repose
(v.) to rest, lie down (The cat, after eating an entire can of tuna fish, reposed in the sun and took a long nap.)
reprehensible
(adj.) deserving rebuke (Jean's cruel and reprehensible attempt to dump her boyfriend on his birthday led to tears and recriminations.)
reprieve
(n.) a temporary delay of punishment (Because the governor woke up in a particularly good mood, he granted hundreds of reprieves to prisoners.)
reproach
(v.) to scold, disapprove (Brian reproached the customer for failing to rewind the video he had rented.).)
repulse
1. (v.) to disgust (Antisocial Annie tried to repulse people by neglecting to brush her teeth.) 2. (v.) to push back (With a deft movement of her wrist and a punch to the stomach, Lacy repulsed Jack's attempt to kiss her.)
reputable
(adj.) of good reputation (After the most reputable critic in the industry gave the novel a glowing review, sales took off.)
requisition
(n.) a demand for goods, usually made by an authority (During the war, the government made a requisition of supplies.)
rescind
(v.) to take back, repeal (The company rescinded its offer of employment after discovering that Jane's resume was full of lies.).)
resilient
(adj.) able to recover from misfortune; able to withstand adversity (The resilient ballplayer quickly recovered from his wrist injury.)
resolute
(adj.) firm, determined (With a resolute glint in her eye, Catherine announced that she was set on going to college in New York City even though she was a little frightened of tall buildings.)
resolve
1. (v.) to find a solution (Sarah and Emma resolved their differences and shook hands.) 2. (v.) to firmly decide (Lady Macbeth resolved to whip her husband into shape.)
respite
(n.) a break, rest (Justin left the pub to gain a brief respite from the smoke and noise.)
resplendent
(adj.) shiny, glowing (The partygoers were resplendent in diamonds and fancy dress.)
restitution
(n.) restoration to the rightful owner (Many people feel that descendants of slaves should receive restitution for the sufferings of their ancestors.)
restive
(adj.) resistant, stubborn, impatient (The restive audience pelted the band with mud and yelled nasty comments.)
retract
(v.) withdraw (As the media worked itself into a frenzy, the publicist hurriedly retracted his client's sexist statement.)
revel
(v.) to enjoy intensely (Theodore reveled in his new status as Big Man on Campus.)
revere
(v.) to esteem, show deference, venerate (The doctor saved countless lives with his combination of expertise and kindness and became universally revered.)
revoke
(v.) to take back (After missing the curfew set by the court for eight nights in a row, Marcel's freedom of movement was revoked.)
rhapsodize
(v.) to engage in excessive enthusiasm (The critic rhapsodized about the movie, calling it an instant classic.)
ribald
(adj.) coarsely, crudely humorous (While some giggled at the ribald joke involving a parson's daughter, most sighed and rolled their eyes.)
rife
(adj.) abundant (Surprisingly, the famous novelist's writing was rife with spelling errors.)
ruminate
(v.) to contemplate, reflect (Terry liked to ruminate while sitting on the banks of the river, staring pensively into the water.)
ruse
(n.) a trick (Oliver concocted an elaborate ruse for sneaking out of the house to meet his girlfriend while simultaneously giving his mother the impression that he was asleep in bed.)
saccharine
(adj.) sickeningly sweet (Tom's saccharine manner, although intended to make him popular, actually repelled his classmates.).)
salutation
(n.) a greeting (Andrew regularly began letters with the bizarre salutation "Ahoy ahoy.")
salve
(n.) a soothing balm (After Tony applied a salve to his brilliant red sunburn, he soon felt a little better.)!")
satiate
(v.) to satisfy excessively (Satiated after eating far too much turkey and stuffing, Liza lay on the couch watching football and suffering from stomach pains.)
scathing
(adj.) sharp, critical, hurtful (Two hours after breaking up with Russell, Suzanne thought of the perfect scathing retort to his accusations.)
scintillating
(adj.) sparkling (The ice skater's scintillating rhinestone costume nearly blinded the judges.)
scrupulous
(adj.) painstaking, careful (With scrupulous care, Sam cut a snowflake out of white paper.)
scurrilous
(adj.) vulgar, coarse (When Bruno heard the scurrilous accusation being made about him, he could not believe it because he always tried to be nice to everyone.)
sedentary
(adj.) sitting, settled (The sedentary cat did little but loll in the sun.)
semaphore
(n.) a visual signal (Anne and Diana communicated with a semaphore involving candles and window shades.)
seminal
(adj.) original, important, creating a field (Stephen Greenblatt's essays on Shakespeare proved to be seminal, because they initiated the critical school of New Historicism.)
sensual
(adj.) involving sensory gratification, usually related to sex (With a coy smile, the guest on the blind-date show announced that he considered himself a very sensual person.)
sensuous
(adj.) involving sensory gratification (Paul found drinking Coke, with all the little bubbles bursting on his tongue, a very sensuous experience.)
serendipity
(n.) luck, finding good things without looking for them (In an amazing bit of serendipity, penniless Paula found a $20 bill in the subway station.)
serene
(adj.) calm, untroubled (Louise stood in front of the Mona Lisa, puzzling over the famous woman's serene smile.)
servile
(adj.) subservient (The servile porter crept around the hotel lobby, bowing and quaking before the guests.)
sinuous
(adj.) lithe, serpentine (With the sinuous movements of her arms, the dancer mimicked the motion of a snake.)
sobriety
(n.) sedate, calm (Jason believed that maintaining his sobriety in times of crisis was the key to success in life.).)
soluble
(adj.) able to dissolve (The plot of the spy film revolved around an untraceable and water-soluble poison.)
solvent
1. (n.) a substance that can dissolve other substances (Water is sometimes called the universal solvent because almost all other substances can dissolve into it.) 2. (adj.) able to pay debts (Upon receiving an unexpected check from her aunt, Annabelle found herself suddenly solvent.)
somnolent
(adj.) sleepy, drowsy (The somnolent student kept falling asleep and waking up with a jerk.)
sophomoric
(adj.) immature, uninformed (The mature senior rolled her eyes at the sophomoric gross-out humor of the underclassman.)
sovereign
(adj.) having absolute authority in a certain realm (The sovereign queen, with steely resolve, ordered that the traitorous nobleman be killed.)
speculative
(adj.) not based in fact (Sadly, Tessa was convicted on merely speculative evidence.)
spurious
(adj.) false but designed to seem plausible (Using a spurious argument, John convinced the others that he had won the board game on a technicality.)
stagnate
(v.) to become or remain inactive, not develop, not flow (With no room for advancement, the waiter's career stagnated.)
staid
(adj.) sedate, serious, self-restrained (The staid butler never changed his expression no matter what happened.)
stingy
(adj.) not generous, not inclined to spend or give (Scrooge's stingy habits did not fit with the generous, giving spirit of Christmas.)
stoic
(adj.) unaffected by passion or feeling (Penelope's faithfulness to Odysseus required that she be stoic and put off her many suitors.)
stolid
(adj.) expressing little sensibility, unemotional (Charles's stolid reaction to his wife's funeral differed from the passion he showed at the time of her death.)
strenuous
(adj.) requiring tremendous energy or stamina (Running a marathon is quite a strenuous task. So is watching an entire Star Trek marathon.)
strident
(adj.) harsh, loud (A strident man, Captain Von Trapp yelled at his daughter and made her cry.)
stupefy
(v.) to astonish, make insensible (Veronica's audacity and ungratefulness stupefied her best friend, Heather.)
subjugate
(v.) to bring under control, subdue (The invading force captured and subjugated the natives of that place.)
sublime
(adj.) lofty, grand, exalted (The homeless man sadly pondered his former wealth and once sublime existence.)
submissive
(adj.) easily yielding to authority (In some cultures, wives are supposed to be submissive and support their husbands in all matters.)
succinct
(adj.) marked by compact precision (The governor's succinct speech energized the crowd while the mayor's rambled on and on.)
superfluous
(adj.) exceeding what is necessary (Tracy had already won the campaign so her constant flattery of others was superfluous.).)
surrogate
(n.) one acting in place of another (The surrogate carried the child to term for its biological parents.)
swarthy
(adj.) of dark color or complexion (When he got drunk, Robinson's white skin became rather swarthy.).)
taciturn
(adj.) not inclined to talk (Though Jane never seems to stop talking, her brother is quite taciturn.)
tangential
(adj.) incidental, peripheral, divergent (I tried to discuss my salary, but the boss kept veering off into tangential topics.)
tantamount
(adj.) equivalent in value or significance (When it comes to sports, fearing your opponent is tantamount to losing.)
tedious
(adj.) dull, boring (As time passed and the history professor continued to drone on and on, the lecture became increasingly tedious.)
temerity
(n.) audacity, recklessness (Tom and Huck entered the scary cave armed with nothing but their own temerity.)
temperance
(n.) moderation in action or thought (Maintaining temperance will ensure that you are able to think rationally and objectively.)
tenable
(adj.) able to be defended or maintained (The department heads tore down the arguments in other people's theses, but Johari's work proved to be quite tenable.)
tenuous
(adj.) having little substance or strength (Your argument is very tenuous, since it relies so much on speculation and hearsay.)
terrestrial
(adj.) relating to the land (Elephants are terrestrial animals.)
timorous
(adj.) timid, fearful (When dealing with the unknown, timorous Tallulah almost always broke into tears.)
tirade
(n.) a long speech marked by harsh or biting language (Every time Jessica was late, her boyfriend went into a long tirade about punctuality.)
toady
(n.) one who flatters in the hope of gaining favors (The other kids referred to the teacher's pet as the Tenth Grade Toady.)
tome
(n.) a large book (In college, I used to carry around an anatomy book that was the heaviest tome in my bag.)
torpid
(adj.) lethargic, dormant, lacking motion (The torpid whale floated, wallowing in the water for hours.)
torrid
(adj.) giving off intense heat, passionate (I didn't want to witness the neighbor's torrid affair through the window.)
tortuous
(adj.) winding (The scary thing about driving in mountains are the narrow, tortuous roads.)
tractable
(adj.) easily controlled (The horse was so tractable, Myra didn't even need a bridle.)
tranquil
(adj.) calm (There is a time of night when nothing moves and everything is tranquil.)
transgress
(v.) to violate, go over a limit (The criminal's actions transgressed morality and human decency.).)
travesty
(n.) a grossly inferior imitation (According to the school newspaper's merciless theater critic, Pacific Coast High's rendition of the musical Oklahoma was a travesty of the original.)
tremulous
(adj.) fearful (I always feel a trifle tremulous when walking through a graveyard.)
trenchant
(adj.) effective, articulate, clear-cut (The directions that accompanied my new cell phone were trenchant and easy to follow.)
trepidation
(n.) fear, apprehension (Feeling great trepidation, Anya refused to jump into the pool because she thought she saw a shark in it.)
trite
(adj.) not original, overused (Keith thought of himself as being very learned, but everyone else thought he was trite because his observations about the world were always the same as David Letterman's.)
truculent
(adj.) ready to fight, cruel (This club doesn't really attract the dangerous types, so why was that bouncer being so truculent?)
truncate
(v.) to shorten by cutting off (After winning the derby, the jockey truncated the long speech he had planned and thanked only his mom and his horse.).)
ubiquitous
(adj.) existing everywhere, widespread (It seems that everyone in the United States has a television. The technology is ubiquitous here.)
umbrage
(n.) resentment, offense (He called me a lily-livered coward, and I took umbrage at the insult.)
uncanny
(adj.) of supernatural character or origin (Luka had an uncanny ability to know exactly what other people were thinking. She also had an uncanny ability to shoot fireballs from her hands.).)
utilitarian
(adj.) relating to or aiming at usefulness (The beautiful, fragile vase couldn't hold flowers or serve any other utilitarian purpose.)
utopia
(n.) an imaginary and remote place of perfection (Everyone in the world wants to live in a utopia, but no one can agree how to go about building one.).)
validate
(v.) to confirm, support, corroborate (Yoko's chemistry lab partner was asleep during the experiment and could not validate the accuracy of her methods.).)
vehemently
(adv.) marked by intense force or emotion (The candidate vehemently opposed cutting back on Social Security funding.)
veneer
(n.) a superficial or deceptively attractive appearance, façade (Thanks to her Chanel makeup, Shannen was able to maintain a veneer of perfection that hid the flaws underneath.)
venerable
(adj.) deserving of respect because of age or achievement (The venerable Supreme Court justice had made several key rulings in landmark cases throughout the years.).)
verbose
(adj.) wordy, impaired by wordiness (It took the verbose teacher two hours to explain the topic, while it should have taken only fifteen minutes.)
verdant
(adj.) green in tint or color (The verdant leaves on the trees made the world look emerald.)
vestige
(n.) a mark or trace of something lost or vanished (Do you know if the Mexican tortilla is a vestige of some form of Aztec corn-based flat bread?).)
vigilant
(adj.) watchful, alert (The guards remained vigilant throughout the night, but the enemy never launched the expected attack.)
vilify
(v.) to lower in importance, defame (After the Watergate scandal, almost any story written about President Nixon sought to vilify him and criticize his behavior.)
vindicate
(v.) to avenge; to free from allegation; to set free (The attorney had no chance of vindicating the defendant with all of the strong evidence presented by the state.)
vindictive
(adj.) vengeful (The vindictive madman seeks to exact vengeance for any insult that he perceives is directed at him, no matter how small.)
virtuoso
(n.) one who excels in an art; a highly skilled musical performer (Even though Lydia has studied piano for many years, she's only average at it. She's no virtuoso, that's for sure.).)
vivacious
(adj.) lively, sprightly (The vivacious clown makes all of the children laugh and giggle with his friendly antics.)
vocation
(n.) the work in which someone is employed, profession (After growing tired of the superficial world of high-fashion, Edwina decided to devote herself to a new vocation: social work.)
vociferous
(adj.) loud, boisterous (I'm tired of his vociferous whining so I'm breaking up with him.)
wallow
(v.) to roll oneself indolently; to become or remain helpless (My roommate can't get over her breakup with her boyfriend and now just wallows in self-pity.)
wane
(v.) to decrease in size, dwindle (Don't be so afraid of his wrath because his influence with the president is already beginning to wane.)
wanton
(adj.) undisciplined, lewd, lustful (Vicky's wanton demeanor often made the frat guys next door very excited.)
whimsical
(adj.) fanciful, full of whims (The whimsical little girl liked to pretend that she was an elvin princess.)
wily
(adj.) crafty, sly (Though they were not the strongest of the Thundercats, wily Kit and Kat were definitely the most clever and full of tricks.)
winsome
(adj.) charming, pleasing (After such a long, frustrating day, I was grateful for Chris's winsome attitude and childish naivete.)
wistful
(adj.) full of yearning; musingly sad (Since her pet rabbit died, Edda missed it terribly and sat around wistful all day long.)
wizened
(adj.) dry, shrunken, wrinkled (Agatha's grandmother, Stephanie, had the most wizened countenance, full of leathery wrinkles.)
wrath
(n.) vengeful anger, punishment (Did you really want to incur her wrath when she is known for inflicting the worst punishments legally possible?)
yoke
(v.) to join, link (We yoked together the logs by tying a string around them.) Z
zealous
(adj.) fervent, filled with eagerness in pursuit of something (If he were any more zealous about getting his promotion, he'd practically live at the office.).) | https://quizlet.com/71107647/sat-vocab-a-z-flash-cards/ | CC-MAIN-2017-51 | refinedweb | 19,193 | 50.57 |
Using Ajax with a Scaffolded Site
February 5, 2013
Paul Rouse
Using Ajax with a Scaffolded Site
This is cookbook recipe, also available from the Wiki.
A common scenario is that part of an application requires Ajax, while the rest is based on dynamically generated HTML. The core functionality of Yesod includes everything you need to implement this, but the scaffolding leans more towards the HTML side, especially in its handling of login and its reporting of errors. However, the default functions can easily be overridden with more general ones which handle Ajax properly. This article explains how.
In what follows, I look at
- Customising error handling to avoid sending HTML error pages in response to an Ajax request.
- Customising authentication to avoid or mitigate redirections when responding to an Ajax request.
- Testing using
Yesod.Test.
- An example handler and client-side code, to illustrate the choices on which the rest of the discussion is based.
A caveat
To give concrete examples, I have had to make choices about the way Ajax calls are done. To be specific, I use jQuery in about the simplest way possible, which means that:
- Data is sent to the server as a set of form fields, with one parameter for each top-level attribute of the JavaScript object being sent.
- The response can be text or JSON, as long as it is consistent with the setting of the
dataTypein the Ajax call on the client side.
- For an error response, with an HTTP error status, reading the body as text is an easy option for the client.
- The requests include a header
X-Requested-With: XMLHttpRequest
You may want to make different choices, such as sending JSON data in all requests and responses. The details will change, but the main points I am talking about here will remain valid.
An example Yesod handler, and the corresponding client-side code, are given in the appendix at the end to illustrate these choices, and generally motivate the discussion.
I should also mention that issues #478 and #479 on GitHub discuss related issues, but not really the detailed scenario I have chosen here.
Error Handler
The first problem to look at is error handling. The example code shown later
can raise a 404 error if the database entry is not found at all, and a
permissionDenied error if the user is trying to use someone else's
clipboard. Errors like these short-circuit the handler and return a result
using the
errorHandler function of the
Yesod instance.
The scaffolded site is set up to use the default error handler. This produces
a brief HTML message in a page formatted by
defaultLayout, and is probably
not what we want in response to an Ajax request!
To change it, we need to implement the
errorHandler method of the
Yesod
typeclass, rather than using the default setting. It is normal Handler code,
and takes an
ErrorResponse (see the documentation for
Yesod.Handler), so we
need to write something like this in
Foundation.hs:
import Network.HTTP.Types (mkStatus) import Network.Wai (Request(..)) import Data.Text (append, pack, unwords) import Control.Monad (when) ... instance Yesod App where ... errorHandler errorResponse = do $(logWarn) (append "Error Response: " $ pack (show errorResponse)) req <- waiRequest let reqwith = lookup "X-Requested-With" $ requestHeaders req errorText NotFound = (404, "Not Found", "Sorry, not found") errorText (InternalError msg) = (400, "Bad Request", msg) errorText (InvalidArgs m) = (400, "Bad Request", unwords m) errorText (PermissionDenied msg) = (403, "Forbidden", msg) errorText (BadMethod _) = (405, "Method Not Allowed", "Method not supported") when (maybe False (== "XMLHttpRequest") reqwith) $ do let (code, brief, full) = errorText errorResponse sendResponseStatus (mkStatus code brief) $ RepPlain $ toContent $ append "Error: " full defaultErrorHandler errorResponse
The critical part of this is recognising the Ajax call by the
X-Requested-With
header. If you are using a different Ajax setup, you might need to look for
something different, of course, but this one works for jQuery.
In the Ajax case, we produce a plain text response, which is what I chose as
easiest in our example scenario - if you prefer JSON, then feel free to produce
it here. If the request is not Ajax, we call the
defaultErrorHandler,
which is what would have been used if we had not done any of this.
If you have been watching, you will have noticed that I also sneaked in some logging - it is entirely optional, but I think it is helpful.
The other issue which arises when working with Ajax is the way redirection occurs when a user needs to log in during an Ajax request.
The first thing that happens is a redirection to the login page.
This uses a 303 status code, and so cannot be trapped in JavaScript - the
browser itself automatically follows it. So we will be redirected to a
login page. More precisely, we arrive at the
loginHandler of the
YesodAuth
instance. Our problem, just as in the error handler, is that we do not want
it to generate an HTML login form if this happens when handling an Ajax request.
Therefore, in the
YesodAuth instance, we implement the
loginHandler,
rather than accepting the default, again in
Foundation.hs.
instance YesodAuth App where .... loginHandler = do tm <- getRouteToMaster master <- getYesod clearUltDest req <- waiRequest let reqwith = lookup "X-Requested-With" $ requestHeaders req when (maybe False (== "XMLHttpRequest") reqwith) $ do sendResponseStatus (mkStatus 403 "Forbidden") $ RepPlain $ toContent ("Login required" :: Text) let title = renderMessage master ["en"] MsgSiteTitle defaultLayout $ do setTitleI title mapM_ (flip apLogin tm) (authPlugins master)
As before, we recognise an Ajax request from the
X-Requested-With header.
For Ajax we produce an error instead of a login page, leaving the client-side
code to decide how to tidy up and get the user to a place where they can log in.
There are a few subtleties here. Firstly, we use a 403 response in the Ajax
case. 401 would not be a good choice, since it would be an invitation to
do HTTP authentication, not session-based login. However 403 has the
complication that it also gets used for other
permissionDenied errors
(see above). This is resolved by taking a little care to ensure that the
two cases are unambiguously distinguished by the start of the message,
so that the client code can handle them appropriately.
The next subtlety concerns the "ultimate destination" - see the
Sessions chapter of the Yesod Book.
The ultimate destination is set in a couple of places in Yesod, and only one
of them is controlled by the setting of
redirectToReferer (in the
YesodAuth typeclass). In most situations we cannot avoid it being set.
The problem is that a successful login is followed by a redirection to the
ultimate destination, and in an Ajax situation, this can result in being
redirected, using GET, back to a resource which should be accessed with POST
or PUT, for example. To avoid this, we just clear the ultimate destination
in all cases - if you want to be more selective, remember that it is stored in
the session, so it survives between requests until it is cleared or used.
Finally, the call to
defaultLayout generates the login form for the
non-Ajax case. It is essentially copied from the default login handler
declared in the
YesodAuth typeclass in
Yesod.Auth. I have moved few things
outside, and I have used a site title set in our messages file(s) rather
than the one from
Yesod.Auth.Message. This is one place you can modify the
HTML generated, for example by wrapping each authentication widget in a
div with a recognisable
id so that you can apply CSS styles.
Testing
It is a good idea to write some tests, and it is easy to do with
Yesod.Test.
To construct an Ajax request (of the sort I have been dealing with), we need
to set up the parameters, and make an HTTP request which includes the correct
X-Requested-With header. Here is one reasonably general function for doing
it, which assumes that any data is provided as a Map whose keys mirror the
attributes of the JavaScript object used on the real client:
import qualified Data.Map as Map ajaxRequest :: StdMethod -> B.ByteString -> Map.Map Text Text -> OneSpec conn () ajaxRequest method url datacontent = do let params = mapM_ (uncurry byName) $ Map.toList datacontent doRequestHeaders (renderStdMethod method) url [("X-Requested-With", "XMLHttpRequest")] params
doRequestHeaders is a very recent addition to
Yesod.Test. If you want to
use it at the moment, you will need to pick up the latest version from
GitHub - you can simply make a local copy of
Test.hs and import that.
Yesod.Test gives us a way of getting at the raw response body. Any
decoding needs to be allowed for explcitly, which in our example means
remembering that the body is utf-8 encoded.
We write two separate top-level specs, so that we can control the
order - the ordering of the
it specs within a single
describe is
probably not what you expect.
testdata = "A unicode string\x2122" url = "/clipboard/..." -- In a real example, get this from the server clipSpecs1 :: Specs clipSpecs1 = describe "The clipboard (part 1)" $ do it "can be set" $ do ajaxRequest PUT url $ Map.fromList [ ("clip", testdata) ] statusIs 200 clipSpecs2 :: Specs clipSpecs2 = describe "The clipboard (part 2)" $ do it "can be read, producing the utf-8 encoding of what we stored" $ do ajaxRequest GET url Map.empty bodyEquals $ map (chr . fromIntegral) (B.unpack $ encodeUtf8 testdata) statusIs 200
Actually that is not quite all: for our running example we need to log in in
each
it spec. A recipe for packaging that is the subject of
another cookbook article.
Appendix: Example handler and client-side code
This simple handler, and matching JavaScript, motivates the assumptions made in the discussion above, and also just might help someone get started!
In this example, users have to be logged in, and by the time we reach the
handler function, this has already been checked because of a suitable
definition of
isAuthorized in the
Yesod instance in
Foundation.hs.
For more on authentication and authorization, see the
Yesod Book.
Each user has a persistent clipboard for cutting and pasting things, which for
our present purposes can be taken as unicode strings. The server simply stores
the data and returns it to the client when requested, so we need read and write
operations, which rather naturally map onto HTTP GET and PUT methods. They will
act on entries in a database table, defined like this in
config/models:
ClipBoard user UserId -- Who owns this clipboard data Text -- The data UniqueCbUser user
Elsewhere in the application, a single clipboard entry is set up for each user, but for this example we can just assume that it exists.
The route is
/clipboard/#ClipBoardId ClipboardR GET PUT
and the handler code is
module Handler.Clipboard ( getClipboardR, putClipboardR ) where import Import import Yesod.Auth (requireAuthId) import Control.Monad (when) checkEntry :: ClipBoardId -> Handler ClipBoard checkEntry cbid = do userid <- requireAuthId -- Auth already checked, but we need userid cb <- runDB $ get404 cbid when (clipBoardUser cb /= userid) $ permissionDenied "Incorrect user - did you invent the URL?" return cb getClipboardR :: ClipBoardId -> Handler RepPlain getClipboardR cbid = do cb <- checkEntry cbid return $ RepPlain $ toContent $ clipBoardData cb putClipboardR :: ClipBoardId -> Handler () putClipboardR cbid = do _ <- checkEntry cbid d <- runInputPost $ ireq textField "clip" runDB $ update cbid [ClipBoardData =. d]
There are a few things to notice here:
- In the GET handler, the response is simply a utf-8 encoded string sent with type
text/plain(
toContentdoes the utf-8 encoding for
Text).
- The PUT handler uses an "Input Form" (see the Forms chapter of the Yesod Book). In this case there is a single parameter to decode as
Text, but if we had sent a more complex structure on the JavaScript side, there would have been further form fields here.
- Two errors can occur, both most likely caused by not following the official URL. In a real application, the URL would have been provided by the server, so these errors should not occur unless a user types a URL by hand.
Finally, glossing over the way the client gets hold of the URL, jQuery code can send data like this:
$.ajax ({ type: "PUT", url: "/clipboard/" + clipid, data: { clip: clipdata }, dataType: "text", success: function () { alert ("It worked") }, error: function (jqxhr) { alert ("error response: " + jqxhr.responseText); } });
and get it back again this way:
$.ajax ({ type: "GET", url: "/clipboard/" + clipid, dataType: "text", success: function (data) { alert ("The data was: " + data); }, error: function (jqxhr) { alert ("error response: " + jqxhr.responseText); } }); | http://www.yesodweb.com/blog/2013/02/ajax-with-scaffold | CC-MAIN-2014-15 | refinedweb | 2,072 | 58.42 |
Download presentation
Presentation is loading. Please wait.
Published byRachel Pugh Modified over 4 years ago
1
1 Arrays, Strings and Collections [1] Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering University of Melbourne, Australia
2
2 Arrays - Introduction An array is a group of contiguous or related data items that share a common name. Used when programs have to handle large amount of data Each value is stored at a specific position Position is called a index or superscript. Base index = 0 The ability to use a single name to represent a collection of items and refer to an item by specifying the item number enables us to develop concise and efficient programs. For example, a loop with index as the control variable can be used to read the entire array, perform calculations, and print out the results.
3
3 Arrays - Introduction 69 61 70 89 23 10 9 0 1 2 3 4 5 6 index values
4
4 Like any other variables, arrays must declared and created before they can be used. Creation of arrays involve three steps: Declare the array Create storage area in primary memory. Put values into the array (i.e., Memory location) Declaration of Arrays: Form 1: Type arrayname[] Form 2: Type [] arrayname; Examples: int[] students; int students[]; Note: we dont specify the size of arrays in the declaration. Declaration of Arrays
5
5 Creation of Arrays After declaring arrays, we need to allocate memory for storage array items. In Java, this is carried out by using new operator, as follows: Arrayname = new type[size]; Examples: students = new int[7];
6
6 Initialisation of Arrays Once arrays are created, they need to be initialised with some values before access their content. A general form of initialisation is: Arrayname [index/subscript] = value; Example: students[0] = 50; students[1] = 40; Like C, Java creates arrays starting with subscript 0 and ends with value one less than the size specified. Unlike C, Java protects arrays from overruns and under runs. Trying to access an array beyond its boundaries will generate an error message.
7
7 Arrays are fixed length Length is specified at create time In java, all arrays store the allocated size in a variable named length. We can access the length of arrays as arrayName.length: e.g. int x = students.length; // x = 7 Accessed using the index e.g. int x = students [1]; // x = 40 Arrays – Length
8
8 Arrays – Example // StudentArray.java: store integers in arrays and access public class StudentArray{ public static void main(String[] args) { int[] students; students = new int[7]; System.out.println("Array Length = " + students.length); for ( int i=0; i < students.length; i++) students[i] = 2*i; System.out.println("Values Stored in Array:"); for ( int i=0; i < students.length; i++) System.out.println(students[i]); } :w
9
9 Arrays can also be initialised like standard variables at the time of their declaration. Type arrayname[] = {list of values}; Example: int[] students = {55, 69, 70, 30, 80}; Creates and initializes the array of integers of length 5. In this case it is not necessary to use the new operator. Arrays – Initializing at Declaration
10
10 Arrays – Example // StudentArray.java: store integers in arrays and access public class StudentArray{ public static void main(String[] args) { int[] students = {55, 69, 70, 30, 80}; System.out.println("Array Length = " + students.length); System.out.println("Values Stored in Array:"); for ( int i=0; i < students.length; i++) System.out.println(students[i]); }
11
11 Two Dimensional Arrays Two dimensional arrays allows us to store data that are recorded in table. For example: Table contains 12 items, we can think of this as a matrix consisting of 4 rows and 3 columns. Item1Item2Item3 Salesgirl #1101530 Salesgirl #2143033 Salesgirl #3200321 Salesgirl #4102004 Sold Person
12
12 2D arrays manipulations Declaration: int myArray [][]; Creation: myArray = new int[4][3]; // OR int myArray [][] = new int[4][3]; Initialisation: Single Value; myArray[0][0] = 10; Multiple values: int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}}; int tableA[][] = {{10, 15, 30}, {14, 30, 33}};
13
13 Variable Size Arrays Java treats multidimensional arrays as arrays of arrays. It is possible to declare a 2D arrays as follows: int a[][] = new int [3][]; a[0]= new int [3]; a[1]= new int [2]; a[2]= new int [4];
14
14 Try: Write a program to Add to Matrix Define 2 dimensional matrix variables: Say: int a[][], b[][]; Define their size to be 2x3 Initialise like some values Create a matrix c to storage sum value c[0][0] = a[0][0] + b[0][0] Print the contents of result matrix.
15
15 Arrays can be used to store objects Circle[] circleArray; circleArray = new Circle[25]; The above statement creates an array that can store references to 25 Circle objects. Circle objects are not created. Arrays of Objects
16
16 Create the Circle objects and stores them in the array. //declare an array for Circle Circle circleArray[] = new Circle[25]; int r = 0; // create circle objects and store in array for (r=0; r <25; r++) circleArray[r] = new Circle(r); Arrays of Objects
17
17 String Operations in Java
18
18 Introduction String manipulation is the most common operation performed in Java programs. The easiest way to represent a String (a sequence of characters) is by using an array of characters. Example: char place[] = new char[4]; place[0] = J; place[1] = a; place[2] = v; place[3] = a; Although character arrays have the advantage of being able to query their length, they themselves are too primitive and dont support a range of common string operations. For example, copying a string, searching for specific pattern etc. Recognising the importance and common usage of String manipulation in large software projects, Java supports String as one of the fundamental data type at the language level. Strings related book keeping operations (e.g., end of string) are handled automatically.
19
19 String Operations in Java Following are some useful classes that Java provides for String operations. String Class StringBuffer Class StringTokenizer Class
20
20 String Class String class provides many operations for manipulating strings. Constructors Utility Comparisons Conversions String objects are read-only (immutable)
21
21 Strings Basics Declaration and Creation: String stringName; stringName = new String (string value); Example: String city; city = new String (Bangalore); Length of string can be accessed by invoking length() method defined in String class: int len = city.length();
22
22 String operations and Arrays Java Strings can be concatenated using the + operator. String city = New + York; String city1 = Delhi; String city2 = New +city1; Strings Arrays String city[] = new String[5]; city[0] = new String(Melbourne); city[1] = new String(Sydney); … String megacities[] = {Brisbane, Sydney, Melbourne, Adelaide, Perth};
23
23 String class - Constructors public String()Constructs an empty String. Public String(String value)Constructs a new string copying the specified string.
24
24 String – Some useful operations public int length()Returns the length of the string. public charAt(int index)Returns the character at the specified location (index) public int compareTo( String anotherString) public int compareToIgnoreCase( String anotherString) Compare the Strings. reigonMatch(int start, String other, int ostart, int count) Compares a region of the Strings with the specified start.
25
25 String – Some useful operations public String replace(char oldChar, char newChar) Returns a new string with all instances of the oldChar replaced with newChar. public trim()Trims leading and trailing white spaces. public String toLowerCase() public String toUpperCase() Changes as specified.
26
26 String Class - example // StringDemo.java: some operations on strings class StringDemo { public static void main(String[] args) { String s = new String("Have a nice Day"); // String Length = 15 System.out.println("String Length = " + s.length() ); // Modified String = Have a Good Day System.out.println("Modified String = " + s.replace('n', 'N')); // Converted to Uppercse = HAVE A NICE DAY" System.out.println("Converted to Uppercase = " + s.toUpperCase()); // Converted to Lowercase = have a nice day" System.out.println("Converted to Lowercase = " + s.toLowerCase()); }
27
27 StringDemo Output [raj@mundroo] Arrays [1:130] java StringDemo String Length = 15 Modified String = Have a Nice Day Converted to Uppercase = HAVE A NICE DAY Converted to Lowercase = have a nice day [raj@mundroo] Arrays [1:131]
28
28 Summary Arrays allows grouping of sequence of related items. Java supports powerful features for declaring, creating, and manipulating arrays in efficient ways. Each items of arrays of arrays can have same or variable size. Java provides enhanced support for manipulating strings and manipulating them appears similar to manipulating standard data type variables.
Similar presentations
© 2018 SlidePlayer.com Inc. | https://slideplayer.com/slide/677736/ | CC-MAIN-2018-51 | refinedweb | 1,436 | 53.31 |
This is a communication I had last week that deals with updating coordinates within Rosetta. Hopefully, this helps anyone else who has the same problem.
Hello.
My name is ____. We are trying to develop a good ab initio protocol using PyRosetta. I am very happy with the flexibility PyRosetta allows, however I have a question about some strange outputs from the program.
To give you a background, I am trying to use a disulfide bond constraint in which after a fold, if an incorrect disulfide bond has been formed, the program reverts to the pose that existed before the particular move.
In order to do this, I am using a manual calculation of bond length using 'sulfera.xyz - sulferc.xyz' in order to get the distance between each x y z coordinates, and then using the 3 Dimensional Pythagorean theorem to calculate bond distance. My Code looks like this:
sulfidefour = pose.residue(4).atom("SG")
sulfidesix = pose.residue(6).atom("SG")
currectdisulfide=True
def disulfidecheck():
correctdisulfide=True
if disulfides != 0:
print sulfidefour.xyz()
print sulfidesix.xyz()
print sulfidefifte.xyz()
print sulfide_23.xyz()
print sulfide_25.xyz()
print sulfide_36.xyz()
SSbond = sulfidefour.xyz() - sulfidesix
SSbond = sulfidefour.xyz() - sulfidefifte
(etc.)
The problem I am having is that sometimes after a move, a single x y or z coordinate jumps to an insane number, after which the program cannot handle the number, and discontinues.
As an example, the last time I tried to run the program a sulfer atom jumped from:
7.214785689331332E-313 2.398900546303664E-312 2.139682428053075E-314
to
5.740792175477635E+198 2.407337605170826E-312 2.139682428053075E-314
The coord. are in angstroms, so how is this possible? Is this a known issue?
Thank you for taking the time to read this email.
Jeff:
hm. are you in full-atom mode or centroid mode? in centroid mode those atoms might not exist.
the pose should know to update the coords before giving you the xyz values...I think...
you might also try calling the side-chain packer to do a rotamer-pack of the sc coords
Phil:
I'm not too familiar with the python, but in C++ you could possibly get some funny behavior if you are holding onto atom/xyz references over periods of time during which the pose has been modified by certain operations such as repacking or residue replacement. In general, it's safer to get residue/atom info from the pose via calls to pose.residue(seqpos) or pose.xyz(atomid) as needed rather than storing returned (const) references to internal data for extended periods. This ensures that everything gets updated properly. The pose will update xyz coords following torsion angle changes and internal coords following xyz changes, but for efficiency reasons it does this in a lazy updating scheme triggered by access to the residue/xyz info. Once you get a const reference to an xyzVector from the pose, there's no further communication mechanism that tells the pose you might have read coordinates from the vector at some later time.
Not sure how coordinate access is handled in python, but did you try getting residue/atom information from the pose anew? I'm worried that the problem is old references to position information either going out of date or not triggering appropriate updating calls.
-Phil
Phil,
I think I know what you meant. I changed the call to pose.xyz call of coordinates:
sulfidefour = AtomID(4, 4)
sulfidesix = AtomID(4, 6)
def disulfidecheck():
correctdisulfide=True
if disulfides != 0:
print pose.xyz(sulfidefour)
print pose.xyz(sulfidesix)
print pose.xyz(sulfidefifte)
print pose.xyz(sulfide_23)
print pose.xyz(sulfide_25)
print pose.xyz(sulfide_36)
SSbond = pose.xyz(sulfidefour) - pose.xyz(sulfidesix)
xD = SSbond.x
yD = SSbond.y
zD = SSbond.z
dSquared = (xD**2) + (yD**2) + (zD**2)
d = math.sqrt(dSquared)
print d
if d < 2.11:
correctdisulfide = False
Problem seems solved. I guess for this call, the coordinates are now updated from all of the moves..Thanks for your help.
I hope this helps anyone in the same situation, or has questions about the updating of a pose.
-J | https://www.rosettacommons.org/node/1777 | CC-MAIN-2020-50 | refinedweb | 684 | 60.92 |
I am trying to form a list of strings from the header of a csv file in pyspark. The header in csv file is in unicode format. I wrote this code which reads the header but it doesn't form the list with individual values from the header:
def filter(line):
return line
read_file = sc.textFile('').zipWithIndex().filter(lambda (line, rownum): rownum == 0).map(lambda (line, rownum): line)
data = (read_file
.map(lambda line: line.split(","))
.filter(lambda line: len(line) >= 1)
.map(filter))
print data.collect()
[[u'header1', u'header2', u'header3', u'header4', u'header5']]
['header1','header2','header3','header4','header5']
Easy enough to fix your specific problem:
just use
flatMap instead of
map
data = read_file.flatMap(lambda l: l.split(","))
Obviously taking
[0] of the result as in
data.collect()[0] is also a solution.
However the way you currently doing it you are iterating over the whole file to discard all lines but the first one. I would recommend using
.take(1) on the rdd.
first_line = sc.textFile('test.csv').take(1) first_line[0].split(",")
This second solution is a lot faster on long files.
Also note that your filter function does not currently serve any purpose, you could just leave out
.map(filter). | https://codedump.io/share/kMkDptLetAnQ/1/form-a-list-of-strings-from-the-header-of-a-csv-file-in-pyspark | CC-MAIN-2018-05 | refinedweb | 206 | 61.43 |
26 U.S. Code § 6111 - Disclosure of reportable transactions
(a) In general
Each material advisor with respect to any reportable transaction shall make a return (in such form as the Secretary may prescribe) setting forth—
Such return shall be filed not later than the date specified by the Secretary.
(b) Definitions
For purposes of this section:
(1) Material advisor
(A) In general
The term “material advisor” means any person—
(i) who provides any material aid, assistance, or advice with respect to organizing, managing, promoting, selling, implementing, insuring, or carrying out any reportable transaction, and
(c) Regulations
The Secretary may prescribe regulations which provide—
(1) that only 1 person shall be required to meet the requirements of subsection (a) in cases in which 2 or more persons would otherwise be required to meet such requirements,
Source(Added Pub. L. 98–369, div. A, title I, § 141(a),July 18, 1984, 98 Stat. 677; amended Pub. L. 99–514, title II, § 201(d)(13), title XV, § 1531(a), title XVIII, § 1899A(54),Oct. 22, 1986, 100 Stat. 2142, 2749, 2961; Pub. L. 105–34, title X, § 1028(a),Aug. 5, 1997, 111 Stat. 926; Pub. L. 108–357, title VIII, § 815(a),Oct. 22, 2004, 118 Stat. 1581; Pub. L. 109–135, title IV, § 412(zz),Dec. 21, 2005, 119 Stat. 2641.)
Prior Provisions
Amendments
2005—Subsec. (b)(1)(A)(ii). Pub. L. 109–135substituted “aid, assistance, or advice” for “advice or assistance”.
2004—Pub. L. 108–357amended section catchline and text generally, substituting provisions relating to disclosure of reportable transactions for provisions relating to registration of tax shelters and inclusion of identification numbers on returns.
1997—Subsecs. (d) to (f). Pub. L. 105–34added”.
Effective Date of 2004 Amendment
Pub. L. 108–357, title VIII, § 815(c),Oct. 22, 2004, 118 Stat. 1583, provided that: “The amendments made by this section [amending this section and sections 6112 and 6708 of this title] shall apply to transactions with respect to which material aid, assistance, or advice referred to in section 6111(b)(1)(A)(i) of the Internal Revenue Code of 1986 (as added by this section) is provided after the date of the enactment of this Act [Oct. 22, 2004].”
Effective Date of 1997 Amendment
Pub. L. 105–34, title X, § 1028(e),Aug. 5, 1997, 111 Stat. 928, provided that:
“(1) In general.—Except as provided in paragraph (2), the amendments made by this section [amending this section and sections 6662 and 6707 of this title] shall apply to any tax shelter (as defined in section 6111(d) of the Internal Revenue Code of 1986, as amended by this section) interests in which are offered to potential participants after the Secretary of the Treasury prescribes guidance with respect to meeting requirements added by such amendments.
“(2) Modifications to substantial understatement penalty.—The amendments made by subsection (c) [amending section 6662 of this title] shall apply to items with respect to transactions entered into after the date of the enactment of this Act [Aug. 5, 1997].”
Effective Date of 1986 Amendment
Amendment by section 201(d)(13))(13).
Pub. L. 99–514, title XV, § 1531(b),Oct. 22, 1986, 100 Stat. 2749, provided that: “The amendment made by this section [amending this section] shall apply to any tax shelter (within the meaning of section 6111 of the Internal Revenue Code of 1986 [formerly I.R.C. 1954] as amended by this section) interests in which are first offered for sale after December 31, 1986.”
Effective Date
Pub. L. 98–369, div. A, title I, § 141(d),July 18, 1984, 98 Stat. 680, as amended by Pub. L. 99–514, § 2,Oct. 22, 1986, 100 Stat. 2095, provided that:
“(1) In general.—The amendments made by this section [enacting this section and section 6707 of this title and renumbering former section 6111 assection 6112 of this title] shall apply to any tax shelter (within the meaning of section 6111 of the Internal Revenue Code of 1986 [formerly I.R.C. 1954], as added by this section) any interest in which is first sold to any investor after August 31, 1984.
“(2) Substantial investment test.—For purposes of determining whether any investment is a tax shelter by reason of section 6111(c)(1)(B)(iii) of such Code (as added by this section), only offers for sale after August 31, 1984, shall be taken into account.
“(3) Furnishing of shelter identification number for interests sold before september 1, 1984.—With respect to interests sold before September 1, 1984, any liability to act under paragraph (1) of section 6111(b) of such Code (as added by this section) which would (but for this sentence) arise before such date shall be deemed to arise on December 31,. | http://www.law.cornell.edu/uscode/text/26/6111?quicktabs_8=1 | CC-MAIN-2014-10 | refinedweb | 792 | 63.19 |
I realized when i export an FBX from 2.8, collection are not taken in consideration.
when i import an FBX to 2.8 from 2.79 group hierarchy are destroy.
which workflow will allow me to keep collection hierarchy while exporting an fbx from 2.8.
drag and drop mesh into an empty is not working as in 2.79.
thanks in advance for your help.
I realized when i export an FBX from 2.8, collection are not taken in consideration.
Is this a feature of FBX?
no is not and I’m asking how to do it, how to export an FBX in 2.8 and keep the collection hierarchy the same, like a group.
I have exactly the same question. Right now I’m using a script I created for this task:
import bpy sCollection = bpy.context.collection def parentCol(_colParent, _objParent): for col in _colParent.children: newObj = bpy.data.objects.new("empty", None) bpy.context.scene.collection.objects.link(newObj) newObj.name = col.name newObj.parent = _objParent if len(col.objects) > 0: objs = col.objects for obj in objs: obj.parent = newObj else: parentCol(col, newObj) root = bpy.data.objects.new("empty", None) bpy.context.scene.collection.objects.link(root) root.name = sCollection.name parentCol(sCollection, root)
The script translates the hierarchy of collections into a new structure with parented empties.
Is there another or better solution?
Highly unlikely, as Collections are a ‘blender only’ thing, and FBX is based on regular hierarchy setups that every 3d application will understand after import.
As a long time 3D artist I can only say Collections make sloppy workflow in this regard.
It’s like opening a 3DSMax file and see everything names box1… box 100, curve 1 … 50 etc.
No structure whatsoever on scene level itself.
I do understand the design philosophy behind it, but Collections are trying to do too much imho.
Personally I find the link between grouping things in Collections and using them for rendering as well
very annoying. I would rather have seen a split between them.
And the fact that you have to use Collections for linking objects is not my favorite option either.
It gives you twice the work if you want to do it in a proper way.
I understand your frustration.
Personally, I find working with collections in the first place quite pleasant.
But I think, just like you, that Blender should be able to follow the industry standard at this point and allow a smooth exchange of data.
What about other formats? Is the hierarchy transferred in Gltf or USD?
In USD it is for sure, that’s one of the ‘perks’ of the format.
Gltf I 'm not sure, haven’t used that yet. But I bet it is, as it also supports animation.
Continuing the discussion from Blender 2.8 Export FBX while keeping Collections Hierarchy:
Finally! THANK YOU!!! A NON-Destructive File export. Was getting mad to have 200+ parts FUSED after exporting. Blender needs a hiarchy overhaul. | https://blenderartists.org/t/blender-2-8-export-fbx-while-keeping-collections-hierarchy/1142655 | CC-MAIN-2021-49 | refinedweb | 503 | 61.63 |
30 June 2011 15:14 [Source: ICIS news]
HOUSTON (ICIS)--Mitsui & Co has agreed to take a 12.5% working interest in SM Energy’s Eagle Ford shale gas property in Texas, the Japanese industrial and trading major said on Thursday.
Under the deal, Mitsui, through a subsidiary, will “carry up to $680m (€469m) of SM Energy’s future development cost” of the 47,000-acre (19,000ha) project, it said.
Eagle Ford is considered to be one of the “most attractive shale plays” in the ?xml:namespace>
“We have expanded our shale oil/gas portfolio in the
Ethane extracted from Eagle Ford shale gas could be a source of feedstock for a cracker Dow Chemical plans to build on the US Gulf coast.
Dow has signed ethane and propane supply contracts based on Eagle Ford shale gas.
($1 = €0.69 | http://www.icis.com/Articles/2011/06/30/9474122/mitsui-co-in-680m-deal-to-develop-texas-eagle-ford-shale.html | CC-MAIN-2014-41 | refinedweb | 141 | 66.37 |
When.
These secret identities serve a variety of purposes, and they help us
to understand how variables work. In this lesson, we'll be writing
a little less code than we've done in previous articles, but we'll
be taking a detailed look at how variables live and work.
Related Reading
Learning Cocoa with Objective-C
By James Duncan Davidson, Apple Computer, the machine compiles your code, however,
it does a little bit of translation. At run
time, the computer sees nothing but 1s and 0s, which is all the
computer ever sees: a continuous string of binary
numbers that it can interpret in various ways.
This back and forth is an important concept to understand in C programming,
especially on the Mac's RISC architecture. Almost every variable you work with can be represented in 32
bits of memory: thirty-two 1s and 0s define
the data that a simple variable can hold. There are exceptions, like
on the new 64-bit G5s and in the 128-bit world of AltiVec; but for the
most part, when we're dealing with variables like int
and the other types we'll learn later in the lesson, we're
going to be dealing with convenient names for blocks of thirty-two 1s
and 0s.
int
Being able to understand that basic idea opens up a vast amount of power
that can be used and abused, and we're going to look at a few
of the better ways to deal with it in this article..
When a variable is finished with it's work, it does not go into
retirement, and it is never mentioned again. Variables simply cease to exist, and the thirty-two bits
of data that they held is released, so that some other variable may
later use them.
But variables get one benefit people do not; the end is always clearly
marked and easy to determine. Every variable is declared inside a block
of code, and that block determines its lifespan. When that block closes,
the variables declared within it are freed. If the block they are declared
in has blocks within it, the variable lives on through those blocks.
Contrariwise, variables declared within those blocks cease to exist
outside of their blocks of origin. This hierarchical relationship provides
a simple pattern to follow, and the variable's lifetime is called
its scope..
Each Stack Frame represents a function.
The bottom frame is always the main function, and the frames
above it are the other functions that main calls.
At any given time, the stack can show you the path your code has taken
to get to where it is. The top frame represents the function the code
is currently executing, and the frame below it is the function that
called the current function, and the frame below that represents the
function that called the function that called the current function,
and so on all the way down to main, which is the starting
point of any C program.
main
Inside each stack frame is a slew of useful information. It tells the
computer what code is currently executing, where to go next, where to
go in the case a return statement
is found, and a whole lot of other things that are incredible useful
to the computer, but not very useful to you most of the time. One of
the things that is useful to you is the part of the frame that keeps
track of all the variables you're using. So the first
place for a variable to live is on the Stack. This is a
very nice place to live, in that all the creation and destruction of
space is handled for you as Stack Frames are created and destroyed.
You seldom have to worry about making space for the variables on the
stack. The only problem is that the variables here only live as long
as the stack frame does, which is to say the length of the function
those variables are declared in. This is often a fine situation, but when you need to store information for longer than a single
function, you are instantly out of luck.
return.
Let's see an example by converting our favoriteNumber
variable from a stack variable to a heap variable. The first thing we'll
do is find the project we've been working on and open it up in
Project Builder. In the <main.c> file, we'll start right
at the top and work our way down. Under the line:
favoriteNumber
<main.c>
#include <stdio.h>
<stdio.h>
insert
#include <libc.h>
<libc
int favoriteNumber = (3 * 4) / 2;
We're going to break this apart and make it two lines:
int* favoriteNumber = malloc(sizeof(int));
*favoriteNumber = (3 * 4) / <malloc> does. This function takes
an argument that specifies how much
space you need and then returns a pointer to that space. We've passed
it the result of another function, <sizeof>, which we pass int,
a type. In reality, <sizeof> is a macro,
but for now we don't have to care: all we need to know is that
it tells us the size of whatever we gave it, in this case an int.
So when <malloc> is done, it gives us an address in the heap where
we can put an integer. It is important to remember that the data is
stored in the heap, while the address of that data is stored in a pointer
on the stack.
int*
<malloc>
<sizeof>.
The rest of our conversion follows a similar vein. Instead of going through
line by line, let's just compare end results: when the transition
is complete, the code that used to read:! */
countTo(favoriteNumber);
return 0;
}
Should now look like this:
int main (int argc, const char * argv[]) {
//Computes our favorite number
int* favoriteNumber = malloc(sizeof(int));
*favoriteNumber = (3 * 4) / 2;
*favoriteNumber = integerForSeedValue(*favoriteNumber + 2);
/* now let's tell the world
what our favorite number is! */
countTo(*favoriteNumber);
free(favoriteNumber);
return 0;
}
Note the new asterisks whenever we reference favoriteNumber,
except for that new line right before the return. <free>
simply tells the computer that you had this space, but you're
done and the memory can be freed for use by something else later on.
<free>
This code should compile and run
just fine, and you should see no changes in how the program works. So
why did we do all of that?.
Seth Roby
graduated in May of 2003 with a double major in English and Computer Science, the Macintosh part of a three-person Macintosh, Linux, and Windows graduating triumvir. | http://www.macdevcenter.com/pub/a/mac/2003/10/07/cocoa.html?page=last&x-order=date | CC-MAIN-2014-10 | refinedweb | 1,105 | 66.78 |
Search: Search took 0.02 seconds.
How to add profiles?
Rendering nested list in mobile deviceStarted by horcle_buzz, 29 Apr 2013 6:47 PM
- Last Post By:
- Last Post: 30 Apr 2013 5:50 PM
- by horcle_buzz
[OPEN] Profiled Views not showing up after building production/testing
Not able to to use device profiles
Building facebook like application in Secha Touch
- Last Post By:
- Last Post: 17 Aug 2012 12:35 PM
- by mitchellsimoens
Ext.app.Application.setCurrentProfile() and profile-specific controllers
- Last Post By:
- Last Post: 6 Aug 2012 6:15 AM
- by mitchellsimoens
Ext.app.Application.setCurrentProfile
Sencha Touch 2 Profiles IssueStarted by DiegoPaleo, 17 May 2012 7:16 AM
- Last Post By:
- Last Post: 23 May 2012 6:28 AM
- by mitchellsimoens
Implementing device profiles afterwardsStarted by invalidoyt, 22 Mar 2012 8:22 AM
- Last Post By:
- Last Post: 22 Mar 2012 12:25 PM
- by invalidoyt
Problem with profile devices
When to use CSS vs. Profiles and Device Info
- Last Post By:
- Last Post: 15 Mar 2012 5:03 AM
- by mitchellsimoens
profile usage in ST2 MVC
- Last Post By:
- Last Post: 9 Mar 2012 2:40 PM
- by mitchellsimoens
[FIXED] [beta2]Ext.Application. loadControllerDependencies error
[FIXED] [PR4] Profile "name" vs "namespace" and documentation
Some guidance in setting multiple device profiles for MVC app.
Results 1 to 15 of 15 | https://www.sencha.com/forum/tags.php?tag=profile | CC-MAIN-2015-27 | refinedweb | 224 | 54.15 |
Lock a mutex, with a time limit
#include <threads.h> #include <time.h> int mtx_timedlock( mtx_t *mutex, const struct timespec * ts );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The mtx_timedlock() function locks the mutex object referenced by mutex. If the mutex is already locked, the calling thread blocks until the mutex becomes available as in mtx_lock(). If the mutex can't be locked without waiting for another thread to unlock the mutex, the wait is terminated when the specified timeout expires. ts passes, as measured by the clock on which timeouts are based (i.e., when the value of that clock equals or exceeds ts), or if the absolute time specified by ts has already been passed at the time of the call.
If the mutex can be locked immediately, the validity of the ts parameter isn't checked, and the function won't fail with a timeout. | http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/m/mtx_timedlock.html | CC-MAIN-2018-43 | refinedweb | 160 | 64.3 |
Hi, Elin,
One option you have is to use EPi blocks as "local blocks". When you are defining a block, you can set AvailableInEditMode to false, ie:
[SiteContentType( GUID = "751FCE02-423B-4409-9CC5-744A37BAD015", AvailableInEditMode = false)] [SiteImageUrl] public class ImageBlock : SiteBlockData { [Display( GroupName = SystemTabNames.Content, Order = 1)] [UIHint(UIHint.Image)] [Searchable(false)] public virtual Url ImageUrl { get; set; } [Display( GroupName = SystemTabNames.Content, Order = 2)] [CultureSpecific] public virtual string ImageAlt { get; set; } }
When you want it to be displayed on the page, you define a page property:
[Display( GroupName = SystemTabNames.Content, Order = 300)] public virtual ImageBlock Image { get; set; }
So, you don't have a ContentArea, but an image block as a property.
This is a bit inflexible for your use, as I understand it, as it gives you exact number of properties on the page. However, it will have the same lifecycle as the page and will be present as a part of the page.
If you, however, need to add blocks to ContentArea only on one page, as you described, I don't think there is this "PageBlocks" functionality.
You can simulate it, by hooking to ContentCreated event and create a folder for each page and delete it on ContentDeleted by page name or so. It seems like a bit of overhead and also, as far as I can see you can't set access rights to the whole folder, only to each block, so you don't gain much and you still need to cover the pagename changes etc. So, basically, you help editors by creating their blocks folder inside a folder called, let's say, "Page blocks" and later cleaning it up for them by deleting this folder.
If you have a block that displays some page specific data, like price, name, etc and it's always on the same place, local block as described in the example is perfect, no need to overuse this new functionality of "shared blocks". If you don't have a specific structure, than I think you need to build up this functionality.
Hope this helps,
Marija
Do you know if it is possible in Episerver 7 to have local blocks, that are tied to a specific page and not visible to use on other pages on the site?
I would like to use blocks for creating pages in a flexible way - in our site this use would be more common than re-use of the same blocks (same content) on several pages.
For images it is possible to place them in the "page files" folder or in the "global files" folder - images placed in the "page files" folder will then be deleted when the page is deleted. I would like to be able to work in this way when organizing the blocks aswell. Is it possible? | https://world.episerver.com/forum/legacy-forums/Episerver-7-CMS/Thread-Container/2013/5/Blocks-on-page--local-blocks/ | CC-MAIN-2020-16 | refinedweb | 465 | 64.54 |
#include <pcomm.h>
PComm (char *pcrDev, tcflag_t baudRate=B9600, const char *name=0)
The PComm Constructor.
~PComm ()
The PComm Destructor.
bool PCOpen (const char *pcrDev=PCRDEV, tcflag_t baudRate=B9600)
Opens another file descriptor to the serial device.
void PCClose ()
Closes the currently active file descriptor.
size_pc PCTell (char *)
Issue a command string to the radio.
size_pc PCAsk (char *)
Issue a status request from the radio.
size_pc PCHear (char *)
Receive a repsonse from the radio.
size_pc PCRawWrite (char *)
writes directly to the current socket.
size_pc PCRawRead (char *)
reads directly from the current socket.
size_pc Write (char *)
Internal function to write to the socket.
size_pc Read (char *)
Internal function to read from the socket.
void resetCall ()
resets the radio and port.
void countCall ()
function to keep track on the number of calls.
int callCount
Counter for number of times the radio has been written to.
char callBuf [256]
Internal buffer for radio reset.
struct timeval* timeOut
Used in the select for timeout(s).
fd_set* FDSet
Socket set used in the select.
int retVal
Select()'s return value.
struct termios* oldtio
Stores the port's original settings.
struct termios* newtio
Port settings to be applied for current session.
int fd
Socket descriptor used for current session.
char pcrDevice [256]
Current serial/comm device.
tcflag_t pcrSpeed
Current baud rate.
bool errRead
Was there an error reading?
bool errWrite
Was there an error writing?
char askBuf [256]
Buffer for sending data in PCAsk.
char hearBuf [256]
Buffer for receiving data in PCHear.
char writeBuf [256]
Buffer for writing data used in wrapper Write().
char readBuf [256]
Buffer for reading data used in wrapper Read().
char int_name [256]
Internal object name. Warning: not necessarily populated.
size_pc writeCtr
Send bytecount used in wrapper function Write().
size_pc readCtr
Receive bytecount used in wrapper function Read().
size_pc askCtr
Receive bytecount used in PCAsk.
size_pc tellCtr
Send bytecount used in PCTell.
size_pc hearCtr
Receive bytecount used in PCHear.
The Primitive Communications Object.
PComm object is the serial i/o object. It facilitates the low level grunt work for reading and writing to the serial device(s). It handles the string manipulation necessary for communication with the radio.
Definition at line 47 of file pcomm.h.
The PComm Constructor.
Parameters:
This is the easiest way to open the serial device for communications with the radio. If the serial device cannot be opened for processing the object will abort with a -1 status code to the operating system.
You must send it at least the device name which is to be opened as the first argument. Optionally, you can send it an initial baudrate and an internal object name.
The PComm Destructor.
Destroys the object, and closes any open file descriptors to the serial device. It also restores any old (initial) settings to the serial device.
Definition at line 62 of file pcomm.cpp.
Opens another file descriptor to the serial device.
Parameters:
Opens a file descriptor to the device pcrDev (which is by default your system's PCRDEV define) at the speed baudRate (which is by default as delinated in your termios.h set to 9600 baud).
Warning: You can only call this as long as the object is alive. If you do destry the object remember to call this function only after setting up the port configuration correctly.
Returns: true or false based on success value.
Definition at line 79 of file pcomm.cpp.
Closes the currently active file descriptor.
Used in conjunction with PCOpen(...) so that you can release and regain the socket after an initialization procedure.
Definition at line 173 of file pcomm.cpp.
Issue a command string to the radio.
Parameters:
Sends a command to the radio via the custom made wrapper function Write() . This doesnt really alter the message at all for reading and writing to the radio.
Returns: number of bytes actually written gets returned, or (-1) on error.
See also: pcrdef.h
Definition at line 194 of file pcomm.cpp.
Issue a status request from the radio.
Parameters:
This function makes sure that mesg isnt empty, as well as making sure that mesg is two bytes long. Any queries sent to the radio should be the header of the information requested to be returned.
It then zero's out the ask buffer, and copies the message into the ask buffer. Then it concatenates the PCRQST command terminator, and calls Write() sending it the ask buffer.
Returns: the number of bytes asked minus the PCRQST command terminator.
See also: PCRQST() pcrdef.h
Definition at line 217 of file pcomm.cpp.
Receive a repsonse from the radio.
Parameters:
This function makes sure that mesg is pointing to a valid address (ie: is malloc'd) then it zero's out the message string and hearBuffer. It then calls Read()... remembering the number of bytes read, it cuts out the end-of-command marker read in (CR-LF) and copies what it heard into the message string.
If the radio kept spitting out LF chars, it checks for the err bool.
Returns: the number of bytes read, or -1 on err.
See also: pcrdef.h
Definition at line 251 of file pcomm.cpp.
writes directly to the current socket.
Parameters:
Sends a command directly to the socket without any preprocessing
Returns: number of bytes actually written
See also: pcrdef.h PCRawRead(char *mesg)
Definition at line 304 of file pcomm.cpp.
reads directly from the current socket.
Parameters:
Reads directly from the socket without any preprocessing
Returns: number of bytes read.
See also: pcrdef.h PCRawWrite(char *mesg)
Definition at line 337 of file pcomm.cpp.
Internal function to write to the socket.
Parameters:
sends a command to the radio/socket.
It zero's out the internal class's write buffer, and copies the message passed in called submesg into the write buffer. It appends the special end-of-command marker to the write buffer, and exec's write(). Select() is used to see if we are ready to write to the socket in the FDSet.
Returns: what was actually written minus two. Since the minus two is to account for the end-of-command marker. On error we return -2
See also: Read()
Definition at line 370 of file pcomm.cpp.
Internal function to read from the socket.
Parameters:
It reset's the read counter, and loopbreaker. The read counter keeps track of the number of bytes read in. The loop breaker makes sure that read doesnt get stuck reading New Lines from the radio for ever and ever. Since we are ignoring newlines when we read. The radio has a tendency of sending newlines even when it has nothing to say.
it executes read() into the internal variable read buffer, and increments the loop breaker. If the number of bytes read is greater than 1, then some useful data was read in... no need to re-loop. When good data is read, it is copied into the submesg string from the read buffer. Select() will determine if the socket in FDSet is ready to read data.
Returns: If after five times, the read() read in anything less than 1, then break, and set errRead to true, while returning the number of bytes read. If after five seconds fd says that it's still not ready, then it will return, setting the read counter to a negative value.
See also: Write()
Definition at line 416 of file pcomm.cpp.
resets the radio and port.
This function reset's the radio and the port when called. It is necessary to reset the radio after a certain number of read() and write()'s. In this case we have made it after 200 write() calls.
It closes the port, and reopens the port. Zero's out the call buffer, and copy's the poweron/ecmd command strings into the call buffer. It then select()'s to see if we are ready to write to the buffer. After which it writes to the radio to tell it, that we are back online and want it to come up. Then it bzero's the call buffer and reads what the radio has to say. It loops in that mode if it received only one character of data (the radio likes to send nothing but newlines sometimes) AND the number of loops is less than 10. We dont want to get stuck there.
Warning: this function is necessary for the radio to operate properly under the manual update mode. If you override this function make sure to run the radio in auto-update mode.
See also: countCall()
Definition at line 496 of file pcomm.cpp.
function to keep track on the number of calls.
this function keeps track of the number of calls that were sent to the radio before the last reset. it calls resetCall() every 200 calls, otherwise it increments the call count.
See also: resetCall()
Definition at line 564 of file pcomm.cpp.
Counter for number of times the radio has been written to.
Definition at line 68 of file pcomm.h.
Internal buffer for radio reset.
Definition at line 70 of file pcomm.h.
Used in the select for timeout(s).
Definition at line 73 of file pcomm.h.
Socket set used in the select.
Definition at line 75 of file pcomm.h.
Select()'s return value.
Definition at line 77 of file pcomm.h.
Stores the port's original settings.
Definition at line 79 of file pcomm.h.
Port settings to be applied for current session.
Definition at line 81 of file pcomm.h.
Socket descriptor used for current session.
Definition at line 83 of file pcomm.h.
Current serial/comm device.
Definition at line 85 of file pcomm.h.
Current baud rate.
Definition at line 87 of file pcomm.h.
Was there an error reading?
Definition at line 90 of file pcomm.h.
Was there an error writing?
Definition at line 92 of file pcomm.h.
Buffer for sending data in PCAsk.
Definition at line 94 of file pcomm.h.
Buffer for receiving data in PCHear.
Definition at line 96 of file pcomm.h.
Buffer for writing data used in wrapper Write().
Definition at line 98 of file pcomm.h.
Buffer for reading data used in wrapper Read().
Definition at line 100 of file pcomm.h.
Internal object name. Warning: not necessarily populated.
Definition at line 102 of file pcomm.h.
Send bytecount used in wrapper function Write().
Definition at line 104 of file pcomm.h.
Receive bytecount used in wrapper function Read().
Definition at line 106 of file pcomm.h.
Receive bytecount used in PCAsk.
Definition at line 108 of file pcomm.h.
Send bytecount used in PCTell.
Definition at line 110 of file pcomm.h.
Receive bytecount used in PCHear.
Definition at line 112 of file pcomm.h.
Generated automatically by Doxygen for Icom PCR-1000 Library from the source code. | http://www.makelinux.net/man/3/P/pcomm | CC-MAIN-2014-15 | refinedweb | 1,806 | 69.99 |
Does anyone know how I can copy a grayscale image into the alpha channel of another image? This is important because some game engines attribute special meaning to the alpha channel of images that would normally involve a totally separate image. (I suppose it’s a memory saving feature.) For example, the specular map might be placed in the alpha channel of the diffuse texture.
How do I copy a grayscale image into the alpha channel of another image?
Since this is a Blender Python forum I guess you want to write a script for it? That would be of interest to me as well for similar reasons to yours.
Currently, I use external image editors or tools to achieve that purpose. It hadn’t occurred to me to use some internal Blender process as I usually edit the image externally and use it as a UV mapped texture.
Paul
I believe the image layer project adds abilities to switch channels:
And I added swizzle support to an own custom build. But no transfer between different images.
You can do this with a script however:
import bpy source = bpy.data.images['Source'] target = bpy.data.images['Target'] source_pixels = source.pixels[:] target_pixels = list(target.pixels) assert len(source_pixels) == len(target_pixels) for i in range(0, len(source_pixels), 4): target_pixels[i+3] = source_pixels[i] target.pixels[:] = target_pixels target.update()
Two images of the same pixel count are expected (and actually also same width and height, otherwise results will be odd).
One needs to be called Source, the other Target. The red channel values are copied to the target’s alpha channel (in a grayscale image, red, green and blue channels should be identical). | https://blenderartists.org/t/how-do-i-copy-a-grayscale-image-into-the-alpha-channel-of-another-image/619194 | CC-MAIN-2019-30 | refinedweb | 281 | 58.28 |
How to make a Telegram members scraper and adder to copy and add unlimited members to you group
We are going to scrape Telegram group members and add it to your own group. We will also use a bunch of techniques to be able to add unlimited members to your Telegram group by bypassing Telegram limitations that suppresses the process after adding 50 members. this article includes Telegram group member extractor tutorial and also inclues the python code of Telegram group member adder so you will be able to copy Telegram group members.
Step 1: Obtain API ID and API HASH
In order to communicate with Telegram API, we are required to obtain API ID and API HASH from My Telegram page.
Step 2: Export competitor group members
Visit the tutorial here to learn to export members from a Telegram group.
Step 3: Creating multiple accounts for adding members and how to bypass the adding limits
In case you don't know, there are many factors that effect the number of members each account can add everyday.
Which country to use for making accounts?One of the most important factors is the country that the simcart blongs to. Countris like USA, Spain, Netherlands, Sweden have by far the best virtual numbers for creating accounts and adding members. There are many websites out there that sell virtual numbers for very cheap and reasonable prices. however it is recommend to use real simcarts if possible.
Can my API ID and API HASH get poisened and detected as spammer?Another factor that is important, is the API ID and API HASH that you use for creating accounts. Incase those API credintials are poinsened (detected as unsual or spammy behaviour), you will have to obtain new ones from a new account because each account can only have one pair of API ID and API HASH.
Is it safe to add a lot members to a single group in a short time?Another factor is relevant to how you use the numbers, if you add many members to a group in one signle day, the chances are that many of those members report the group spam and this might make the Telegram spam detection algorithms ban the adder accounts or even the group itself might get deleted! So you need to be cautious with this process.
What should I do when the accout gets flooded?Please note that if an account (session) is flooded, there is a high chance that it might get pure again after 10 minutes, 12 hours or 3 days. However spammy accounts tend to get deleted after hitting a flood error caused by adding members. In case a number is detected as a spammer by Telegram, deleting that account and registering again won't help to purify the spam flag on that account.
What should I do if every account I make gets Deleted (Deleted Account) after using it for adding members?In such cases, create your accounts using an Official version of Telegram (Telegram for iOS, Android, etc) and wait for 3 days. after 3 days, make a session out of the account. This will make the account stronger.
What other things matter in creating accounts?Based on my personal experience, the creator of a group also effects the way you can add members to that group. Like groups thare are created by Asian accounts might not get members that are from other continents. For example a group from India has a very hard time accepting members from europian countries. So if you try to add (europian) members to such (indian) groups your accounts are very likely to get deleted! This applies to many Asian groups from different countries as well.
from telethon import TelegramClient, sync
This will create a session out of the number you enter (after running the python file) and saves the session into a file named
client = TelegramClient(SESSION_FILE_NAME, API_ID, 'API_HASH')
client.start()
SESSION_FILE_NAME for future use (adding members!).
Remember to change the
SESSION_FILE_NAME each time you make a new session so you won't overwrite the previous one!
Step 4: Adding members to your own group using the sessions you have created
Ok here we go!
Our script iterates over all the session that you have created and will use them one by one to add members until they get flooded or banned or stopped by any kind of terminating exception.
Let's import the required modules first.
import logging
import time
import random
import os
from telethon import TelegramClient, sync, connection
from telethon.errors.rpcerrorlist import FloodWaitError
from telethon.errors.rpcerrorlist import FloodError, UserAlreadyParticipantError, InviteHashInvalidError, InviteHashExpiredError
Now we write a single line of code to collect all session files (all acccounts) that are in the current folder
all_sessions = [x for x in os.listdir('.') if 'session' in x and 'journal' not in x]
Now lets iterate through all sessions using a
for loop, and connect to the API!
for session in sessions:
client = TelegramClient(session.split('.')[0], API_ID, 'API_HASH')
try:
client.connect()
me = client.get_me()
if not me:
continue
except ConnectionError:
continue
Now that we are connected to the API, lets get the group detailts we are trying to add members to and join it!
group = client.get_entity('')
client(JoinChannelRequest(group))
We joined the group! Now lets add the members we have in our list to the our group! We're going to open the file, read each line (each line is a user we want to add). and try adding the user to the group. In case we get any flood errors as the exception, we switch the account to add the rest of members using a frech session!
with open(members_file, 'r') as the_file:
members = the_file.read().split('\n')
for m in members:
if switch_account == True:
break
try:
client(InviteToChannelRequest(group, [m]))
except Exception as ex:
if any(s in str(ex) for s in ['Too many', 'deleted/deactivated', 'banned', 'seconds is required', 'USER_DEACTIVATED_BAN', 'write in this chat']):
switch_account = True
Author: Amin Etesamian
copy telegram group members telegram group member adder telegram group member extractor scrape telegram group python add unlimited members in telegram group | https://telmemeber.com/single/33/How-to-make-a-Telegram-members-scraper-and-adder-to-copy-and-add-unlimited-members-to-you-group | CC-MAIN-2021-10 | refinedweb | 1,023 | 60.65 |
Swapping TexturesHow i could do to swap texture "menu.bmp" and "f40.bmp"?
[code]
void initRendering() {
glEnable(G...
Join together menu with gameplayHello at all.
I'm triying to make the game go to the simulation by pressing 'g'.
I know the me...
Direction moving (sine and cosine)The "car" still not do direction turning, it goes straight if you turn it ;)
Direction moving (sine and cosine)Hello!
I have this basic code:
[code]
#include <iostream>
#include <stdlib.h>
#include <iom...
Problem with basic functionNow i think this is the final work but it not works for some reason
[code]
#include <iostream>
#in...
This user does not accept Private Messages | http://www.cplusplus.com/user/Marc_Colome/ | CC-MAIN-2017-26 | refinedweb | 110 | 78.85 |
For most of the incomplete items I see that the scan is not able to get the information for the software items which results in categorizing it in the category as "No antivirus". When investigated I found that the only missing part was the software Inventory.
When tried to re-scan each of these items individually, it was able to get the information on all the software's installed. But how do I run the re-scan on all these in one go? I tried using the incremental scan as well as full scan and also I tried to use all option for scan speed (Slow, Medium and slow) but it is still not able to get the information properly even after subsequent schedules?
Any suggesstions?
3 Replies
Feb 26, 2011 at 2:05 UTC
this could be a feature request - as you say, it's only manual that I can find...
Feb 26, 2011 at 2:33 UTC
Petes PC Repairs is an IT service provider.
cut the scan ranges down to smaller chunks and run a different tmes
remember you can use the plugins to wake machines run the scan then put them to sleep
Feb 26, 2011 at 10:25 UTC
If you are having some difficulties picking up software information with the scan, try running a scan with speed set to slow, incremental disabled and scanner send all data instead of deltas = true.
Depending on where you saw some machines as "No Antivirus", that could be normal if they are servers. Spiceworks gets the AntiVirus up-to-date information through WMI and the namespace that contains that information is not present on Windows servers. | https://community.spiceworks.com/topic/129982-how-to-re-scan-only-the-incomplete-items | CC-MAIN-2017-13 | refinedweb | 278 | 61.09 |
Since I have recently become interested in convex hulls, I decided to go on telling you about the algorithmic geometry. Today we are going to review the building of the so-called minimal convex hulls. Though the picture on the right provides an exhaustive explanation of what they actually are, you will find more formal definitions and two classical examples below.
Minimal Convex Hull Notion
Let the plane have a given finite number of A points. The hull of this set is any closed line H with no self-intersections, so that all A points are within this line. If H is convex (for example, any tangent to this line does not intersect it in any point), the corresponding hull is also named convex. Finally, a minimal convex hull is a convex hull of the minimal length (minimal perimeter). I have not checked (I guess it can be proved by contradiction), but it seems obvious that a minimal convex hull is required to be convex. All the mentioned definitions are depicted below:
The main peculiarity of a minimal convex hull of A points set is the fact that this hull represents a convex polygon. Its vertices are some points of A. Therefore, the task of minimal convex hull searching comes to selecting and ordering the necessary points. Ordering is necessary, as an output of an algorithm should be a polygon (i.e. a sequence of vertices). Let’s add an additional condition for the order of vertex location – the orientation of a polygon should be positive. Reminding you that positive is the counter clockwise traversing of a figure.
The task of building a minimal convex hull is considered to be one of the simplest tasks in computational geometry. There are plenty of different algorithms for it. We are going to review two of them: Graham scan and Jarvis march. Their description is illustrated by the code in Python. Both algorithms require orientation function which was reviewed in details in my previous post. Keep in mind that this function determines from which side C point is located relatively to AB vector. The returned positive value corresponds to the left side (the three points constitute a «left turn» or counter-clockwise orientation), the negative one – to the right side («right turn» or clockwise orientation).
def orientation(A,B,C): return (B[0]-A[0])*(C[1]-B[1])-(B[1]-A[1])*(C[0]-B[0])
Graham scan
This algorithm has three steps. At the first step we search for any point in A that enters the minimal convex hull for sure. It’s no brainer that such point will be, for example, the one with the least x-coordinate (the left-most one in A). We will move this point (we’ll name it starting point) to the beginning of the list and will work with the remaining points. For certain reasons, the initial array of A points will not be changed. We’re going to use the indirect addressing for all manipulations with the points. We’ll create P list that will store numbers of the points (their position in A array). Thus, at the first stage of the algorithm the first point in P should be the one with the least x-coordinate. The code:
def grahamscan(A): n = len(A) # number of points P = range(n) # number of point numbers for i in range(1,n): if A[P[i]][0]<A[P[0]][0]: # if P[i] point is on the left from P[0] point, P[i], P[0] = P[0], P[i] # swap the numbers of these points
The second step of Graham scan is sort a set of points in increasing order (except for P[0]) as for their left position with regard to the starting R=AP[0] point. We’ll say that B<C if C point is on the left from RB vector.
To achieve such ordering, we can apply any sort algorithm based on pair-wise comparison of these elements, for instance, a quicksort. Due to certain reasons, I will use the insertion sort.
I will really appreciate if you can tell me how to apply the native Python sort here…
Anyway, the insertion sort (do not forget about the indirect addressing and the fact that the starting point is not sorted):
for i in range(2,n): j = i while j>1 and (rotate(A[P[0]],A[P[j-1]],A[P[j]])<0): P[j], P[j-1] = P[j-1], P[j] j -= 1
The following picture illustrates the sort result:
If we now join the points in the obtained order, we will get a polygon that is not actually a convex.
Let’s move on to the third step. All we have to do is to cut angles. In order to do that, we should traverse all the remaining vertices and delete the ones where the right turn happens (the angle in such vertex is bigger than straight). Create S stack (a list) and place the first two vertices into it (they enter the minimal convex hull for sure).
S = [P[0],P[1]]
Then look through all other vertices, keep track of recent three points, and find the angle formed by them. If orientation of these points is not counterclockwise, we can cut the angle by removing the last vertex from the stack. As soon as orientation is clockwise, it is no longer necessary to cut angles, so we will place the current vertex into the stack.
for i in range(2,n): while orientation(A[S[-2]],A[S[-1]],A[P[i]])<0: del S[-1] # pop(S) S.append(P[i]) # push(S,P[i])
As a result, the sought sequence of vertices is in S stack. It also has the needed orientation, which defines the minimal convex hull of A points set.
return S
The time complexity of the first and the last steps of the algorithm is linear (or O(n)).
Though the latter case has a nested loop, but each vertex inside this loop is pushed into the stack just once and can not be popped from there more than once. Therefore, the algorithm complexity is defined by the second step – sorting. That’s exactly why the insertion sort is not the best variant when n are big. If we replace it with the quicksort, we will get a summarized algorithm complexity O(nlogn).
Can we improve this time? It is proved, that If the algorithm is based on the pair-wise comparison of points (like ours), the estimate can not be improved in the general case. From this point of view, Graham scan is the best solution here. Nevertheless, it has one characteristic which is not nice. It is not adaptive in the sense that it does not matter, how many vertices will enter the minimal convex hull (three, five, ten or n), the time will be linearly- logarithmic anyway. Jarvis march, which we are going to review below, has the mentioned adaptivity.
Complete source code of the Graham Scan:
def grahamscan(A): n = len(A) # number of points P = range(n) # the list of point numbers for i in range(1,n): if A[P[i]][0]<A[P[0]][0]: P[i], P[0] = P[0], P[i] # swap the numbers of these points for i in range(2,n): # insertion sort j = i while j>1 and (rotate(A[P[0]],A[P[j-1]],A[P[j]])<0): P[j], P[j-1] = P[j-1], P[j] j -= 1 S = [P[0],P[1]] # create the stack for i in range(2,n): while rotate(A[S[-2]],A[S[-1]],A[P[i]])<0: del S[-1] # pop(S) S.append(P[i]) # push(S,P[i]) return S
Jarvis March
Jarvis march (aka gift wrapping algorithm) is conceptually simpler than Graham Scan. There are two steps in it and it does not require sorting. The first step is the same – we need a starting point that enters the minimal convex hull for sure. Let’s take the left-most point from A:
def jarvismarch(A): n = len(A) P = range(n) for i in range(1,n): if A[P[i]][0]<A[P[0]][0]: P[i], P[0] = P[0], P[i]
At the second step we will build a minimal convex hull. The idea is that we make the starting vertex a current one, find the right-most point in A with regard to the current vertex and make it current, etc. The process finishes when the current vertex will again become the starting one. As soon as the point is inside the minimal convex hull, we can ignore it. That’s why we should create another H list that will store the minimal convex hull vertices in the correct order. Let’s place a starting vertex in it and move it to the end of P list (that’s exactly where we will find it and finish the algorithm).
H = [P[0]] del P[0] P.append(H[0])
Now let’s make an infinite loop. For each iteration loop find the left-most point of P with regard to the last vertex in H. If this vertex is the starting one, we will terminate the loop, otherwise – move the found vertex from P to H. After the loop is done, we will return H, which will contain the hull in it.
while True: right = 0 for i in range(1,len(P)): if rotate(A[H[-1]],A[P[right]],A[P[i]])<0: right = i if P[right]==H[0]: break else: H.append(P[right]) del P[right] return H
Wow! I’ve managed to tell you about Jarvis march without using any pictures! The following one illustrates all of it!
Let’s estimate time complexity of Jarvis march. The first step is linear (O(n)). The second one is more interesting. We have a nested loop, the number of external iterations that is equal to the number of h heights in the minimal convex hull. As for internal iterations, their quantity does not exceed n. So time complexity of the complete algorithm is O(hn). This formula is a bit unusual, as time complexity is defined not only by length of the input data, but also by the output length (output-sensitive algorithm). At worst, all points from A belong to the minimal convex hull (i.e. A is a convex polygon itself), then h=n and complexity becomes quadratic. At best (if all points from A are not on the same line), h=3 and complexity becomes linear. We just have to understand, which of the cases is ours. It is not a simple task, unless you we have a time machine. We can judge from the type of the task. If there are plenty of points and they evenly fill some area, Jarvis can be faster. But if the data is gathered at the boundary, Graham will be faster.
**Time machine is quite a useful thing in the context of algorithms. Using it, we can immediately solve any task requiring a billion years of calculations. We should just start a program, get into the time machine, “fly” to the future and come back. We just have to find out the way of providing continuous computer operation for several billion years.
The Complete code of Jarvis march:
def jarvismarch(A): n = len(A) P = range(n) # start point for i in range(1,n): if A[P[i]][0]<A[P[0]][0]: P[i], P[0] = P[0], P[i] H = [P[0]] del P[0] P.append(H[0]) while True: right = 0 for i in range(1,len(P)): if rotate(A[H[-1]],A[P[right]],A[P[i]])<0: right = i if P[right]==H[0]: break else: H.append(P[right]) del P[right] return H
Summary
To my mind, the task of building minimal convex hulls is quite a good way to begin with computational geometry. It is quite simple to think out an algorithm of your own, but it will certainly be a variation of Jarvis march. It has been affirmed that this task has plenty of applications, the bigger part of which is related to pattern recognition, clusterization, and so on. Besides that, this task is also used as a supplement for solving more difficult tasks of computational geometry. It is worth noting that this task has quite an interesting three-dimensional generalization.
Thank you for reading the post!
1. Instead of defining «hull», one can just state it as a «a closed curve that encloses all the points». «Hull» by itself isn't used much outside this paragraph, and one can just say «closed curve» instead of «hull» to refer to the hull because there is little ambiguity.
2. One can then define what it means for a closed curve to be convex.
3. Replace all occurrence of «minimal convex hull» with «convex hull». Define the «convex hull of S» as the region bounded by the shortest convex closed curve that contains all the points in S.
4. Finally, one can state that what it means to «find the convex hull». State it as finding the boundary curve of the convex hull(which is the original «minimal convex hull»).
One can prove this definition is equivalent to the convex hull definition for finite set of points on the plane in wikipedia.
Off-topic: this conversation brought us to an interesting idea. What if we would let our users to edit articles and send diffs to authors, similar to git pull requests?
Also, is the full code available somewhere (e.g. Github)? It would be nice to see! Thanks for the informative post!
Upload image | https://kukuruku.co/hub/algorithms/building-a-minimal-convex-hull?ModPagespeed=noscript | CC-MAIN-2022-33 | refinedweb | 2,313 | 70.33 |
Hi,
I just started programming in C++, so I wonder if I just have messy programming, or that this is something wierd. My problem is the following:
I have to fill a matrix with numbers (normally with random numbers, but for the example I just fill them fill the iteration variable, see code below). After some weird results farther down the code, I noticed that the numbers I filled the matrix with, also showed up in another non-related variable.
I started to play around with that, and the wierd thing is, that if I declare a new variable after the variable that was filled up first, that new variable gets filled instead of the previous one.
In the code below I fill 3 three variables (each a 1 dimension matrix) with the number 12 for every element.
Then I fill a 2 dimensional matrix with different numbers.
The last (in order of declaration) 1 dimensional matrix takes over values which should only be in the 2 dimensional matrix.
I do not know what is happening here. I use the bloodshed dev c++ compiler.
Any suggestions are greatly appreciated. I think can ignore the problem by declaring an extra 1 dimension matrix that I will never use, but still it feels like there is something happening I don't know.
Here's the code:
Code:#include <iostream> #include <stdio.h> #include <cmath> #include <sstream> #include <string> using namespace std; int main() { int maxalleles=10; double freq[maxalleles], margw[maxalleles], mutant[maxalleles]; double w[maxalleles][maxalleles]; for (int i=1; i<=maxalleles; ++i){ freq[i]=12; margw[i]=12; mutant[i]=12; for (int j=1; j<=maxalleles; ++j){ w[i][j]=i; w[j][i]=w[i][j];//mirror the matrix, nessecary for calculations furtheron, but not in this code. } } for (int i=1; i<=maxalleles; ++i){ cout<<"allele "<<i<<" = "<<freq[i]<<"\n"; cout<< "margw "<<i<<" = "<<margw[i]<<"\n"; cout<<"mutant "<<i<<" = "<<mutant[i]<<"\n"; for (int j=1; j<=maxalleles; ++j){ cout<<"matrix "<<i<<" "<<j<<" ="<<w[i][j]<<"\n"; } } cin.get(); } | http://cboard.cprogramming.com/cplusplus-programming/60006-why-does-my-iteration-fill-matrix-fill-another-non-related-matrix-well.html | CC-MAIN-2015-27 | refinedweb | 342 | 50.06 |
Details
Description
This patch changes the way GC requests TLS data: Instead of asking VM GC calls to TM directly.
After the patch is applied GC is able to report static offsets for all TLS fields it uses to JIT
Issue Links
- depends upon
HARMONY-1942 [drlvm] Back-branch polling TLS offset is incorrect. Stability and performance fix
- Closed
Activity
- All
- Work Log
- History
- Activity
- Transitions
The patch must be applied inside of gc_cc folder after the patch from H1942.
There are two outstanding issues:
1)
We need to get consensus on Xiao Feng's comments on API design
2)
A patch for GCV5 will need to be added to this JIRA. There needs to be one commit for all GCs.
Weldon,
this patch does not break the old design. So GCv4 and GCv5 will continue work as they are.
Does frontier allocation still works? Why don't we disable it with 'return false' otherwise?
Boolean gc_supports_frontier_allocation(unsigned *offset_of_current, unsigned *offset_of_limit) {
// Need additional support for object offset in native stubs.
- *offset_of_current = field_offset(GC_Thread_Info, tls_current_free);
- *offset_of_limit = field_offset(GC_Thread_Info, tls_current_cleaned);
+ *offset_of_current = tls_offset_current;
+ *offset_of_limit = tls_offset_clean;
return true;
^^^ here
You are right. the offsets I use here have different meaning. I will update the patch.
Here is a microtest, that shows that there are no performance degradation with this patch:
public class Test {
public static void main(String[] args)
public static void foo2() {
long t1 = System.currentTimeMillis();
Object o = null;
for (int i=0;i<400*1000*1000;i++)
long t2 = System.currentTimeMillis();
System.out.println("Time:"+(t2-t1) + " o="+o);
}
}
The results:
1) clean + H1942:
Time:14734 o=java.lang.Object@205dbce4
2) clean + H1942 + this JIRA
Time:13719 o=java.lang.Object@20f2d684
3) clean + H1942 + this JIRA + helper inlining JIRA (Note: JIT does optimize address ariphmethics today and do not moves fs[14]+offset out of the loops)
Time:2640 o=java.lang.Object@20488304
Of course the performance benefit on real application will be 100 times lower.
Could not resist and run the test on SUN and BEA. The results I have on my PC:
4) Sun 1.5
Time:2375 o=java.lang.Object@45a877
5) BEA 1.5
Time:9375 o=java.lang.Object@2ca699
The updated patch.
gc_supports_frontier_allocation return 'false' now.
Patch is ok to me now. Good work!
smoke test passes on windowsxp and linux w/ gcc 4.0.2
the patch | https://issues.apache.org/jira/browse/HARMONY-1949?focusedCommentId=12444820&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2015-35 | refinedweb | 396 | 59.5 |
Offloading tasks to run in the background can be really useful. There are times when your users don’t need to wait around for a task (such as sending an email) to finish
One thing that’s always bothered me though is the ceremony involved in consuming messages. Whether it’s RabbitMQ or Amazon SQS I’ve had to write some variation of a
while(true) loop to keep checking the queue for any new messages.
Azure Web Jobs can really simplify your message consuming code and finally get rid of those pesky loops!
Storage queues
I opted to use storage queues instead of service bus as webjobs uses them “out of the box” and they’re easy to get started with.
public void SubmitDetails(string fromEmail, string fromName, string message) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=accountName;AccountKey=someKey"); CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference("contact-us"); queue.CreateIfNotExists(); var contactUsMessage = new ContactUsMessage(fromEmail, fromName, message); queue.AddMessage(new CloudQueueMessage(JsonConvert.SerializeObject(contactUsMessage))); }
This code is simple enough. I need a queue so this code creates one (if it doesn’t already exist) then pushes a message onto it.
Webjobs work so you don’t have to
The real fun starts when we consume these messages using webjobs.
There’s a webjobs project template available in Visual Studio which adds a webjobs project to any existing solution. Keeping the webjobs project with your web site makes it easy to manage.
class Program { // Please set the following connection strings in app.config for this WebJob to run: // AzureWebJobsDashboard and AzureWebJobsStorage static void Main() { var host = new JobHost(); // The following code ensures that the WebJob will be running continuously host.RunAndBlock(); } }
This boilerplate code in program.cs tells us what to do next.
I already had a storage account set up in Azure (I used it earlier when sending messages) so I set that in app.config for both **AzureWebJobsDashboard **and AzureWebJobsStorage.
A word to the wise, you can’t use the development storage (emulator) for webjobs so don’t even try (I found out the hard way when my first attempt blew up).
With the connection sorted I turned to receiving messages when they’re pushed onto the queue.
public class Functions { // This function will get triggered/executed when a new message is written // on an Azure Queue called queue. public static void ProcessQueueMessage([QueueTrigger("contact-us")] ContactUsMessage message, TextWriter log) { EmailSender.Send(message.FromEmail, message.FromName, message.Message); } }
This is brilliant. I love the fact that the message is automatically deserialised. It’s easy to test too because the webjobs.exe can run locally as well as being deployed to the cloud.
So how do you deploy this thing to Azure?
At first I was concerned that publishing to an existing web site on Azure might overwrite the site with the WebJob but using the Publish as Azure WebJob menu option in Visual Studio deploys it alongside your web app.
Making it visible
When you view the app in the Azure Portal there is a link to view the WebJob and it’s dashboard.
My first attempt to view the dashboard didn’t go so well when I got this error.
“Make sure that you are setting a connection string named AzureWebJobsDashboard in your Microsoft Azure Website configuration by using the following formatDefaultEndpointsProtocol=https;AccountName=NAME;AccountKey=KEY pointing to the Microsoft Azure Storage account where the Microsoft Azure WebJobs Runtime logs are stored."
For some reason Microsoft feel the need to tell you this twice.
This is easy to correct, you just need to set your storage connection strings for your web app in the portal (via settings).
And that’s that. You might have noticed that I actually have two web job instances up and running for this web app. If you’re thinking about smaller, more focused services (microservices) this is useful as you can split up your background tasks into their own webjobs. Just add more webjobs project to your solution.
Turning it up to eleven
There’s a lot more that can be done with Azure Web Jobs, not least running scheduled tasks and using Service Bus to perform multiple actions from the same message.
Finally I’d love to hear from you, what do you want to know about web jobs, If you’ve used them what challenges have you faced? | https://jonhilton.net/2016/02/18/azure-bites-background-tasks-for-your-web-site-using-azure-webjobs/ | CC-MAIN-2020-40 | refinedweb | 731 | 54.83 |
Martijn Faassen wrote: >> I would really like to hear what kind of directives you imagine for >> Silva here (and what you mean by "new ways to configure components"). > > > The following are candidates, though note I haven't thought this through > deeply for any of them: > > * a way to register a Silva content object. > > * a way to register a content object version. > > * a way to register a Silva metadata set. > > * registering directory views (could go into CMF, though Silva is not > using it directly now)
Advertising
... > * registering a silva service into the Silva root > > * configuring which objects can be addable. > > * setting up zope 2 permission/role mapping in Silva root. > > * setting up the zope 2 catalog indexes. I guess most of these fall under the "registering something that isn't a utility or adapter" category which is fine. Though I wouldn't be surprised some of those registrations could be boiled down to simpler, Zope-3-style things like menu items or utilities. Oh wait, you mention that yourself :). > * a way to register an XSLT renderer. > > * registering XML importers and exporters. These two immediately triggered "adapter" in my mind :). > I think some, or even all, of these can probably turn *eventually* into > Zope 3-style approaches directly - probably services will become some > sort of local utilities, and directory views will become Zope 3 view, > XSLT another, and the importers/exporters will become some sort of > adapters, addables menus. > > The emphasis is on eventually, as I certainly expect it to be useful in > a transition phase to clean out Silva's current grotty install.py and > replace it with ZCML that doesn't require significant refactorings of > Silva yet. Replacing this stuff with native Zope 3 components is > generally a major task. I agree on the eventuality. It's important, though, that we do try to find a good match between the Zope 3 ways of doing things and the historical baggage. In Zope 3 we have developed a nice way of looking at things and fit them into very simple concepts. It should be preserved. Btw, I find it a bit scary that you're trying to replace an install method with a lot of ZCML directives. I'm not sure I would welcome a procedure expressed through configuration. It seems like some of these problems are better tucked away using a deployment framework like GenericSetup. But then again, I'm not really familiar with Silva and that install.py thing. >>> Sometimes a new, short directive is a lot easier to >>> remember than to remember long.dotted.names.pointing.to.places and 3 >>> directives. Having to remember (or worse, look up) long dotted names is >>> extremely common in ZCML and I consider it at least as big a problem as >>> having to learn directives. >> >> >> I agree. Many of these long dotted names belong into Python, though. >> >> >>> Let's use abstraction and naming things where it makes sense. >>> >>> Heh, perhaps we need to go the other way and add a namespace directive >>> for long dotted names instead. :) >> >> >> -1. > > > I put in a smiley, but I'm serious about the underlying problem of > exposing a lot of long dotted names into Python modules into ZCML. No worries, I got the tone of the message. However, to every satire there's a true core message, as you're pointing out yourself. I too am concerned, but I also think that because dotted names actually have a meaning, they might be handier in the end than cryptic short forms. And then there's also the point of intrinsic information of a component that we're currently putting into ZCML but are starting to put into Python. I has already reduced the amount of dotted names necessary. > I wonder whether we can do things to make this look simpler. If the > dotted names were not hiding in attributes but in element content, we > could come up with some kind of XML vocabulary for them, even. :) At least it would give you the possibility to define and use XML entities for them :). Seriously, though, I wouldn't be sure of my vote for a system like that. As said, dotted names have a meaningful background (Python import paths). Abbreviations most likely don't. I rather build something that makes sense than one that relies on too many naming conventions... >>>> That said, there might still be a small percentage of cases where >>>> custom >>>> directives are a valid tool. I can accept their being on the same >>>> namespace as >>>> others. In fact, I would like it to be that way, reducing the amount of >>>> dead chickens (namespace declarations). >>> >>> >>> Namespace declarations are not dead chickens. They're things that the >>> XML language requires. Indentation and colons are not dead chickens in >>> Python either. *particular* namespace declarations may be unnecessary - >>> but not dead chickens, just perhaps the wrong solution. >> >> >> Yeah, sorry, bad wording. I just think having to declare 3 to 5 different >> namespaces on the top of the file of which some have no apparent >> meaning or distinction seems like clutter to me. > > > Some indeed have no apparent meaning and distinction; I think > zcml:condition could be safely folded into Zope's namespace. When I see > apidoc or wfmc I can identify what is involved, though - possibly they > can still be eliminated but they definitely have meaning to me. > > In the documentlibrary, so far we've only used two namespaces, zope and > browser. In schooltool, more namespace happen: apidoc, wfmc, i18n and > zcml. I think eliminating the 'zcml' namespace would get us down to 2 or > less declarations for most .zcml files. I think the 'zcml' namespace should be separate from the 'zope' one because 'zcml' is meta-ish whereas 'zope' is about actual and factual directives. I would rather see 'meta' directives folded into 'zcml' (like I propose in the proposal). >> Note that I absolutely see the necessity for namespace declarations. For >> example, I would like to see ZPT require the declaration of TAL, METAL >> and >> I18N namespaces. Note that there the entire namespace story is different. >> There they are used for what I think namespaces are intended, separating >> several XML models (e.g. the HTML model from the additional >> TAL/METAL/I18N model). > > I think Zope 3 extensions extend the Zope 3 XML model. They're less > different than combining XHTML with TAL, but I still see a core > vocabulary with potentially arbitrary extensions. Seems like a good distinction, though it also would suggest that perhaps everything living in 'zope.*' packages should only use one namespace ('zope'), just like other packages would use other namespaces. *That* would be a ZCML namespace policy I would be comfortable with. Philipp _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub: | https://www.mail-archive.com/zope3-dev@zope.org/msg04119.html | CC-MAIN-2017-04 | refinedweb | 1,120 | 64.71 |
[FollowUp] jQuery Mobile Seems incompatible with XPages in Domino 9.0April 21, 2013 – 11:18 am
This is a follow up on an article, David Leedy wrote yesterday
I recently ran into an issue with Domino 9 and jQuery Mobile. I had to completely deactivate Dojo. Otherwise the mobile components did not render. But doing so, I would lost all of the XPages functions like partial refresh et al. On friday, my colleague at BCC asked a question on StackOverflow regarding a problem with jQuery Mobile. He finally got it working by ACTIVATING Dojo in the application.
Over the weekend, I tried to find out, what was going on. Here are my findings
In our project we are using jQuery 1.9.1 + jQuery Mobile 1.3.1 and the application needs to work even on Domino 8.5.1. This part works. No problem here.
There is a difference in the development platform. While my colleague uses IBMNotes/Domino 8.5.3, I use IBM Notes/Domino 9.
ND 8.5.3 comes with Dojo 1.5.1 and ND 9 has Dojo 1.8.1 as its default. Should not make any difference …
The first hint came from Mark Roden
jQuery Mobile uses attributes like data-role=”page” and if Mark was right, using a different namespace , changing the attributes to data-bcc-role=” … should fix the issue. To make a long story short; it does not.
Next, I installed the application on ND 8.5.1 FP3 and it worked as expected. The only thing that did nor work was pagers in views and other events.
This is caused by the createForm=”false” entry in the page root. This setting was recommended bay several members of the community; so I just folowed their recommendation.
To make events work, you have to put a xp:form tag around your view control. Tim Tripcony posted an interesting entry on StackOverflow. I recommend, that you read this article.
After adding the tag to the controls, everything worked just fine.
Next was to upgrade the server step by step to release 9. Everything worked fine until I upgraded the server to version 9. I then moved the dojo-xxx folders from the previous installations to the IBM\Lotus\Domino\data\domino\js folder. Next I configured the server to use a specific Dojo version by editing the xsp.properties file in IBM\Lotus\Domino\data\properties.
With xsp.client.script.dojo.version=1.5.1 my application started to work on ND9 without any issue. Here is an overview of which version of Dojo and Domino worked, which had issues and which combinations did not work at all.
But configuring the whole server to use a different Dojo version is not a good idea. In ND 9, you can also set the dojo version in xsp.properties in the application.
So my workaround for now is to set the dojo version to 1.5.1 in the application. ND9 has Dojo 1.5.2 installed in the IBM\Lotus\Domino\data\domino\js folder, but using this version, events are not triggerd. You will see the following error in WebInspector console in Safari.
One Response to “[FollowUp] jQuery Mobile Seems incompatible with XPages in Domino 9.0”
Just for clarification: You can define the dojo version on application level in Domino versions prior version 9.
Dojo 1.5.2 has no XSP libraries, but you can copy the folder dojo-1.5.1/ibm/xsp to your dojo-1.5.2/ibm/ folder. Then your XPages functionality should work.
BTW: what will happen if you are using the Dojo Lite version?
By Sven Hasselbach on Apr 21, 2013 | http://www.eknori.de/2013-04-21/followup-jquery-mobile-seems-incompatible-with-xpages-in-domino-9-0/ | CC-MAIN-2016-44 | refinedweb | 617 | 69.18 |
[
]
Christopher Currens resolved LUCENENET-515.
-------------------------------------------
Resolution: Fixed
Sorry, Simon. I thought I closed this out already. It looks good to me.
> bring back TokenStream.GetAttribute(Type).
> ------------------------------------------
>
> Key: LUCENENET-515
> URL:
> Project: Lucene.Net
> Issue Type: Improvement
> Components: Lucene.Net Core
> Affects Versions: Lucene.Net 3.0.3
> Reporter: Jens Melgaard
> Fix For: Lucene.Net 3.6
>
>
>...
> {code}TokenStream.GetAttribute(typeof(TermAttribute));{code}
> And god I hated that, so now I replaced it with the much more beautiful:
> {code}TokenStream.GetAttribute<TermAttribute>();{code}
> And deleted that old hag of a method taking a Type... And now I am happy...
> BUT!...
> What when...
> {code}
> Type myNotDefinedHereType = GetTypeFromSomeWhere();
> TokenSteam.GetAttribute.... ?????!?!?!?... Uhm... What now????
> {code}
> Now you have to write a whole lot of reflection mess, use a dynamically compiled delegate
using IL-Emit or the Mono Compiler as a Service...
> All of those 3 workarounds are generally just ugly...
> If you keept both...
> {code}
> Type myNotDefinedHereType = GetTypeFromSomeWhere();
> TokenSteam.GetAttribute(myNotDefinedHereType);
> {code}
> While it might be unlikely that it will ever be used, there is always the off case, and
API's should support both...
> So instead of:
> {code}
> public virtual T GetAttribute<T>() where T : IAttribute
> {
> Type key = typeof (T);
> if (!this.attributes.ContainsKey(key))
> throw new ArgumentException("This AttributeSource does not have the attribute
'" + key.FullName + "'.");
> else
> return (T) this.attributes[key].Value;
> }
> {code}
> Do:
> {code}
>;
> }
> {code}
--
This message is automatically generated by JIRA.
If you think it was sent incorrectly, please contact your JIRA administrators
For more information on JIRA, see: | https://mail-archives.eu.apache.org/mod_mbox/lucenenet-dev/201212.mbox/%3CJIRA.12622900.1354884549095.56827.1356643212188@arcas%3E | CC-MAIN-2021-21 | refinedweb | 250 | 53.47 |
#include <cafe/vpad.h> #define VPAD_BUTTON_PROC_MODE_LOOSE 0 #define VPAD_BUTTON_PROC_MODE_TIGHT 1 void VPADSetButtonProcMode( s32 chan, u8 mode );
None.
Sets the method by which the button status should be processed inside the
VPADRead function.
When the
VPADRead function is called, the existing VPAD library copies the most recent button status into the
VPADStatus structure within the ring buffer..
If the
VPAD_BUTTON_PROC_MODE_LOOSE is set by this function, only the most recent values are accessed when the
VPADRead functions are called, and those values are copied into all the current-frame sampling buffers.
2013/05/08 Automated cleanup pass.
2012/10/05 Added the comment.
2011/03/30 Initial version.
CONFIDENTIAL | http://anus.trade/wiiu/personalshit/wiiusdkdocs/fuckyoudontguessmylinks/actuallykillyourself/AA3395599559ASDLG/pads/vpad/VPADSetButtonProcMode.html | CC-MAIN-2018-05 | refinedweb | 107 | 57.27 |
UPDATE:
This thread is out of date (well, at least the beginning) and no longer the most optimal means to reach the community.
If you have useful things to contribute, our irc/mailing list/wiki is probably a better choice.
See:
Inspired by
ideas on how i sort of want it:
- Uzbl.
In my opinion, any program can only be really useful if it complies to the unix philosophy.
Web browsers are frequent violators of this principle. Time to change that!
Right now uzbl is in a very early state but here are some ideas I would like to (not) implement
- each instance of uzbl renders 1 page (eg it's a small wrapper around webkit), no tabbing, tab previews, or speed dial
things. we have window managers for that.
- simple ini config file ("profile") for keyboard, network,.. settings
- implement some basic keyboard shortcuts for going up, down, refresh etc
- listen to signals and do useful stuff when triggered.
- open up a socket file/fifo/.. so we can easily control each instance by writing things like 'uri <foo>' to
/tmp/uzbl-pid
- MAYBE (if needed): 1 control application called uzblctrl or something. use this to modify the behavior of a uzbl
instance (change url, refresh). use xdotool to get the window with focus. eg uzblctrl -win <id> -url <http://>.
use xbindkeys to bind keys to call uzblctrl.
- no bookmark management builtin. make your own solution. for pulling a bookmark a plaintxt-based program using dmenu
would work great here. combine with uzbltcrl and xbindkeys.
uzblctrl should support an option to query the current page so you can script something to add to your bookmarks. use
zenity or something to add tags.
- similar story for history.
-)
- no download manager. allow user to pick wget/curl/a custom script/...
- no build in command interpreters like ubiquity. uzbl should be accessible and you should use a shell or similar.
to figure out:
- password management. maybe an encrypted store that unlocks with an ssh key?
- how to handle hyperlinks? number them like konqueror does?
NOTE:
- My c skills are very rusty, it will take me a while to get back up to speed
current state? very close to zero.
you can all uzbl --uri http://<someurl> and it will open a window with the rendered page. That's it.
howto @ … 580e/HOWTO
Last edited by Dieter@be (2009-06-19 07:17:30)
< Daenyth> and he works prolifically
4 8 15 16 23 42
Offline
I applaud you for trying to think out of the box!
I disagree though on the tabbing issue. I think that it would be silly to have single windows for each page. i have a reason for that. when i have my browser open for reference work or something, i usually move it around, out of the way or something and it would annoy me to no end if i had to move all the windows around one by one (and yes, i am sure there would be some clever thing to make a certain window manager do that for me, but I don't think that is the task of a window manager. (although the name "window manager" would technically suggest it, i still don't think so)
good luck nontheless!
cheers
Barde
Offline
At the moment, what it really needs is a way to open a link in a new window (middle-click?)
This weekend I'll definitely do some reading up on C / WebKit and see if I can contribute to this.
Last edited by Barrucadu (2009-04-22 20:54:05)
Offline
Maybe you can do tabbing in the control window. Like store a cache of all pages for quick switching. i.e. ./uzbl --cache ~/.uzbl/cache/tab1, not sure how webkit works with that, and it would definitely have to be stored in RAM not disk...
By the way does webkit have multiple rendering methods? Is it possible to tweak things to be more compact?
Offline
The tabbing part could actually be put into a separate application, this would make it more general and usable for other applications too (terminals comes to my mind). Anyway, I think this is an interesting approach for a web browser.
Offline
one note on the whole tabbing discussion:
the 'philosophy' behind ditching the tabs? unix = one tool, one job; leave stuff like that to the WM, that's what it's there for. many WMs will tab any and all apps (PekWM and Fluxbox i believe). and this is actually an awesome and underused feature IMO. you pick a window, drag it 'onto' another window, and now you've got a tabbed titlebar of Terminal, Firefox, and Pidgin (or whatever) you can use the mouse wheel or keystrokes to move through the layers / tabs. from there, it's not a far mental leap to dumping a few uzbl windows onto each other and getting --all-- the existing tab functionality entirely from the WM.
... i would miss firefox's S-C-t though, that one's a life saver.
Offline
@brisbin33: But what about 50+ tabs?
Offline
Just to clarify one thing, I was thinking on tab support as a separate application for those window managers that doesn't have built-in support for tabbing, for example openbox, icewm, metacity.
To be far, I don't think tabs are that important and I think it might be better to keep it as simple as possible in the beginning and extend it with feature later on.
Offline
This is a gui based browser right? or is thisa CLI based one?
As for GUI browsers, some things that I always use :
1) Tabs
2) ability to retain session, so that you don't have to enter the password at a site everytime you visit it. This is one of the reasons, I use links etc sparingly.
3) speed dial -- although I guess this is better of being a separate add on.
There's no such thing as a stupid question, but there sure are a lot of inquisitive idiots !
Offline
Offline
Screenshots?
Archi686 User | Old Screenshots | Old .Configs
Vi veri universum vivus vici.
Offline
Picture a browser that has nothing but the content and a statusbar. That's the screenshot.
archlinux - please read this and this — twice — then ask questions.
-- |
Offline
This is so awesome.
Archi686 User | Old Screenshots | Old .Configs
Vi veri universum vivus vici.
Offline
I love it, please stick to your original view, one instance, one page, one window. Plus uzblctrl.
Tabs could be implemented maybe with a seperate app + xembed, although I have no idea how that works, or if xembed is even capable of that, but you get my point.
Or of course as you mentioned window manager tabs too (Edit, I'll also point out that Xmonad has a nice tabbing layout that would be sweet for this)
I'll say it again, I love it
Yet another edit, after reading the other post: Vi keybindings for movement would be great. o + url like vimperator would be great too but that might be going a bit far, probably other ways of achieving that.
Last edited by HashBox (2009-04-22 23:41:00)
Offline
- each instance of uzbl renders 1 page (eg it's a small wrapper around webkit), no tabbing, tab previews, or speed dial
things. we have window managers for that.?
I don't know if there's a better example of convoluting a principle like "one tool, one job." Tabs can provide basic HCI usability. Just because tabs can sometimes be implemented poorly does not mean that tabs should never be implemented at all. Having a window manager deal with a bunch of browser windows is just a bit silly..
Offline
Dieter@be wrote:
- each instance of uzbl renders 1 page (eg it's a small wrapper around webkit), no tabbing, tab previews, or speed dial
things. we have window managers for that.brisbin33 wrote:?
, indeed. GNU Screen's entire purpose is to make multiple programs (perhaps a text-mode browser) easy to manage. It makes perfect sense to let the WM do its job.
Offline
-)
How's that going to work when using a proxy, since the proxy will do all the DNS resolution?
BlueHackers // privy.email // husk firewall compiler
Are you familiar with our Forum Rules and How To Ask Questions The Smart Way?
Online
On the hyperlinks selection matter, what possibilities does webkit offer? IIRC the hints system in vimperator and conkeror is a xulrunner feature, does webkit provide something we could use instead?
What does not kill you will hurt a lot.
Offline
This looks very interesting. It will be perfect with XMonad + XMonad.Layout.Tabbing. Following the progress of this one closely.
Last edited by Ashren (2009-04-23 06:19:13)
Offline
Offline
Wow this is awesome. I'll try to help anyway I can. But as said before..tabs are a must (I use tiling managers...can't have 20 windows running about
)
Flash works seeing how it uses webkit..so for me personally tabs are the only thing stoping me from using this fulltime.
Lemme know if you need any graphics for it, I may find some free time to provide that. But using global gtk themes would be more advised
PS: Is the name final? This might turn into a really well known project..naming should be a great concern
I vote: Bare (Browser) , with a bear like logo (get the word play there I trust)
Add an address text entry there..shouldn't be too hard, I might find some time to do some deving on it this weekend too
PS2: First thing to take care of: --uri loads nada if you don't provide the http:// (eg "--uri" fails)
Last edited by Wra!th (2009-04-23 08:16:37)
MacGregor DESPITE THEM!
7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Offline
I vote: Bare (Browser) , with a bear like logo (get the word play there I trust)
Bare does sound like a good name, uzbl is short enough, but in my opinion hard to remember.
Add an address text entry there..shouldn't be too hard, I might find some time to do some deving on it this weekend too. I dunno, just throwing ideas out there.
My idea of this app would be having the core renderer as one executable, and that being as minimalist as possible, and then having the uzblctrl app able to control the running instances, maybe through id numbers (or window id's as I think was already in the todo). This would be sufficient to be scripted via external means.
Another small project, or maybe as part of this one, could be to create a sort of wrapper, that would implement the tabbing functionality, and maybe an address bar and more traditional browser UI. Sounds like a minimalist Chrome of sorts
Offline
I started working on the tab feature. I am at work so can't really get much done now, but this would qualify as a start.
Things are shamefully hardcoded but this is the jist of it. Obviouslly create_browser() and create_statusbar() need to be rewritten to create individual widgets (webkit widgets too), otherwise tabs will be useless. Yay finally a project to work on
// <gtk/gtknotebook.h> #include <webkit/webkit.h> static GtkWidget* main_window; static GtkWidget* uri_entry; static GtkStatusbar* main_statusbar; static WebKitWebView* web_view; static gchar* main_title; static gint load_progress; static guint status_context_id; static GtkWidget* tabs;); gchar* title = g_string_free (string, FALSE); gtk_window_set_title (window, title); g_free (title); } static void link_hover_cb (WebKitWebView* page, const gchar* title, const gchar* link, gpointer data) { /* underflow is allowed */ gtk_statusbar_pop (main_statusbar, status_context_id); if (link) gtk_statusbar_push (main_statusbar, status_context_id, link); }); return scrolled_window; } static GtkWidget* create_statusbar () { main_statusbar = GTK_STATUSBAR (gtk_statusbar_new ()); status_context_id = gtk_statusbar_get_context_id (main_statusbar, "Link Hover"); return (GtkWidget*)main_statusbar; }); tabs = gtk_notebook_new(); GtkWidget* vbox = gtk_vbox_new (FALSE, 0); gtk_box_pack_start (GTK_BOX (vbox), create_browser(), TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (vbox), create_statusbar(), FALSE, FALSE, 0); gtk_notebook_append_page (GTK_NOTEBOOK (tabs), vbox, gtk_label_new ("TAB 1")); GtkWidget* vbox2 = gtk_vbox_new (FALSE, 0); gtk_box_pack_start (GTK_BOX (vbox2), gtk_label_new("tab 2 content"), TRUE, TRUE, 0); gtk_notebook_append_page (GTK_NOTEBOOK (tabs), vbox2, gtk_label_new ("TAB 2")); main_window = create_window (); gtk_container_add (GTK_CONTAINER (main_window), tabs);; }
MacGregor DESPITE THEM!
7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Offline.
It could be packed next to the status bar so it doesn't waste extra space. I'ma get at it
MacGregor DESPITE THEM!
7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Offline | https://bbs.archlinux.org/viewtopic.php?pid=541194 | CC-MAIN-2016-44 | refinedweb | 2,089 | 72.26 |
Important: Please read the Qt Code of Conduct -
Is there a way to check next events?
Hello,
I would like to check which event will be after QEvent::FocusIn in my application.
I am now in FocusIn function and I know that will be other events after that ( for example mousePressEvent ). How to check it?
I think about:
qDebug()<<eventsQueque.nextEvent();
- mrjj Lifetime Qt Champion last edited by
Hi
I dont think you can check that.
Can i ask what you need it for ?
@mrjj A few days ago I ask about: why QT doesn't see all clicks on the QPushButton ( if I click on them I show a popup window ).
Please check this code:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPushButton> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); public slots: void clickedSlot(); private: Ui::MainWindow *ui; QPushButton *button; QWidget *widget; }; #endif // MAINWINDOW_H
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); button = new QPushButton(this); button->setGeometry(100,100,100,100); connect(button, SIGNAL(clicked()), this, SLOT(clickedSlot())); widget = new QWidget; widget->setWindowFlag(Qt::Popup); widget->setFixedSize(300,300); } MainWindow::~MainWindow() { delete ui; } void MainWindow::clickedSlot() { static int click=1; qDebug()<<click; if(click%2==1) { widget->show(); } else { widget->hide(); } click++; }
This code above is very simple - I only add pushButton and widget. Now please click 2 times fast in a "button". In a qDebug() I get only "1". QWidget should be hide and it is hide. But this hide is because of popup. Now I would like click next time. Now widget should be visible ( this is the third click ), but it isn't ( because QT thinks that is my second clicked on button ).
And that queue with events could be helpful for me ( this is only my try - if you know something better to achieve what I want ( the click%2==1 show, click%2==0 hide, but when QT see all clicks ) - please write :) )
@TomNow99 said in Is there a way to check next events?:
I would like to check which event will be after QEvent::FocusIn in my application.
Only if you can see into the future ;-)
You do not have access to the Qt event queue. If you really wanted to do something like this, you'd have to not act on current event, wait till the next event arrived and act on it there. Doubtless with a timeout.
@TomNow99 said in Is there a way to check next events?:
void MainWindow::clickedSlot()
{
static int click=1;
qDebug()<<click;
if(click%2==1)
{
widget->show();
}
else
{
widget->hide();
}
click++;
}
Instead of counting consecutive clicks, you could check, whether your dialog is shown already or not...
void MainWindow::clickedSlot() { if( !widget->isVisible() ) { widget->show(); } else{ widget->hide(); } }
@Pl45m4 Of course I tried your solution a few days ago. Please look: when the widget has set flag Qt::Popup and when it is visible, when I clicked pushButton with your code I always get widget->show(). Why? Popup is before clicked() signal, so popup hide widget I go to clicked slot and widget is hide, so I show it. Next click the same. So my every click is widget->show().
@TomNow99 said in Is there a way to check next events?:
when I clicked pushButton with your code I always get widget->show()
Yeah, that's how popups are supposed to work.
But why do you want to hide your popup widget especially with this button, when your popup widget will hide on any click anyway? Why do you need
Qt::Popup?
@Pl45m4 I try create something like comboBox. This comboBox has 2 parts: pushButton and widget. When I clicked on pushButton I would like to show or hide widget. User can click outside this button or click on it, so I have to get part "show" and "hide" in clicked slot.
- mrjj Lifetime Qt Champion last edited by
Hi
You can still do this with event filters. | https://forum.qt.io/topic/117808/is-there-a-way-to-check-next-events/1 | CC-MAIN-2021-39 | refinedweb | 677 | 72.46 |
Which XPath to use when cleaning up the Google Play store?
I am browsing the google play store to view applications. I can only get 40 reviews. The problem is the xhr path when reaching the scrapy throws error:
Http status code not processed or resolved
code:
import scrapy from scrapy.exceptions import CloseSpider from scrapy.spider import BaseSpider from scrapy.http import Request class Product(scrapy.Item): brand = scrapy.Field() title = scrapy.Field() class aqaqspider(BaseSpider): name = "gaana" allowed_domains = ["play.google.com"] start_urls = [ "", ] page = 1 def parse(self, response): products = response.xpath('//div[@class="single-review"]') if not products: raise CloseSpider("No more products!") for product in products: item = Product() #item['brand'] = product.xpath(".//span[contains(@class, 'qa-brandName')]/text()").extract()[0].strip() item['title'] = product.xpath('.//.//div/div/span[@class="author-name"]/a/text()').extract()[0].strip() yield item self.page += 1 yield Request(url="" , headers={"Referer": "", "X-Requested-With": "XMLHttpRequest"}, callback=self.parse, dont_filter=True)
Please don't say this is against the Terms of Service. I know this, but I need to learn and move on. I am not using anything.
+3
source to share
No one has answered this question yet | https://daily-blog.netlify.app/questions/2220576/index.html | CC-MAIN-2021-21 | refinedweb | 196 | 55.5 |
# Installing GitLab on OKD (OpenShift Origin)
This document describes a basic outline of how to get GitLab up and running on
an OKD instance using the official Helm charts.
**Note:**:
This guide has been tested only on Openshift Origin 3.11.0 and is not guaranteed
to work on other versions, or SaaS offering of OpenShift, OpenShift Online.
If you face any problems in installing or configuring GitLab by following this
guide, open issues at our [issue tracker]().
Feedback and Merge Requests to improve this document are welcome.
## Known issues
The following issues are known and expected to be applicable to GitLab
installations on OpenShift:
1. Requirement of `anyuid` scc:
- Different components of GitLab, like Sidekiq, unicorn, etc., use UID 1000 to run services.
- PostgreSQL chart runs the service as the `root` user.
- [Issue #752]() is open to investigate more on fixing this.
1. If using `hostpath` volumes, the persistent volume directories in host need to
be given `0777` permissions, for granting all users access to the volumes.
1. Automatic issuing of SSL certificates from Let's Encrypt will not work with
OpenShift router. We suggest [using your own certificates](../tls.md#option-2-use-your-own-wildcard-certificate).
[Issue #894]() is open to
investigate more on fixing this.
## Prerequisite steps
1. Refer to [official documentation]()
to install and configure a cluster.
1. Run `oc cluster status` and confirm the cluster is running:
```bash
oc cluster status
```
The output should be similar to:
```
Web console URL:
Config is at host directory
Volumes are at host directory
Persistent volumes are at host directory /home/okduser/openshift/openshift.local.clusterup/openshift.local.pv
Data will be discarded when cluster is destroyed
```
Note the location of Persistent Volumes in the host machine (in the above example
`/home/okduser/openshift/openshift.local.clusterup/openshift.local.pv`).
The following command expects that path in the `PV_HOST_DIRECTORY` environment variable.
1. Modify the permissions of PV directories (replace the path in the following
command by the value from above):
```bash
sudo chmod -R a+rwx ${PV_HOST_DIRECTORY}/*
```
1. Switch to the system administrator user:
```bash
oc login -u system:admin
```
1. Add `anyuid` scc your namespace's default user:
```bash
oc project ${YOUR_NAMESPACE}
oc adm policy add-scc-to-user anyuid -z default -n ${YOUR_NAMESPACE}
oc adm policy add-scc-to-user anyuid -z gitlab-runner -n ${YOUR_NAMESPACE}
```
CAUTION: **Warning**:
This setting will be applied across the specified namespace and will result
in Docker images that does not explicitly specify user running as `root`.
1. Create the service account and `rolebinding` for RBAC and [install Tiller](../tools.md#helm):
```bash
kubectl create -f
helm init --service-account tiller
```
If you want to enable Git over SSH, you need to take further steps. Theses steps can be taken either before
or after installation. The reason is that OpenShift [Routers]()
only support HTTP and HTTPS protocols and accept traffic on limited number of ports. Hence, for SSH you have to
bypass Routers and use OpenShift Service Network directly.
One method to expose a service is to assign an external IP access directly to the service, in this case GitLab
Shell. You can use [Service with External IP]()
to get SSH traffic into the cluster, but it requires more advanced configuration on both OpenShift and the nodes.
For further details, see [OpenShift manual]().
## Next Steps
Continue with the [installation of the chart](../deployment.md) once you have
the cluster up and running, and the static IP and DNS entry ready.
Before doing so take note of the following changes from the normal chart
installation procedure:
1. We will be using OpenShift's built-in router, and hence need to disable
the nginx-ingress service that is included in the charts. Pass the following
flag to the `helm install` command:
```bash
--set nginx-ingress.enabled=false
```
1. [Use your own SSL certificates](../tls.md#option-2-use-your-own-wildcard-certificate)
1. If you want to enable Git over SSH, you have to assign at least one external IP address to GitLab
Shell service (you can assign multiple external IPs if needs be). Use the following command argument
to pass one or more external IPs, as an array:
```bash
--set gitlab.gitlab-shell.service.externalIPs='{x.x.x.x}'
```
```bash
--set gitlab.gitlab-shell.service.externalIPs='{x.x.x.x,y.y.y.y}'
```
You may have to use an alternative port, in case SSH port is already in use on your node. You may
have to use a different domain name as well. You can use the following for this purpose:
```bash
--set global.shell.port=222
--set global.hosts.ssh=ssh.gitlab.example.com
``` | https://gitlab.com/gitlab-org/charts/gitlab/blame/master/doc/installation/cloud/openshift.md | CC-MAIN-2019-39 | refinedweb | 774 | 55.24 |
0
I hope someone can point out to me what I am doing wrong here. I have a set of picture boxes in an array. If I use the following code with the PictureBox array declared in the private sub, there is no issue. If I put the array as part of a public class so that I can access the array from other private functions, I get the Nullreference error. I don't understand why!
Public class 'declare my array Dim Pboxes() As PictureBox = {PB1, PB2, PB3, PB4, PB5, PB6, PB7, PB8} Dim TBoxes() As TextBox = {TB1, TB2, TB3, TB4, TB5, TB6, TB7, TB8} Private Sub Test 'call a function Call ClearBoxes(Pboxes, TBoxes) End sub Public Sub ClearBoxes(ByRef Pics() As PictureBox, ByRef Txt() As TextBox) For i As Integer = 0 To 7 If Not (Pics(i).Image Is Nothing) Then <<<<<< Nullref at this point Pics(i).Image.Dispose() Pics(i).Image = Nothing End If Txt(i).Text = Nothing Next i End Sub End class | https://www.daniweb.com/programming/software-development/threads/427831/nullreference-exception-was-unhandled | CC-MAIN-2017-34 | refinedweb | 167 | 70.94 |
Beginner’s Guide to Recursion in Python
This article was published as a part of the Data Science Blogathon
Introduction:
Hello Readers, hope all of you are doing great. In this article, we will be covering all the basics needed for a beginner to start with recursion in python.
What is Recursion?
In many programs, you must have implemented a function that calls/invokes some other function. For example :
def A(): b()
Here we see that the function ‘A’ calls the function ‘B’
So a basic example of recursion would be the case, when the function would call itself, in place of some other function.
A function is said to be a recursive function if it calls itself.
They are of two types: indirect and direct recursion.
When a function calls itself directly, from within its body, it is direct recursion. Example :
def rec(): rec()
On the other hand, when a function calls some other function, which in turn calls its caller function again, is called indirect recursion. Example :
def A(): B() def B(): A()
Base Case for Recursion in Python
Let us consider the following code :
def fun1(): print("Hello function 2") fun2() def fun2(): print("Hello function 1") fun1()
Can you predict what shall be the output?
Yes, you guessed it right, the code will print endlessly !!
This is because the functions will keep on calling each other endlessly.
But does this mean, that the entire memory will be used up in the process? NO, python will return an error to prevent that and stop right there.
The error will be something like:
RuntimeError: maximum recursion depth1 exceeded...
So clearly, when using recursion, we must write a sensible code, that instructs the compiler, when to stop the process, this is where Base Case comes into play.
A Base Case is a case, whose result is known or predetermined, without any recursive calling. you will have a better understanding of a base case when u see an example.
Example to calculate the sum of ‘n’ numbers using recursion in Python
Shown below, is the code, to calculate e the sum of first ‘n’ numbers, using recursion.
def rec(n): if n==1 : return 1 # This is a Base Case else: return (n+rec(n-1)) last = int(input("Enter the upper limit")) s = rec(last) print("Sum of series from 1 to ", last," is :", s)
The output of the above code came out to be :
Enter the upper limit 4 Sum of series from 1 to 4 is :10
Let us understand how the code works :
In the ‘main’ block, the rec function is called, with the value that the user entered, which in this case was 4, i.e., rec(4) was invoked initially.
Now the control, shifts to line 1, where code of rec() begins. The variable ‘n’ is assigned value 4.
As n==1 turns out to be false, it goes to the else part.
Line 5 calculates return value as n+rec(n-1), as n=4, it becomes 4 + rec(3)
So rec is again called with value 3. So this goes on and on until the value of n reduces to 1, and the base case is hit, and 1 is returned. No variable s gets the value 10 returned., which then prints the sum of the series in the next line.
Recursive Definition
A Recursive definition is a definition that is made in terms of the smaller version of itself. Consider the following example :
xn = x*x*x*x…n times
Now it can be represented in terms of recursive definition as follows :
xn = x*(xn-1) for n > 1 (This is the recursive definition)
=x (for n=1) or 1 (for n=0)
Writing a recursive function
Before you start writing a recursive function, you must know, that every recursive function must have at least two cases. They are :
1) The Base Case, that we know how to solve, which leads to the recursion to end. In other words, it is the case whose value is pre-known.
2) The Recursive Case is the more general case of the problem we are trying to solve, using a recursive call to the same function.
For example, Power (x,n) = x * Power(x, n-1)
Here , the base case would be :
Power (x,n) = 1 when n=0, or x (when n=1)
NOTE : The base case in a recursive function, MUST BE REACHABLE!
Computing GCD Recursively
We can efficiently compute the gcd of two numbers using the concept of recursion. Note that this holds for positive p and q.
If p>q,
the gcd of p and q is the same as the gcd of p and p%q. That is our python code to compute gcd.
def gcd(p,q):
if q== 0:
return p
return gcd (q,p%q)
Here, the base case is when q is 0, with gcd (p,0) = p. To see that the reduction step converges to the base case, observe that the second input strictly decreases in each recursive call since p%q <q. If p<q the first recursive call switches arguments.
This recursive approach to calculate the GCD of two numbers is called Euclid’s Algorithm.
Recursion versus Iteration
A simple yet crisp difference between the two would be :
In iteration, the block of code is executed repeatedly, using the same memory space. That is, the memory space, once allocated, is used for each pass of the loop.
On the other hand, in recursion, since it involves a function call at each step, fresh memory is allocated for each recursive call. For this reason, because of the function call overheads, the recursive function runs slower than its iterative counterpart.
Disadvantages of recursion
Recursion, along with it, also brings some of its own disadvantages. Some are :
- It is slower as compared to iteration.
- Logical but difficult to find the error, if any exists.
- Requires extra storage space this is because, for every recursive call, separate memory is allocated for the variables.
- Recursive functions often throw a Stack Overflow Exception when processing or operations are too large.
Ending Notes
That ends your journey through recursion, a programming technique in which a function calls itself. Recursion, as you saw, is rightfully isn’t appropriate for every task, and is not always an alternative to iteration. But some programming problems need it. In those situations, it’s a great technique to have at your disposal.
About the Author :
Hey there, I am Pinak Datta, currently, a second-year student, pursuing Computer Science Engineering from Kalinga Institute of Industrial Technology, Bhubaneswar. My interests include Web development, Competitive Coding, and a bit of Machine Learning too. Please feel free to connect with me through my socials. I always love to have a chat with similarly minded people.
Leave a Reply Your email address will not be published. Required fields are marked * | https://www.analyticsvidhya.com/blog/2021/09/beginners-guide-to-recursion-in-python/ | CC-MAIN-2022-33 | refinedweb | 1,152 | 61.56 |
Findings:
- Removing AOL Instant Messenger from your Mac
- Odd numbered Star Trek movies suck
- Life sucks, then you die
- Flying is cool -- It's landing that sucks
- sucks to your assmar
- boys suck
- AOL/Netscape
- AOL Instant Message Protocol
- Chronology Sucks
- TV Sucks
- I wanted to show you something, but the verb sucked
- Fanatical AOL User
- Teach your grandmother how to suck eggs
- career day
- Brain tumor
- A general rhetorical refutation of the position "X sucks"
- Most advertising sucks on purpose
- Preventing AOL Instant Messenger from installing with Netscape
- Why C++ doesn't suck
- Why Pascal Sucks
- Wouldn't it suck to be God's mom and not even get laid in the deal?
- The ground sucks the warmth from my bare and blistered feet
- It really sucks: A Kirby vacuum salesperson's story
- The end of free AOL hours
- Pizza Sucks.™
- Things that sucked about my Alaskan Fishing Adventure
- Why thin client interfaces suck
- SporPops suck (user)
- Evil AOL Instant Messenger graphical smileys
- Why C sucks
- Teenage love can suck pretty bad
- Why 'X' suck(s)
- life sucks (user)
- AOL Instant Messenger
- You can suck dick and still be a virgin, Mary
- Why Diablo II sucks
- Welcome to The Suck
- Fun with AOL say!
- No More AOL CDs
- Clockwatching sucks
- High school can kill you
- Zip him back up, he sucks.
- Unforeseen consequences of the evil AOL instant messenger graphical smileys
- Music was better in the old days
- There is no suck, only blow
- why Yahoo sucks
- Writing a solid metaphor and/or simile
- T35.com sucks
- AOL Delinquent
- Suck and Blow
- Your favorite band sucks
- Towler sucks (user)
- Type my letter, get my coffee, suck my dingdong
- Revolution is not an AOL Keyword
- Primus Sucks!
- subtlety sucks
- Suck line
- School holidays suck
- AOL InstaKiss
- Slashdot Sucks
- Some critical thoughts on the aesthetics of Dragonball Z
- I'm leaving, you all suck
- We suck Young Blood
- suck my load (user)
- Connie the AOL girl
- life sucks
- All of a sudden everything sucks
- Sucking at The Sims
- Suck My Kiss (user)
- poets suck
- 61 things to do with an AOL CD
- Connecting your gaming system to AOL
- The "My parents suck with computers" node
- suck it up
- Life sucks, then you die, then you come back
- polluting the AOL namespace
- seasons suck haiku
- Sucks to be you
- Improving your chess game
- Everyone's code sucks
- accessing the AOL network using unauthorized software
- MTV sucks
- Why the Bible sucks
- When life gives you lemons, suck on them. Seriously, lemons taste awesome.
- Connecting a Gaming Console to AOL Cable
- why life doesn't suck: a pep talk
- Anthropomorphism is for sucks
- Hand them a straw, and they'll suck the life out of you.
- AOL Canada
- Everything Sucks
- suck eggs
- the network sucks
- Why Perl sucks
- nodshell to suck on
- Things I've seen done with those Free AOL CDs
- Why the news media sucks
- the first time always sucks
- fair suck of the sav
- Tales of AOL
- AOL (user)
- Excuse me, could you explain again why you suck?
- Problems with the Power Mac G4 Cube
- I still suck my thumb
- Why Force Fields Suck
- AOL Keyword: Slashdot
- Why Linux sucks
- Suck, squeeze, bang, blow
- Hi, I couldn't help noticing that your life sucks
- Suck It and See
- guy that sucks (user)
- Could AOL phone home?
- Suck it in
- Why does taking a programming class in a language you already know suck so much?
- you suck (user)
- AOL!
- suck
- Why YNN Sucks
- Toad Suck Daze
- College sucked for me too
- A letter to AOL
- Science Fiction sucks
- Watch out! This chair will suck the life force out of you
- You noders still fucking suck, but your needing my wisdoms bad
- Brad Sucks
- u can go suck a fuck (user)
- AOL
- AOL member
- Getting to know you noders fucking sucked
- Getting over "Disco Sucks!"
- Car, honk if you suck: car advertising in America
- Diary of an AOL user
- Things that suck
- You suck, I rule
- Microsoft's .NET strategy
- Evan Sucks (user)
- Enya Sucks So Much More When It's 4:00am at Wal-Mart
- AOL is not the Internet
- Ska Sucks
- Your mother sucks cocks in hell
- Why Catholic School Sucks
- Men suck, right? Men are just plain clueless, isn't that so?
- Life sucks, get a helmet
- AOL chat
- AOL V4.0 Cookie
- Anything popular must suck
- Why Does Smoking Suck?
- Sucks Less!
- It's possible to suck on a straw and breathe at the same time
- AOL Keywords
- magic sucks
- Moving sucks
- Why Mondays suck: an essay I wrote with Albert Camus
- Suck up
- AOL is broken
- I sucked a lot of cock to get where I am
- Life sucks. Get over it.
- Modern video games suck
- Why most collectible card video games suck
- It sucks not being a bear.
- AOL Time Warner
- AOL PLUS
- Stalkers suck
- Why France sucks
- The Radio Still Sucks
- Cartman Sucks
- Leaked AOL memo about hackings and how to handle press
- Psalm 69: The Way To Succeed and the Way to Suck Eggs
- Why nodes about Canada suck
- 67 reasons why Butterfinger McFlurries suck
- Cancer sucks
If you Log in you could create a "AOL Sucks" node. If you don't already have an account, you can register here. | http://everything2.com/title/AOL+Sucks | crawl-003 | refinedweb | 875 | 62.24 |
scalabradscalabrad
A scala interface to labrad.
Running ScalabradRunning Scalabrad
Binary distributions of scalabrad are distributed via bintray. Simply download and install the archive file for the version you want and unpack it on your machine. For example, if you download scalabrad-0.5.0.tar.gz and untar it in some directory
$PATH/, then you can run
$PATH/scalabrad-0.5.0/bin/labrad to start the manager. You'll need to have Java 8 installed on your system, but all other dependencies are included in the package. Windows
.bat files are also included in the distribution, though you may need a tool like 7-Zip to extract the
.tar.gz archive.
Invoke the manager with the
--help option to see documentation of the command line parameters and environment variables that can be used to configure the manager. Note that environment variable names used for configuration must be uppercase, as specified in the help text, even if the underlying OS treats environment variable names as case insesitive (such as Windows).
The scala manager is API-compatible with the old delphi manager. It can store registry data in a different formats to make the registry more efficient, and because the old registry format was ill-defined and had problems encoding and decoding some labrad data. If you have existing registry data that was saved with the old manager, you can configure the manager to continue to read and write in that format (see the command line help for the manager on how to do this), or you can use the included migration tool to migrate the data to the new format. The migration tool is in the bin directory with the manager, e.g.
$PATH/scalabrad-0.5.0/bin/labrad-migrate-registry.
The manager supports using TLS to secure connections to labard for v0.5.0 and above. If you need to allow old clients to continue to connect without TLS authentication, the manager must be called with the flag
--tls-required=false.
ContributingContributing
For instructions on how to contribute to scalabrad, see contributing.md.
Code StyleCode Style
Code should follow the scala style guide.
Code should be documented with scaladoc. Note that we prefer the indentation style common in java where asterisks in multiline doc comments are aligned to the left, rather than to the right:
/** * NO!! */ /** * YES!! */
The Google java style guide has some good advice about where comments should be included:
At the minimum, Javadoc is present for every public class, and every public or protected member of such a class.".
In scala a method like
getFoo would probably just be called
foo, or preferably you would just have public immutable member
foo, but the principle is the same: completely obvious comments distract more than they inform. | https://index.scala-lang.org/labrad/scalabrad/scalabrad/0.7.7?target=_2.11 | CC-MAIN-2020-16 | refinedweb | 460 | 52.49 |
rekcah has asked for the wisdom of the Perl Monks concerning the following question:
#open(LOUTPUT,"lastoutput") or die "Unable To Open lastoutput File.
#Please Ensure That This File Exists And Contains On One Line. This Fi
+le
#Must Only Contain Numbers";
#$number=<LOUTPUT>;
$number=3;
#close(LOUTPUT);
$divisor = 2;
test();
sub test() {
# Un-Comment The Next Line For More Output
#print("NUM=$number DIV=$divisor\n");
if ($number / $divisor == int($number / $divisor)) {
# Number Is Prime
if ($number == $divisor) {
print("Prime $number\n");
# open(OUTPUT,">>output");
# print(OUTPUT "$number\n");
# close(OUTPUT);
}
# Number Is Not Prime
$divisor = 2;
$number = $number + 1;
}
$divisor = $divisor + 1;
#sleep(1);
test();
}
# open(LOUTPUT,">lastoutput");
# print(LOUTPUT "$number");
# close(LOUTPUT);
[download]
Considering the sub is recursive and NEVER exits, is this really that surprising? The variables $number and $divisor are in the same address in memory the entire time (just print a ref to them and compare the addresses during every pass). The problem you are encountering is that a new call to the sub is getting pushed onto the internal stack with each call and never getting popped.
antirice The first rule of Perl club is - use PerlThe ith rule of Perl club is - follow rule i - 1 for i > 1
Hi!
It's not $Divider and $Number which eat up your memory (they're always the same variabile). The problem lies in the fact that your subroutine calls itself without a condition for doing that, causing and endless recursion.</p.
Michele.
#!/usr/bin/perl -w
use strict;
for my $test_number (5 .. 1000) {
next unless ($test_number % 2);
my ($prime , $factor) = IsPrime($test_number);
if ($prime) {
print "$test_number is prime\n";
}
else {
print "$test_number is not prime - divisible by $factor\n";
}
}
sub IsPrime {
my $input = shift;
my $t_number = 3;
while ($t_number < sqrt($input)) {
return (0, $t_number) unless ($input % $t_number);
$t_number += 2;
}
return 1;
}
[download]
There are faster ways to decide this problem, as well. I'm no mathematician, but your algorithm is dividing by all odd factors between 3 and sqrt(x); this can be improved by dividing by all *prime* factors between 3 and sqrt(x).
Since you're already finding all these numbers, just use dynamic programming-- when you find a prime, hash it for later reference. Then in your loop just go through the keys of your hash.
Cheers - L~R
The problem is not that your variables keep grabbing more memory without releasing it--they aren't. The problem is that test() is calling itself recursively. Each call requires the allocation of a certain amount of stack space, which is released when the function exits, but in this case it never does so the call frames just pile up.
Perl does do tail calls, just not automatic ones. Change that last test() into a goto &test and see if that doesn't make things much better.
PerlMonks, of course - how could you ask?
Other tech
Porn
Shopping
News
Sports
Games & puzzles
Social media
Arts & music
Job hunting
Whichever pays my bills
Results (207 votes). Check out past polls. | https://www.perlmonks.org/?node_id=270723 | CC-MAIN-2020-45 | refinedweb | 506 | 57.4 |
The AIX DFS:
The AIX EDFS:
Businesses have a need to share all kinds of data, including bulletin board notices, operations manuals, and even computer programs. Their goal is to store and manage the data centrally while making it easily and reliably available to users on the network.
The AIX EDFS allows data sharing with the reliability and manageability characteristics required by most corporations today. Because DFS is an application built on top of the DCE technology infrastructure, it inherits all of the underlying benefits -- security, scalability, availability, interoperability and the ability to operate over wide-area networks (WANs).
As corporations begin to "up-size" from today's departmental local area networks (LANs), they are looking for centralized administration and enterprise directory services. EDFS is designed to meet these needs.
Users access and interact with DFS files in the same way they would their local files. (POSIX single-site file semantics, including byte-range locking, are preserved across the network.) All DFS files are part of a single global namespace. Users can access data anywhere in the network without knowing its physical location; they only have to know its name!
The data can actually reside in the DFS physical file system, LFS, or in a client's native file system, such as the AIX Journalled File System (JFS). The DFS server takes data stored by the physical file system and makes it available to clients through its file exporter. For example, Ms. Jones can export her private AIX JFS file called &period.&period.&period./ibm/fs/user/jones/notes and Mr. Brown, in a remote city, can access it with the same name. Network File System (NFS) clients can access unprotected DFS data or secured DFS data if they use the NFS/DFS Authenticating Gateway. AFS clients can access DFS data through a vendor gateway, such as Lan Server Novel(r) and Apple(r) file systems, which are possible in the future.
Each DFS client in the network accesses files through its cache manager. For example, when you first open a spreadsheet, it is cached into local memory or disk where it is available for subsequent use. What are the benefits?
DFS maintains cache coherency among clients, ensuring data integrity. All of this is part of the basic DFS services in the AIX DCE Base S ervices product.
Smart data organization and tools Administrative tasks are greatly simplified through the EDFS data organization and tools. The concept of data being contained in "filesets" provides a convenient way to group administrative tasks, such as data backup, relocation and replication. The EDFS filesets are location- independent, so they can be transparently replicated or moved to another aggregate for load balancing.
EDFS uses DCE's Kerberos(tm) style of security to ensure that users are who they say they are. EDFS access control lists allow or deny users access to data and programs with a high degree of granularity. This is important for intercompany as well as intracompany collaboration and sharing of information.
EDFS is very effective in making large amounts of data available to many users in an enterprise environment.
Here are some examples where you can effectively put the advanced features of EDFS to work for you as a repository for:-4308-00/G2214308 | http://ps-2.kev009.com/rs6k-austin.ibm.com-1996/edfs.old.html | CC-MAIN-2021-17 | refinedweb | 543 | 54.42 |
Hi. I am a beginner in C++ programming. My assignment is to create a C++ Program to find the sine of a number without any library other than iostream by using Taylor Series:
sin (x) = (x/1!) - (x^3/3!) + (x^5/5!) - (x^7/7!) + (x^9/9!) ...... (x^n/n!).
I've spent 4-5 hours on this but i just cant seem to make it right. I have to submit it within 6hrs.
Here is what i have done till now:
#include <iostream>
double fact (int f); //declaration of factorial function
double power(double x, int y); //declaration of power function
double sin(int x); //declaration of sine function
//double cos(int x); //declaration of cosine function
//double tan(int x); //declaration of tangent function
using namespace std;
int main()
{
float x=0;
cout << "Enter the value of x in Sin(x): " << endl;
cin >> x;
cout << "Sine of " << x << " is " << sin(x);
cout << endl;
}
return 0;
}
//Function for Factorial
double fact (int x)
{
double f=1;
if (x==0)
{
return f;
}
else
for (int i=1; i<=x; i++)
{
f=f*i;
}
return f;
}
//Function for Power
double power (double x, int y)
{
double p=1;
for (int i=1; i<=y; i++)
p=p*x;
return p;
}
//Function for Sin
double sin (int x);
{
double sum_pos = 0;
double sum_neg=0;
double t_sum=0;
for (int i=1; i<=1000; i+=4)
{
sum_pos = sum_pos + (power (x,i) / fact (i));
}
for (int i=3; i<=1000; i+=4)
{
sum_neg = sum_neg + (power (x,i) / fact (i));
}
t_sum = sum_pos - sum_neg;
return t_sum;
}
Please help me. I would be grateful to any sort of help.
Why do your start a new thread with exactly the same problem that is discussed in your previous thread?
Please get back, read what guys wrote you in response to your problem and try to implement what they recommended.
Victor Nijegorodov
Originally Posted by VictorN
Why do your start a new thread with exactly the same problem that is discussed in your previous thread?
Please get back, read what guys wrote you in response to your problem and try to implement what they recommended.
that was some other problem. i cannot use math library and i have to call the function of factorial and power in the function of sine. i dont know how to do that. without using sine function, i can make it work but by using sine function, the program is not compiling. i really need some help here.
Originally Posted by weirdom3
... the program is not compiling. i really need some help here.
What compiler errors do you get?
And, please, edit your post adding Code tags! Have a look at my reply to you in your previous thread!
View Tag Cloud
Forum Rules | http://forums.codeguru.com/showthread.php?529157-can-t-seem-to-set-var&goto=nextnewest | CC-MAIN-2016-44 | refinedweb | 462 | 69.01 |
This chapter isn't meant to provide a comprehensive study of XML (Extensible Markup Language). However, we'll look at the basic components of an XML document, which will aid our study of the usage of XML in the context of WebLogic Server. If you're already familiar with the structure of an XML document, you may skip this section and move along to the next section of this chapter.
The Standard Generalized Markup Language (SGML), defined in the ISO standard 8879:1986, outlines the process for data interchange between different subsystems that makes it structured and consistent. You should be familiar with one type of an SGML document: an HTML document. HTML is a subset of SGML. As you might already know, an HTML document is nothing but a structured representation of data in such a way that a browser that understands HTML can display the data by using the data formats specified in the HTML document. The browser uses these format requirements in conjunction with the user's preferences to display the data. Thus, an HTML document ensures that the formats are always adhered to, irrespective of which browser or application uses the document. How the formats are rendered may depend on the settings of the browser.
HTML is presentation oriented. It does not concern itself with interpreting the data that's represented; all it knows is how the data looks to the user. Thus, if you have your application reading an HTML document, it'll be very difficult to make your application understand the document's content. This is where XML fits in. Like HTML, XML also derives from SGML and can be considered a subset of SGML. However, unlike HTML, XML is not about data presentation. XML does not address the format of the data; instead, it enables you to describe the structure and meaning of your data.
XML is a foundation for many different standards and protocols. Notably,
Web Services technologies
J2EE and WebLogic deployment descriptors
Ant
As its name suggests, XML is extensible. You can use an XML document to describe data using elements that you define for your application. Any other application that has to use this data needs to be aware of the elements that it has to look for in the document. When the application understands the tags and how to parse them, it can easily access the data being sent. Because of these reasons, XML has become the de facto standard for data transfer over the Internet.
For instance, in our example, Listing 29.1 could be a sample XML file that the airline sends to the bank for billing the credit card.
1. <?xml version="1.0"?>
2. <!DOCTYPE paymentInfo SYSTEM "paymentinfo.dtd">
3. <paymentInfo>
4. <creditCard number="1234123412341234" type="MC" expiration="03/2005"/>
5. <amount>354.99</amount>
6. </paymentInfo>
It's very evident from this listing that unlike an HTML document, an XML document does not have any predefined tags, although the structure of the XML document is quite similar to an HTML document in that it has elements and attributes. You're free to decide on and use elements that best describe your data. For instance, here we have defined an element called creditCard, which has three attributes: number, type, and expiration. We also have an amount element, which indicates the total amount to be charged. Both these tags are wrapped inside a root element called paymentInfo. As long as the bank is aware of the format, the billing application can easily use the data that is being passed in by the airline.
An XML document consists of two parts: the header and the content.
The XML header describes the XML file. As you can see in line 1 of Listing 29.1, we tell the user that the contents are formed based on the version 1.0 specification of XML. The header can also contain other attributes such as the encoding and an indication of whether the document can stand alone or requires other documents to make it complete.
In line 2, the header contains the DOCTYPE definition of the document. The airline and the bank have mutually agreed on a set of tags that they'll use to communicate. But how does the bank ensure that the requests adhere to the agreed structure? The bank system uses a dictionary that's based on the mutually agreed structure. This dictionary is known as a document type definition or DTD document. The DOCTYPE is a mechanism by which the XML indicates to the parser which DTD it conforms to. Based on this definition, the parser validates whether the XML follows all the rules laid out using the DTD. In line 2 of this example, we indicate to the parser that the XML uses a DTD called paymentinfo.dtd (which resides in the file system) by using the keyword SYSTEM. Using the SYSTEM keyword makes the parser look for the DTD either in the relative or absolute file system or in the URL, based on the data that's provided.
XML documents may also use DTDs that lie in some public domain. To do this, they use the keyword PUBLIC instead of SYSTEM. If you look at the ejb-jar.xml file, which describes an EJB deployment, you'll notice that the DOCTYPE is given as follows:
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.
//DTD Enterprise JavaBeans 2.0//EN' >
Here we indicate to the parser that it needs to pick up the DTD mentioned in the PUBLIC domain under the name Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN.
You can combine both the SYSTEM and PUBLIC keywords to specify to the parser that it must look for the PUBLIC ID first, as shown in the following header. If the parser cannot resolve the PUBLIC ID, it can then use the SYSTEM URL to specify the DTD. However, the SYSTEM keyword is omitted when combining the two.
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.
//DTD Enterprise JavaBeans 2.0//EN'
''>
Apart from these, you may also see other tags in the header that describe processing instructions (or PIs) of the XML. These header elements typically consist of a target followed by the data. The data is normally represented as key-value pairs, although that isn't a requirement.
Remember that although the header provides more meaning to your XML document, it isn't required for the XML to be complete. All these tags are optional. If your XML document includes a DOCTYPE declaration and the parser validates it, the document is considered to be valid. If the document doesn't contain a DOCTYPE, the parser won't validate it. In such a case, your XML document will be considered well formed if it follows the rules laid out by the W3C about the structure of XML documents. Not using a DOCTYPE obviously prevents the parser from validating the document, and improves performance at the expense of checking for the validity of the document. Needless to say, valid XML documents should also be well formed.
As mentioned earlier, the XML content is pretty much open for definition by the application in question. It does have to be well formed; that is, it must conform to some basic rules that are laid out by the W3C. The W3C document can be accessed online at. This section aims at defining some of the pieces of the puzzle that make up your XML content.
An element in an XML document describes a piece of data. Consider lines 4 and 5 in Listing 29.1. We define two elements, one being a creditCard and the other being an amount. At a first glance, these two might look different, but they really aren't that different. Each element describes a particular piece of the data.
Elements are made up using arbitrary element names, which are enclosed in angled brackets (< and >). Names must begin with a letter or an underscore. Names can be of any length, and can contain letters, numbers, underscores, hyphens, and periods. Names cannot contain embedded spaces. Element names are case sensitive. You can typically use the same naming conventions that you follow for naming Java variables to create XML element names. Understand that element names can be as descriptive as you choose, but making them unnecessarily long can cause confusion while reading the XML file.
All open elements must be closed. Elements are closed by using an ending tag, which consists of a forward slash (/) followed by the name of the element that's being closed; for example, </amount>. Between an opening and closing element tags, you may have any number of sub-elements and raw text.
XML tags cannot be nested, but HTML tags can be. HTML does not require the document to be well formed, whereas XML does.
Now consider the difference between lines 4 and 5 in Listing 29.1. Line 4 describes a credit card element and looks like the following:
4. <creditCard number="1234123412341234" type="MC" expiration="03/2005"/>
This is a well-formed element. However, it doesn't have a closing tag of </creditCard>. Or does it? In the case of an HTML document, for many tags you must explicitly define the closing tag for an empty tag such as this. But in the case of an XML document, you can use a shortcut to close the tag, thus reducing the clutter in your document. The shortcut is the use of a /> characters to close your element. This is the same as defining the creditCard tag with its attributes, closing the tag with the angle bracket, and subsequently including a </creditCard> tag. Thus, in this case, we define an element called creditCard, define some attributes to it, and close it all within the same tag. This concept can be extended to define empty tags, which act like Booleans in your XML document. For instance, if the airline were to tell the bank that the bank needs only to authorize the amount and not actually make the charge, it could add a new element, <authorizeOnly/>, in its XML document. These are known as empty tags. Of course, in an XML document, there are several ways in which a particular piece of data can be represented. For instance, the <authorizeOnly/> tag means the same as a <operation type="authorize"/> element.
The root element is the top-level element that does not include the header information. There can be only one root element in your XML document in order to make it a well-formed XML. For instance, in our examples, the <paymentInfo> element forms the root element. For all practical purposes, the root element is like any other element in the XML document. It is just special because it describes the data that's represented by the document.
Consider line 4 in Listing 29.1. From this line, it's obvious that an element can contain not only data between the start and end tags, but it can also contain attributes. Attributes define an element. Attributes are defined as key-value pairs within the starting tag of an element. Thus, in our credit card example, the attributes of the credit card are its number, type, and expiration date. Naming attributes follow the same rules as naming elements. The value of the attribute is enclosed within a set of either single or double quotes. Typically, it is standard practice to use double quotes for specifying values. Thus, you can define an element called <paymentInfo> as follows, which practically replaces the entire XML document described earlier:
<paymentInfo cardNum="xxx" type="xx" expDate="xx/xxxx">
200.00
</paymentInfo>
Here you list the credit card data as attributes and the amount as the value of the element. Another form of representing the same data is the following:
<paymentInfo>
<creditCard>
<number>xxxx</number>
<type>xx</type>
<expDate>xx/xxxx</expDate>
</creditCard>
<amount>200.00</amount>
</paymentInfo>
So, which is the correct way of representing this XML? Well, there are no correct or incorrect ways. These are all different representations. What determines whether a data is to be represented as a value or an attribute of an element? Again, there is no hard-and-fast rule to determine this. One general rule of thumb is that if a data can have multiple values or is very long, that data is generally better off defined as an element rather than an attribute of an element. Also, data that's defined using attributes can be described in the DTD. In other words, the DTD can tell to the parser the possible valid values that can go into an attribute. Thus, if your data requires that kind of validation, you should choose to use an attribute rather than an element. Finally, the order of the data might be important, or data could be repeated. In such cases, using elements instead of attributes allows repetition of tags and validation of the order of the data . Attributes cannot be repeated nor can their order validated.
Sometimes it becomes important that you use characters that are usually considered special characters in your XML data. For instance, you already know that an XML file is built using tags that are wrapped in angle brackets. So, how would you use an angle bracket within your data? For instance, if you want to represent the mathematical condition x < y as an XML condition element, how would you do it? The first thing that comes to mind is to represent it as follows:
<condition>x < y</condition>
It doesn't take more than a few seconds to realize that this does not make this document a well-formed XML document. That leaves us with the question how we represent the less than symbol in XML. To represent such data, you use entity references. An entity reference is a special symbol that represents different data within an XML document. Thus, when a parser parses out your document and encounters an entity reference, it knows to replace it with the correct data that's represented by that entity reference. Entity references are of the format &[reference-name];, where the [reference-name] part of the reference is replaced with the appropriate entity name. These symbols are the same ones that are used in HTML and URLs. The valid entity references are listed in Table 29.1.
Data Represented
Data
Entity Reference Used
Less than bracket
<
<
Greater than bracket
>
>
Ampersand
&
&
Double quote
"
"
Apostrophe
'
'
Thus, you can represent the mathematical condition as
<condition>x < y</condition>
A parser that parses this element will know to replace the < with a < symbol.
Sometimes, certain data that's represented by your XML document may be so complex that it's better for the parser not to attempt to parse it, and to simply feed it to the application. An example of this would be a snippet of code that is embedded within your XML document. Your code will probably make use of so many special characters that if you use entity references for each of them, you're bound to mess up the XML document. One way of avoiding this is by wrapping your data within a CDATA block. By doing so, you're instructing the parser not to attempt to parse the data, but simply to return it to the application. These data elements don't contain any entity references. They are considered to be raw text. Thus, a condition block that uses CDATA looks like this:
<condition>
<![CDATA[
x < y ;
]]>
</condition>
You can include comments within an XML document by beginning them with the string <!-- and ending them with -->. The following is a valid comment within an XML document:
<!-- This document represents a mathematical condition -->
A namespace qualifies a name. Conceptually, namespaces in XML are very simple, but can cause a great deal of heartburn in understanding if you don't work with an example. Consider the simple XML file shown in Listing 29.2, which describes how a book inventory has to be displayed on the screen. It has embedded HTML code to provide formatting.
1. <html>
2. <head><title>Book Inventory</title></head>
3. <body>
4. <bookInventory>
5. <table>
6. <tr>
7. <td>Title</td><td>Published by</td>
8. </tr>
9. <tr>
10. <td>
11. <title>
12. WebLogic Server Unleashed
13. </title>
14. </td>
15. <td>
16. <publisher>SAMS Publications</publisher>
17. </td>
18. </tr>
19. </table>
20. </bookInventory>
21. </body>
22. </html>
Here we're creating an HTML table that contains information about some books. All is well when we look at it, but consider an application parsing through this XML document. It has to deal with a whole lot of HTML code, when all it's looking for is the data about the books. Look at lines 2 and 11. In line 2, we display the title of the HTML page, and in line 11, we have the title of the book. Both the tags are defined as title. Although this is correct, it can get very tricky for an application that's parsing through this XML document.
To work around this, XML namespaces were introduced. An XML namespace is essentially a qualifier to a name. Instead of saying title, you would now qualify the title to either the presentation logic or to the data. The XML 1.0 specification used URIs for qualifying tag names. Namespace qualifier URIs are written within curly braces just before the tag/attribute names. Thus, the title tag that specifies the title of the page may be written as
<{}title>
Book Inventory
</{}title>
However this is bound to make the XML unreadable. To overcome this problem, XML also provides a shorthand mechanism to specify namespaces. To specify a shorthand, use the reserved xmlns tag. For example, here we create a presentation namespace that points to the HTML namespace, and then use it to qualify all HTML tags in our XML file.
<presentation:html xmlns:
<presentation:head><presentation:title>
Book Inventory
</presentation:title></presentation:head>
...
Here we specify a shorthand called presentation by defining the attribute xmlns:presentation to the html tag. We point this shorthand to the URI that qualifies HTML. When we specify a tag or an attribute that is of type html, we simply add the prefix presentation: to the tag name; for example, presentation:title. Note that children of all levels within the html tag will have access to this shorthand.
If you try typing in the URI that we specified into a Web browser's address bar, there's a very good chance that your browser will take you nowhere. This is because the XML specification does not require that the URI specified be valid or even that it exists. All the specification requires is a unique URI that can then be used by applications to access the data.
Given all this, the complete XML document with namespaces defined for html and the data would look as follows:
<presentation:html xmlns:data=""
xmlns:
<presentation:head><presentation:title>
Book Inventory
</presentation:title></presentation:head>
<presentation:body>
<data:bookInventory>
<presentation:table>
<presentation:tr
<presentation:td>Title</presentation:td>
<presentation:td>Published by</presentation:td>
</presentation:tr>
<presentation:tr
<presentation:td><data:title>WebLogic Server 7.0 Unleashed
</data:title></presentation:td>
<presentation:td>
<data:publisher>SAMS</data:publisher>
</presentation:td>
</presentation:tr>
</presentation:table>
</data:bookInventory>
</presentation:body>
</presentation:html>
You can also specify a default namespace by not having any prefix to the xmlns attribute. Any tag or attribute that isn't prefixed by a namespace tag will be associated with the default namespace. | http://books.gigatux.nl/mirror/beaweblogic8.1/0672324873_ch29lev1sec1.html | CC-MAIN-2021-43 | refinedweb | 3,262 | 55.54 |
Hi guys,
I've been rather inactive these days mainly busy with personal affairs but also with Cocoon
2.2 demo
application coding. The thing is hosted on github, project called cocoon-blog[1].
The project status should be considered as highly unstable. There is quite a lot of interesting
functionality already implemented like DAOs in JS, jDBI (2.0.x) integration, configuration
of HSQL,
dirtylicious theme, etc. but all these pieces are not integrated with each other yet.
At the moment, I'm facing some annoying problem that effectively stops me from developing
further
given my (very) limited resources these days. The problem is with debugging blocks in Eclipse.
I'm
using run-jetty-run plugin[2] for running blocks inside Eclipse.
In the past this technique worked very well together with eclipse:eclipse plug-in that allowed
me to
import block into Eclipse's workspace. Normally, following steps should work: (assuming
run-jetty-run is installed):
1. Go to block (e.g. dirtylicious-theme)
2. Run mvn clean cocoon:prepare
2. Run mvn eclipse:eclipse
3. Import block into workspace
4. Create Debug configuration of "Jetty Webapp" type. As webapp dir property value set
"target/rcl/webapp".
5. Run debugging of block.
As I said, this worked very well in the past but for some unknown reason I'm facing lots of
classpath issues. The latest is:
Caused by: java.lang.NoClassDefFoundError: org/apache/excalibur/source/SourceValidity
I've checked dirtylicious-theme block imported to Eclipse and there is no sourceresolve dependency
created by eclipse:eclipse but dependency:list shows it.
I would like to ask other folks for a help with confirming if it's a common problem and maybe
finding some solution to this problem. Of course, I could figure out all missing dependencies
and
add them by hand but we use Maven for some reason, do we?
So go to, click on Download button
and test
my steps please. I will be very grateful for any feedback.
PS. Are there any other folks interested in collaborating on this project? My intention is
to make
this project as fork-friendly as possible so others can play with it and possibly contribute
their
own ideas. If there is any interest I could outline project's goals and plans.
[1]
[2]
--
Best regards,
Grzegorz Kossakowski | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200805.mbox/%3C483C7F42.7020200@tuffmail.com%3E | CC-MAIN-2017-26 | refinedweb | 387 | 59.6 |
/* * .49 2005/11/30 12:47:37 csoutheren * Removed tabs, reformatted some code, and changed tags for Doxygen * * Revision 1.48 2005/11/25 03:43:47 csoutheren * Fixed function argument comments to be compatible with Doxygen * * Revision 1.47 2005/09/18 11:05:36 dominance * include/ptlib/channel.h, include/ptlib/pstring.h, src/ptlib/common/contain.cxx, * src/ptlib/common/pchannel.cxx: * correct the STL defined checking to use proper syntax. * * include/ptlib/object.h: * re-add typedef to compile on mingw * * make/ptlib-config.in: * import a long-standing fix from the Debian packs which allows usage of * ptlib-config without manually adding -lpt for each of the subsequent * projects * * Revision 1.46 2005/08/05 20:44:46 csoutheren * Fixed typo * * Revision 1.45 2005/08/05 20:41:41 csoutheren * Added unix support for scattered read/write * * Revision 1.44 2005/08/05 19:42:09 csoutheren * Added support for scattered read/write * * Revision 1.43 2004/04/09 06:38:10 rjongbloed * Fixed compatibility with STL based streams, eg as used by VC++2003 * * Revision 1.42 2003/12/19 04:29:52 csoutheren * Changed GetLastReadCount and GetLastWriteCount to be virtual * * Revision 1.41 2003/09/17 05:41:58 csoutheren * Removed recursive includes * * Revision 1.40 2003/09/17 01:18:02 csoutheren * Removed recursive include file system and removed all references * to deprecated coooperative threading support * * Revision 1.39 2002/09/16 01:08:59 robertj * Added #define so can select if #pragma interface/implementation is used on * platform basis (eg MacOS) rather than compiler, thanks Robert Monaghan. * * Revision 1.38 2002/07/04 23:35:47 robertj * Fixed documentation error * * Revision 1.37 2002/04/09 02:30:18 robertj * Removed GCC3 variable as __GNUC__ can be used instead, thanks jason Spence * * Revision 1.36 2002/01/26 23:55:55 craigs * Changed for GCC 3.0 compatibility, thanks to manty@manty.net * * Revision 1.35 2001/11/13 04:13:22 robertj * Added ability to adjust size of ios buffer on PChannels. * * Revision 1.34 2001/09/11 03:27:46 robertj * Improved error processing on high level protocol failures, usually * caused by unexpected shut down of a socket. * * Revision 1.33 2001/09/10 02:51:22 robertj * Major change to fix problem with error codes being corrupted in a * PChannel when have simultaneous reads and writes in threads. * * Revision 1.32 2001/06/04 10:13:08 robertj * Added compare function to compare value of os_handle. * Added has function based on os_handle value. * * Revision 1.31 2001/05/22 12:49:32 robertj * Did some seriously wierd rewrite of platform headers to eliminate the * stupid GNU compiler warning about braces not matching. * * Revision 1.30 1999/11/05 09:37:46 craigs * Made static form of ConvertOSError public scope * * Revision 1.29 1999/10/09 01:22:06 robertj * Fixed error display for sound channels. * * Revision 1.28 1999/03/09 02:59:49 robertj * Changed comments to doc++ compatible documentation. * * Revision 1.27 1998/09/23 06:20:18 robertj * Added open source copyright license. * * Revision 1.26 1998/02/03 06:29:10 robertj * Added new function to read a block with minimum number of bytes. * * Revision 1.25 1997/07/08 13:15:03 robertj * DLL support. * * Revision 1.24 1996/11/04 03:41:04 robertj * Added extra error message for UDP packet truncated. * * Revision 1.23 1996/09/14 13:09:17 robertj * Major upgrade: * rearranged sockets to help support IPX. * added indirect channel class and moved all protocols to descend from it, * separating the protocol from the low level byte transport. * * Revision 1.22 1996/08/17 10:00:19 robertj * Changes for Windows DLL support. * * Revision 1.21 1996/07/27 04:15:07 robertj * Created static version of ConvertOSError(). * Created static version of GetErrorText(). * * Revision 1.20 1996/05/26 03:24:40 robertj * Compatibility to GNU 2.7.x * * Revision 1.19 1996/04/15 12:33:03 robertj * Fixed SetReadTimeout/SetWriteTimeout to use const reference so works with GNU compiler. * * Revision 1.18 1996/04/14 02:53:30 robertj * Split serial and pipe channel into separate compilation units for Linux executable size reduction. * * Revision 1.17 1996/02/19 13:12:48 robertj * Added new error code for interrupted I/O. * * Revision 1.16 1996/01/23 13:09:14 robertj * Mac Metrowerks compiler support. * * Revision 1.15 1995/08/12 22:28:22 robertj * Work arounf for GNU bug: can't have private copy constructor with multiple inheritance. * * Revision 1.14 1995/07/31 12:15:42 robertj * Removed PContainer from PChannel ancestor. * * Revision 1.13 1995/06/17 11:12:21 robertj * Documentation update. * * Revision 1.12 1995/06/04 08:42:00 robertj * Fixed comment. * * Revision 1.11 1995/03/14 12:41:03 robertj * Updated documentation to use HTML codes. * * Revision 1.10 1995/03/12 04:36:53 robertj * Moved GetHandle() function from PFile to PChannel. * * Revision 1.9 1994/12/21 11:52:48 robertj * Documentation and variable normalisation. * * Revision 1.8 1994/11/28 12:31:40 robertj * Documentation. * * Revision 1.7 1994/08/23 11:32:52 robertj * Oops * * Revision 1.6 1994/08/22 00:46:48 robertj * Added pragma fro GNU C++ compiler. * * Revision 1.5 1994/08/21 23:43:02 robertj * Moved meta-string transmitter from PModem to PChannel. * Added common entry point to convert OS error to PChannel error. * * Revision 1.4 1994/07/17 10:46:06 robertj * Unix support changes. * * Revision 1.3 1994/07/02 03:03:49 robertj * Changed to allow for platform dependent part. * * Revision 1.2 1994/06/25 11:55:15 robertj * Unix version synchronisation. * * Revision 1.1 1994/04/20 12:17:44 robertj * Initial revision * */ #ifndef _PCHANNEL #define _PCHANNEL #ifdef P_USE_PRAGMA #pragma interface #endif #include <ptlib/mutex.h> /////////////////////////////////////////////////////////////////////////////// // I/O Channels class PChannel; /* Buffer class used in PChannel stream. This class is necessary for implementing the standard C++ iostream interface on #PChannel# classes and its descendents. It is an internal class and should not ever be used by application writers. */ class PChannelStreamBuffer : public streambuf { protected: /* Construct the streambuf for standard streams on a channel. This is used internally by the #PChannel# class. */ PChannelStreamBuffer( PChannel * chan // Channel the buffer operates on. ); virtual int overflow(int=EOF); virtual int underflow(); virtual int sync(); #ifdef __USE_STL__ virtual pos_type seekoff(off_type, ios_base::seekdir, ios_base::openmode = ios_base::in | ios_base::out); virtual pos_type seekpos(pos_type, ios_base::openmode = ios_base::in | ios_base::out); #else virtual streampos seekoff(streamoff, ios::seek_dir, int); #endif BOOL SetBufferSize( PINDEX newSize ); private: // Member variables PChannel * channel; PCharArray input, output; public: PChannelStreamBuffer(const PChannelStreamBuffer & sbuf); PChannelStreamBuffer & operator=(const PChannelStreamBuffer & sbuf); friend class PChannel; }; /** Abstract class defining I/O channel semantics. An I/O channel can be a serial port, pipe, network socket or even just a simple file. Anything that requires opening and closing then reading and/or writing from. A descendent would typically have constructors and an #Open()# function which enables access to the I/O channel it represents. The #Read()# and #Write()# functions would then be overridden to the platform and I/O specific mechanisms required. The general model for a channel is that the channel accepts and/or supplies a stream of bytes. The access to the stream of bytes is via a set of functions that allow certain types of transfer. These include direct transfers, buffered transfers (via iostream) or asynchronous transfers. The model also has the fundamental state of the channel being {\it open} or {\it closed}. A channel instance that is closed contains sufficient information to describe the channel but does not allocate or lock any system resources. An open channel allocates or locks the particular system resource. The act of opening a channel is a key event that may fail. In this case the channel remains closed and error values are set. */ 00277 class PChannel : public PObject, public iostream { PCLASSINFO(PChannel, PObject); public: /**@name Construction */ //@{ /// Create the channel. PChannel(); /// Close down the channel. ~PChannel(); //@} /**@name Overrides from class PObject */ //@{ /**Get the relative rank of the two strings. The system standard function, eg strcmp(), is used. @return comparison of the two objects, #EqualTo# for same, #LessThan# for #obj# logically less than the object and #GreaterThan# for #obj# logically greater than the object. */ virtual Comparison Compare( const PObject & obj ///< Other PString to compare against. ) const; /**Calculate a hash value for use in sets and dictionaries. The hash function for strings will produce a value based on the sum of the first three characters of the string. This is a fairly basic function and make no assumptions about the string contents. A user may descend from PString and override the hash function if they can take advantage of the types of strings being used, eg if all strings start with the letter 'A' followed by 'B or 'C' then the current hash function will not perform very well. @return hash value for string. */ virtual PINDEX HashFunction() const; //@} /**@name Information functions */ //@{ /** Determine if the channel is currently open. This indicates that read and write operations can be executed on the channel. For example, in the #PFile# class it returns if the file is currently open. @return TRUE if the channel is open. */ virtual BOOL IsOpen() const; /** Get the platform and I/O channel type name of the channel. For example, it would return the filename in #PFile# type channels. @return the name of the channel. */ virtual PString GetName() const; /** Get the integer operating system handle for the channel. @return standard OS descriptor integer. */ int GetHandle() const; /** Get the base channel of channel indirection using PIndirectChannel. This function returns the eventual base channel for reading of a series of indirect channels provided by descendents of #PIndirectChannel#. The behaviour for this function is to return "this". @return Pointer to base I/O channel for the indirect channel. */ virtual PChannel * GetBaseReadChannel() const; /** Get the base channel of channel indirection using PIndirectChannel. This function returns the eventual base channel for writing of a series of indirect channels provided by descendents of #PIndirectChannel#. The behaviour for this function is to return "this". @return Pointer to base I/O channel for the indirect channel. */ virtual PChannel * GetBaseWriteChannel() const; //@} /**@name Reading functions */ //@{ /** Set the timeout for read operations. This may be zero for immediate return of data through to #PMaxTimeInterval# which will wait forever for the read request to be filled. Note that this function may not be available, or meaningfull, for all channels. In that case it is set but ignored. */ void SetReadTimeout( const PTimeInterval & time ///< The new time interval for read operations. ); /** Get the timeout for read operations. Note that this function may not be available, or meaningfull, for all channels. In that case it returns the previously set value. @return time interval for read operations. */ PTimeInterval GetReadTimeout() const; /** \n characters will result in the number of bytes returned being less than the size of the buffer supplied. @return the number of bytes read. */ virtual PINDEX GetLastReadCount() const; /** Read a single 8 bit byte from the channel. If one was not available within the read timeout period, or an I/O error occurred, then the function gives with a -1 return value. @return byte read or -1 if no character could be read. */ virtual int ReadChar(); /** Read len bytes into the buffer from the channel. This function uses Read(), so most remarks pertaining to that function also apply to this one. The only difference being that this function will not return until all of the bytes have been read, or an error occurs. @return TRUE if the read of #len# bytes was sucessfull. */ BOOL ReadBlock( void * buf, ///< Pointer to a block of memory to receive the read bytes. PINDEX len ///< Maximum number of bytes to read into the buffer. ); /** Read #len# character into a string from the channel. This function simply uses ReadBlock(), so all remarks pertaining to that function also apply to this one. @return String that was read. */ PString ReadString(PINDEX len); /** Begin an asynchronous read from channel. The read timeout is used as in other read operations, in this case calling the OnReadComplete() function. Note that if the channel is not capable of asynchronous read then this will do a sychronous read is in the Read() function with the addition of calling the OnReadComplete() before returning. @return TRUE if the read was sucessfully queued. */ virtual BOOL ReadAsync( void * buf, ///< Pointer to a block of memory to receive the read bytes. PINDEX len ///< Maximum number of bytes to read into the buffer. ); /** User callback function for when a #ReadAsync()# call has completed or timed out. The original pointer to the buffer passed in ReadAsync() is passed to the function. */ virtual void OnReadComplete( void * buf, ///< Pointer to a block of memory that received the read bytes. PINDEX len ///< Actual number of bytes to read into the buffer. ); //@} /**@name Writing functions */ //@{ /**. */ void SetWriteTimeout( const PTimeInterval & time ///< The new time interval for write operations. ); /** Get the timeout for write operations to complete. Note that this function may not be available, or meaningfull, for all channels. In that case it returns the previously set value. @return time interval for writing. */ PTimeInterval GetWriteTimeout() const; /**. ); /** Get the number of bytes written by the last Write() call. Note that the number of bytes written may often be less, or even more, than that asked for. A common case of it being less is where the disk is full. An example of where the bytes written is more is as follows. On a #PTextFile# channel on the MSDOS platform, there is translation of \n to CR/LF pairs. This will result in the number of bytes returned being more than that requested. @return the number of bytes written. */ virtual PINDEX GetLastWriteCount() const; /** Write a single character to the channel. This function simply uses the Write() function so all comments on that function also apply. Note that this asserts if the value is not in the range 0..255. @return TRUE if the byte was successfully written. */ BOOL WriteChar(int c); /** Write a string to the channel. This function simply uses the Write() function so all comments on that function also apply. @return TRUE if the character written. */ BOOL WriteString(const PString & str); /** Begin an asynchronous write from channel. The write timeout is used as in other write operations, in this case calling the OnWriteComplete() function. Note that if the channel is not capable of asynchronous write then this will do a sychronous write as in the Write() function with the addition of calling the OnWriteComplete() before returning. @return TRUE of the write operation was succesfully queued. */ virtual BOOL WriteAsync( const void * buf, ///< Pointer to a block of memory to write. PINDEX len ///< Number of bytes to write. ); /** User callback function for when a WriteAsync() call has completed or timed out. The original pointer to the buffer passed in WriteAsync() is passed in here and the len parameter is the actual number of characters written. */ virtual void OnWriteComplete( const void * buf, ///< Pointer to a block of memory to write. PINDEX len ///< Number of bytes to write. ); //@} /**@name Miscellaneous functions */ //@{ /** Close the channel, shutting down the link to the data source. @return TRUE if the channel successfully closed. */ virtual BOOL Close(); enum ShutdownValue { ShutdownRead = 0, ShutdownWrite = 1, ShutdownReadAndWrite = 2 }; /** Close one or both of the data streams associated with a channel. The default behavour is to do nothing and return FALSE. @return TRUE if the shutdown was successfully performed. */ virtual BOOL Shutdown( ShutdownValue option ); /**Set the iostream buffer size for reads and writes. @return TRUE if the new buffer size was set. */ BOOL SetBufferSize( PINDEX newSize ///< New buffer size ); /** Send a command meta-string. A meta-string is a string of characters that may contain escaped commands. The escape command is the \ as in the C language. The escape commands are: \begin{description} \item[#\a#] alert (ascii value 7) \item[#\b#] backspace (ascii value 8) \item[#\f#] formfeed (ascii value 12) \item[#\n#] newline (ascii value 10) \item[#\r#] return (ascii value 13) \item[#\t#] horizontal tab (ascii value 9) \item[#\v#] vertical tab (ascii value 11) \item[#\\#] backslash \item[#\ooo#] where ooo is octal number, ascii value ooo \item[#\xhh#] where hh is hex number (ascii value 0xhh) \item[#\0#] null character (ascii zero) \item[#\dns#] delay for n seconds \item[#\dnm#] delay for n milliseconds \item[#\s#] characters following this, up to a \w command or the end of string, are to be sent to modem \item[#\wns#] characters following this, up to a \s, \d or another \w or the end of the string are expected back from the modem. If the string is not received within n seconds, a failed command is registered. The exception to this is if the command is at the end of the string or the next character in the string is the \s, \d or \w in which case all characters are ignored from the modem until n seconds of no data. \item[#\wnm#] as for above but timeout is in milliseconds. \end{description} @return TRUE if the command string was completely processed. */ BOOL SendCommandString( const PString & command ///< Command to send to the channel ); /** Abort a command string that is in progress. Note that as the SendCommandString() function blocks the calling thread when it runs, this can only be called from within another thread. */ void AbortCommandString(); //@} /**@name Error functions */ //@{ /** Normalised error codes. The error result of the last file I/O operation in this object. */ 00664 enum Errors { NoError, /// Open fail due to device or file not found 00667 NotFound, /// Open fail due to file already existing 00669 FileExists, /// Write fail due to disk full 00671 DiskFull, /// Operation fail due to insufficient privilege 00673 AccessDenied, /// Open fail due to device already open for exclusive use 00675 DeviceInUse, /// Operation fail due to bad parameters 00677 BadParameter, /// Operation fail due to insufficient memory 00679 NoMemory, /// Operation fail due to channel not being open yet 00681 NotOpen, /// Operation failed due to a timeout 00683 Timeout, /// Operation was interrupted 00685 Interrupted, /// Operations buffer was too small for data. 00687 BufferTooSmall, /// Miscellaneous error. 00689 Miscellaneous, /// High level protocol failure 00691 ProtocolFailure, NumNormalisedErrors }; /**Error groups. To aid in multithreaded applications where reading and writing may be happening simultaneously, read and write errors are separated from other errors. */ 00700 enum ErrorGroup { 00701 LastReadError, ///< Error during Read() operation 00702 LastWriteError, ///< Error during Write() operation 00703 LastGeneralError, ///< Error during other operation, eg Open() NumErrorGroups }; /** Get normalised error code. Return the error result of the last file I/O operation in this object. @return Normalised error code. */ Errors GetErrorCode( ErrorGroup group = NumErrorGroups ///< Error group to get ) const; /** Get OS errro code. Return the operating system error number of the last file I/O operation in this object. @return Operating System error code. */ int GetErrorNumber( ErrorGroup group = NumErrorGroups ///< Error group to get ) const; /** Get error message description. Return a string indicating the error message that may be displayed to the user. The error for the last I/O operation in this object is used. @return Operating System error description string. */ virtual PString GetErrorText( ErrorGroup group = NumErrorGroups ///< Error group to get ) const; /** Get error message description. Return a string indicating the error message that may be displayed to the user. The #osError# parameter is used unless zero, in which case the #lastError# parameter is used. @return Operating System error description string. */ static PString GetErrorText( Errors lastError, ///< Error code to translate. int osError = 0 ///< OS error number to translate. ); //@} /** Convert an operating system error into platform independent error. This will set the lastError and osError member variables for access by GetErrorCode() and GetErrorNumber(). @return TRUE if there was no error. */ static BOOL ConvertOSError( int libcReturnValue, Errors & lastError, int & osError ); /**@name Scattered read/write functions */ //@{ /** Structure that defines a "slice" of memory to be written to */ #if P_HAS_RECVMSG typedef iovec Slice; #else 00764 struct Slice { void * iov_base; size_t iov_len; }; #endif typedef std::vector<Slice> VectorOfSlice; /** Low level scattered read from the channel. This is identical to Read except that the data will be read into a series of scattered memory slices. By default, this call will default to calling Read multiple times, but this may be implemented by operating systems to do a real scattered read @return TRUE indicates that at least one character was read from the channel. FALSE means no bytes were read due to timeout or some other I/O error. */ virtual BOOL Read( const VectorOfSlice & slices // slices to read to ); /** Low level scattered write to the channel. This is identical to Write except that the data will be written from a series of scattered memory slices. By default, this call will default to calling Write multiple times, but this can be actually implemented by operating systems to do a real scattered write @return TRUE indicates that at least one character was read from the channel. FALSE means no bytes were read due to timeout or some other I/O error. */ virtual BOOL Write( const VectorOfSlice & slices // slices to read to ); //@} protected: PChannel(const PChannel &); PChannel & operator=(const PChannel &); // Prevent usage by external classes /** Convert an operating system error into platform independent error. The internal error codes are set by this function. They may be obtained via the #GetErrorCode()# and #GetErrorNumber()# functions. @return TRUE if there was no error. */ virtual BOOL ConvertOSError( int libcReturnValue, ErrorGroup group = LastGeneralError ///< Error group to set ); /**Set error values to those specified. Return TRUE if errorCode is NoError, FALSE otherwise */ BOOL SetErrorValues( Errors errorCode, ///< Error code to translate. int osError, ///< OS error number to translate. ErrorGroup group = LastGeneralError ///< Error group to set ); /** Read a character with specified timeout. This reads a single character from the channel waiting at most the amount of time specified for it to arrive. The #timeout# parameter is adjusted for amount of time it actually took, so it can be used for a multiple character timeout. @return TRUE if there was no error. */ int ReadCharWithTimeout( PTimeInterval & timeout // Timeout for read. ); // Receive a (partial) command string, determine if completed yet. BOOL ReceiveCommandString( int nextChar, const PString & reply, PINDEX & pos, PINDEX start ); // Member variables /// The operating system file handle return by standard open() function. 00848 int os_handle; /// The platform independant error code. 00850 Errors lastErrorCode[NumErrorGroups+1]; /// The operating system error number (eg as returned by errno). 00852 int lastErrorNumber[NumErrorGroups+1]; /// Number of byte last read by the Read() function. 00854 PINDEX lastReadCount; /// Number of byte last written by the Write() function. 00856 PINDEX lastWriteCount; /// Timeout for read operations. 00858 PTimeInterval readTimeout; /// Timeout for write operations. 00860 PTimeInterval writeTimeout; private: // New functions for class void Construct(); // Complete platform dependent construction. // Member variables BOOL abortCommandString; // Flag to abort the transmission of a command in SendCommandString(). // Include platform dependent part of class #ifdef _WIN32 #include "msos/ptlib/channel.h" #else #include "unix/ptlib/channel.h" #endif }; #endif // End Of File /////////////////////////////////////////////////////////////// | http://pwlib.sourcearchive.com/documentation/1.10.10-3ubuntu1/channel_8h-source.html | CC-MAIN-2017-26 | refinedweb | 3,806 | 57.16 |
This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.
In message <36F6754F.92537D4B@interix.com>you write: > (Is "one" here referring to the specific item above, or to the whole patch? > I'm presuming the latter in this response.) The whole patch. Consider that most of the basic files are non-controversial. We could have installed them some time ago. But since they were bundled with other patches which probably do need some work, they were put near the bottom of my queue. > This is a tricky interaction with ld having to do with placing the > ___CTOR_LIST___ and ___DTOR_LIST___ symbols correctly in the PE > environment along with some other changes that are not yet > submitted. This change can be reasonably deferred until the rest > of the package comes along, if that makes life simpler. Let's defer it temporarily and come back to it later. When that happens I'll want additional technical info describing why none of our existing mechanisms work. > It also runs on the Alpha; Ok. Thanks. > above you indicated a preference for bite-sized > chunks, and holding the Alpha until later was for exactly that reason. Yup. That's the right thing to do. > > > * i386/i386.c (load_pic_register): Use __GLOBAL_OFFSET_TABLE on > > > Interix. > > > * i386/i386.md (prologue_get_pc_and_set_got): Likewise. > > This is an Alpha interaction (Alpha on NT doesn't use the leading > underscore convention). Can defer until it forces the issue, but > alternatives welcome. Instead of using #ifdef INTERIX blah blah #endif Create a definition for the name of the GOT variable and use it in i386.c and i386.md. Then provide an override in interix.h. That way we avoid infesting the generic i386 files with system specific #ifdefs. > > > * gcc.c (main): Add specs handling for environment variables. > > > Add $INTERIX_ROOT/usr/lib/ etc to startfiles_prefixes. > > Interix specific and guarded. Not acceptable. We don't want to put those kinds of ifdefs into generic code if we can avoid it. You need to look for a cleaner way to address this issue. > > > > > > * sdbout.c (syms.h): Don't include on Interix. > > > > > > * protoize.c (abspath): Preserve multiple leading slashes. > > > > > > * toplev.c (main): No sbrk on Interix. > > > > > > * c-parse.y (absdcl1): Allow attributes in explicit typespecs. > > > (%expect): Update. > > > * c-parse.h: Regenerate. > > > * c-parse.c: Likewise. > > We'll resolve these once we've resolved the basic config patches. We > > should go after them one by one. > > I presume you'd like the ones between sdbout and c-parse.c as separate > chunks. Actually, each should be a separate patch since each addresses an independent issue. > Specifically what action is required at this time? Are you going to apply > the easy ones above, or do you need a new bundle with just those, plus > a series of smaller patches for the more controversial ones? (Just so we > know precisely what you require.) I took care of the basic config files. I'm going to look at some of the other changes. Basically, I'm going to resolve those which don't need reworking or additional explanation. Then we'll need to iterate on the remaining changes. We already know that the gcc.c & i386.c/i386.md changes need some additional work. You should deal with the needed changes to gcc.c and i386.c/i386.md and resend those patches (separately). jeff | https://gcc.gnu.org/ml/gcc-patches/1999-03n/msg00613.html | CC-MAIN-2019-43 | refinedweb | 562 | 69.58 |
On 09/06/2014 18:15, Andrei Shakirin wrote:
> Hi Sergei,
>
> I am also a bit concerned about autocomplete feature actively used in IDEs (mentioned
by Dan). Keeping unsupported element in schema can be a bit confusing because of that.
> Therefore if handling the client in the old namespace via the transformation feature
will be too complicated in option (1), I would prefer option (2) with keeping dependency client
-> frontend.
>
> Regards,
> Andrei.
>
>> -----Original Message-----
>> From: Sergey Beryozkin [mailto:sberyozkin@gmail.com]
>> Sent: Freitag, 6. Juni 2014 11:57
>> To: CXF Dev
>> Subject: How to get a public jaxrs.xsd at org.apache.cxf support multiple CXF
>> versions
>>
>> Hi
>>
>> In CXF 3.0.0 we've had a "client" element used to be defined in jaxrs.xsd
>> shipped with the rt/frontend/jaxrs module moved out (alongside with the code
>> supporting Client API) to a new jaxrs-client.xsd (with a new target namespace
>>) now shipped with the rt/rs/client module.
>>
>> This is documented in the migration guide.
>>
>> Note that I've updated a target namespace for a 'client' element not for some
>> design reasons but only due to the fact that I came to the conclusion it was not
>> possible to have a shared/single target namespace for schemas shipped in
>> multiple modules.
>>
>> So, after 3.0.0 has been released I've pushed a new jaxrs.xsd schema without
>> the 'client' element to org.apache.cxf. And we've started getting reports of CXF
>> 2.x clients using jaxrs:client getting the validation issues.
>>
>> So I wonder what would should the best strategy be for supporting multiple CXF
>> versions validating against a public jaxrs schema be, without having to
>> introduce the numbers or dates into target schema namespace (just for the
>> sake of simplicity, given that the schemas are in themselves are very stable
>> now, with only very attributes or optional elements possibly added in the
>> future).
>>
>> I can think of 4 options:
>>
>> 1. The current workaround has been to restore the old 'client' element only in
>> the public jaxrs.xsd at org.apache.cxf/schemas just to keep CXF 2.x clients using
>> jaxrs:client getting the validation working.
>> If it works and will have no side-effects over a some period of time then may be
>> we can settle with this solution, even though it's effectively a hack.
>>
>> 2. Revert the migration of 'client' into a new target namespace "jaxrs-client",
>> have "client" restored in jaxrs.xsd, and either 'include' jaxrs.xsd or use it
>> directly in rt/rs/client. The downside: we will never be able to break a link
>> between RS client and RS frontend modules, which is on the map, at the
>> moment only the RS frontend has benefited from getting the client code moved
>> out of it, while the client code is still depending on all of the frontend RS; may
it
>> is not a big deal really
>>
>> 3. In CXF 3.0.1: update a shipped jaxrs.xsd to have a new target namespace,
>> "", restore the old jaxrs.xsd at org.apache.cxf and
>> redirect "/jaxrs3x" requests to a new jaxrs3x.xsd file.
>> This is probably the best solution as far as the best practice is concerned.
>>
>> 4. Add jaxrs2x.xsd file to org.apache.cxf and advise CXF 2.x clients working with
>> jaxrs:client update schemaLocation elements accordingly.
>> This will work but kind of not cool, breaking the validation for the existing
>> working clients is not good, even though it is a tiny change.
>>
>> Any comments please ?
>> Right now I'd like to see if 1. works and open to doing 3. in CXF 3.0.1
>>
>> Thanks, Sergey
>>
Having superfluous elements in the schema is confusing and inefficient
(if something like JAXB is run against the schema it will generate
invalid members).
Please go for option 3.
Any change to a schema should result in a new namespace; and any
incompatible change must result in a new namespace.
Jim | http://mail-archives.apache.org/mod_mbox/cxf-dev/201406.mbox/%3C539946B4.5040100@spudsoft.co.uk%3E | CC-MAIN-2018-26 | refinedweb | 662 | 75.1 |
.
For our own template engine, we wanted event handler creation and component instantiation to be first class scenarios, and we wanted both to be possible from imperative code as well as declarative code.:id="{{ $id('photo') }}":
Here’s what the page looks like (no matter which of the three versions of the page you choose)::?
There’s been quite a few blog posts and tweets lately around the following (slightly distorted) quote:
“If you don’t know English, you’re not a programmer”
”
“如果你不会英文, 你就不是一个程序员”
(Thanks to Hong Li for the translation).
I had actually already done a similar simplification from Nikhil’s original behavior that he wrote a few years ago by not handling the hover effect from the component but from CSS. Changing a style on hover is now best done by adding a “:hover” style, which all modern browsers can handle on any element.
We could in principle take this simplification all the way and get rid of the behavior altogether to rely only on CSS if all modern browsers could handle CSS 2.1’s “:focus” pesudo-class. Unfortunately as of today, even in version 8, Internet Explorer does not. It should in RTM as it is supposed to fully support CSS 2.1 but that won’t be usable for a while as previous versions will remain prevalent for some more time.
Anyway, I modified the behavior to use that method of restyling instead of the label substitution used before and was able to reduce the code size further down to 70 lines. You can download the updated behavior from here:.
Microsoft Ajax has the interesting ability to combine more than one component onto a single element. In the previous talk, I alluded to this possibility and one of the commenters (Tiamat) asked me to show how this is done..
The behavior is pretty similar to the in-place editing behavior Nikhil built a while ago (but it works against the latest Ajax framework). It attaches to any text input or text area. In the absence of JavaScript, nothing happens and the input is directly usable, which makes for a graceful degradation story. When JavaScript is enabled, the behavior hides the input and replaces it with a span that has the same dimensions and the same contents. Clicking on the span hides it, brings back the input and gives it focus, enabling edition of the value. When focus moves away from the input, the behavior hides the input again, copies the new value into the span and brings it back. Please note that for accessibility, you can also tab to the span instead of clicking on it. Check out the video, it shows that much better than any text description ever could:
The EditInPlace behavior does all that in 80 lines of readable code, doc-comments included. Before we look at some key parts of the code, let’s look at how you can use the control:
<input type="text" id="email" value="bleroy@example.com"/>
<script type="text/javascript" src="Script/MicrosoftAjax.js"></script>
<script type="text/javascript" src="Script/EditInPlace.js"></script>
<script type="text/javascript">
Sys.Application.add_init(function() {
$create(Bleroy.Sample.EditInPlace,
{ cssClass: "editInPlace" }, {}, {}, $get("email"));
});
</script>
Include the library and behavior scripts, throw in some input or text area, $create the behavior over the input, setting properties such as cssClass if you have to. In the example, I’ve defined the style “editInPlace:hover” in the CSS so that the user gets this nice hint something might happen if you click when you hover over the control. This is the effect you see in the first few seconds of the video. Pretty simple.
Of course, you can also use the new declarative syntax once you’ve included MicrosoftAjaxTemplates.js:
<body xmlns:sys="javascript:Sys" sys:activate="*"
xmlns:
<input type="text" id="email" value="bleroy@example.com"
sys:
Here, the xmlns are the equivalent of server-side @Register directives in ASP.NET, sys:activate asks the framework to instantiate all declarative controls on the page and sys:attach does the actual instantiation. The properties of the behavior are set by using attributes with the prefix that we defined earlier for it. This declarative snippet is equivalent to the previous one that was using $create.
Let’s now look at a few aspects of building this behavior. First, let’s look at the skeleton of the code:
/// <reference name="MicrosoftAjax.js"/>
Type.registerNamespace("Bleroy.Sample");
Bleroy.Sample.EditInPlace = function(element) {
Bleroy.Sample.EditInPlace.initializeBase(this, [element]);
}
Bleroy.Sample.EditInPlace.prototype = {
}
Bleroy.Sample.EditInPlace.registerClass( "Bleroy.Sample.EditInPlace", Sys.UI.Behavior);
Here, we’re declaring the only dependency of this file using an XML doc-comment. This will point Visual Studio to the Ajax library so that we get IntelliSense when for example we type “Sys.” from within that file.
Then, we’re declaring the Bleroy.Sample namespace, which is where we’ll build the behavior.
The behavior itself is defined on the next line. A type in JavaScript and Microsoft Ajax really is the same objet as its constructor. Something to get used to… The only thing the constructor does for the moment is calling its base constructor using initializeBase. In its complete version, it also does some checking on the target element’s tag name to check it’s either a text area or an input, and it initializes private fields, which is good practice for a better and more predictable debugging experience.
The next block is where the meat of the component is going to go: the prototype. This is where we’re going to define properties, events and methods.
Last, we register the class with the framework using registerClass, pointing it to its base class, Sys.UI.Behavior. A behavior is a component that attaches to an HTML element, like a control, except that there can be only one control per element (DataView is a control for example) whereas there can be as many behaviors as you want per element (which enables for example a watermark, an auto-complete and an edit in place behavior to be combined on the same textbox).
Let’s now look at the initialization phase of the behavior, where the events will get hooked from and the span will be created and added to the DOM:
initialize: function() {
Bleroy.Sample.EditInPlace.callBaseMethod(this, "initialize");
var elt = this.get_element(),
span = this._span = document.createElement("SPAN");
var bounds = Sys.UI.DomElement.getBounds(elt);
span.style.position = "absolute"; Sys.UI.DomElement.setLocation(span, bounds.x, bounds.y);
span.style.width = bounds.width + "px";
span.style.height = bounds.height + "px";
span.tabIndex = elt.tabIndex;
span.className = this._class;
Sys.UI.DomEvent.addHandlers(this._span, {
click: this.beginEdit,
focus: this.beginEdit
}, this);
elt.parentNode.insertBefore(this._span, elt);
this._oldVisibility = elt.style.visibility;
this._inputBlur = Function.createDelegate(this, this.endEdit);
Sys.UI.DomEvent.addHandler(elt, "blur", this._inputBlur);
this.endEdit();
}
The method first calls base using callBaseMethod. Then it creates the span element and sets its position and size to be exactly equivalent to the input tag it will have to replace so that it doesn’t upset the layout of the page. It also sets the CSS class to the current value of the cssClass property (which is stored in the private field this._class). Two handlers are added to the new span: one for click and one for focus and both point to the same method, this.beginEdit. The way we’re creating the events is by using the very handy addHandlers method, which will attach several event handlers at once and will also take care of creating delegates with the specified context (this) so that the handler can have access to all the members of the behavior instance. Finally, the new span is added to the DOM right before the input element. Once that span has been created, we can store the old visibility mode of the input for later use, create a blur delegate for the input element that will call endEdit and then call endEdit to substitute the input for the span. Notice that we created the delegate manually rather than use addHandlers here. I’ll explain why in a moment.
A good practice is to free all the resources and clean up after yourself from dispose. Let’s look how this is done:
dispose: function() {
if (this._span) {
Sys.UI.DomEvent.clearHandlers(this._span);
this._span.parentNode.removeChild(this._span);
var elt = this.get_element();
Sys.UI.DomEvent.removeHandler(elt, "blur", this._inputBlur);
elt.style.visibility = this._oldVisibility;
this._inputBlur = this._spanClick = this._span = null;
}
Bleroy.Sample.EditInPlace.callBaseMethod(this, "dispose");
}
Here we made sure that the method can be called multiple times by testing for the presence of what we’re going to clean. If the method is ever called again it will pretty much be a no-op.
The dispose method starts by clearing all event handlers from the span element. It can do so by calling the handy clearHandlers method. We can afford to do that here because we completely own that element: we created it and managed it so we can safely use a very big hammer and crush all events without having to wonder if somebody else left their fingers on the table. For the input element that is quite different as there may be other behaviors attached to it that may have created their own events. That’s why here we’re targeting our cleaning efforts exclusively at what we created. This is why we created the delegate to endEdit ourselves so that we could keep a reference to it and use that later when removing the handler.
Other tasks in dispose include removing the span from the DOM, resetting the input element’s visibility style and clearing private variables.
And of course, the last thing we do is call base so that we can do our cleaning up without having to wonder if base already destroyed some of the objects we still need.
Now that the initial setup and cleanup are in place, beginEdit and endEdit only have some trivial showing, hiding and focusing of the elements to do:
beginEdit: function() {
/// <summary>Puts the behavior in edit mode</summary>
var elt = this.get_element();
this._span.style.visibility = "hidden";
elt.style.visibility = this._oldVisibility;
elt.focus();
this.raisePropertyChanged("isEditing");
}
endEdit: function() {
/// <summary>Puts the behavior out of edit mode</summary>
var elt = this.get_element();
this._span.innerHTML = elt.value;
this._span.style.visibility = this._oldDisplay;
elt.style.visibility = "none";
this.raisePropertyChanged("isEditing");
}
The only thing worth singling out here is that we’re taking care of triggering change notifications on isEditing every time the editing mode changes.
The rest of the code is pretty trivial property accessors that are implemented using the get_ and set_ prefixes.
I hope this helps.
Get the full source code for the behavior and the sample page:
UPDATE: fixed a bug in the positioning of the span.
UPDATE: Nikhil just blogged about building an edit in place behavior for Silverlight. I feel a little silly now because of the way he implemented that not by replacing the textbox with a label but by just making the border transparent on blur. This should work just as well in HTML and would make the code probably a lot simpler. I may try that when I have time. Anyway, check it out, great read as usual:
UPDATE: I rewrote the behavior to use Nikhil's trick of restyling the border:):
David has an excellent post about a pretty cool ASP.NET feature that you almost certainly don’t know about. I had no idea for sure. Check it out.
UPDATE: and there he goes again...
We published some documentation for ASP.NET Ajax 4.0 Preview 3: | http://weblogs.asp.net/bleroy/archive/2008/11.aspx | CC-MAIN-2014-15 | refinedweb | 1,961 | 55.13 |
I am trying to make a simple program that allow you to enter the value of an item, then adds on a sales tax of 5.6 percent and outputs in the following format:"Item price of $10.00 with sales tax is 10 dollars and 56 cents".
I have made a program so far that calculates the sales tax, adds it to the item price and then gives a resulting floating point number. However, I do not know how to display the result in the format above. Here is what I have written so far. Any help would be great!
Code:
#include <stdio.h>
#define TAXRATE .056
int main(void)
{
float item, tax, total_cost;
printf("Enter the value of your item\n");
scanf(" %f", &item);
tax = item * TAXRATE;
total_cost = item + tax;
printf("Your item of $%.2f with sales tax is %.2f", item, total_cost);
getchar();
return 0;
} | https://cboard.cprogramming.com/c-programming/139577-price-plus-sales-tax-calculator-printable-thread.html | CC-MAIN-2017-17 | refinedweb | 147 | 85.08 |
.NET musings from the chick side
In VSS you had to add the file to the VSS project explicitly. I can't count the times that the solution in VSS did not compile because someone had added new file to their solution, referenced it from existing code, and then forgot to add the new file to source control. When the developer compiled the solution prior to check in, it compiled on her local environment because she had the file, so she thought all was well.
The file addition on check-in in Team System Version Control (TSVC) that in my opinion is a vast improvement over VSS.
When you add files to your project (such as a new project, new class, or new external dependency file), the new file appears in your solution with a yellow cross to indicate that is new and does not yet exist in source control. Here I added a new test class to my test project called ContentCacheTest.cs. The file was actually through the Create Unit Tests Wizard. Team System checked out the test project
It is also added to source control at that time:
When you check in your changeset, the new file is added to source control automatically.
The model of checking in a file addition does have one aspect that "got" me. When you add a file directly to source control, you still need to check in the file, or it doesn't "officially exist" in source control.
For example:
I am using Rhino Mocks in my tests, so I added the Rhino.Mocks.dll to my "ExternalDependencies" folder in the team project and then referenced it from my project. I checked the project in as changeset "Add Rhino.Mocks".
I then added the Rhino.Mocks assembly files to Source Control inthe corresponding ExternalDependencies folder by clicking on the add button. They appeared in Source Control and my project built fine. when I ran my build on the build server however, it failed with the following error:
BlogMLReaderTest.cs(4,7): error CS0246: The type or namespace name 'Rhino' could not be found (are you missing a using directive or an assembly reference?)
Hmm, but I did add the Rhino.Mocks assembly to Source Control - I can see it!
But wait - It has a yellow cross next to it and the Pending Change column shows "add". So just adding the files to Source Control does not make them part of the source code (as it did in VSS).
I checked in the two files, ran my build on the build server, and all was well.
Print | posted on Wednesday, May 28, 2008 11:19 AM
Design by Bartosz Brzezinski
Design by Phil Haack Based On A Design By Bartosz Brzezinski | http://geekswithblogs.net/KirstinJ/archive/2008/05/28/adding-files-to-tfs-team-system-version-control.aspx | crawl-002 | refinedweb | 459 | 77.98 |
Here is a better version of a handler which allows use of Cheetah
templates with mod_python.
from mod_python import apache
import os
# It is assumed that Apache config or .htaccess file
# blocks access to ".tmpl", ".py" and ".pyc" files.
def handler(req):
# Assume REST style URLs. Ie., no extension is used
# for accessing Cheetah pages. On this basis, first
# perform a check that there is a ".py" file in
# existance. This is done because can't distinguish
# between a non existant module and a module which has
# a coding error in it when using the function
# "apache.import_module()". By returning DECLINED,
# Apache will then serve up any static files in the
# directory which may otherwise be matched.
target = req.filename + ".py"
if not os.path.exists(target):
return apache.DECLINED
# Grab the module name to look for from the last part
# of the path. This means that pages can be spread
# across subdirectories as well.
directory,module_name = os.path.split(req.filename)
# Import the module. Any coding error in the module
# being imported is thrown back to the user. Error
# also results if by chance the target just vanished.
module = apache.import_module(module_name,[directory])
# Ensure that there is a class defined in the module
# of the appropriate name.
if not hasattr(module,module_name):
return apache.DECLINED
# Create instance of the class and setup request object.
tmpl = getattr(module,module_name)()
tmpl.req = req
# Assume that HTML is being generated.
req.content_type = "text/plain"
req.send_http_header()
# Now generate the actual content and return it.
req.write(tmpl.respond())
return apache.OK
Graham Dumpleton wrote ..
> I somewhat suspect that you aren't going to get the code as by
> default generated by Cheetah to play well with publisher. As to
> your original custom handler, you could clean it up somewhat
> by using something like:
>
>
> from mod_python import apache
> import string
>
> def handler(req):
>
> req. module_name = string.replace (req.uri, start, "")
>
> # try:
> # exec ("""import %s
> #tmpl = %s.%s()
> #tmpl.req = req""" % (module_name, module_name, module_name))
> # except ImportError:
> # return apache.HTTP_NOT_FOUND
>
> module = apache.import_module(module_name)
> if not hasattr(module,module_name):
> return apache.HTTP_NOT_FOUND
>
> tmpl = getattr(module,module_name)()
> tmpl.req = req
>
> req.send_http_header()
> req.write(tmpl.respond())
>
> return apache.OK
>
> I still see some issues with this code in as much as I think it
> requires everything to be in the one directory. Ie., can't have
> subdirectories. Using "start" as a fixed value is not good, but
> that can also be fixed. Also, you can't mix different file types
> in the same directory.
>
> When I get a chance, I'll write you a better version of this
> which would fix these problems and provide new abilities as well.
> I am surprised though that someone hasn't already written a
> better handler for integrating Cheetah with mod_python.
>
> BTW, I am not on the Cheetah mailing list, so ensure any responses
> also go back to the mod_python list as well.
>
> Graham
>
> On Tuesday, March 15, 2005, at 02:17 AM, Stephane Bortzmeyer wrote:
>
> > I always used Cheetah on Apache with a custom mod_python handler (see
> >). I would like to
> > use mod_python's publisher
> >, in order
> > to limit my liability :-) specially for security reasons.
> >
> > It works fine but not if I use Cheetah's inheritance, as described in
> >
> > inheritanceEtc.extends.html.
> > My foobar.tmpl Cheetah file is compiled as foobar.py, which includes
> a
> > foobar class. I added a index() routine but Cheetah puts in in the
> > foobar class, not directly in the foobar module. When
> > mod_python.publisher calls index(), it finds nothing and returns
> > NOT_FOUND.
> >
> >
> >
> > My SiteLogic.py:
> >
> >
> > from Cheetah.Template import Template
> >
> > class SiteLogic(Template):
> > """ Pure Python class containing methods for the site """
> >
> > # Never found because Cheetah puts it in a class
> > def index(req):
> > return "Dummy"
> >
> >
> >
> > My Site.tmpl:
> >
> >
> >
> > #from SiteLogic import SiteLogic
> > #extends SiteLogic
> > #implements respond
> >
> > #def title
> > No title #slurp
> > #end def
> >
> > #def body
> > <P>Default body.
> > #end def
> >
> > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
> > <HTML>
> > <HEAD>
> > <TITLE>
> > $title
> > </TITLE>
> > </HEAD>
> > <BODY>
> > <H1>$title</H1>
> > $body
> > <HR>
> >
> >
> >
> > A typical page:
> >
> >
> > #from Site import Site
> > #extends Site
> > #implements body
> > #def title
> > #end def
> >
> > <P>Some content.
> > _______________________________________________
> > Mod_python mailing list
> > Mod_python at modpython.org
> >
>
> _______________________________________________
> Mod_python mailing list
> Mod_python at modpython.org
> | http://www.modpython.org/pipermail/mod_python/2005-March/017639.html | crawl-002 | refinedweb | 702 | 59.9 |
It’s now easier than ever to make a mobile game with Felgo, you’d like to create your own mobile game, you’ll have to make code changes at some point. These 7 simple steps will help you morph the Platformer Level Editor example included in your Felgo installation into your own game.
To get started, open your Felgo installation folder and then navigate to this path: “…\Examples\Felgo\demos\PlatformerWithLevelEditor”. Copy this folder, paste it to your desktop and then rename it to “My Platformer”. If you haven’t downloaded Felgo yet (It’s Free), you can get it here!
Now we can make whatever changes we like to the demo without affecting the original example. This is helpful as you can always refer back to the original example for help. Open the folder, rename the Qt Project File to “My Platformer” as well and then open the file. Once Qt Creator opens, you can configure the project and start making your own mobile game.
1. Toggle the Double Jump Feature
Some key features of any game are the abilities of the player. When you first try out the Platformer Level Editor demo, you’ll notice the player has the ability to perform a double jump. If you don’t want this feature in your own game, it can be changed very easily. We just need to make a couple of simple changes to the Player.qml code.
- Open the Player.qml file in the entities folder
- Press Ctrl + F to enable Qt Creator’s “Find” capabilities
doubleJumpEnabled
- Change
property bool doubleJumpEnabled: true
to
property bool doubleJumpEnabled: false
- Find the next instances of
doubleJumpEnabled
and make sure that they are also changed to equal a “false” setting
- Hit Ctrl + R to run the game example
The double jump feature will now be disabled! If you’d like to enable the feature again, you just need to change all the “false” settings back to “true”.
2. Adjust Your Mobile Game Physics
After your player settings, your in-game physics will be one of the most defining features of your game. In-game physics control the speed of your player, the strength of your game’s gravity and more. Adjusting your game’s physics is one of the easiest things to do when you create your own game with the level editor.
- Run the game example and select Levels from the main menu
- Press the green “Plus” button on the My Levels menu
- You’ll now find yourself in level editor mode. Select the pencil tool and draw some ground for your character to stand on
- Now press the arrow button on the right hand side of the screen. This will open up the physics settings of your game.
- Adjust the Acceleration setting to 2000
- Press the green “Play” button at the top of the screen
Now you can test out the new physics settings. If you’d like to make further adjustments, you can just press the arrow button on the left and edit the settings as you test. This is a great feature that makes creating your own game a much more intuitive process.
3. Personalize the UI
For the best results, you can create a personalized UI for your game. The Current UI of the Platformer Level Editor example goes well with the sample game but your user interface should suit your own game design. There are two main places where we can adjust the UI: in MenuScene.qml and in LevelScene.qml.
Making changes to the MenuScene.qml file will change the menu scene that appears when you start the game. The background of this scene is currently styled using this code snippet:
// background Rectangle { id: background anchors.fill: parent.gameWindowAnchorItem gradient: Gradient { GradientStop { position: 0.0; color: "#4595e6" } GradientStop { position: 0.9; color: "#80bfff" } GradientStop { position: 0.95; color: "#009900" } GradientStop { position: 1.0; color: "#804c00" } } }
We’re going to change the background by replacing this code with this snippet to create a green background:
// background Rectangle { id: background anchors.fill: parent.gameWindowAnchorItem color: "green" } }
Or else you can use a custom image like this:
// background Rectangle { id: background anchors.fill: parent.gameWindowAnchorItem Image { source: "yourcustomimage.png" } }
You can adjust the background of LevelScene.qml in the same way.
If you’d like to change the buttons of the MenuScene.qml, you just need to create new image files and then change the image.source property of the PlatformerImageButton to point to the new image. The PlatformerImageButton component is also used in the LevelScene file along with the PlatformerSelectableTextButton component. You can easily edit this button by changing its screenText property to say whatever you’d like.
Let’s change this:
PlatformerSelectableTextButton { id: demoLevels screenText: "Demos" width: 80 // this button is selected if the state is demoLevels isSelected: levelScene.state == "demoLevels" // set state to demoLevels onClicked: levelScene.state = "demoLevels" }
To this:
PlatformerSelectableTextButton { id: demoLevels screenText: "Felgo!" width: 80 // this button is selected if the state is demoLevels isSelected: levelScene.state == "demoLevels" // set state to demoLevels onClicked: levelScene.state = "demoLevels" }
And get this change:
These UI changes are easy to do and will give you the skills to change all of the other UI elements as well.
4. Customize Game Entities
The platformer Level Editor comes with a number of predefined entities such as player enemies, power-ups and collectables. These entities cover the most common features of platformers and can be customized easily. This allows you to create a unique experience for your players and bring your game to life.
Let’s change the Mushroom.qml file so it looks like a burger. You can get the burger image asset from here.
The first thing to do is move the burger.png file to the correct directory. Locate the asset and then move it to the “…\Desktop\My Platformer\assets\powerups” folder. Then we need to update the code to make the burger appear in the game. Change this code from the Mushroom.qml file:
// set image image.source: "../../assets/powerups/mushroom.png"
To this:
// set image image.source: "../../assets/powerups/burger.png"
And now you have a burger power-up in your game!
You can do the exact same with player enemies, physical entities like the ground and platforms, and the level finish goal to create a game that looks completely different to the original Platformer Level Editor demo.
5. Add Game Entities
Besides customizing the existing game entities, you might want to add your own enemies or physical components. There are a few different ways to add these entities depending on what you’d like to achieve. This is the skill that really enables you to turn the example into your own game. The easiest entities to add are ground entities.
At the moment, there are two different types of ground; grass and dirt. Let’s add sand to the game. You can get the sand asset here. Once you have the file, move it to this folder: “…\Desktop\My Platformer\assets\ground”.
Next we’ll create a Sand.qml file. Right click on the entities folder from the project tree in Qt Creator and then click “Add new…”. From here we can create a new QML File (Qt Quick 2) that we’ll name “GroundSand”. Now we’ll copy the code from the GroundDirt.qml file and adjust the code to use the Sand.png asset.
Copy this code from GroundDirt.qml into GoundSand.qml:
import QtQuick 2.0 import Felgo 3.0 Ground { variationType: "grass" image.source: "../../assets/ground/ground_grass.png" }
And then change the image.source property so it reads like this:
import QtQuick 2.0 import Felgo 3.0 Ground { variationType: "sand" image.source: "../../assets/ground/sand.png" }
Now you need to update Sidebar.qml so the new asset shows up in the level editor when you want to make your game. First we need to change the buttons property so the sand is a selectable variation. This is the code snippet that you need to edit in Sidebar.qml:
// this property holds all BuildEntityButtons // we use this in the unselectAllButtonsButOne() function property var buttons: [groundButton, ground2Button, platformButton, spikeballButton, spikesButton, opponentJumperButton, opponentWalkerButton, coinButton, mushroomButton, starButton, finishButton]
We’re going to add a button called groundSandButton to this list:
// this property holds all BuildEntityButtons // we use this in the unselectAllButtonsButOne() function property var buttons: [groundButton, ground2Button, groundSandButton, platformButton, spikeballButton, spikesButton, opponentJumperButton, opponentWalkerButton, coinButton, mushroomButton, starButton, finishButton]
Further down the SideBar.qml file, we’re going to add the actual button component for GroundSand.qml. Find the BuildEntityButtons and then add a PlatformerBuildEntityButton to the list using this code:
PlatformerBuildEntityButton { id: groundSandButton visible: entityGroups.activeGroup == 1 toCreateEntityTypeUrl: "../entities/GroundSand.qml" onSelected: selectBuildEntityButton(this) onUnselected: unselectBuildEntityButton() }
An important thing to note here is the visible property, which will determine whether the asset shows up in the ground group, the enemy group or the power-up and collectables group. We want the sand to belong to entity group 1. Run your game and you’ll now find sand as an option when editing levels!
You can add more entities to the game by repeating this process. You just need to create a new qml file in the entities folder, and then add it as a variation in Sidebar.qml along with a button to make it selectable in the level editor.
6. Add Your Own Levels
When you’ve added your own entities, customized the UI and made some general game design decisions, you’ll want to start creating your own levels. The first thing to do is delete the levels that come preloaded with the example. To do this:
- Expand the “Other Files” directory in your project tree.
- Expand the “qml” directory underneath
- Expand the “levels” directory
- Right click each of the .json files and select “Delete File…” for each of the levels
- Navigate to the following folder on your system, “…\Desktop\My Platformer\qml\levels”
- Delete the 4 .json files from this folder. Do not delete the folder.
Once you’ve completed these steps, the 4 levels that come with the example will be removed from the game. In order to create some levels for your game, you need to add a button component to your GameScene.
Open the PlatformerWithLevelEditorMain.qml file and find the GameScene component. It looks like this:
GameScene { id: gameScene onBackPressed: { // reset level gameScene.resetLevel() // switch to levelScene gameWindow.state = "level" } }
You’re going to add a button to this component that will allow you to export your custom made levels from the level editor to your documents folder. Replace the above code snippet with this:
GameScene { id: gameScene onBackPressed: { // reset level gameScene.resetLevel() // switch to levelScene gameWindow.state = "level" } SimpleButton { text: "Export Level" onClicked: levelEditor.exportLevelAsFile() } }
This adds a button to the level editor that allows you to export all your levels. Just hit “Export Level” when you’re happy, navigate to your documents folder and copy the JSON files to your levels folder. It’s helpful to rename the new levels you create as they’re all exported with the same file name. Renaming them will prevent old levels being overwritten or duplicates being created. Your custom made levels are now saved and packaged with your game!
7. Include the Felgo Game Network
If you’re finished creating your game, there’s one more thing you should do before publishing. The Felgo Game Network is a free feature that enables you to include leaderboards and achievements in your game. The Platformer Level Editor is a great retention tool as it allows your players to create new game content, so there’s always something new to do. By adding the Felgo Game Network, you can increase this retention even more by building a competitive community around your game.
Adding the Felgo Game Network to your game is a simple process that can be completed in about 10 minutes but have a lasting effect on your game. Check out this tutorial to find out how to take advantage of one of the best features Felgo has to offer.
Create Your Own Mobile Game with Felgo
So there you have it. With this simple guide you can make your own mobile game in the shortest time possible. If you’ve followed this guide and released your own game in this way, let us know in the comments. Make sure to share this article with your Facebook friends and Twitter followers!
Explore Level Editor Benefits!
References
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- | https://felgo.com/game-resources/make-mobile-games | CC-MAIN-2019-39 | refinedweb | 2,077 | 65.32 |
Immediate FunctionsOct 6, 2015
This article is intended for JavaScript beginners.
The browser environment is one big JavaScript
closure that will encapsulate in its
scope all of the code that is to be run. Because of this, any functions or variables that are created in
<script> tags or external
.js files that are not defined within a function will end up as global variables! And we all know that global varibles are bad. Let's dig in to this some more.
Every time you define a function and then define a variable with
var inside of that function, that variable only exists inside of that function. For example, what is the value of
result that is logged to the console?
// app.js function kelvinToFahrenheit(kelvin) { var result = Math.round(kelvin * (9/5) - 459.67); return result; } kelvinToFahrenheit(274.3); console.log(result);
The correct answer would be
undefined (with a nice error), for
result only exists within the
scope of the
kelvinToFahrenheit function. However, the function
kelvinToFahrenheit now exists globally.
Why does this matter? Well, when you include a script on to a web page, its code now becomes part of this global closure. So if you define
function kelvinToFahrenheit() without giving it a separate closure or namespace (more on namespaces in a second), then it is now a "global function," meaning that it exists in the global namespace. If any other library you ever include uses a variable called
router, your variable (or that library's) is going to overwrite whichever came before it and cause massive issues. The same thing is true for variables:
// app.js var currentTempInKelvin = 294.11;
So what are your options?
Immediately Invoked Function Expressions (IIFEs)
// app.js ;(function() { // your code here })();
The semi-colon here is a defensive technique used for when files are concatenated together--if somebody in one file forgets to close their file/library/definition out with a semi-colon, then your code is going to be an extension of theirs.
The
() towards the end is nothing more than the invocation of the immediate function we've defined.
Thus, when you write
// app.js ;(function() { var currentTempInKelvin = 294.11; })();
and then you try to
console.log(currentTempInKelvin); from the browser's JavaScript console, you will get
undefined, for
currentTempInKelvin now only exists within that anonymous function's scope. Hurray! No more globals.
But what if we want to access something in a global fashion? We know about the problems of name-clashing, so let's also try to reduce that. Let's combine what you did with the immediate function and do global variables in a less-bad way using namespacing.
Namespacing
Namespacing allows us to limit our use of global variables to one global by nesting all of our functionality within one global object that we'll call
WeatherApp.
// app.js // No var declaration means global! ;(function() { WeatherApp = { kelvinToFahrenheit: {} }; })();
or
// app.js ;(function() { WeatherApp = {}; WeatherApp.kelvinToFahrenheit = {}; })();
or (better)
// app.js ;(function() { window.WeatherApp = {}; window.WeatherApp.kelvinToFahrenheit = {}; })();
or (recommended)
// app.js ;(function(scope) { scope.WeatherApp = {}; scope.WeatherApp.router = {}; })(this);
This last method allows you to use this code and pass in any contextual scope. Since
this is equivalent to
window at the global level, when you run this in the browser,
this is
window, so
WeatherApp will be added to the
window global.
When you leave out the
var, you create a global variable, so be careful! I recommend being explicit with to what object you are adding a
namespace. If you're going the global variable route, then you should nest every single thing you're doing inside of your
WeatherApp namespace in order to avoid having more than 1 global variable.
Conclusion
This is a great pattern to utilize when you have relatively simple JavaScript you would like to add to a webpage and not have its contents clash with other libraries & code. If your code begins to get too complicated for this file, then we can start to look at the CommonJS module exporting & requiring pattern that is currently implemented by the wonderful Browserify library (aka, Node.js but in the browser). I will cover this in the future, but in the mean time, leverage the power of immediate functions for great good! | https://robertwpearce.com/blog/immediate-functions.html | CC-MAIN-2017-34 | refinedweb | 706 | 66.03 |
Introduction to Variables().
The Numeric Systems
Introduction
When a computer boots, it “loads” the operating
system. If you want to use a program, you must find it either on the
Start menu or from its directory and take the necessary action to open
it. Such a program uses numbers, characters, meaningful words, pictures,
graphics, etc, that are part of the program. As these things are
numerous, so is the size of the program, and so is the length of time
needed to come up. Your job as a programmer is to create such programs
and make them available to the computer, then to people who want to
interact with the machine.
To write your programs, you will be using alphabetic
letters that are a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r,
s, t, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q,
R, S, T, U, V, W, X, Y, Z. You will also use numeric symbols 0, 1, 2, 3,
4, 5, 6, 7, 8, 9. Additionally, you will use characters that are not
easily readable but are part of the common language; they are ` ~ ! @ #
$ % ^ & * ( ) _ + - = : “ < > ; ‘ , . /. Some of these symbols are used
in the C# language while some others are not. When creating your
programs, you will be combining letters and/or symbols to create English
words or language instructions.
Some of the instructions you will give to the computer could
consist of counting the number of oranges, converting water to soup, or making
sure that a date occurs after January 15. After typing an instruction, the
compiler would translate it to machine language. The computer represents any of
your instructions as a group of numbers. Even if you ask the computer to use an
orange, it would translate it into a set of numbers. As you give more
instructions or create more words, the computer stores them in its memory using
a certain amount of space for each instruction or each item you use.
There are three numeric systems that will be involved in
your programs, with or without your intervention.
The Binary System
When dealing with assignments, the computer considers a
piece of information to be true or to be false. To evaluate such a piece, it
uses two symbols: 0 and 1. When a piece of information is true, the computer
gives it a value of 1; otherwise, its value is 0. Therefore, the system that the
computer recognizes and uses is made of two symbols: 0 and 1. As the information
in your computer is greater than a simple piece, the computer combines 0s and 1s
to produce all sorts of numbers. Examples of such numbers are 1, 100, 1011, or
1101111011. Therefore, because this technique uses only two symbols, it is
called the binary system.
When reading a binary number such as 1101, you should not
pronounce "One Thousand One Hundred And 1", because such a reading is not
accurate. Instead, you should pronounce 1 as One and 0 as zero or o. 1101 should
be pronounced One One Zero One, or One One o One.
The sequence of the symbols of the binary system depends on
the number that needs to be represented.
The Decimal System
The numeric system that we are familiar with uses ten
symbols that are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Each of these symbols is
called a digit. Using a combination of these digits, you can display numeric
values of any kind, such as 240, 3826 or 234523. This system of representing
numeric values is called the decimal system because it is based on 10 digits.
When a number starts with 0, a calculator or a computer
ignores the 0. Consequently, 0248 is the same as 248; 030426 is the same as
30426. From now on, we will represent a numeric value in the decimal system
without starting with 0: this will reduce, if not eliminate, any confusion.
Decimal Values: 3849, 279, 917293, 39473
Non- Decimal Values: 0237, 0276382, k2783, R3273
The decimal system is said to use a base 10. This allows you
to recognize and be able to read any number. The system works in increments of
0, 10, 100, 1000, 10000, and up. In the decimal system, 0 is 0*100 (=
0*1, which is 0); 1 is 1*100 (=1*1, which is 1); 2 is 2*100
(=2*1, which is 2), and 9 is 9*100 (= 9*1, which is 9). Between 10
and 99, a number is represented by left-digit * 101 + right-digit *
100. For example, 32 = 3*101 + 2*100 = 3*10 +
2*1 = 30 + 2 = 32. In the same way, 85 = 8*101 + 5*100 =
8*10 + 5*1 = 80 + 5 = 85. Using the same logic, you can get any number in the
decimal system. Examples are:
2751 = 2*103 + 7*102 + 5*101
+ 1*100 = 2*1000 + 7*100 + 5*10 + 1 = 2000 + 700 + 50 + 1 = 2751
67048 = 6*104 + 7*103 + 0*102
+ 4*101 + 8*100 = 6*10000 + 7*1000+0*100+4*10+8*1 = 67048
Another way you can represent this is by using the following
table:
When these numbers get large, they become difficult to read;
an example is 279174394327. To make this easier to read, you can separate each
thousand fraction with a comma. Our number would become 279,174,394,327. You can
do this only on paper, never in a program: the compiler would not understand the
comma(s).
The Hexadecimal System
While the decimal system uses 10 digits (they are all
numeric), the hexadecimal system uses sixteen (16) symbols to represent a
number. Since the family of Latin languages consists of only 10 digits, we
cannot make up new ones. To compensate for this, the hexadecimal system uses
alphabetic characters. After counting from 0 to 9, the system uses letters until
it gets 16 different values. The letters used are a, b, c, d, e, and f, or their
uppercase equivalents A, B, C, D, E, and F. The hexadecimal system counts as
follows: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, and f; or 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, A, B, C, D, E, F. To produce a hexadecimal number, you use a
combination of these sixteen symbols.
Examples of hexadecimal numbers are 293, 0, df, a37, c23b34,
or ffed54. At first glance, the decimal representation of 8024 and the
hexadecimal representation of 8024 are the same. Also, when you see fed, is it a
name of a federal agency or a hexadecimal number? Does CAB represent a taxi, a
social organization, or a hexadecimal number?
From now on, to express the difference between
a decimal number and a hexadecimal one, each hexadecimal number will
start with 0x or 0X. The number will be followed by a valid
hexadecimal combination. The letter can be in uppercase or
lowercase.
Legal Hexadecimals: 0x273, 0xfeaa, 0Xfe3, 0x35FD, 0x32F4e
Non-Hex Numbers: 0686, ffekj, 87fe6y, 312
Legal Hexadecimals: 0x273, 0xfeaa, 0Xfe3, 0x35FD, 0x32F4e
Non-Hex Numbers: 0686, ffekj, 87fe6y, 312
There is also the octal system but we will not use it
anywhere in our applications.
Signed and Unsigned.
This is the basis of our counting items.
In real life, there are numbers counted in decrement values.
Such numbers start at –1 and move down to -2, -3, -4 etc. These numbers are
qualified as negative.
When you write a number “normally”, such as 42, 502, or
1250, the number is positive. If you want to express the number as negative, you
use the – on the left side of the number. The – symbol is called a sign.
Therefore, if the number does not have the – symbol, C++ (or the compiler)
considers such a number as unsigned. In C++, if you declare a variable that
would represent a numeric value and you do not initialize (assign a value to)
such a variable, the compiler will consider that the variable can hold either a
signed or an unsigned value. If you want to let the compiler know that the
variable should hold only a positive value, you will declare such a variable as
unsigned.
Data Types
In order to use a variable in your program, the compiler
must be aware of it. Once the compiler knows about a variable, it would reserve
an amount of memory space for that variable
Using its name, you can refer to a particular variable when
necessary. Because there are various types of variables a program can use, such
as the employee's name, his home address, the desired salary, years of
experience, education level, etc for our employment application analogy, the
compiler needs a second piece of information for each variable you intend to
use. This piece of information specifies the amount of space that a variable
needs. You can see that, to store a character, such as an employee's gender (M
or F) or an answer as Y or N to a question, the compiler would certainly not
need the same amount of space to store the name of the last school attended by
an employee.
A data type is an amount of space needed to store the
information related to a particular variable.
The name of a variable allows you and the compiler to refer
to a particular category of information in your program. The data type allows
the compiler to reserve an adequate amount of memory space for a variable.
Because you are the one who writes a program, you also tell the compiler the
amount of memory space each particular variable will need. Based on this, the C#
language provides categories of data types used to specify this amount of space
needed for a variable.
As stated already, before using a variable, you must
communicate your intentions to the compiler. Making the compiler aware is
referred to as declaring the variable. To declare a variable, you have two
options:
DataType VariableName;
Providing a value for a variable is referred to as
initializing it. This can be done for declared with either a data type or the
var keyword:
To initialize a variable, on the right side of its name,
type the assignment operation, which is =, followed by a value::
Table of Numeric Conversions.
A Byte
A byte is a group or eight consecutive bits. The bits are
counted from right to left starting at 0:
The most right bit is bit 0; it is called the least
significant bit. It is also referred to as the Low Order bit, the LO bit, or
LOBIT. The most left bit is bit 7; it is called the most significant bit. It
is also referred to as the High Order bit, the HI bit, or HIBIT. The
other bits are referred to following their positions:
Using the binary system, you can represent the byte using a
combination of 0s and 1s. When all bits have a value of 0, the byte is
represented as 00000000. On the other hand, when all bits have a value of 1, the
byte is represented as 11111111. When the number grows very large, it becomes
difficult to read. Therefore, you can represent bits in groups of four. Instead
of writing 00000000, you can write 0000 0000. This makes the number easier to
read.
If you have the patience to create combinations of bits
using the boxes as we did for the group of 4, you would find out that there are
256 possible combinations. Another way to find it out is by using the base 2
technique:
27 + 26 + 25 + 24
+ 23 + 22 + 21 + 20
= 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
= 255
Therefore, the maximum decimal value you can store in a byte
is 255.
Remember that the byte with all bits having a value of 0 has
its value set to 0. Since this byte also holds a valid value, the number of
combinations = 255 + 1 = 256.
When a byte is completely represented with 0s, it provides
the minimum value it can hold; this is 0000 0000, which is also 0. When all bits
have a value of 1, which is 1111 1111, a byte holds its maximum value that we
calculated as 255 in the decimal system. As done with the group of 4 bits, we
get the following table::
using System;
class Exercise
{
static void Main()
{
Console.WriteLine('n');
}
}, you can use the var keyword and initialize the variable with a
character in single-quotes. Here is an example:
using System;
class Exercise
{
static void Main()
{
var Gender = 'F';
Console.Write("Student Gender: ");
Console.WriteLine(Gender);
}
}
Alternatively, you can use the char keyword. Here is
an example:
using System;
class Exercise
{
static void Main()
{
char Gender = 'M';
Console.Write("Student Gender: ");
Console.WriteLine(Gender);
}
}
This would produce:
Student an unsigned:
using System;
class ObjectName
{
static void Main()
{
Byte Age = 14;
Console.Write("Student Age: ");
Console.WriteLine(Age);
Age = 12;
Console.Write("Student Age: ");
Console.WriteLine(Age);
}
}.
Alternatively, you can also use the var keyword to declare
the variable and initialize it with a small number. Here is an example:
using System;
class Exercise
{
static void Main()
{
var Age = 14;
Console.Write("Student Age: ");
Console.WriteLine(Age);
Age = 12;
Console.Write("Student Age: ");
Console.WriteLine(Age);
}
}
Instead of a decimal number, you can also initialize an
integral variable with a hexadecimal value. When doing this, make sure the
decimal equivalent is less than 255. Here is an example:
using System;
class Exercise
{
static void Main()
{
var Number = 0xFE;
Console.Write("Number: ");
Console.WriteLine(Number);
}
}
Number: 254
Press any key to continue . . .
Practical
Learning: Using Bytes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GeorgetownCleaningServices2
{
class Program
{
static void Main(string[] args)
{
byte Shirts;
byte Pants;
Shirts = 4;
Pants = 1;
Console.WriteLine("-/- Georgetown Cleaning Services -/-");
Console.WriteLine("========================");
Console.WriteLine("Item Type Qty");
Console.WriteLine("------------------------");
Console.Write("Shirts ");
Console.WriteLine(Shirts);
Console.Write("Pants ");
Console.WriteLine(Pants);
Console.WriteLine("========================");
Console.WriteLine();
}
}
}
-/- Georgetown Cleaning Services -/-
========================
Item Type Qty
------------------------
Shirts 4
Pants 1
========================:
using System;
class NumericRepresentation
{
static void Main()
{
sbyte RoomTemperature = -88;
Console.Write("When we entered, the room temperature was ");
Console.WriteLine(RoomTemperature);
Console.WriteLine();
}
} to 32767. Here is an example:
using System;
class Exercise
{
static void Main()
{
var SchoolEffective = 1400; // Number of Students
Console.Write("School Effective: ");:
using System;
class Exercise
{
static void Main()
{
short NumberOfPages;
short Temperature;
NumberOfPages = 842;
Temperature = -1544;
Console.Write("Number of Pages of the book: ");
Console.WriteLine(NumberOfPages);
Console.Write("Temperature to reach during the experiment: ");
Console.Write(Temperature);
Console.WriteLine(" degrees\n");
}
}
Number of Pages of the book: 842
Temperature to reach during the experiment: -1544 degrees either the var of the ushort keyword. An unsigned
short integer can hold numbers that range from 0 to 65535 and therefore can fit
in 16 bits. Here is an example:
using System;
class NumericRepresentation
{
static void Main()
{
// These variables must hold only positive integers
ushort NumberOfTracks;
ushort MusicCategory;
NumberOfTracks = 16;
MusicCategory = 2;
Console.Write("This music album contains ");
Console.Write(NumberOfTracks);
Console.WriteLine(" tracks");
Console.Write("Music Category: ");
Console.Write(MusicCategory);
Console.WriteLine();
}
}
This music album contains 16 tracks
Music Category: 2
Practical
Learning: Using Unsigned Short Integers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GeorgetownCleaningServices2
{
class Program
{
static void Main(string[] args)
{
byte Shirts;
byte Pants;
ushort OtherItems;
Shirts = 4;
Pants = 1;
OtherItems = 3;
Console.WriteLine("-/- Georgetown Cleaning Services -/-");
Console.WriteLine("========================");
Console.WriteLine("Item Type Qty");
Console.WriteLine("------------------------");
Console.Write("Shirts ");
Console.WriteLine(Shirts);
Console.Write("Pants ");
Console.WriteLine(Pants);
Console.Write("Other Items ");
Console.WriteLine(OtherItems);
Console.WriteLine("========================");
Console.WriteLine();
}
}
}
-/- Georgetown Cleaning Services -/-
========================
Order Date: 7/15/2002
------------------------
Item Type Qty
------------------------
Shirts 4
Pants 1
Other Items 3
========================
Press any key to continue . . . | http://www.functionx.com/csharp3/Lesson02.htm | CC-MAIN-2016-44 | refinedweb | 2,654 | 63.19 |
In this tutorial, we are going to learn about react native layout. In the last tutorial, we looked at react native styling. If you have not read it I will suggest you do so.
In react native, learning to layout and structure your application will help you create an inspiring and attractive interface your users will love.
React native component uses flexbox to layout its children. Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number.
Apart from these slight differences, if you have used flexbox in CSS, you will be familiar with it and will get going at the end of this tutorial.
The first thing to have in mind is that react native flexbox uses these properties – flexDirection, alignItems and justifyContent to decide placement of children in a layout.
The flexDirection of a component determines the primary axis of its layout. If the flexDirection is column then the axis will be vertical otherwise it will be horizontal. The diagram below illustrate how flexDirection, primary and secondary axis are related.
Let start with a simple example with the default flexDirection column. We are going to add three child Views inside a parent View.
The flex style property does not accept percentage and values with unit rather it uses the concept of ratio to apportion space to child components.
The main or parent content View is assigned a flex value of 1. This implies that the component will fill all the available space in the window.
Let try and see some example that will help us understand this concept much better.
Create a new React Native App
In other to follow this tutorial and get your hand dirty with code, create a new react native application and give it a name of your choice.
If you have not created a react native application before, you can follow my tutorial on React Native setup to get going.
Once you are done with creating your react native project, run either of these command depending on the platform you are targeting.
React-native run-ios or react-native run-android
Now that you have started your emulator and you can see the default boilerplate page that comes with react native project setup, Go to the root directory of your project, open the app.js file in any Javascript IDE of your choice.
Copy the code below and paste it in the file and the reload your project. If everything works out for you, you will see a screen-shot like below., backgroundColor: '#1f2041', }, firstrow: { flex: 1, backgroundColor: "#ffc857" }, secondrow: { flex: 1, backgroundColor: "#4b3f72" }, thirdrow: { flex: 1, backgroundColor: "#119da4" }, fourthrow: { flex: 1, backgroundColor: "#19647e" } });
FlexDirection Row
Let try and change the flexDirection of the parent component from the default column to row.
const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', backgroundColor: '#1f2041', }, }
Below is the result of the changes.
Now that we have an idea of how flex works, we will move over to justifycontent. The code snippet is below and note that the only thing we will be changing is the justifyContent value., paddingTop: 40, backgroundColor: '#1f2041', justifyContent: 'flex-start' }, firstrow: { width: 160, height: 160, backgroundColor: "#ffc857" }, secondrow: { width: 160, height: 160, backgroundColor: "#4b3f72" }, thirdrow: { width: 160, height: 160, backgroundColor: "#119da4" }, fourthrow: { width: 160, height: 160, backgroundColor: "#19647e" } });
justifyContent
When you want to distribute child components in their parent component along the primary axis you will need to use justifyContent to achieve that.
In other to see the effect of this style property, we are going to assign our child component’s width and height some values because it is very hard to notice any effect if we use flex since the component will fill up the width and height space of the component.
JustifyContent has five values which we will see how they differ from each other. They are
flex-start, center, flex-end, space-around and space-between
Flex-start
In flex-start, the child components are align at the beginning of the page. Each subsequent component follows the one proceeding it. You can see that a space is left at the bottom of the page.
Center
When you pass a value of center to justifyContent , the child view are placed in the center of the screen either vertical or horizontal depending on the primary axis direction. Notice the equal space distribution in the top and bottom of the page.
Flex-end
When you set the value of justifyContent to flex-end, it will give you the opposite of what you get when you use flex-start. Instead of placing the starting point of the child components at the top, it will push them down to the bottom.
Space-around
With space-around, all child components are distributed with equal space around them.
Space-between
With space-width, the child components are given equal space between then as shown in the diagram below.
alignItems
AlignItems is use to distribute child components along the secondary axis. Like the justifyContent, alignItems can take any of the following values –
flex-start, center, flex-end and
stretch
For stretch to have an effect, children must not have a fixed dimension along the secondary axis. In the following, setting alignItems: stretch does nothing until the width: 50 is removed from the children.
Other Option to distribute child components in react native
Apart from what we have discussed here, there are other few options you can employ to create a complex layout in your application. We will not discuss them but if you want to read more on this topic you can go the react native developer page
Let create a react native interface base on what we have learned
We have covered lots of ground on react native layout but if we go home now we might not remember some of the things we have learnt. Not just that, for us to become better and better, we need to practice as much as possible.
With this in mind, we are going to create a simple weather app user interface.
The screen-shot of what we will create is shown below.
Create a react native project and name it Weatherappui or any name of your choice.
Once you are done, open the App.js file and copy the code below and paste in the file.
import React, { Component } from 'react'; import { Platform, StyleSheet, Image, Text, View, ImageBackground } from 'react-native'; import DegreeComponent from './app/DegreeComponent'; export default class App extends Component<{}> { render() { return ( <View style={styles.container}> <ImageBackground style={styles.upperregion} source={require('./assets/mybg.png')}> <View style={styles.innerupperregion}> <Text style={styles.today}> TODAY </Text> <Text style={styles.degrees}> 23<DegreeComponent> </DegreeComponent>C</Text> <Image style={styles.weathericon} source={require('./assets/weathericon.png')}/> <Text style={styles.weathercondition}>Partly Sunny</Text> </View> <View style={styles.lowerinnerregion}> <Text style={[styles.addwhite, {fontSize: 18}]}>MALMO, SWEDEN </Text> <Text style={[styles.addwhite, {fontSize: 14}]}>8:40 pm</Text> </View> </ImageBackground> <View style={styles.lowerregion}> <View style={styles.fivecolumns}> <Text style={styles.columntitle}>MON</Text> <Image style={styles.iconsmall} source={require('./assets/smallicon.png')} /> <Text style={styles.temp}>6/1</Text> </View> <View style={styles.fivecolumns}> <Text style={styles.columntitle}>TUE</Text> <Image style={styles.iconsmall} source={require('./assets/smallicon.png')} /> <Text style={styles.temp}>6/4</Text> </View> <View style={styles.fivecolumns}> <Text style={styles.columntitle}>WED</Text> <Image style={styles.iconsmall} source={require('./assets/smallicon.png')} /> <Text style={styles.temp}>6/20</Text> </View> <View style={styles.fivecolumns}> <Text style={styles.columntitle}>THU</Text> <Image style={styles.iconsmall} source={require('./assets/smallicon.png')} /> <Text style={styles.temp}>5/15</Text> </View> <View style={styles.fivecolumns}> <Text style={styles.columntitle}>FRI</Text> <Image style={styles.iconsmall} source={require('./assets/smallicon.png')} /> <Text style={styles.temp}>7/18</Text> </View> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#ffffff', }, upperregion: { flex: 2, alignItems: 'center', }, lowerregion: { flex: 1, flexDirection: 'row', backgroundColor: '#f4f4f4' }, innerupperregion: { marginTop: 120, backgroundColor: 'transparent', alignItems: 'center', flex: 2 }, lowerinnerregion: { flex: 1, justifyContent: 'flex-end', backgroundColor: 'transparent', alignItems: 'center', paddingBottom: 20 }, today: { fontSize: 21, color: 'white' }, degrees: { fontSize: 72, color: 'white' }, weathericon: { width: 120, height: 60, marginTop: 40, }, weathercondition: { fontSize: 18, color: 'white', marginTop: 20, }, addwhite: { color: 'white' }, fivecolumns: { flex: 1, paddingTop: 40, alignItems: 'center' }, columntitle: { fontSize: 13, color: '#2188db', fontWeight: 'bold' }, iconsmall: { width: 56, height: 32, marginTop: 30 }, temp: { fontSize: 16, color: '#666666', marginTop: 20 } });
Take time and go through the code. You will see how we have used all the knowledge we got from react native layout tutorial to create this weather app interface.
To create the degree sign, we have to create our own custom component.
Go to your react native project root directory, create a new folder called app.
Inside the app folder, create a new file and name it DegreeComponent.js.
Open the created file and paste the code below in it.
import React, {Component} from 'react'; import { StyleSheet, Text, Image, View } from 'react-native'; class DegreeComponent extends Component{ render(){ return( <View style={styles.circleicon}> </View> ); }; } const styles = StyleSheet.create({ circleicon: { width: 10, height: 10, borderRadius: 5, borderWidth: 2, borderColor: '#FFFFFF', marginTop: -50 }, }); module.exports = DegreeComponent;
You will also need to create another folder in the project root directory but now you can name it assets. This is where we will keep all our project assets like images.
Copy the required images and paste them inside the assets folder.
Finally, run the application. If everything works out for you, you will get a similar interface like the one above.
If you have any questions or suggestions, kindly use the comment box below and remember to subscribe for my fresh tutorials. | https://inducesmile.com/facebook-react-native/react-native-layout-example-tutorial/ | CC-MAIN-2020-34 | refinedweb | 1,629 | 56.76 |
Sine the 0.10.2 release, Rcpp contains an internal class
Timer which can be used for fine-grained benchmarking. Romain motivated
Timer in a post to the mailing * list where
Timer is used to measure the different components of the costs of random number generation.
A slightly modified version of that example follows below.
#include <Rcpp.h> #include <Rcpp/Benchmark/Timer.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector useTimer() { int n = 1000000; // start the timer Timer timer; for(int i=0; i<n; i++) { GetRNGstate(); PutRNGstate(); } timer.step("get/put") ; for(int i=0; i<n; i++) { GetRNGstate(); rnorm(10, 0.0, 1.0); PutRNGstate(); } timer.step("g/p+rnorm()"); for(int i=0; i<n; i++) { // empty loop } timer.step( "empty loop" ) ; NumericVector res(timer); for (int i=0; i<res.size(); i++) { res[i] = res[i] / n; } return res; }
We get the following result, each expressing the cost per iteration in nanoseconds:
useTimer()
get/put g/p+rnorm() empty loop 1.634e+03 2.573e+03 2.620e-04
The interesting revelation is that repeatedly calling
GetRNGstate() and
PutRNGstate() can amount to about 60% of the cost of RNG draws. Luckily, we usually only have to call these helper functions once per subroutine called from R (rather than repeatedly as shown here) so this is not really a permanent cost to bear when running simulations with R.
It also show the usefulness of a fine-grained timer at the code... | http://www.r-bloggers.com/using-the-rcpp-timer/ | CC-MAIN-2014-42 | refinedweb | 243 | 65.52 |
Adding Redux With NgRx/store to Angular 2 — Part 2 (Testing Reducers)
In this post, I'm sharing my insights on achieving using ngrx/store, working with more than one reducer in Angular 2, and testing reducers as well.
Join the DZone community and get the full member experience.Join For Free
In my recent article about adding redux with ngrx/store to Angular 2, I showed a nice example of integrating this awesome state management library to my open source project Echoes Player. Since then, I really wanted to integrate YouTube player into this Angular 2 version. In this post, I'm sharing my insights on achieving using ngrx/store, working with more than one reducer in Angular 2, and testing reducers as well.
Creating a YouTube Player Reducer
First, I defined and created a reducer for the YouTube player in Echoes. This approach of defining first the reducer helps me to design what data the app needs for this feature and how I'd like to use it.
At first, I defined the actions for this player's reducer: }
Similar to the previously "videos" reducer (from my last article about ngrx/store), I defined a reducer for the player. It is a pure function that expects to get a state object and an Action object. The action object will always include an "action.type" of this action. It can also include an "action.payload" if the action is supposed to pass data.
For better readability and perhaps easier maintenance, I like to keep the creation of a new state in small functions, which I can test as well. Those are the "playVideo" and "toggleVisibility" functions. Remember, a reducer should return a new state and should mutate the old state object.
All in all, the "player" reducer function can also be tested (which is described later in this article): } }
Testing Reducers in ngrx/store and Angular 2
I've written before that I like to write tests. Testing reducers turned out to be quite simple—a reducer is a function that gets an input and should always return an output. Let's see how we can test the new player reducer.
First, we need to setup the relevant testing utils that we're going to use—using jasmine for testing:); }); });
Connecting the Reducer to a Component
Now, we need to use this reducer in Echoes Player. For that, I created a YouTube player component. It should play a YouTube media when it's picked and display the played media title in the bottom bar.
The youtube-player component, registers to the youtube-player store in the constructor function and updates its player property whenever an action of this reducer is performed. This action lets the player display the title of the currently played media:
import { Component, EventEmitter, Input, Output, ChangeDetectionStrategy } from 'angular2/core'; import { NgModel, NgClass, AsyncPipe } from 'angular2(); } }
Notice how I use the "subscribe" method (this is RxJS method) in order to register to a change in the player store (which will eventually) will render the media title to the YouTube player template. Within this callback function, I can also instruct the player to either play/pause/queue—however, currently, the "player" store structure doesn't have a property for "player.state"—I'm still not sure that this is the correct way to achieve this and still investigating this practice. If you have any idea/suggestion—please let me know (in this article comments, the contact page or the GitHub repository).
The "playerService" is a service to interact with the YouTube player instance (3rd party module). In order to instruct the player to play a certain media from the video thumbs list, the "youtube-videos" component invokes the "playVideo" method of this service. This method ("playVideo") also dispatches the action "PLAY" and updates the "player" state:
file: src/app/youtube-videos/youtube-videos.ts }); }
Using this method, I'm just updating the current state of the player—indicating the media that is playing at the moment. I'm still looking for a way to dispatch a "PLAY_MEDIA" action, which will eventually, invoke the 3rd party YouTube player module to play the expected media that is sent as a payload in this action.
Final Thoughts
Here is a final screenshot of the player playing media and displaying it's title:
There's still a lot more to RxJS that can be explored. I just touched the surface of it in this post.
As always, this post's specific code is available on GitHub, the rest of the up-to-date code of Echoes Player is on the master branch.
Published at DZone with permission of Oren Farhi. See the original article here.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/adding-redux-with-ngrxstore-to-angular2-part-2-tes | CC-MAIN-2022-27 | refinedweb | 792 | 60.04 |
Using ApolloClient with node.js. "fetch is not found globally and no fetcher passed"
I am attempting to use an Apollo Client on a node.js server to interface with another GraphQL API using the following code:
import fetch from 'node-fetch' import { createHttpLink } from 'apollo-link-http' import ApolloClient from 'apollo-boost' import { API_URL } from '...' const client = new ApolloClient({ link: createHttpLink({ uri: API_URL, fetch: fetch, }), })
Which yields the following error:
module initialization error: Error fetch is not found globally and no fetcher passed, to fix pass a fetch for your environment like. For example: import fetch from 'node-fetch'; import { createHttpLink } from 'apollo-link-http'; const link = createHttpLink({ uri: '/graphql', fetch: fetch }); at Object.checkFetcher (/var/task/node_modules/apollo-link-http-common/lib/bundle.umd.js:78:19) at createHttpLink (/var/task/node_modules/apollo-link-http/lib/bundle.umd.js:32:30) at new HttpLink (/var/task/node_modules/apollo-link-http/lib/bundle.umd.js:203:38) at new DefaultClient (/var/task/node_modules/apollo-boost/lib/index.js:80:24)
I understand that the Apollo Client by default is expecting to be run in a browser context where a
fetch method will be available, and that in a node.js I need to polyfill or otherwise provide a
fetch method, but I having trouble figuring out exactly how to do this.
Following the example code at it appears that I should be able to pass this information in using the
link option, and reading the
apollo-boost source code seems to suggest that you can pass this information in using
fetcherOptions, but neither of these solutions seem to work.
Can anyone provide some example code for initializing an Apollo Client in node.js with a fetcher?
For reference here is my
package.json
{ "name": "API-Service", "version": "1.0.0", "description": "", "private": true, "scripts": {}, "dependencies": { "apollo-boost": "^0.1.6", "apollo-link-http": "^1.5.4", "graphql": "^0.13.2", "babel-polyfill": "^6.26.0", "json-rules-engine": "^2.1.0", "node-fetch": "^2.1.2", "mysql": "^2.15.0" } }
It turns out that the
ApolloClient provided by the
apollo-boost library does not accept a
link option. Switching to use the vanilla
apollo-client allows you to specify your fetching mechanism.
Although
apollo-boost and
apollo-client both export an
ApolloClient in the docs, they take wildly different options.
import fetch from 'node-fetch' import { createHttpLink } from 'apollo-link-http' import { InMemoryCache } from 'apollo-cache-inmemory' import ApolloClient from 'apollo-client' import { API_URL } from '...' const client = new ApolloClient({ link: createHttpLink({ uri: API_URL, fetch: fetch, }), cache: new InMemoryCache(), })
Does apollo-client work on node.js?, First, let's get all our files and dependencies in place. Create a folder called nodejs-apollo-client and open it in your terminal of choice. Now run npm init in your terminal to initialize NPM in the directory. Then execute the script below to install the dependencies. Ask apollo client authors to publish ESM package with "type": "module" field in package.json; Use workarounds in the source code; Use esm; Here's a workaround: import apolloClient from 'apollo-client'; const { ApolloClient } = apolloClient; Bonus: full example
If you still want to use Apollo Boost in Node.js but need to polyfill the native fetch API of the browser, try out cross-fetch. I used it for my minimal example over here. And that's how it can be used after installing it:
import 'cross-fetch/polyfill'; import ApolloClient from 'apollo-boost'; const client = new ApolloClient({ uri: '', });
Using Apollo to Query GraphQL from Node.js, In this tutorial, we will be using the Apollo Client 3.0 preview since it includes local state management Next, create an Apollo config file called apollo.config.js . In this tutorial, we will use the Apollo client library within a Node.js Express app to provide a middleman to your third-party endpoint, without the need to rewrite your GraphQL queries and mutations. In addition to Apollo, there are several NPM libraries, like lokka and express-graphql, that we could use to abstract our third-party endpoint.
You can add
fetch option directly to the
ApolloClient from
apollo-boost. Here is the example code
Ref.
import ApolloClient from 'apollo-boost'; import fetch from 'node-fetch'; const client = new ApolloClient({ fetch: fetch });
Tested with
apollo-boost version
0.4.3
5. Connect your API to a client - Apollo Basics, -side library that leverages the power of a GraphQL API to handle data fetching and management for you, so that you can spend less time plumbing data and more on building your application. I am new to GraphQL and Apollo and I am really struggling with setting up an apolloClient in node.js. First I want to mention that I sucessfully set up an apollo client within nuxt using nuxt's apollo module. So I am completely sure that my endpoint and my token are working.
You can use the
whatwg-fetch polyfill:
yarn add whatwg-fetch
The installation instructions depend on your usage (e.g Babel, Webpack etc.) and are in the provided link.
In my case I needed the polyfill for my Jest tests so I just put this in my test setup file:
import 'whatwg-fetch';
Apollo Client 1.0: A flexible, community-focused JavaScript GraphQL , , and provides funding for the open source part of the project..
A complete introduction to Apollo, the GraphQL toolkit, You can use Apollo Server with all popular JavaScript HTTP servers, including Express, Connect, Hapi, Koa, Restify, and Lambda. This server can be queried If your app is browser based and you are using cookies for login and session management with a backend, it's.
Apollo Server, Intended outcome: execute normally in node environment. import ApolloClient from 'apollo-boost'; import fetch from 'node-fetch'; const uri I somehow check if we're running it in the browser/node.js environment and only apollographql / apollo-client. Code Issues 397 Pull requests 70 Actions Projects 1 Security Insights. Join GitHub today. GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together. A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL
Build a GraphQL server with Node.js - Apollo Server, rocket: A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server - apollographql
- I tried all of the suggestions below, none of them works I would always get teh error
Invariant Violation: 1... (or that self is undefined when using whatwg-fetch)... Is there another solution?
- does it mean that we cannot use apollo-boost?
- This worked for me using react native and Jest! Thanks
- this is not working with React and Jest, do we have to make any other changes in jest config or so?
- THANK YOU ! I confirmed this also works with
@apollo/react-hooks3.1.0 and
apollo-boost0.4.4 inside
next.js 9.0.5. 👍
- This is exactly the solution that I come up with for Jest as well.
- Thanks, works with next 9.1.4 and apollo-boost 0.4.4, too!
- This works for me as well for the latest version (at this time) of Apollo boost | https://thetopsites.net/article/50688998.shtml | CC-MAIN-2021-31 | refinedweb | 1,198 | 57.37 |
.
> It's not a troll..
No, just lazy. Sorry, but or goodness sakes its a free program that comes in binaries for just about any distro (deb, many rpms, etc.) Just download the thing and try it out!
Erik
Yes, the import filters (in particular for Word 97 and 2000) have much improved.
Looking for help with the other formats though (Excel, Powerpoint, Word-95...). Contributions welcome !!!
Joe, if you were one of those who filed problem reports, you might now be sorted out since, when I checked a few days ago, I had closed all MS Word filter bug reports I have received (well, unless they happened to be Word 95 files). If not, then YMMV...
This is not a dig, and I certainly don't claim to be able to fix everything every time, my point is simply that I can only work with the material I have.
Koffice still crashed on me when i tried to open a word document. It seems to have gotten a lot better though. I came across this new Linux desktop site Cool place to discuss this stuff as well.
Craig
You wouldn't happen to be the same Craig that helps *run* gui-lords, would you? Just wondering.... ;-) (I have no inside knowledge, just put together the fact that Craig, with the aim username of blackfam972 could quite possibly be the same person as blackfarm@mountain.net.)
Well i have submitted a few stories but i have no connection with the site. I don't know anyone there or anything like that. But yes i guess.
I think Koffice really is on track to being a more than adequate suite. I like Kword alot - there are still a few crashes and missing features but this is just a matter of time.
Good luck to everyone involved !
Crashes ? In beta 3 ? I want to hear about them ! :)
I had a problem with the PI sign. First I couldn't preview before printing, and then when I save to .ps and then print it out, formula with PI was not on the paper.Also, parts of the table have not been printed. Without the formula everything works just fine. One more thing,I have to write many formulas in my documents so I have to turn off anti-aliasing before using KWord because it's impossible to see any formula on the screen.
Make sure to use Qt 2.3.1 if you are using anti-aliasing.A bug in the font metrics was found and fixed, and it was the reason for the wrong placement of the formula text, when anti-aliasing was enabled.
Well I know I should have reported this to the bug page , just haven't quite worked that out yet and assumed that someone had already done so. The main problems I have encountered have been
1 Tables , crashing the prrogram on insertion. I do remember tables working albeit primitively in Kword 1 - i think..
2 Abiword import/export didn't function (not exactly a crash)
These are the only things I have encountered so far.
Running SuSE 7.2, KDE 2.1.2 64MB RAM
Good luck with the rest of kword
Hello craig this is also craig. You sould send your crash repots to David Faure
Look guys, don't got bothering David with vague bug reports via email, use bugs.kde.org. It would be very helpful to the developers if your could send backtraces also. To enable this you need to have the GNU compiler collection installed (specifcally GDB, the debugger) and compile qt with -debug + configure kde --enable-debug. If you can't or won't do this either explain in plain clear english how to reproduce the bug or attach a document that causes the crash.
I've checked out all 3 betas of Kword 1.1. I am really impressed by the overall quality of the software, and amazed that people are actually writing and giving away such high-quality stuff. However, as a practical matter, Kword in its current incarnation is useless for me since the math typesetting is extremely buggy. Many characters and symbols don't show up at all, and when they show up, they displace the text around them so that the overall effect is ugly. Also many characters display on the screen, but don't print out. I am not sure whether these problems are due to user error or not. Anyway, I'm sure that the issues will be ironed out in future releases.
Magnus.
For serious mathematical typesetting nothing can realistically hold a candle to Latex. Fortunately, under linux we have LyX (): it's basically a very powerful interface to Latex (even though it actually goes beyond that). You retain access to 100% of Latex's power, but ~95% of the time you can do things from the gui. For me it's the perfect technical typesetting system, and it improves every day!
i have problems with gifs embedded in kword documents: they show nicely on the screen, but in the print (preview) they are invisible. someone has the same problem ?
i meant jpeg ... sorry (gif works fine)
I have kde 2.2 beta1 (cvs)
koffice cvs 03/07/2001
and can't reproduce the problem here.
can you try this kwd file ? it triggers the problem for me
it triggers another problem btw, calculated cells in an embedded kspread do not show up until you activated it once.
I try your document and can't reproduce the problem. File->Print preview is correct.
perhaps you have kdelib 2.1.2 ?
kdelibs 2.2 have a new library for printing.
and I think koffice use it.
>it triggers another problem btw, calculated
>cells in an embedded kspread do not show up
>until you activated it once.
Yes, already true.
You can submit a bug report.
thank.
--With the KIllustrator naming troubles it might be a good time to review all the Koffice suite names to avoid further problems. I think the naming tradition of just putting a K infront of an application type has out lived its coolness. Clever uses of the K like Kapital are still cool but Kword or Koffice should be reconsidered in my opinion. Maybe konqioffice or something like that. I'm not a developer so if I'm way off base let me know. I just think its a good time to review the naming skeem before the final release.
Craig Black
ICQ 103920729
Renaming KOffice (which shouldn't be necessary, along with KWord), should become KDE Office, IMO. So you have KDE, and you can add KDE Office. Thus, a software trademark on KDE should protect both to a limited extent, and we'll be creating a namespace that somebody else won't "stumble" into.
KOffice joins the ranks of MS Office, Corel Office, StarOffice, Open Office and many others.
KWord fits right in with WordPerfect, WordStar, MS Word, etc.
KWrite fits in with XYWrite and others.
And for one, I really like the names. I can't ever remember how to spell kvivo or Aethera, and they are neigh unpronouncable (in a reliable, singular way) to english speaking persons. (BTW - if you really want to get anal with names, make them all Japanese, skipping a few characters, and you'll have easy to pronounce names for most of the rest of the world).
--
Evan
KWrite is named Kate now, I believe, so that breaks that trend.
I agree that KWord is kind of a stinky name. Eventually, it would be a lot more consistent if we didn't put K in front of the names of apps in the K-menu, this makes it easier to find apps in sorted listings. However, I also believe that it's a good idea to leave the K in the exec names, if only so that people don't have to rewrite their DCOP scripts if/when we make this change.
KSpread and KPresenter imho have good names, simple and descriptive. They completely ignore the marketing bull and goes straight for a name that's relevant (Outlook? Powerpoint? Excel? Whatever) Krayon is good too, since it actually begins with K as opposed to just slapping it on, and it's relevant too (At least, as relevant as the name Paintbrush).
Any suggestions for renaming KWord? Not that I have any power in the matter myself, mind you. Here's a few ideas:
-KRichText (can't get more descriptive then that :-)
-KType
-KPress
-KPage
-Kompose
-KIndite
(Indite defined by WordNet as "produce a literary work")
-KText
How about
Kompose (Word Process)
Kalculate (Spreadsheet)
Kanvas (Illustrator)
Krayon (Paint)
Kommunicate (EMail or Instant Messaging)
Ah, neato names. I really sort of like the functional Kpresenter and kspread names myself, but Kanvas is a very nice name, especially considering that KIllustrator must be renamed for stupid legal reasons.
There is absolutely no need to rename anything but MAYBE KIllustrator (I'm not sure even about that one).
"Office", "Word", "Write" and such have been around for years.
That's not to say that renaming them "KDE *****" wouldn't be to advantage in other respects.
That would be cool as well. I just think the K in front of the application type has out lived its coolness. kdeword would be good.
The preview apparently wasn't written by a genuine beginner, but probably a well-seasoner KWord coder. Am I right?
All software hates me, so to really dumb-test a program, I need to run it just a few minutes. Let's see... KWord....
1. Damn, I have Finnish language setting, but I want to tell you descriptions in English. But... Hey, KControl doesn't list English! Ok, this is not a KWord problem.
2. Aww, about 40% of the screen icons are broken. Ok, I have a beta version, so this is probably expected.
3. I want to start writing a typical article, with a title, and below that my name and date. I select style..."Head 1." No, that's not good. "Contents Title", that must be it. Ok, it's centered, but has silly fancy lines. Ok, it'll do.
4. Name...that's easy to add, and there seems to be an automatic date field too! Good, although the number of automatic variables is rather limited. Where are the 200 function fields? I really like those.
5. I begin writing text. Ouh, the ctrl-arrow-keys don't behave as usual in word processors, nor can I select text with them (together with shift). Not nice at all.
6. Actually, selection seems broken. If I start selecting a new region, it leaves the old selection there. No, it's not a multiple selection feature, but looks like a bug.
7. Selecting something and erasing it by typing or with backspace doesn't seem to work.
8. Let's see if there are any application settings... No.
9. Ok, I'll try adding a KSpread sheet in the document. I draw the frame...what's happening? It doesn't come there. Blah, it's broken. Wait! There's something there, it's just invisible. Ok, nice, now I can add my table.
10. I'll try adding a text frame. Ok, it appears, although the frame is drawn badly. I can edit it, cool. But now I want to change the indentation, but hey, the frame doesn't have its own ruler. Oh, the document ruler seems to control it, but it's just rather misleading.
11. I add a table. Hmm. The screen flashes strangely. It doesn't seem to be possible to move between cells with keyboard. Ehh. Can I edit the borders of the table? ...no. Hmm, the table wants to be 100% wide, can I change that? No. Ok, tables unusable.
(At this point, the screen very often gets messed up, some portions printed in two locations on screen, some portions missing altogether.)
12. What the hell just happened? Most of the toolbars went suddenly empty! Ok, when I minimize and maximize them the icons come back. Phew!
13. I tried to add a picture. A jpeg, anything, but the file dialog didn't want to display any image files, just directories. Perhaps the filters were invalid. A translator's mess-up, perhaps?
Ok, maybe that's enough for now. The program didn't crash now, although it did with my previous try. I don't remember what I did then.
Nothing really complex anyhow.
To summarize, it looks like KWord has a lot of potential, and has many nice features, but is definitely not usable yet. Stop adding features, just clean up the problems, please.
An addendum:
It finally crashed when I had posted my review and hit the Quit button.
Hi,
Are you using the KOffice 1.1 Beta 3 version?
--kent
Umm...no. The version seems to be a few months old. Sorry!
Damn, I really should have checked the version first. Oh well.
Marko, do us all a favour and download the beta 3 and then retype your post with your finding. It'll be nice to see your account of how koffice has progressed in the last few months. I'm sure you'll be surprised :-)
Okay, let's see. I'll first check the version... KWord 1.1 (beta 3). Right. I hope this is correct now...
1. I start writing my standard test article, and want to add a title. No title style. Actually, the number of default styles is even less than before. Ok, I format the title manually. Succeeds.
2. I want to customize the keyboard a little at first, because I want to be able to change the paragraph style quickly from keyboard. I open the keyboard editor...I remove ctrl+alt+s from "Stylist" and give it to "Style" (I guess I can choose the current style with that, right?). No, doesn't work. The keyboard setting appears in the menu, but the menu won't open when I push the keys. This is probably KDE API problem, not KWord? Anyhow, it doesn't work. A pity, this is the key which I always define first in all word processors.
3. I try moving the cursor. Works nicely now.
4. I try selecting text. Works nicely, also when jumping words with ctrl pressed. Good. BUT, when I try to continue the selection over a paragraph break, it messes up. For example, type a line with 30 chars + enter + a second line with 30 chars. Then move to middle of first line, press shift and cursor down. Messes up. Still hold shift and now move back cursor up -> messes even more (also lines below these two).
5. Copying text with ctrl+insert seems to work, but pasting with shift+insert doesn't (although ctrl+v works). I hope this isn't a problem with my global KDE settings. Anyhow, the paragraph to which I paste flashes annoyingly and is sluggish. But, it works which is most important.
6. I create a table. Changing the width isn't very user-friendly, but seems to work. Moving between cells with keyboard is pain. Tab is usually standard key for moving forward, here it's the down-key. No way to move to the cell below?
7. I really would like to edit table borders.
8. There doesn't seem to be floating tables, where you could attach a description below. ...or a way to make auto-numbered tables or figures. You know, "Figure 6. This is..."
9. I create a floating text frame. Seems to work, although the table I wrote suddenly vanishes when I move the text frame above it.
10. I create an equation box. Umm... I can't move the cursor in without mouse. Not nice. I try to write something simple. How do I get multiplication dot? The symbol widget seems to list many LaTeX symbols, but how do I insert them to the equation? Just selecting one from the widget doesn't add it. Oh, I can type them, that's nice. Ahh, \cdot. Ok, excellent. I think this is VERY difficult to grasp for those who haven't used LaTeX...
11. I'll add a KSpread object... EEK! It got stuck! I think that the KSpread frame interacted somehow with the ordinary table I had done earlier, as they touched a little, and it went into a bizarre formatting loop. My machine slowed down, and I had to kill KWord. Restart KWord...
12. I want to try to replicate the problem so I first add a table. Wait, how do I move the cursor after the table now? Not with keyboard. Ok, I'll try mouse. Umm...no. I'll try fiddling with keyboard... Hey, the table disappeared! It's now invisible, although it flickers at times. Ok, I'll try to draw another table. Umm, now the first table came visible. I'll try to replicate the KSpread problem again...no, can't. Ok, it's very sluggish, and moves the ordinary table strangely, but seems to work. I fiddle with it a bit more... Hey, now it's getting stuck. CRASH!
...
#5 0x408a280b in QObject::inherits () from /usr/lib/qt-2.3.0/lib/libqt.so.2
#6 0x403e00dd in KMainWindow::toolBarIterator () at eval.c:41
#7 0x403df931 in KMainWindow::finalizeGUI () at eval.c:41
#8 0x404c4474 in KXMLGUIBuilder::finalizeGUI () at eval.c:41
#9 0x40469686 in KXMLGUIFactory::addClient () at eval.c:41
#10 0x40074706 in KoMainWindow::slotActivePartChanged () at eval.c:41
#11 0x400b4080 in KoMainWindow::KXMLGUIClient virtual table () at eval.c:41
...
13. Ok, I restard KWord and try to add image frame. As earlier, the file open dialog doesn't show any image files. I think the filter settings or their Finnish translations are messed up.
14. I try to add a ToC... Ok, the header comes there. But it's empty. Ah, I'll add a few Head 1 -styled lines. Update ToC...still empty. *scratches head* Umm... hey, I can't move the ToC elsewhere, very easily at least. Oh well.
15. Ok, I'll finally add a few footnotes...mmmm...no footnotes? Ok... Well, I guess you could do them with superscripts manually, but...
Maybe this is enough for now. I didn't go through all features, just the most obvious ones. Note that I *never* have used embedded Excel sheets in MS Word, as the ordinary tables are much nicer to use. Embedding isn't that useful, I think. I would like to see the KSpread tables not just floating, but inline, so that you can easily add a title, etc.
To summarize, the basic functionality was MUCH MUCH better now than in the previous version, and I agree that KWord can now be used for some limited production use for very simple documents. However, many important features are still buggish.
> chars. Then move to middle of first line,
> press shift and cursor down. Messes up. Still > hold shift and now move back cursor up ->
> messes even more (also lines below these two).
Please describe a bit more exactly what you mean by "messing up" and send a bug report.
> the paragraph to which I paste flashes
> annoyingly and is sluggish. But, it works
> which is most important.
Flashing when pasting ?
What CPU do you have ?
I think this is fixed in the meantime :-)
> 8. There doesn't seem to be floating tables,
> where you could attach a description below.
> ...or a way to make auto-numbered tables or
> figures. You know, "Figure 6. This is..."
Yeah. Me too.
Keep on testing koffice and send bug reports :-)
Bye
Alex
In your first comment, you complain about a lot of serious general issues. That is, they would have been serious if they had been true.
Since they weren't, you find some not-so-general issues that might (or might not) be true. Then you concede that the program might be used for "very simple documents". You turn 145 degrees while trying to make it look like it was the world that turned around you :-)
I'll agree though, that some operations are rather sluggish. I'm sure they will work better in the next release. There are, as well, a number of minor otherirritants.
On the whole, I'm very impressed - I'm sure that you would have been too, if you hadn't started out with a completely faulty perspective :-)
Yeh, I'm really sorry for using the wrong version at first.
I don't think that the issues I encountered were not-so-general. I was just trying to write a short technical article, with pictures and tables with a title below. Perhaps a few equations, footnotes, and references. Pretty trivial.
But anyhow, I'm rather critical about software, because I have to struggle with it so often. World is full of badly working software, and some good features can't always compensate for some annoying problems. Softwares should also be easy to use, and not require half an hour to learn. The real computer-dumb people trying the softwares won't complain, they just get annoyed and give up using Linux.
Anyhow, I think KWord is very promising program, and may be, together with KSpread and other KOffice programs, very important for the success of the entire Linux/GNU movement.
I'd estimate that KWord is about 60% complete. MS Word is perhaps 95%, and usually more stabile and easier to use than KWord, at the moment. StarOffice is perhaps 90-95% complete, although it has a few nice features which MS Word doesn't have, and vise versa.
I usually use KLyX, which is about 90-95% feature-complete (if you count the LaTeX inlines in), for my purposes (usually writing scientific articles), but it may be hellishly difficult to use if you're not familiar with LaTeX. I like the "Document Style" thinking in KLyX. KWord doesn't yet have many predefined templates such as "Letter" or "Book", which would have appropriate paragraph style sets.
Of course, whether the issues are trivial or not depends on what kind of work you do. I'm just a common writer (journalist) who doesn't do much technical stuff other than for fun.
On the whole, I agree wholeheartedly with your point on software in general. There is a lot left to do on KWord in that regard. On the other hand, that's part of my point, really - if you had started out with the right version, your comment would have been very different, since the software has evolved enormously from 1.0 via 1.1b2 to b3.
(I gave up completely on 1.0 (it crashed when I looked at it) but 1.1b3 is rock steady and does more or less anything I need - that's why I'm very confident that KWord very soon will be useful even for the computer-dumb :-) )
Regarding your over-all assment of the completeness of the programs, I think you're about right - I think, though, that when KWord reaches 95%, this might turn out to be quite a bit more than 95% of MS Word.
Koffice is great but I noticed 1 *major* thing that it needs. I saw that it has PowerPoint and Excel imports but I dont see any MS Word '97 imports in KWord. You definately need that before a final release.
>I dont see any MS Word '97 imports in KWord.
Something's wrong then, because KWord most certainly imports MS Word documents (97 or 2000, don't know about XP). It's one of the most requested features.
I think you need kde 2.2 library.
Here I can import MsWord document
(kde2.2beta1 and koffice 1.1beta3)
If you're using kdelibs-2.1.x, just select the doc file after typing '*' in the filter combo, or add '*.doc' to the file type for application/msword in the file-type editor (kcontrol).
This should be mentionned on the website....
Hi,
I'm having some ideas about how to solve present and future problems regarding trademarks.
1) How to pay Adobe: put a huge box in Linuxtag, near the KDE booth, to collect money. I'm sure every KDE friend will donate at least $1 !
2) KOffice is becoming a serious office suite, if we want to compete with commercial office suites we need to register KDE program names.
We should register at least:
KDE, Konqueror, KOffice and all KOffice programs.
Registration fees are quite expensive, but the KDE League could help (if it doesn't help KDE this time, what is good for?)
How does one actually comment a document? All other actions were well documented, this one wasn't.....
If you look, it wasn't actually comments on a document, but just new frames added with the comments.
Yeah, I thought that was a pretty sneaky trick..
I think it would be a lot better if we could see some real groupware functionality... ie seperate out the backend and frontend, and allow some kind of interactive editing over the network.
Maybe via that DCOP-SOAP bridge. Hm, CORBA sorta looks like it might have been the best choice after all.
What I would like to see would be the ability to add comments, and also to "lock" an area of the document, then edit it, and this would all show up on everyones displays.
I think this would need a pretty big overhaul for KParts, and DCOP would have to be marshalled over something other than X. Every program that could be embedded would also need the same split.
Anyway, its a nice dream...
The backend and the frontend are already separated, that's the whole reason for the Document/View design.
Having some sort of DCOP interface between the two, to allow remote editing.... is for KOffice 3.0 ;-)
Let's get something working well in the normal case first, the design is there for such things later.
People seem to be fairly impressed with KWord. I hope that as much effort has been put in KSpread. It's not a serious office suite without a serious spreadsheet. | https://dot.kde.org/2001/07/03/kword-11beta3-review?page=1 | CC-MAIN-2019-04 | refinedweb | 4,374 | 75.81 |
- : Creating map from list of pairs
Mon, 2009-01-12, 18:50
>>>>> "Dave" == Dave Ray writes:
Dave> Secondly, is there a nicer way to turn an Option into a Set than
Dave> this:
Well, there's:
def toSet[T](o : Option[T]) : Set[T] = Set(o.toList:_*)
which is shorter, but less "nice" in one sense, since it involves
creating a list along the way. This is how I would write it inline, but
in a library of utility methods, I would write it your way -- or maybe
measure to see what's fastest.
Seth Tisue schrieb:
> Well, there's:
>
> def toSet[T](o : Option[T]) : Set[T] = Set(o.toList:_*)
Or if you want to give the "use descriptive names" faction a fit:
def toSet[T](o : Option[T]) = (Set[T]() /: o)(_ + _)
- Florian | http://www.scala-lang.org/old/node/550 | CC-MAIN-2015-06 | refinedweb | 138 | 73.92 |
29 October 2010 10:08 [Source: ICIS news]
DUSSELDORF (ICIS)--Korean polymer additive major Songwon Industrial has made two strategic moves to strengthen its positions in China and India, the company said on Friday.
Jongho Park, chairman of the board, said his firm had “finalised a 30% stake with the option to increase to 50%” in Tangshan Baiful Chemical of Tianjin, China.
Tangshan makes secondary thioester antioxidants. The deal was signed at a press conference at the K 2010 – the international trade fair for the plastics and rubber industry in ?xml:namespace>
The company said the new joint venture, called Songwon Baifu, would become operational in the first quarter of 2011, subject to legal approvals.
Songwon Baifu will sell thioesters directly to the Chinese market and use Songwon’s global network for sales outside the country. It will have a capacity of 6,000 tonnes/year.
Away from the show, Songwon and HPL India also signed a letter of intent to form a joint venture - Songwon HPL Additives.
HPL will transfer all of its business and assets related to polymer stabilisers to a new company that will be owned 40% by HPL and 60% by Songwon, the company said.
This was expected to be operational by the first quarter of 2011.
Speaking on the sidelines of the meeting, Park said the new ventures would help Songwon meet the growing needs for antioxidants and ultraviolet protection in the rapidly expanding polymer markets of the Middle East and China.
He said Songwon had paid around $20m (€14.4m) in total on the two deals.
( | http://www.icis.com/Articles/2010/10/29/9405676/south-koreas-songwon-industrial-reveals-china-india-investments.html | CC-MAIN-2014-42 | refinedweb | 262 | 60.04 |
Edit topic image
Recommended image size is 715x450px or greater
We have a cisco 831 set up at a branch office. It connects to the internet via a cable modem. It connects back to the main office via a site to site vpn. Everything was working fine and then this morning we came in and the branch office could not connect to anything. From my local system I can ping the external ip address and the internal ip address of the router so our vpn connection is working. From the branch office router I can ping google, I can ping our local office but I can not ping any internal ip addresses. When I run a show ip nat trans command I see nat translations so that appears to be working. This router is set up to distribute DHCP addresses and the computers local to that router are getting DHCP addresses. Those computers can not ping anything, including the local router/default gateway.
Below is an output from show run
version 12.4
no service pad
service timestamps debug datetime msec
service timestamps log datetime msec
service password-encryption
!
hostname [sanitized]
!
boot-start-marker
boot system flash:c831-k9o3sy6-mz.124-25c.bin
boot-end-marker
!
logging buffered 51200 warnings
enable [sanitized]
!
aaa new-model
!
!
!
aaa session-id common
!
!
no ip dhcp use vrf connected
ip dhcp excluded-address 172.24.117.1 172.24.117.199
ip dhcp excluded-address 172.24.117.241 172.24.117.254
!
ip dhcp pool Carroltonpool
import all
network 172.24.117.0 255.255.255.0
default-router 172.24.117.254
dns-server 172.24.112.18 172.24.112.26 4.2.2.2
lease 0 2
!
!
ip cef
no ip domain lookup
ip auth-proxy max-nodata-conns 3
ip admission max-nodata-conns 3
!
!
!
no crypto engine onboard 0
username [sanitized]
!
!
!
class-map match-all mark
match access-group 100
class-map match-all priority-traffic
match ip dscp cs1
!
!
policy-map queueing
class priority-traffic
bandwidth 200
policy-map mark-priority
class mark
set ip dscp cs1
policy-map shaping
class class-default
shape average 512000
service-policy queueing
!
!
!
crypto isakmp policy 120
encr 3des
hash md5
authentication pre-share
group 2
lifetime 28800
crypto isakmp key [sanitized] address [sanitized]
!
!
crypto ipsec transform-set vpnset esp-3des esp-md5-hmac
!
crypto dynamic-map dynmap 10
set transform-set vpnset
!
!
crypto map pariser 2 ipsec-isakmp
set peer [sanitized]
set transform-set vpnset
match address 190
!
!
!
interface Ethernet0
description $ETH-LAN$$ETH-SW-LAUNCH$$INTF-INFO-Ethernet 10/100$
ip address [sanitized]
ip nat inside
ip virtual-reassembly
ip route-cache flow
load-interval 30
no cdp enable
hold-queue 32 in
!
interface Ethernet1
ip address [sanitized]
ip nat outside
ip virtual-reassembly
load-interval 30
duplex auto
no cdp enable
crypto map pariser
service-policy output shaping
!
interface Ethernet2
no ip address
!
interface FastEthernet1
duplex auto
speed auto
!
interface FastEthernet2
duplex auto
speed auto
!
interface FastEthernet3
duplex auto
speed auto
!
interface FastEthernet4
duplex auto
speed auto
!
ip default-gateway [sanitized]
ip forward-protocol nd
ip route 0.0.0.0 0.0.0.0 [sanitized]
ip route 0.0.0.0 0.0.0.0 [sanitized]
!
ip http server
ip http authentication local
no ip http secure-server
ip http timeout-policy idle 5 life 86400 requests 10000
!
ip nat inside source route-map nonat interface Ethernet1 overload
!
access-list 101 permit esp any any
access-list 101 permit gre any any
access-list 101 permit ip any any
access-list 101 permit tcp any any
access-list 101 permit icmp any any
access-list 102 deny ip 172.24.117.0 0.0.0.255 172.24.112.0 0.0.0.255
access-list 102 deny ip 172.24.117.0 0.0.0.255 172.24.114.0 0.0.0.255
access-list 102 permit ip 172.24.117.0 0.0.0.255 any
access-list 112 permit ip 172.24.117.0 0.0.0.255 172.24.112.0 0.0.0.255
access-list 112 permit ip 172.24.117.0 0.0.0.255 172.24.114.0 0.0.0.255
access-list 190 permit ip 172.24.117.0 0.0.0.255 172.24.112.0 0.0.0.255
access-list 199 permit ip 172.24.117.0 0.0.0.255 172.24.112.0 0.0.7.255
!
route-map nonat permit 10
match ip address 102
!
!
!
control-plane
!
!
line con 0
no modem enable
line aux 0
line vty 0 4
exec-timeout 120 0
privilege level 15
transport input all
transport output all
!
scheduler max-task-time 5000
12 Replies
Aug 7, 2013 at 7:25 UTC
If you can ping the inside IP of the branch router from the main office, but not any other internal IP addresses, the rest of your branch office network may be disconnected from the router. I assume you connect the branch router to a switch. Could that connection have been unplugged?
In other words, is Eth1 up/up? Can you put the output from "show int bri" or "show int"?
Aug 7, 2013 at 7:28 UTC
Yes it does connect to a switch and we've checked those connections.
Interface IP-Address OK? Method Status Protocol
FastEthernet1 unassigned YES unset down down
FastEthernet2 unassigned YES unset down down
FastEthernet3 unassigned YES unset up up
FastEthernet4 unassigned YES unset down down
Ethernet0 172.24.117.254 YES NVRAM up up
Ethernet1 [sanitized] YES NVRAM up up
Ethernet2 unassigned YES NVRAM down down
NVI0 unassigned NO unset up up
Aug 7, 2013 at 7:31 UTC
If it was a switch issue, i would think none of the computers connected would recieve a dhcp address.
Aug 7, 2013 at 7:35 UTC
Have you tried renewing one of the leases?
Aug 7, 2013 at 7:36 UTC
I don't see any configuration for FastEthernet3 in the posted config. Why is the interface up?
Does the 'show arp' command show that your router has learned MAC addresses on the inside interface?
I'm unsure of the exact syntax, but I think the command is 'show arp', and I think it should be available in the 831 router.
Try finding the MAC of the inside IP, and make sure that the clients show that MAC in their ARP table. It could possibly be a duplicate IP issue.
I would also try power cycling the switch just to be sure.
If you do a continuous ping from a workstation to the inside address (gateway) is it consistently unreachable? or intermittent? Can devices on the branch LAN ping each other?
Aug 7, 2013 at 7:36 UTC
i've tried renewing one of the leases and changing one of the static ip addresses to dhcp and they both were successful in getting an ip address
Aug 7, 2013 at 7:50 UTC
The show arp command only shows mac addresses for the inside interface, the cable modem and the isp default gateway and no internal ip addresses.
As to why FastEthernet3 shows as up, on the back of the router where it connects to the internal network it is called Ethernet0 and there are ports 1-4, and we have the switch plugged in to the 3rd port on the router under Ethernet0
Aug 7, 2013 at 7:52 UTC
When I try to manualy set an ip address on FastEthernet3 I get an error stating IP Addresses may not be configured on L2 links
Aug 7, 2013 at 7:54 UTC
I understand. I wasn't familiar with the 831. I looked at some pictures and I see what you mean.
If the router isn't learning any MAC addresses of inside hosts, especially after you try and ping the gateway (inside interface) there's a problem between your switch and the router.
Can the devices communicate with each other on the switch? Can you try moving a client to one of the other ethernet ports on the 831? All of those ports should work. You may also try moving the switch from port 3 to another of those four.
Aug 7, 2013 at 7:56 UTC
The four interfaces (1-4) are just like switchports that all connect to E0 (inside interface)
Try connecting a device to one of those other E0 ports on the 831, which will take the switch out of the mix completely and see if it can ping the gateway.
Aug 7, 2013 at 8:23 UTC
Ok, so it was an issue with the switch. It's an unmanaged switch and someone created a loop back causing us to have issues. Thanks for all your help.
Aug 7, 2013 at 8:25 UTC
Glad you got it figured out! Loops can cause some seriously funky issues. | http://community.spiceworks.com/topic/367594-no-internet-access-cisco-router | CC-MAIN-2015-48 | refinedweb | 1,486 | 64.41 |
Hi all, My button won't redirect to the location in my account section.
I have been trying for the past 24 hours and I just can't find a way. I am not sure if the button is functioning at all. If you want to take a look its
upon login go to profile and the button will be there, "createProfileButton"
please help its driving me crazy.
thank you, code is posted below. one for profile page and other for sign in page.
this is the code i have for the my profile page (I followed a video)
import wixData from 'wix-data'; $w.onReady(function () { $w("#updateProfile").onReady( () => { let isEmpty = $w("#updateProfile").getCurrentItem(); let theName = $w("#firstName").value; if ( isEmpty === null ) { $w("#createProfileButton").show(); $w("#updateProfileButton").hide(); $w("#profileArea").collapse(); $w("#welcomeUser").text = `Welcome New User. Please create a profile!`; } else { $w("#updateProfileButton").show(); $w("#welcomeUser").text = `Welcome ${theName}`; $w("#profileArea").expand(); } } ); $w("#updateProfile").onAfterSave( () => { let theName = $w("#firstName").value; $w("#welcomeUser").text = "Update Completed!"; const millisecondsToDelay = 2500; setTimeout(() => { $w("#welcomeUser").text = `Welcome ${theName}`; }, millisecondsToDelay); }); });
this is the code for the sign up page..
import wixUsers from 'wix-users'; import wixData from 'wix-data'; import wixLocation from 'wix-location'; $w.onReady(function () { let user = wixUsers.currentUser; let userId = user.id; // "r5cme-6fem-485j-djre-4844c49" let isLoggedIn = user.loggedIn; // true user.getEmail() .then( (email) => { let userEmail = email; $w("#emailText").value = userEmail; let referralCode = userId.split("-")[4]; } ); $w("#createProfileButton").onClick( () => { let toInsert = { "firstName": $w("#firstName").value, "lastName": $w("#lastName").value, "emailAddress": $w("#emailText").value, }; wixData.insert("Members", toInsert) .then( () => { wixLocation.to("/account/my-profile"); } ) .catch( (err) => { let errorMsg = err; $w("#error").show(); } ); }); });
Hey Craig,
The Create Profile button isn't connected to anything - so it seems that this button in fact is not functioning. You probably should connect it to "Submit":
I hope this helps,
Yisrael
Hi Yisrael and thanks for the reply, when I add the submit my button blanks out on the live site. The create profile button is supposed to redirect me to the update profile page, there is then a button there which is connected to the submit function.
This button is not connected to Submit, and it has no action associated with it. So, clicking on this button does just what it was told to do - nothing.
haha I hear you but I took submit off as on the live site it greys the button out. I added submit back if you want to see and see if you can make sense of it?
the action is specified in the code? $w("#createProfileButton").onClick( () => { let toInsert = { "firstName": $w("#firstName").value,
I don't see that code on the page. You'll need to provide some sort of action to that button. You can take a look at the article How to Create Custom Member Profile Pages with Wix Code for ideas on how to do this.
I did create the function which is $w.onReady(function () {
So it is connected that way but it just does not work so i am missing something some where | https://www.wix.com/corvid/forum/community-discussion/button-not-working-with-wixlocation-to | CC-MAIN-2019-47 | refinedweb | 511 | 69.38 |
Hey all I'm new C++ and am having a little trouble with a simple program. The program calculates the square root of a number the user inputs. When I input -1 or any negative it comes up as 1.#ind. Ideally when the user types -1 i want -1 to come up as the answer. I know this is not right but it is whats required. Thanks.
#include <iostream> #include <cmath> using namespace std; double weirdSquareRoot(double input) { return sqrt(input); } int main() { double x, someNumber; cout << "Enter a number (a double): "; cin >> x; someNumber = weirdSquareRoot(x); cout << "The square root is " << someNumber << endl; | https://www.daniweb.com/programming/software-development/threads/272303/divison-by-zero-error | CC-MAIN-2017-34 | refinedweb | 105 | 71.44 |
0
Hello, i have to create a program for-
If the age is less than 18-You are still a kid
18-30 adult
30-60 middle age
greater than 60-senior citizen
else for any other impossible age (-ve or 0 age) ' wow '
Here is my attempt,
#include <stdio.h> #include <conio.h> void main() { clrscr(); int n; printf("Please enter your age "); scanf("%d" , &n); if (0<n<18) printf("You are still a kid"); else if (18<=n<30) {printf("You are an adult"); else if (30<=n<60) {printf("You are a middle-aged person"); else if (60<=n) {printf("You are a senior citizen"); else {printf("Wow !!!"); } } } } getch(); }
My compiler says 'Misplaced else'
Please help me find my mistake.
Thank you. | https://www.daniweb.com/programming/software-development/threads/286417/multiple-conditional-statements | CC-MAIN-2018-30 | refinedweb | 126 | 61.7 |
I am having trouble center aligning text on a card for a Zebra ZXP Series 3 using the Card Printing SDK.
I found in one of your examples codes how to center a barcode for the Card. But how can I center text for a card?
For example, for a barcode its:
// Barcode Drawing---------------------------------------------------
int rotation = 0; // origin lower left and no rotation
int barcodeType = 0; // Code 39
int barcodeWidthRatio = 2; // narrow bar = 2 dots, wide bar = 5 dots
int barcodeMultiplier = 2; // {2..9}
int barcodeHeight = 75; // 75 dots
int textUnder = 1; // true
string barcodeData = "123456789";
//To calculate the full length of a Code 39 bar code:
//L = [(C+2) (3R + 7) - 1] X Where
//L = Length of bar code
//C = Number of characters
//R = Ratio of wide-to-narrow bars
//X = Number of dots times 0.0033 inches per dot (0.08847 mm per dot); for the 5:2 ratio, X = Dots times 2
//See ZXP3 SDK Manual for the forumulas used to calcuate the length of other barcode types.
// Calculate the length of the barcode
int C = barcodeData.Length;
double R = 5.0 / 2.0;
int X = 2;
int length = (int)((C + 2) * (3 * R + 7) - 1) * X;
int startX = (int)Math.Floor((CARD_WIDTH - length) / 2.0); //Center barcode horizontally
int startY = (int)Math.Floor(((CARD_HEIGHT - barcodeHeight) / 2.0) + barcodeHeight); //Center barcode vertically
// Sends Barcode data to the Monochrome Buffer
if (DrawBarcode(startX, startY, rotation, barcodeType, barcodeWidthRatio, barcodeMultiplier, barcodeHeight, textUnder, _asciiEncoder.GetBytes(barcodeData), out errValue) == 0)
{
msg = "Printing DrawBarcode Error: " + errValue.ToString();
return;
}
But how and where can i find the formula for centering a label / text on a card??? It says it's in the manual but it isn't can someone please provide this formula?
As of right now, I am having to manually pad the text left and right in C# to try and get it to appear “centered” on the card. I have different font sizes on the card so It’s really hard when I don’t know the formula on how to center the text on the card. If I could just get the formula, the generic formula to center any text on the card – that would fix my issue! I am only printing on the front side of the card and it is just text.
Right now I am using this to pad my text with spaces left and right. It's sketchy and it appears to look centered in some cases but there may be cases where it isn't. I of course can't sit here and test the 3 billion different name combinations I may be putting on the card.
public string SetTextAlignmentToCenter(string textToCenterAlign, int lengthOfLine)
{
// # of Characters you can put per line on the Badge. Badge is Landscape Orientation
string centeredText = textToCenterAlign.PadLeft(((lengthOfLine - textToCenterAlign.Length) / 2) + textToCenterAlign.Length).PadRight(lengthOfLine);
return centeredText;
}
Points: 1
You voted ‘up’
I stopped using the graphics methods used in the sdk for this reason. I extracted the .net graphics object that the zebra graphics sdk uses to print to a card. I use the following routine to get access to it.
internal static System.Drawing.Graphics GetGraphicsObject(ref ZMTGraphics.ZMotifGraphics g)
{
System.Reflection.FieldInfo dynField = g.GetType().GetField("helper", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
object gg = dynField.GetValue(null);
return (System.Drawing.Graphics)gg.GetType().GetField("graphics").GetValue(gg);
}
The reason I came up with this methods was because I needed to measure a string to be able to shrink to fit and the sdk doesn't provide a public method to do it.
If I were printing on the landscape on a black panel then I'd do
int datalen;
byte[] bmpFrontMonoKPanels;
ZMTGraphics.ZMotifGraphics g = new ZMTGraphics.ZMotifGraphics();
System.Drawing.Drawing2D.GraphicsState gfxstate;
g.ClearGraphics();
g.InitGraphics(0, 0, ZMTGraphics.ZMotifGraphics.ImageOrientationEnum.Landscape, ZMTGraphics.ZMotifGraphics.RibbonTypeEnum.MonoK);
gfx = GetGraphicsObject(ref g);
gfxstate = gfx.Save();
<use the .net system.drawing.graphics gfx object to do my printing>
gfx.Restore(gfxstate);
bmpFrontMonoKPanels = g.CreateBitmap(out dataLen);
g.ClearGraphics();
You just need to use the standard methods for drawing objects i.e. exactly the same as when printing to the old printer object. So finally to draw centred text, create a rectangle that's as big as the region you want the text to appear in, then use the gfx.drawstring overload that has the system.drawing.stringformat and use that to centre the text. No need to pad the string or calculate anything, unless it's too big to fit.
Points: 1
You voted ‘up’
Unfortunately I do not have the ZMTGraphics. I am using the ZXP 3 not the ZXP 7
I only have:
ZBRGraphics.cs
ZBRPrinter.cs
There still has to be a formula to calculate how to horizontally center the text on a card. They have a formula to calculate centering a bar code above in my OP - so I just need them to provide me the one for the text
Points: 0
You voted ‘up’
Yep, sorry though you'd switched to the driverless sdk not the older one as the driverless zxp3 uses the same graphics library as the 7.
Have a look at the ZBRGDIDrawTextRectEx function, as it provides an alignment parameter. Similar to what I said for the 7, create a rectangle that covers the area you want the text to appear and then pass it's position, size and text alignment along with the text and font. Notes on the routine at on page 148 of the sdk manual.
Points: 1
You voted ‘up’
After hours of fighting with the text alignment I finally got a response from Zebra. You have to use the DrawTextEx() method and pass it in the alignment parameter
[DllImport("ZBRGraphics.dll", EntryPoint = "ZBRGDIDrawTextEx", CharSet = CharSet.Auto,
SetLastError = true)]
static extern int ZBRGDIDrawTextEx(int x, int y, int angle, int alignment, byte[] text, byte[] font, int fontSize, int fontStyle, int color, out int err);
public int DrawTextEx(int x, int y, int angle, int alignment, byte[] text, byte[] font, int fontSize, int fontStyle, int color, out int err)
{
return ZBRGDIDrawTextEx(x, y, angle, alignment, text, font, fontSize, fontStyle, color, out err);
}
How to use it (from the "SDK Manual"):
int x = 0;
int y = 0;
int angle = 0; //0 degrees rotation (no rotation)
int alignment = 4; //center justified
string TextToPrint = "Printed Text";
byte[] text = null;
string FontToUse = "Arial";
byte[] font = null;
int fontSise = 12;
int fontStyle = 1; //bold
int color = 0x0FF0000; //black
int err = 0;
int result = 0;
//use the function:
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
text = ascii.GetBytes(TextToPrint);
font = ascii.GetBytes(FontToUse);
result = ZBRGDIDrawTextEx(x, y, angle, alignment, text, font, fontSize,fontStyle, color, out err);
Points: 1
You voted ‘up’
This is a total hack, and I am not sure it is accurate, but printing is basically centered on a vertical card using this calculation:
printVal is the text to print. The Y coordinate is fixed. X is variable.
// center name
// 2.11667 is mm/letter for Ariel 6 pt.
// 12 is dots per mm
// 2 splits it in half for the offset
//15.66 is estimated dots per letter at Ariel 8 pt
if (param == "name")
{
int m_length = (int)Math.Round((((printVal.Length) * 15.66) / 2), MidpointRounding.AwayFromZero);
int m_xcor = paramVal.XCor - m_length;
//Draw a Text
//retValue = graphics.DrawText(m_xcor, paramVal.YCor, ASCIIEncoding.ASCII.GetBytes(printVal),
// ASCIIEncoding.ASCII.GetBytes(paramVal.Font), paramVal.FontSize, lookup[paramVal.FontStyle].Single(),
// Convert.ToInt32(paramVal.FontColor, 16), out errValue);
retValue = graphics.DrawText(m_xcor, paramVal.YCor, ASCIIEncoding.Default.GetBytes(printVal),
ASCIIEncoding.ASCII.GetBytes(paramVal.Font), paramVal.FontSize, lookup[paramVal.FontStyle].Single(),
Convert.ToInt32(paramVal.FontColor, 16), out errValue);
}
Points: 0
You voted ‘up’ | https://developer.zebra.com/comment/42635 | CC-MAIN-2021-21 | refinedweb | 1,278 | 57.06 |
flexible explicit. Class types, collection types, fixed-length collections and type predicates can be annotated as well. Here is a more complex example:
import typecheck as tc @tc.typecheck def foo2(record:(int,int,bool), rgb:tc.re("^[rgb]$")) -> tc.any(int,float) :.
Other kinds of annotations:
- tc.optional(int) will allow int and None,
- tc.enum(1, 2.0, "three") allows to define ad-hoc enumeration types,
- tc.map_of(str, tc.list_of(Person)) describes dictionaries where all keys are strings and all values are homogeneous lists of Persons,
- and so on.
Find the documentation at
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/typecheck-decorator-stable/ | CC-MAIN-2017-39 | refinedweb | 117 | 60.92 |
amarok
#include <IpodWriteDatabaseJob.h>
Detailed Description
A job designed to call IpodCollection::writeDatabase() in a thread so that main thread is not blocked with it.
It is guaranteed by IpodCollection that is doesn't destroy itself while this job is alive. Memory management of this job is up to the caller of it.
Definition at line 30 of file IpodWriteDatabaseJob.h.
Constructor & Destructor Documentation
Definition at line 21 of file IpodWriteDatabaseJob.cpp.
Member Function Documentation
Definition at line 37 of file IpodWriteDatabaseJob.cpp.
Definition at line 44 of file IpodWriteDatabaseJob.cpp.
This signal is emitted when the job has been finished (no matter if it succeeded or not).
This job has failed.
This signal is emitted when success() returns false after the job is executed.
Definition at line 29 of file IpodWriteDatabaseJob.cpp.
This signal is emitted when this job is being processed by a thread.
The documentation for this class was generated from the following files:
Documentation copyright © 1996-2020 The KDE developers.
Generated on Sun Feb 16 2020 06:07:45 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online. | https://api.kde.org/extragear-api/multimedia-apidocs/amarok/html/classIpodWriteDatabaseJob.html | CC-MAIN-2020-10 | refinedweb | 192 | 60.21 |
Event numbers of screen output and run_01_tag_1_banner.txt are different
Dear MG5 team,
I want generate p p > w+ w- h at the LHC in the llljj final state in the SM at the parton-level. Here is how I generate events:
import model sm
generate p p > w+ w- h, w+ > j j, w- > l- vl~, h > l+ vl l- vl~ / z
add process p p > w+ w- h, w+ > l+ vl, w- > j j, h > l+ vl l- vl~ / z
add process p p > w+ w- h, w+ > l+ vl, w- > l- vl~, h > j j l- vl~
add process p p > w+ w- h, w+ > l+ vl, w- > l- vl~, h > l+ vl j j
When I set nevents 100 or 1000, event numbers of screen output and run_01_
Did I miss something? Thanks a lot in advance.
Best,
Gang Li
Question information
- Language:
- English Edit question
- Status:
- Solved
- Assignee:
- No assignee Edit question
- Solved:
- 2017-10-25
- Last query:
- 2017-10-25
- Last reply:
- 2017-10-24
Hi Olivier,
Thanks a lot for your information.
However, when I analyze the lhe file with ExRootAnalysis (here I am doing parton-level analysis). Using Root command treeReader-
So it seems that there are actually 1566 events generated, not 10000 that I required.
Do you have any hint? Thanks.
Best,
Gang Li
Hi,
Yes that's correct if the two number differ, the actual number of event generated is the one written in the html page (or inside the lhe file).
The why is difficult to know like that, you can look at the html diagnostic page (by cliking on the cross-section) there you will see
all the channel of integration and the associated luminosity, then we have found the channel with the smallest luminosity, you can take a look at the associate log.
You will typically see that the code has trouble to converge correctly, this can be due to the presence of some cuts deforming the typical method of integrations.
Cheers,
Olivier
Note that for decay-chain, you have various options that you can try and that can have more efficient results
Hi Olivier,
That solved my problem.
Thanks a lot.
Best,
Gang Li
Hi,
The run_XXX is your input (i.e what you request). In some case, what is asked by the user is too complicated to reach the number of events. In that case, indeed the two number would be different.
Cheers,
Olivier | https://answers.launchpad.net/mg5amcnlo/+question/659783 | CC-MAIN-2017-51 | refinedweb | 409 | 64.75 |
57
The problem with this submission is that if the Python module built by SWIG
is imported into the parent package in its __init__.py file, an error is
generated such as:
Traceback (most recent call last):
...
File "../packages/foo/bar/\swig_generated.py", line xx, in <module>
class Awesome(foo.bar.swig_generated.Wow):
AttributeError: 'module' object has no attribute 'bar'
Python is complaining that module foo.bar doesn't exist, and in fact it
doesn't yet exist because it is in the process of being initialized.
SWIG used to generate:
import base_swig_generated.Wow
class Awesome(swig_generated.Wow):
but now generates
import foo.bar.base_swig_generated.Wow
class Awesome(foo.bar.swig_generated.Wow):
This is an important issue for us because we want our consumers to import
foo.bar, and not 'import foo.bar.swig_generated'--keeping the details of
what parts are generated by SWIG hidden.
Hello William
thanks for the reply,
On Fri, Feb 01, 2013 at 06:27:56AM +0000, William S Fulton wrote:
>.
no, the swig with -E drops the correct typedef (IMHO):
/usr/bin/swig -E -python -I../include -I../src -I../lib \
-I../bindings -o hamlibpy_wrap.c `test -f hamlib.swg || echo \
'./'`hamlib.swg | grep typedef | grep const
typedef int (*chan_cb_t) (RIG *, channel_t**, int, const chan_t*, void*);
typedef int (*confval_cb_t) (RIG *, const struct confparams *, value_t *, void*);
typedef int (*vprintf_cb_t) (enum rig_debug_level_e, void*, const char *, va_list);
typedef int (*rig_probe_func_t)(const hamlib_port_t *, rig_model_t, void*);
typedef const char * const_char_string;
typedef channel_t * const_channel_t_p;
(full output above after grep filters).
And as you can see the full swig command, the swig uses the
hamlib.swg, which contains the typedef:
67 /* needed because rig.swg and rotator.swg macros require identifiers like arg (no spaces) */
68 %header %{
69 typedef char * char_string;
70 typedef const char * const_char_string;
71 typedef channel_t * channel_t_p;
72 typedef channel_t * const_channel_t_p;
73 %}
74
75 /*
76 * The Rig "class"
77 */
78 %include "rig.swg"
(in line 70)
> *);
Sorry, I don't know exactly what I'm doing :), I just put this
function to rig.swg, which included in hamlib.swg. After I run
the swig command above, this function are placed in hamlib_wrap.c
source - is it good, or it isn't enough?
Many thanks for the help,
a.
--
I � UTF-8
Hello,
is it possible, to have SWIG create a java wrapper for the following class D that extends the base class B (instead of A, which is the first base)?
// Derived.h:
class D: public A,B,C{
//...
};
Is there any SWIG statement that says "use B as base class" rather than modifying the header file itself? This is needed as part of a bigger wrapper, and I would like to include the original header files without modifications.
Now another question in the same context of multiple inheritance:
Currently I am adding the required methods from C to D like this:
%extend D{
void Cfun1(){$self->Cfun1();}
void Cfun2(){$self->Cfun2();}
//...
C* baseC(){return $self;}
}
Cfun1() and Cfun2() are methods which are defined for class C. Is there any possibility to have SWIG automatically include all methods from those base classes which are not used as base class in java?
I found that multiple inheritance in java can be simulated to some extent using interfaces and mixin classes. Is anything like this under development for SWIG?
Regards
Andre
On 25/01/13 16:04, Pankaj Kumar Sangra wrote:
> Hello,
> My intention was to expose the functionality given by methods written in
> Classes in C++ language. to the Javascript Frame Work.
>
> I was trying to call the with -> operator in case of pointer object of
> class.
>
>
> Sample Example:
>
> //Source Code of some library is C++ is like that
> Class ATM
> {
> public :
> ATM(int);
> ~ATM();
> Money withDrawMoney(Money);
> };
> Class Money
> {
> public:
> Money();
> ~Money();
> float countAmount(Money);
> }
> //method defination
> Money ATM::withDrawMoney(Money money)
> {
> printf("Entering in "withDrawMoney"function");
> Money amount=new Money(money);
> }
>
> //---------------------------------------------------IN
> SWIG---------------------
>
> In sample.cpp file
>
> Money* myWrap_withDrawMoney(int k, Money requestAmount)
> {
> ATM* atm=new ATM(k);
> Money* money=atm->withDrawMoney(requestAmount);
> return money;
> }
> //---------------------------------
> In sample.i file
>
> %module sample;
> %inline%{
> extern Money* myWrap_withDrawMoney(int k, Money requestAmount);
> %}
> //-----------------------------------------
> In Javascript.js file
>
> var val=0;
> var amountWithDraw=1000;
> sample.myWrap_withDrawMoney(val, amountWithDraw);
>
>
>
> Now my problem is that, I'm not able to call my
> withDrawMoney(requestMoney); from my sample.cpp file.
>
> It is neither showing error nor printing the statement written in the
> C++ library function
> I wanted to call the C++ function from javascript file.
>
> Please suggest me the solution, if I'm doing wrong.
>
>
> Every even little suggestion is appreciable.
SWIG doesn't support Javascript yet. If you got this from Github, I
don't believe it is ready for general use and you will probably have to
help debug and develop the module.
William
On 28/01/13 12:17, peter greenwood wrote:
> typemapIssue.zip
> <>
> C# typemap searching may have an issue OR of course I am doing something
> wrong!
> I am using Swig version 2.0.9. On windows.
> A failing example is include in attached zip.
>
> I am wrapping a number of CPP classes targeting both Java and C# with
> similar interface files. Java is OK. In the failing example included here I
> get the following generated:-
> public void addB(string bvalue) {....
> public string getB(int index) { ...
> I think I should get:-
> public void addB(byte[] bvalue)) {....
> public byte[] getB(int index) {
>
> You can find this method in the class StringVector.
>
> However, in StringMap I get:-
> public void setB(byte[] bkey, byte[] bvalue) { ...
> public byte[] getB(byte[] bkey) {
> which are correct.
>
This line:
%template(StringVector) std::vector<std::string>;
instantiates the StringVector wrappers. Note that it occurs before you
apply the typemaps that you want:
%apply std::string& FSD_BSTRING {
const std::string& bstring,
const std::string& bkey,
const std::string& bvalue
};
Hence they are not used. Solution is to move the typemaps (%apply)
before the %template.
William:
>
>
> I don't know what's need for somebody helps me :).
>
> Here is part of the swig file, which (I think) is relevant:
>
> #define METHOD1(f, t1) void f (t1 _##t1 _VFO_DECL) \
> { self->error_status = rig_##f(self->rig _VFO_ARG, _##t1); }
>
> ...
>
> #define _VFO_ARG ,vfo
> #define _VFO_DECL ,vfo_t vfo = RIG_VFO_CURR
>
> ...
> METHOD1(send_morse, const_char_string)
>
>
> A line from the header file of library:
>
> int (*send_morse) (RIG * rig, vfo_t vfo, const char *msg);
>
>
> Swig generates wrapper file:
>
> /usr/bin/swig -python -I../include -I../src -I../lib -I../bindings -o hamlibpy_wrap.c `test -f hamlib.swg || echo './'`hamlib.swg
>
> So, the source file is hamlib.swg, and the result is
> hamlibpy_wrap.c.
>
>
> In hamlibpy_wrap.c there is a generated part:
>
> SWIGINTERN PyObject *_wrap_Rig_send_morse(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
> ...
> res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_const_char_string, 0 );
> if (!SWIG_IsOK(res2)) {
> SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Rig_send_morse" "', argument " "2"" of type '" "const_char_string""'");
> }
> if (!argp2) {
> SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "Rig_send_morse" "', argument " "2"" of type '" "const_char_string""'");
> } else {
> arg2 = *((const_char_string *)(argp2));
> }
>
>
>
> *);
William
>
>
>
>
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/swig/mailman/swig-user/?viewmonth=201302&page=2 | CC-MAIN-2017-13 | refinedweb | 1,183 | 57.87 |
Build Docker container images in Kubernetes with kaniko
No Docker daemon? Working in a Kubernetes cluster? No problem. Kaniko, a new open source tool, allows developers to build an image in a container without needing any special privileges.
Generally, building an image from a standard Dockerfile requires interactive access to a Docker daemon. But what happens when you don’t have root access? Working without privileges makes it difficult to build container images, especially in environments that can’t easily or securely expose their Docker daemons. Like, for instance, in a Kubernetes cluster.
Introducing kaniko, an open-source tool designed to help developers build container images from a Dockerfile inside a container or Kubernetes cluster.
Kaniko doesn’t rely on a Docker daemon. Instead, it executes each command in userspace within a Dockerfile. The image is built from scratch, and contains only a static Go binary plus the configuration files needed for pushing and pulling images. Then, kaniko pushes the newly built image to a registry. Voila! You’ve now built a container image in a standard Kubernetes cluster or Google Kubernetes Engine!
SEE MORE: Kubernetes v1.10: What’s new and what to expect
How does kaniko work?
Kaniko executor image is responsible for building an image from a Dockerfile and pushing it to a registry.
Here’s how it works: kaniko runs as a container image that takes in three arguments – a Dockerfile, a build context, and the registry where the image is pushed to. It extracts the filesystem of the base image within the executor image.
Then, any commands are executed in the Dockerfile, snapshotting the filesystem in userspace. Kaniko attaches a layer of changed files to the base image after every command. Finally, the executor pushes the new image to the specified registry.
Since Kaniko does all of this completely in user-space within the executor image, it completely avoids needing any privileged access on users’ machines. No Docker daemon, no CLI, no problem.
Kaniko is similar to other tools like img and orca-build. While both of these tools also build container images from Dockerfiles, they approach the problem differently. For example, img builds images as an unprivileged user within a container, compared to how kaniko builds as a root user within a container in an unprivileged environment. Similarly, orca-build executes builds with kernel namespaceing techniques. Kaniko executes builds as a root user within a container.
SEE MORE: A look back and a leap forward: “Docker has been the driving force behind the containerization movement”
Get kaniko
Interested in trying out kaniko? This open-source tool is still in development, but you can try it out for yourself via GitHub. Fair warning, to run kaniko in a Kubernetes cluster, developers need a standard running Kubernetes cluster and a Kubernetes secret.
Be the First to Comment! | https://jaxenter.com/kaniko-docker-kubernetes-143484.html | CC-MAIN-2018-30 | refinedweb | 471 | 56.96 |
You can import many different formats of video file into Unity. Unity stores imported video files as VideoClip assets.
For Unity to preview video files properly, they must be compatible with the Editor platform (the platform you run Unity on). You must also ensure that your files are compatible with the target platforms that your project runs on when you build it. Unity provides options for transcoding files to commonly supported formats, but you can also manage compatibility yourself. See Compatibility with target platforms, below, for more information.
Video source files must use a format your Editor platform supports. Each platform supports a different subset of video file formats.
Video file tracks must also be encoded using a supported codec. Each platform supports a specific subset of codecs, which can vary from one version of the platform to the next.
Tracks encoded using unsupported codecs trigger an error message in the Editor, and you have to convert/re-encode them using a compatible codec before you can use them.
For most plaftforms, H.264 (typically in a .mp4, .m4v, or .mov format) is the optimal supported video codec because it offers the best cross-platform compatibility. Linux is the notable exception.
For Linux, the optimal encoding is usually a .webm container with video tracks encoded using the VP8 codec, and audio encoded using the Vorbis codec.
For information about codec support, consult the official documentation for your Editor platform. For example, Windows and macOS both provide codec compatibility documentation:
The Video Clip Importer can transcode video files that you import into Unity. This is useful when your video sources use a codec that your Editor platform supports, but your target platform does not (see Compatibility with target platforms, below).
To use video files that are compatible with your target platforms, but not your Editor platform, set them up as Streaming Assets. For example, you might want to use the VP9 codec for an Android build, even though the Editor only supports VP8.
To set video files up as Streaming Assets, place them in your Project’s
StreamingAssets folder. To point the Video Player component to Streaming Assets, use the URL property. You can also use Application.streamingAssetsPath to access platform-specific paths to Streaming Assets via scripts.
When you use video files this way, you cannot preview them in the Editor. However, you can create Editor-compatible versions to use as placeholders, include both the compatible- and incompatible version in your project, and decide which one to use at run time.
The example below demonstrates how to use different video URLs for different platforms. For more information, see the documentation on Platform-dependent compilation.
void SetupMovieFile(VideoPlayer vp) { #if UNITY_EDITOR || UNITY_LINUX vp.url = pathToMyVp8File; #elif UNITY_ANDROID vp.url = pathToMyVp9File; #elif UNITY_STANDALONE_WIN vp.url = pathToMyWmvFile; #else vp.url = pathToMyMp4File; #endif }
The VideoPlayer component uses your Editor platform’s native audio and video decoding libraries (see Compatibility on Editor platforms, above) to play video files in the Editor. It’s up to you to ensure that those files meet the requirements for the target platform.
The best natively supported video codec for hardware acceleration is H.264
VP8 is a good choice when cross-platform support is a high priority. It is widely supported and has a comprehensive feature set, but consumes more resources than hardware-accelerated codecs such as H.264.
H.265 is available on devices that support it. See H.265 Compatibility below, for more information.
Android supports VP8 using native libraries, so VP8 may also be hardware-assisted on some Android devices.
While supported in the Unity Editor, the .ogv format is not widely supported on other platforms. Transcode .ogv files into .mp4 (H.264) or .webm (VP8) depending on the target platform.
Below are some key values to look for in your encoding parameters:
Video Codec: H.264, H.265 or VP8.
Resolution: For example: 1280 x 720.
Profile: Applies to H.264/H.265. The profile is a set of capabilities and constraints, often specified by the vendor, such as Baseline or Main. See H.264 or H.265.
Profile Level: Applies for H.264/H.265. Within a given profile, the level specifies performance requirements, for example, Baseline 3.1. See H.264 or H.265.
Audio Codec: Typically AAC (for mp4 videos using H.264/H.265) or Vorbis (for webm videos using VP8).
Audio Channels: depends on platform. For example, the Android recommendation is for stereo files, but many devices will accept 5.1.
The Video Clip Importer provides the option to transcode VideoClip assets into one of the following video codecs:
Transcoded VideoClips use the appropriate audio codec automatically:
If you use videos that you know the target system supports, you can leave the Video Clip Importer’s transcoding options disabled. In that case, Unity does not modify the files at all, and uses them as-is. You can manage encoding using an external program, which allows for finer control.
This section provides useful information about video compatibility, as well as links to external resources.
It is important to follow vendor recommendations for codec support. Codec choices are especially constrained on older mobile platforms. You may need to carefully inspect and convert/re-encode videos that you intend to include in a game running on multiple devices.
This section covers some known issues on specific platforms.
Not all devices support resolutions greater than 640 x 360. Runtime checks are performed to verify this and failures will cause the movie to not be played.
For Android Lollipop (5.0 and 5.1.1) and above, you can use any resolution or number of audio channels, provided the target device supports them.
Format compatibility issues are reported in the
adb logcat output and are always prefixed with
AndroidVideoMedia.
Pay attention to device-specific error messages located near Unity’s error messages: they are not available to the engine, but often explain what the compatibility issue is.
Playback from asset bundles is only supported for uncompressed bundles, read directly from disk.
Native webM/VP8 transparency is not supported. You must transcode VP8-encoded webM clips for transparency to function on Android.
The table below provides platform-specific requirements and encoding/decoding information for the H.265 codec.
2019–05–07 Page amended
5.6 の新機能 | https://docs.unity3d.com/ja/2020.1/Manual/VideoSources-FileCompatibility.html | CC-MAIN-2020-29 | refinedweb | 1,050 | 50.23 |
This section overviews properties that are common to many controls. Controls derive from class Control (namespace System.Windows.Forms). Figure 13.11 lists some of class Control's properties and methods. The properties shown here can be set for many controls. For example, the Text property specifies the text that appears on a control. The location of this text varies depending on the control. In a Windows Form, the text appears in the title bar, but the text of a Button appears on its face.
The Focus method transfers the focus to a control and makes it the active control. When you press the Tab key in an executing Windows application, controls receive the focus in the order specified by their TabIndex property. This property is set by Visual Studio based on the order in which controls are added to a Form, but you can change the tabbing order. TabIndex is helpful for users who enter information in many controls, such as a set of TextBoxes that represent a user's name, address and telephone number. The user can enter information, then quickly select the next control by pressing the Tab key.
The Enabled property indicates whether the user can interact with a control to generate an event. Often, if a control is disabled, it is because an option is unavailable to the user at that time. For example, text editor applications often disable the "paste" command until the user copies some text. In most cases, a disabled control's text appears in gray (rather than in black). You can also hide a control from the user without disabling the control by setting the Visible property to false or by calling method Hide. In each case, the control still exists but is not visible on the Form.
You can use anchoring and docking to specify the layout of controls inside a container (such as a Form). Anchoring causes controls to remain at a fixed distance from the sides of the container even when the container is resized. Anchoring enhances the user experience. For example, if the user expects a control to appear in a particular corner of the application, anchoring ensures that the control will always be in that cornereven if the user resizes the Form. Docking attaches a control to a container such that the control stretches across an entire side. For example, a button docked to the top of a container stretches across the entire top of that container, regardless of the width of the container.
When parent containers are resized, anchored controls are moved (and possibly resized) so that the distance from the sides to which they are anchored does not vary. By default, most controls are anchored to the top-left corner of the Form. To see the effects of anchoring a control, create a simple Windows application that contains two Buttons. Anchor one control to the right and bottom sides by setting the Anchor property as shown in Fig. 13.12. Leave the other control unanchored. Execute the application and enlarge the Form. Notice that the Button anchored to the bottom-right corner is always the same distance from the Form's bottom-right corner (Fig. 13.13), but that the other control stays its original distance from the top-left corner of the Form.
Figure 13.12. Manipulating the Anchor property of a control.
Figure 13.13. Anchoring demonstration.
(This item is displayed on page 610 in the print version)
Sometimes, it is desirable for a control to span an entire side of the Form, even when the Form is resized. For example, a control such as a status bar typically should remain at the bottom of the Form. Docking allows a control to span an entire side (left, right, top or bottom) of its parent container or to fill the entire container. When the parent control is resized, the docked control resizes as well. In Fig. 13.14, a Button is docked at the top of the Form (spanning the top portion). When the Form is resized, the Button is resized to the Form's new width. Forms have a Padding property that specifies the distance between the docked controls and the Form edges. This property specifies four values (one for each side), and each value is set to 0 by default. Some common control layout properties are summarized in Fig. 13.15.
Figure 13.14. Docking a Button to the top of a Form.
The Anchor and Dock properties of a Control are set with respect to the Control's parent container, which could be a Form or another parent container (such as a Panel; discussed in Section 13.6). The minimum and maximum Form (or other Control) sizes can be set via properties MinimumSize and MaximumSize, respectively. Both are of type Size, which has properties Width and Height to specify the size of the Form. Properties MinimumSize and MaximumSize allow you to design the GUI layout for a given size range. The user cannot make a Form smaller than the size specified by property MinimumSize and cannot make a Form larger than the size specified by property MaximumSize. To set a Form to a fixed size (where the Form cannot be resized by the user), set its minimum and maximum size to the same value or set its FormBorderStyle property to FixedSingle.
Using Visual Studio To Edit a GUI's Layout
Visual Studio provides tools that help you with GUI layout. You may have noticed when dragging a control across a Form, that blue lines (known as snap lines) appear to help you position the control with respect to other controls (Fig. 13.16) and the Form's edges. This new feature of Visual Studio 2005 makes the control you are dragging appear to "snap into place" alongside other controls. Visual Studio also provides the Format menu, which contains several options for modifying your GUI's layout. The Format menu does not appear in the IDE unless you select a control (or set of controls) in design view. When you select multiple controls, you can use the Format menu's Align submenu to align the controls. The Format menu also enables you to modify the amount of space between controls or to center a control on the Form.
Figure 13.16. Snap lines in Visual Studio 2005.
(This item is displayed on page 611 | https://flylib.com/books/en/2.255.1/control_properties_and_layout.html | CC-MAIN-2020-34 | refinedweb | 1,063 | 62.07 |
Time series is a set of values of any data that are ordered according to time. It’s a very common data format to observe how things are changing over time. Duration of processes, exchange rates, weather forecasts, heart rate measurements, these are all examples of the time series. Most common applications are metrics from IoT sensors, performance of a system or process, application performance monitoring, clickstream and so on.
Although time series data can be collected very quickly, traditional databases have difficulties in scaling these data since they often remain insufficient with the very large datasets. Because of this disadvantage of traditional relational databases, most people choose to use time series databases (TSDB).
AWS offers a scalable TSDB service for the time series data, called Amazon Timestream. Let’s check its core features, how it works and continue with building our case.
Two years ago, AWS launched Amazon Timestream in Preview and in late September 2020, AWS Timestream was announced to be generally available for the users. Amazon Timestream is a serverless, scalable time series database solution and it is up to 1000x faster in query performance compared to the relational databases. The service also makes it easier to handle trillions of time series data with high performance while charging almost for a tenth of the cost of a traditional relational database.
Amazon Timestream is a fast, scalable, and serverless time series database service for IoT and operational applications.aws.amazon.com/timestream
Let’s start with the convenience of transferring and accessing the data with Amazon Timestream. You do not have to do anything to transfer your data from memory to magnetic store, Amazon Timestream carries out the transfer process for you. Also when it comes to data queries, you don’t have to use separate tools to access your data anymore since you don’t need to specify the data location such as memory or magnetic store.
One of the additional benefits of Amazon Timestream is the built-in security. The service ensures that time series data is always encrypted. Last but not least, you only pay for the write, store and query operations while using Amazon Timestream.
In this tutorial, we are going to build an application that saves the weather data for the last five days to our timestream database and visualizes it with the Grafana dashboard. We are going to use One Call API of OpenWeatherMap as our data source and save the data in Amazon Timestream database. You can check out the project's GitHub repo for the full source code.
This example demonstrates how to load sample data to Amazon Timestream with using Python and boto3.github.com/sufleio/amazon-timestream-grafana-example
Now, we are going to create a database from Amazon Timestream. From the Amazon Timestream console, we selected the standard database and named it
weatherDB.
In the Encryption tab, we will use the default master key. However, you can also provide a master key through AWS KMS as well.
Following these two steps, our database is created. Now, we are going to create a database table, let’s call it
weathertable.
In the Data Retention tab, you will see two retention periods. The most recent recordings, “hot data” are stored in memory. On the other hand, magnetic store keeps cold data and the cold data is permanently erased when the magnetic store period expires. Here, memory store retention describes how long the data will be stored in memory before being moved to the magnetic store.
In our case, our memory store retention period should be at least 5-days since we can not save records older than the retention period of the memory store. Let’s select the memory store retention as 7-days and magnetic store retention period as 1-month.
Now, our timestream database is up to go. Let’s start coding.
First things first, we need to create a client to be able to send time series data to Amazon Timestream. We create our client with boto3 using the credentials of our IAM user with the necessary permissions.
client = boto3.client( 'timestream-write', aws_access_key_id=constants.AWS_ACCESS_KEY_ID, aws_secret_access_key=constants.AWS_SECRET_ACCESS_KEY, region_name=constants.AWS_DEFAULT_REGION )
Or if you run this code on an EC2 instance or AWS Lambda, then you can grant permissions to instance profile role or Lambda role and use following code to create boto3 client. You can check for more information about using IAM roles on boto3 from here.
client = boto3.client( 'timestream-write', region_name=constants.AWS_DEFAULT_REGION )
After we have created our client, we are ready to get daily weather data from the API. Creating a 'list of dictionaries' with the prepare_data() method:
def prepare_data(self, data): records = [] for hourly in data['hourly']: records.append(self.prepare_record(hourly['dt'] * 1000, self.city, 'temp', hourly['temp'])) records.append(self.prepare_record(hourly['dt'] * 1000, self.city, 'feels_like', hourly['feels_like'])) records.append(self.prepare_record(hourly['dt'] * 1000, self.city, 'humidity', hourly['humidity'])) return records
We need to define these keys in our dictionary and add value with prepare_record() method:
In our application,
Dimensions field(s) are common for each city’s analysis. It can be customized by adding other columns such as hostname, country name, timezone etc.
def prepare_record(self, timestamp, city, measure_name, measure_value): # Prepare record to be able to send Amazon Timestream return { 'Time': str(timestamp), 'Dimensions': [{'Name': "city", 'Value': city}], 'MeasureName': measure_name, 'MeasureValue': str(measure_value), 'MeasureValueType': 'DOUBLE' }
PS: Sending epoch timestamp in seconds will result in a
RejectedRecord exception as the timestamp will lie outside of the memory store retention.
Finally, we have reached the last point. All we need to do is send the records to the Amazon Timestream and that’s what our write_records() method does. We will use temperature, feels-like temperature and humidity values from the API response. When the creation of the list is done for each day, we will send it to Amazon Timestream.
def write_records(self): for epoch in self.get_five_past_days(): data = self.get_weather_data(epoch) records = self.prepare_data(data) try: # Send data to Amazon Timestream response = self.client.write_records( DatabaseName=constants.DATABASE_NAME, TableName=constants.TABLE_NAME, Records=records ) print(f"WriteRecords Status: {response['ResponseMetadata']['HTTPStatusCode']}") except self.client.exceptions.ResourceNotFoundException: raise Exception("Table doesn't exists.") except Exception as exc: raise Exception(f"Unexpected error: {exc}")
Run the script with a city that has predefined latitude and longitude information;
python main.py --city Istanbul
Here is the generated data in Amazon Timestream;
You can check the full source code example from:
This example demonstrates how to load sample data to Amazon Timestream with using Python and boto3.github.com/sufleio/amazon-timestream-grafana-example
Now, it is time to visualize our 5-days weather data using Grafana. By following the instructions here, you can install and set up Grafana on your machine. When the setup is completed, run the following command to install the Timestream plugin of Grafana from the command line: grafana-cli plugins install grafana-timestream-datasource
At the "Add Data Sources" tab, search for Amazon Timestream and select it.
Next, provide the credentials file and select your preferred region. After that, hit the “Save & Test” button to see if the connection is successful. Lastly, select your database, table and measure values.
Done! In the Grafana Dashboard, we selected a line graph to visualize temperature values. Here is an example query and its result.
You can also enhance your graphs and dashboards such as adding average value for a specified time period, a secondary measurement for your graph or a secondary location to compare your time series data values as in below:. | https://www.sufle.io/blog/data-visualization-with-amazon-timestream-and-grafana | CC-MAIN-2022-40 | refinedweb | 1,263 | 55.34 |
The program is meant to convert a USD($) quantity inputted by the user (from $0 to $10 max) and output it in quantities of quarters, dimes, nickles, and pennies.
#include <iostream> const double QUARTER {0.25}; const double DIME {0.10}; const double NICKLE {0.05}; const double PENNY {0.01}; void dollarToCoin(double cash, unsigned short& quarters, unsigned short& dimes, unsigned short& nickles, unsigned short& pennies){ double cashRemainder = cash; quarters = cashRemainder / QUARTER; cashRemainder -= QUARTER * quarters; dimes = cashRemainder / DIME; cashRemainder -= DIME * dimes; nickles = cashRemainder / NICKLE; cashRemainder -= NICKLE * nickles; pennies = cashRemainder / PENNY; cashRemainder -= PENNY * pennies; std::cout << "Remaining cash: " << cashRemainder << 'n'; } int main(){ double cash{0}; unsigned short quarters{0}; unsigned short dimes{0}; unsigned short nickles{0}; unsigned short pennies{0}; std::cout << "Input your cash ($0 - $10 max): "; std::cin >> cash; dollarToCoin(cash, quarters, dimes, nickles, pennies); std::cout << "Total quarters: " << quarters << 'n' << "Total dimes: " << dimes << 'n' << "Total nickles: " << nickles << 'n' << "Total pennies: " << pennies << 'n'; return 0; }
The offending line is
nickles = cashRemainder / NICKLE; in the
dollarToCoin() function. here is the pseudocode:
- Starting the program, I input 1.2 as an example
- In the
dollarToCoin()we copy the cash (1.2 dollars) into the
cashRemainder
- We calculate
quartersby dividing
cashRemainder (1.2) / QUARTER (0.25)= 4.8 we save only the integer and lose the .8 (now we have 4 quarters = $1.00)
- We substract those 4 quarters to the
cashRemainder (1.2)giving out
0.2
- This is my confusion part: we calculate total of times
dimes = cashRemainder(0.2) / DIME (0.1)if I debug this part, it output 1 instead of 2.
If I, however, replace
dimes = cashRemaindder / DIME by using –>
dimes = 0.2 / DIME this actually outputs 2.
At the end of the program it should convert the input (1.2) into:
Quarters: 4, Dimes: 2, Nickles: 0, Pennies: 0
I still haven’t optimized the code nor used any libraries (by which I know there are easier ways) I’m just confused as why this happening.
Source: Windows Questions C++ | https://windowsquestions.com/2021/02/13/why-my-c-program-outputs-0-2-0-1-1-instead-of-2/ | CC-MAIN-2021-39 | refinedweb | 336 | 57.47 |
Zitat von "Sunagawa Koji / $B:=@n(B $B9';y(B" <[EMAIL PROTECTED]>:
Advertising
> you can use clear passwd with my patch. > > Please Try this patch. It is for 5.3.9. > Hi, good job ! But it wont apply against 5.3.12. - In my CVS-Tree I thought about dynamically using LDAP-entries, because hardcoding a special row for a special entrie makes it worse to add more new LDAP-entries, because you have a bunge of #ifdefs and you will have to doublecheck the whole code where direct access to an LDAP-entry is made As a result I think it is nice to just address an LDAP-Entrie via pointers. e.g. QMAILDOMAIN = 1; CLEAR_PW = 2; qmailUID = 3; etc which are dynamically setup. So general access to it would be #ifdef CLEAR_PW lm[CLEAR_PW]->mod_values[0] = strdup(password); #endif next would be lm[QMAILDOMAIN]->mod_values[0] = strdup(password); no matter if I "ifdefed" CLEAR_PW or not. This make code much more easy and readable. Hope you understand my point and tell me what do you think. I will release a patch for vpopmail-5.3.12 that uses your way, but I am of the opinion to have a clear interface to what is used or not is better than using static addresses. Cheers Jens | https://www.mail-archive.com/vchkpw@inter7.com/msg10596.html | CC-MAIN-2018-30 | refinedweb | 217 | 72.16 |
Not logged in
Log in now
Weekly Edition
Recent Features
Deadline scheduling: coming soon?
LWN.net Weekly Edition for November 27, 2013
ACPI for ARM?
LWN.net Weekly Edition for November 21, 2013
GNU virtual private Ethernet
Hi Linus,
please pull from:
git://git.kernel.org/pub/scm/linux/kernel/git/lenb/linux-acpi-2.6.git release
Please test this on your Evo before pushing it upstream.
Due to a crash on some ACER laptops, this reverts
the Notify-on-stack fix from 2.6.21 and goes
back to an updated notify work-queue fix that we've
discussed (and struggled with) before.
I'm not totally satisfied that we've reverse engineered
all the bizarre Notify cases that BIOS send us, but this
should work on the machines we've seen to date...
The bulk of the text changes are to restore the invariant
that ACPICA is Lindent clean.
thanks!
-Len
ps. individual patches are available on linux-acpi@vger.kernel.org
and a consolidated plain patch is available here:...
drivers/acpi/dispatcher/dsmethod.c | 12
drivers/acpi/dispatcher/dsopcode.c | 3
drivers/acpi/dispatcher/dsutils.c | 7
drivers/acpi/dispatcher/dswstate.c | 9
drivers/acpi/ec.c | 39 -
drivers/acpi/events/evgpe.c | 5
drivers/acpi/events/evgpeblk.c | 3
drivers/acpi/events/evmisc.c | 20
drivers/acpi/events/evregion.c | 15
drivers/acpi/events/evrgnini.c | 3
drivers/acpi/events/evxface.c | 7
drivers/acpi/events/evxfevnt.c | 2
drivers/acpi/executer/exconvrt.c | 5
drivers/acpi/executer/excreate.c | 6
drivers/acpi/executer/exdump.c | 17
drivers/acpi/executer/exmutex.c | 37 -
drivers/acpi/executer/exnames.c | 3
drivers/acpi/executer/exprep.c | 2
drivers/acpi/executer/exresop.c | 3
drivers/acpi/executer/exsystem.c | 30 -
drivers/acpi/executer/exutils.c | 104 +++-
drivers/acpi/hardware/hwsleep.c | 1
drivers/acpi/namespace/nseval.c | 13
drivers/acpi/namespace/nsinit.c | 7
drivers/acpi/namespace/nswalk.c | 6
drivers/acpi/namespace/nsxfeval.c | 17
drivers/acpi/osl.c | 45 +
drivers/acpi/parser/psopcode.c | 618 ++++++++++++-------------
drivers/acpi/resources/rscalc.c | 3
drivers/acpi/resources/rscreate.c | 13
drivers/acpi/resources/rsdump.c | 8
drivers/acpi/resources/rsinfo.c | 2
drivers/acpi/resources/rslist.c | 7
drivers/acpi/resources/rsmisc.c | 4
drivers/acpi/resources/rsutils.c | 6
drivers/acpi/resources/rsxface.c | 3
drivers/acpi/sleep/main.c | 3
drivers/acpi/sleep/proc.c | 11
drivers/acpi/tables/tbfadt.c | 6
drivers/acpi/tables/tbxface.c | 16
drivers/acpi/thermal.c | 104 ----
drivers/acpi/utilities/utalloc.c | 1
drivers/acpi/utilities/utcache.c | 3
drivers/acpi/utilities/utcopy.c | 4
drivers/acpi/utilities/utdebug.c | 4
drivers/acpi/utilities/utdelete.c | 1
drivers/acpi/utilities/utglobal.c | 6
drivers/acpi/utilities/utmisc.c | 6
drivers/acpi/utilities/utmutex.c | 8
drivers/acpi/utilities/utresrc.c | 1
drivers/acpi/utilities/utxface.c | 2
drivers/misc/Kconfig | 2
drivers/misc/asus-laptop.c | 66 ++
drivers/misc/msi-laptop.c | 12
drivers/misc/sony-laptop.c | 8
include/acpi/acdispat.h | 9
include/acpi/acglobal.h | 2
include/acpi/acinterp.h | 9
include/acpi/aclocal.h | 2
include/acpi/acnamesp.h | 6
include/acpi/acobject.h | 4
include/acpi/acpi_bus.h | 9
include/acpi/acpi_drivers.h | 6
include/acpi/acpi_numa.h | 2
include/acpi/acpiosxf.h | 3
include/acpi/actypes.h | 2
include/acpi/acutils.h | 3
include/acpi/platform/aclinux.h | 21
include/acpi/processor.h | 18
include/linux/acpi.h | 3
70 files changed, 721 insertions(+), 727 deletions(-)
through these commits:
Alexey Starikovskiy (1):
ACPI: created a dedicated workqueue for notify() execution
Corentin Chary (4):
asus-laptop: notify ALL events
asus-laptop: add GPS support
asus-laptop: fix light sens init
asus-laptop: version bump and lindent
Len Brown (6):
ACPI: thermal trip points are read-only
ACPI: delete un-reliable concept of cooling mode
Revert "ACPICA: revert "acpi_serialize" changes"
Revert "Execute AML Notify() requests on stack."
Revert "ACPICA: fix AML mutex re-entrancy"
ACPICA: Lindent
Lennart Poettering (1):
acpi,msi-laptop: Fall back to EC polling mode for MSI laptop specific EC commands
Mattia Dongili (1):
sony-laptop: rename SONY_LAPTOP_OLD to a more meaningful SONYPI_COMPAT
with this log:
commit f685648e7d6520653fa2641840cccc58ba8ef8e0
Merge: f142051... 00eb43a...
Author: Len Brown <len.brown@intel.com>
Date: Thu May 10 04:06:12 2007 -0400
Pull misc-for-upstream into release branch
commit 00eb43a1897a8845d0edb198cec69ac5f1f299dd
Author: Lennart Poettering <mzxreary@0pointer.de>
Date: Fri May 4 14:16:19 2007 +0200
acpi,msi-laptop: Fall back to EC polling mode for MSI laptop specific EC commands
The ACPI EC that is used in MSI laptops knows some non-standard
commands for changing the screen brighntess and a few other things,
which are used by the msi-laptop.c driver. Unfortunately for these
commands no GPE events for IBF and OBF are triggered. Since nowadays
the EC code uses the ec_intr=1 mode by default, this causes these
operations to timeout, although they don't fail. In result, all
operations that you can do with the msi-laptop.c driver take more or
less 1s to complete, which is awfully slow.
In one of the more recent kernels (2.6.20?) the EC subsystem has been
revamped. With that change the EC timeout has been increased. before
that increase the MSI EC accesses were slow -- but not *that* slow,
hence I took notice of this limitation of the MSI EC hardware only very
recently.
The standard EC operations on the MSI EC as defined in the ACPI spec
support GPE events properly.
The following patch adds a new argument "force_poll" to the
ec_transaction() function (and friends). If set to 1, the function
will poll for IBF/OBF even if ec_intr=1 is enabled. If set to 0 the
current behaviour is used. The msi-laptop driver is modified to make
use of this new flag, so that OBF/IBF is polled for the special MSI EC
transactions -- but only for them.
Signed-off-by: Lennart Poettering <mzxreary@0pointer.de>
Acked-by: Alexey Starikovskiy <aystarik@gmail.com>
Signed-off-by: Len Brown <len.brown@intel.com>
commit f142051505154da4ba689e129deb06524c5ece8a
Merge: 19ed0d6... a64e62a...
Author: Len Brown <len.brown@intel.com>
Date: Thu May 10 02:50:09 2007 -0400
Pull misc-for-upstream into release branch
commit 19ed0d6fa894aec0050ab75185e69785a656da91
Merge: 71b43ca... f398532...
Author: Len Brown <len.brown@intel.com>
Date: Thu May 10 02:50:01 2007 -0400
Pull asus into release branch
commit 71b43ca46fc5f0588ef64a14c6133c19a9b3f1ea
Merge: 3dd6786... fd35094...
Author: Len Brown <len.brown@intel.com>
Date: Thu May 10 02:49:34 2007 -0400
Pull acpica into release branch
commit 3dd6786f55219f87fd33e153669600d715ca9270
Merge: f697b67... 88db5e1...
Author: Len Brown <len.brown@intel.com>
Date: Thu May 10 02:49:21 2007 -0400
Pull bugzilla-8385 into release branch
commit f697b677620d04d8c77841745727de85f7e948b1
Merge: de56037... eaca2d3...
Author: Len Brown <len.brown@intel.com>
Date: Thu May 10 02:49:01 2007 -0400
Pull thermal into release branch
commit a64e62a07097f67108f0b68bc15216c3a4a5299b
Author: Mattia Dongili <malattia@linux.it>
Date: Tue May 1 11:19:53 2007 +0900
sony-laptop: rename SONY_LAPTOP_OLD to a more meaningful SONYPI_COMPAT
Signed-off-by: Mattia Dongili <malattia@linux.it>
Signed-off-by: Len Brown <len.brown@intel.com>
commit f398532722b44aa797915d6b784e8694b277c2c7
Author: Corentin Chary <corentincj@iksaif.net>
Date: Sun May 6 14:48:22 2007 +0200
asus-laptop: version bump and lindent
Version bump, lindent, etc ..
Signed-off-by: Corentin Chary <corentincj@iksaif.net>
Signed-off-by: Len Brown <len.brown@intel.com>
commit 832d995029466e12aef66187bc9103487bf7be9f
Author: Corentin Chary <corentincj@iksaif.net>
Date: Sun May 6 14:47:29 2007 +0200
asus-laptop: fix light sens init
Fix a stupid light sens detection bug.
Signed-off-by: Corentin Chary <corentincj@iksaif.net>
Signed-off-by: Len Brown <len.brown@intel.com>
commit e539c2f69ca17f71dd41ba89cde67612a1326c57
Author: Corentin Chary <corentincj@iksaif.net>
Date: Sun May 6 14:47:06 2007 +0200
asus-laptop: add GPS support
Just adds GPS support found in R2H thanks to Sam Lin. It will
make a "gps" file in /sys/devices/platform/asus-laptop/.
Signed-off-by: Corentin Chary <corentincj@iksaif.net>
Signed-off-by: Len Brown <len.brown@intel.com>
commit a9dbcb37a45f45813fc64d672a1f7ae6135650b1
Author: Corentin Chary <corentincj@iksaif.net>
Date: Sun May 6 14:46:41 2007 +0200
asus-laptop: notify ALL events
We need to handle all events, because some dsdt use events >= 0x80
Signed-off-by: Corentin Chary <corentincj@iksaif.net>
Signed-off-by: Len Brown <len.brown@intel.com>
commit fd3509436fde38d4c854bf5a6b83d2c779904f8e
Author: Len Brown <len.brown@intel.com>
Date: Wed May 9 23:34:35 2007 -0400
ACPICA: Lindent
Signed-off-by: Len Brown <len.brown@intel.com>>
commit 262a7a28de060f3a63cae20035876d6f22fd7670
Author: Len Brown <len.brown@intel.com>
Date: Wed May 9 23:01:59 2007 -0400
Revert "ACPICA: fix AML mutex re-entrancy"
This reverts commit c0d127b56937c3e72c2b1819161d2f6718eee877.
These changes to AML locking were made to allow
Notify handlers to be called on the stack
and not deadlock. However, that scheme turns
out to be flawed and was reverted by the previous commit,
so this commit restores the locking to it previous design.
Signed-off-by: Len Brown <len.brown@intel.com>
commit 40d07080e585396dc58bc64befa1de0695318b3b
Author: Len Brown <len.brown@intel.com>
Date: Wed May 9 22:59:38 2007 -0400
Revert "Execute AML Notify() requests on stack."
This reverts commit 5f7748cf91558a5026ded5be93c5bf6c1ac34edf.
While that change fixed the HP
it broke the ACER:
which as AML that caused Linux go recursive
and stack fault.
So this commit by itself will restore the ACER
and again break the HP, which we'll fix another way.
Signed-off-by: Len Brown <len.brown@intel.com>
commit 4d2acd9ea539e0f59178b126f6750ccc41eefcdd
Author: Len Brown <len.brown@intel.com>
Date: Wed May 9 22:56:38 2007 -0400
Revert "ACPICA: revert "acpi_serialize" changes"
This reverts commit a8f4af6dc6600980885c594f52eecd60edd62013.
Thus restoring ACPICA's new acpi_serialize code.
This commit by itself may cause a regression, but
it is reverted in this order so that subsequent
reverts reverts under this one can be made
without conflict.
Signed-off-by: Len Brown <len.brown@intel.com>
commit eaca2d3f6c4de9d4274a4e2be54c9693e76b0303
Author: Len Brown <len.brown@intel.com>
Date: Mon Apr 30 23:27:43 2007 -0400
ACPI: delete un-reliable concept of cooling mode
The scheme where the thermal driver displayed the
cooling mode /proc/acpi/thermal_zone/*/cooling_mode
was flawed in two ways.
First, the success of _SCP doesn't actually mean
that the BIOS moved any trip points.
On many BIOS, _SCP is present, but does nothing.
So displaying what _SCP executed actually
was wrong more times than it was right.
Second, examining the relative position of the
trip points when the thermal_zone is added
is insufficient -- as the BIOS reserves the right
to change the trip points at run-time.
The only reliable way for the user to determine if
the thermal zone is in active, passive, or critical
mode is to examine the relative position of the trip points.
The user can do this without the kernel doing it
for them by looking in /proc/acpi/thermal_zone/*/trip_points
New contents for /proc/acpi/thermal_zone/*/cooling_mode:
If _SCP available:
"0 - Active; 1 - Passive\n"
If _SCP unavailable:
"<setting not supported>\n"
Signed-off-by: Len Brown <len.brown@intel.com>
commit 11ccc0f249cb01a129f54760b8ff087f242935d4
Author: Len Brown <len.brown@intel.com>
Date: Mon Apr 30 22:36:01 2007 -0400
ACPI: thermal trip points are read-only
/proc/acpi/thermal_zone/*/trip_points displays
what the kernel reads from the BIOS via ACPI.
If you echo a string of ':' deliminted numbers to this file
then it will change what it displays.
But it shouldn't, since the kernel has no way to communicate
these changes to ACPI thermal zones. ACPI thermal zone
trip points are read-only.
The kernel does have the opportunity to ask the BIOS to change
the trip points with _SCP - Set Cooling Policy.
Request Active Cooling Mode:
# echo 0 > /proc/acpi/thermal_zone/*/cooling_policy
Request Passive Cooling Mode:
# echo 1 > /proc/acpi/thermal_zone/*/cooling_policy
However, in practice it is quite rare for the BIOS
to support the optional _SCP, and it is even more rare
for the BIOS to export an _SCP that actually changes
the trip points.
Signed-off-by: Len Brown <len.brown@intel.com>
-
To unsubscribe from this list: send the line "unsubscribe linux-acpi" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/234291/ | CC-MAIN-2013-48 | refinedweb | 2,046 | 53.68 |
allthingtalk socket
Hello,
Does someone has ever tried to connect a fipy to 'orange.allthingstalk.com', because I do not manage to connect a socket, it allways shows the error "[Errno 113] ECONNABORTED"
I have a fipy + expansion board with a orange SIM card.
>>> lte.connect() >>> lte.isconnected() True >>> address = socket.getaddrinfo('api.allthingstalk.io',8891) >>> print(address) [(2, 1, 0, '', ('40.68.172.187', 8891))] >>> s = socket.socket() >>> s = ssl.wrap_socket(s) >>> s.connect(address[0][-1]) Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 113] ECONNABORTED >>>
On the other hand, I manage to connect socket to 'google':
>>> lte.connect() >>> lte.isconnected() True >>> address = socket.getaddrinfo('', 443) >>> print(address) [(2, 1, 0, '', ('172.217.17.36', 443))] >>> s = socket.socket() >>> s = ssl.wrap_socket(s) >>> s.connect(address[0][-1]) >>>
It would be great if I had a solution. Thank you in advance
One minor addition I wanted to make.. If AllThingsTalk uses the MQTT protocol, you should not use the HTTP request I was suggesting, but switch to the MQTTClient library from micropython
@Gijs Thank you for your investment. I am going to work with your answer and will inform you as soon as I have a result.
Best regards
Hi
Sorry, my experience is limited with allthingstalk. I believe you should connect to port 80, and then send a HTTP request (GET / POST depending on your settings)
I found this online:
It seems you have to attach the autorization in the headers, and implement your JSON data where i mention data.
When searching, I also found a Python library for allthingstalk, maybe that is compatible with micropython, but Im not sure.. That might make things easier.
In this example, I manually construct the HTTP header and data, such that it will be received properly by AllThingsTalk: (Sorry I did not test this for mistakes in the HTTP, it is merely what it should look like)
import socket s = socket.socket() address = socket.getaddrinfo('api.allthingstalk.io',80)[0][-1] s.connect(address) s.send(b'GET /device/token HTTP/1.0\r\n\r\n Authorization: Bearer maker:token \r\n "Content-Type: application/json" data'
@Gijs Thank you for your answer.
It seems to connect with port 80.
>>> s = socket.socket() >>> address = socket.getaddrinfo('40.68.172.187',80) >>> print(address) [(2, 1, 0, '', ('40.68.172.187', 80))] >>> s.connect(address[0][-1]) >>> s.send(b'R5VBDxxxxxxxxrmROhNnpSgD\nmaker:4SRXQxxxxxxxx1VeVtzN6xSghrrwi5pzkpqgTQq\n{"Test01":{"value":1}}') 93 >>>
I do not have any response on ""
Do I use the right format of micro python command to send the value of Test01?
Hi,
I get this as well for
api.allthingstalk.ioon port 8891, but it does not happen on port 80. I believe the connection is being refused as the port is not open? | https://forum.pycom.io/topic/6308/allthingtalk-socket | CC-MAIN-2022-33 | refinedweb | 469 | 58.89 |
for file screening I have following code in two different directories:
import os, re
g=open('results_1.txt', 'w') #Other has 'results_2.txt'
for filename in os.listdir('.'):
if filename.startswith("f"):
with open(filename, 'r') as f:
content =[line.rstrip() for line in f]
A=filter(lambda x: 'KeyWord_1 :' in x, content)
B=filter(lambda x: 'KeyWord_2 :' in x, content)
print >> g,filename,
for item in A:
print >> g,item,
for item in B:
print >> g,item,
g.close()
From the documentation on
os.listdir:
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.
You need to sort the result using a preferred sort order. You vaguely point out that the resulting order wasn't as expected when you tried sorting it, which I take to mean that you probably do not want a lexicographical sort, but a numeric sort on the trailing numbers in the filename:
def trailing_number(filename): return int(filename.split('_')[1].rstrip('.txt')) sorted(os.listdir('.'), key=trailing_number)
Adapt the above to handle the real format of your filenames. Also don't forget to handle exceptions in
trailing_number which can arise if some of your filenames don't conform to the same format. | https://codedump.io/share/bUOVGAp4F1KN/1/python-same-script-opens-files-in-order-in-one-dir-and-not-in-another | CC-MAIN-2017-17 | refinedweb | 227 | 56.15 |
How to Use Enum Effectively in Java
Enums was introduced in the Java language as part of its version 5 release. Enum stands for enumeration, which literally means a numbered list. Other Object-Oriented languages, such as C++, has this feature for a long time. But, Java made it more powerful and robust. It came a much longer way than just representing a list of numbers. This article goes into the details of enum and how it is to used effectively in Java.
What Is Enum?
The idea of enum is simple in the sense that it represents a set of fixed or constant values. It is ideal for designing a list which has a constant set of states, such as the days of the weeks or a list of month names, and so forth. Although they are represented as a set of names, they actually are constant set of numeric values. They can be treated as a special metadata associated with different elements and constructs of the language. This idea of enum eliminated the need of having many boilerplate XML descriptors that existed in Java programming. Enum incorporated a type-safe and new way to our configuration and customization needs.
Enum as a Class
A typical way to model a set of fixed values in Java is to declare the field as final and static.
public class WeekDays{ public static final int SUNDAY = 0; public static final int MONDAY = 1; public static final int TUESDAY = 2; public static final int WEDNESDAY = 3; public static final int THURSDAY = 4; public static final int FRIDAY = 5; public static final int SATURDAY = 6; }
This definitely is a solution, but it is not an ideal one because these constants have a general data type like any other instance field of a class. As a result, if we use them, we need to document and assert their true meanings at every place we use these constants. This is also not a type-safe representation of the idea that we actually need, because we always can use an integer to mean the constant, be it intentionally or unintentionally, and do something that does not make any sense.
public class WeekDays { // ... public int doSomeNonSense(int data) { return FRIDAY*THURSDAY-data; } }
The Java compiler raises no issues with such semantically wrong statements because they are logically and syntactically correct statements. This is a solution in Java only for versions prior to 5. Now, we can use enum to mean the same thing, as follows:
public enum WeekDays { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
It is like a class with the values listed in the enum definition. The Java compiler assures that it will do the type checking and we cannot resort to any nonsensical statement or mischief. Note that it is but a convention and not a compiler injunction to use UPPERCASE in enum.
Extensible Enum
Enum, as a specialized class, can be extended to have instance fields, constructors, and methods. But, there are some restrictions. Enum cannot have a default no-argument constructor and all its constructors (if any) are private; therefore, it is redundant to specify them explicitly.
public enum Deck { JACKS(3), NINES(2), ACES(1), TENS(1), OTHER(0); private final int card; Deck(final int card) { this.card = card; } public int getCardPoint(){ return card; } }
Note that the enum constructor classes are implicit and do not require new keyword. We can write something as follows:
Deck d = Deck.JACKS; System.out.println(d.getCardPoint());
Instance fields come is quite handy in Java; they can be used to give a different meaning altogether to a typical enum instance field.
Enum, Interfaces, and Generics
Enum cannot extend a class, but can implement an interface because Java does not support multiple inheritances of classes but multiple implementation of interfaces. The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation. This extension need not be stated explicitly in code. Here is a quick example.
public interface CardPoint { public int getCardPoint(); } public enum Deck implements CardPoint{ JACKS(){ @Override public int getCardPoint(){ return 3; } }, NINES(){ @Override public int getCardPoint(){ return 3; } }, TENS(){ @Override public int getCardPoint(){ return 3; } }, OTHER(){ @Override public int getCardPoint(){ return 3; } }; }
Or, instead of being verbose, we can be little more concise, as follows:
public interfaceCardPoint { public int getCardPoint(); } public enumDeck implements CardPoint{ JACKS(3), NINES(2), ACES(1), TENS(1), OTHER(0); private final int card; Deck(final int card) { this.card = card; } @Override public int getCardPoint(){ return card; } }
The Enum<T> generic base class provides quite a few convenient methods. Two frequently used among them are:
- String name(): Returns the name of the enum constant
- int ordinal(): Returns the ordinal of this enumeration constant
Also, the Java compiler automatically generates two static methods for every enum type.
- T valueOf(String name: Returns enum constant from the name supplied as argument.
- T[] values(): Returns all declared enum constants.
Interface Enumeration<E>
There is an interface in Java API, in the java.til package, called Enumeration<E>. According to the Java API Documentation, "an object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series." An example given is that, if we want to print all elements of Vector<E> v, we may do so as follows:
for(Enumeration<E> e = v.elements(); e.hasMoreElements();) System.out.println(e.nextElement());
Enum in Collections
There are two enum collection classes: EnumSet and EnumMap.
The EnumSet<T> is a specialized Set implementation to be used with enum types. They are represented internally as bit vectors. The elements in an enum set must have a single enum type and Null elements are not allowed in the set. The EnumSet<T> cannot be instantiated using a constructor; instead, there are many factory methods to do the same.
For example, we can use the allOf method to create an enum set containing all of the elements in the specified element type.
final Set<Deck> cardDeck = EnumSet.allOf(Deck.class);
If we want to creates an empty enum set with the specified element type:
final Set<Deck> noneCardDeck = EnumSet.noneOf(Deck.class);
We also can state specific enum type to include in the set, as follows:
final Set<Deck> specificCardDeck = EnumSet.of( Deck.JACKS, Deck.ACES );
With EnumMap<T,?> we can set key-value pairs with enum elements. It is a specialized Map implementation to be used with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. Here, the keys are enum constants of the enum type, as follows:
final Map<Deck, String> enumMap = new EnumMap<>(Deck.class); enumMap.put(Deck.JACKS, "J"); enumMap.put(Deck.ACES, "A");
Note that both EnumSet<T> and EnumMap<T,?> are not thread-safe. Therefore, they should be used cautiously in a multithreaded environment.
Points to Remember
Here are few points to remember from the Java Language Specification:
- It is a compile-time error if an enum declaration has the modifier of abstract or final.
- An enum declaration is implicitly final unless it contains at least one enum constant that has a class body.
- A nested enum type is implicitly static. It is permitted for the declaration of a nested enum type to redundantly specify the static modifier.
- It is a compile-time error if the same keyword appears more than once as a modifier for an enum declaration, or if an enum declaration has more than one of the access modifiers public, protected, and private.
- The direct superclass of an enum type E is Enum<E>.
- An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type.
Conclusion
Enum should be used whenever we need to represent a fixed set of constants. Java recommends them because they are designed to be used for that specific purpose. Enum is type-safe, extensible, and fully supported by any modern library or framework.
This article was originally published on October 2,... | https://www.developer.com/java/data/how-to-use-enum-effectively-in-java.html | CC-MAIN-2020-29 | refinedweb | 1,400 | 54.02 |
How to upgrade to Linux Mint 17.2
It is now possible to upgrade the Cinnamon and MATE editions of Linux Mint 17 and Linux Mint 17.1 to version 17.2.
If you’ve been waiting for this I’d like to thank you for your patience.
Upgrade for a reason
.2, upgrading blindly for the sake of running the latest version does not make much sense, especially if you’re already happy and everything is working perfectly.
Make sure to read the release notes and to known the new features so you have all the information you need before deciding whether you want to upgrade.
Be selective with updates
Upgrading to 17.2 will upgrade to Rafaela.
Additional info
- The same upgrade path will be available for the Xfce and KDE editions, after they are released as stable 17.2.
- Although Linux Mint 17.2 features a newer kernel, this upgrade does not change the kernel on your behalf. This is a decision only you should take. Should you decide to upgrade to 17.2’s recommended kernel you can do so by applying the “linux-kernel-generic” update, post-upgrade.
- Your grub menu won’t be automatically updated on your behalf. After you rebooted the computer, you can trigger that update with the following command: “sudo update-grub”.
July 3rd, 2015 at 1:25 pm
Even quicker than I expected! Thanks! 🙂
July 3rd, 2015 at 1:31 pm
Thanks for your effort o/
July 3rd, 2015 at 1:39 pm
As a sidenote, since it’s about Update Manager: could you please provide a feature that allows for enabling a popup window when new updates are available? Some people forget to look at the tiny blue icon…
Edit by Clem: Oh no, we want to please everyone. That means making it easy for those who want to upgrade, but not bug people who don’t want to or who don’t even know there’s a new release. It’ll still be there when they find out, if they ever feel like doing so.
July 3rd, 2015 at 1:39 pm
I think I’ll wait on the upgrade. Qiana is still working just fine. Many thanks to the Mint team!
July 3rd, 2015 at 1:41 pm
Ok well I guess the “17.1” people are too eager to go that way no matter. We love new stuff ! So may I suggest a backup solution just in case, which has always work for me. Use Macrium Reflect Free before to image your previous installation. The program knows just fine Linux partitions and even grub. If you don’t have a dual boot with windows, it is easy to make a boot disk on a windows computer. So if something goes wrong with the update, simply re-image back the partition(s). It will also re-instate the boot sector with previous grub entries. Good luck ! I am going in myself.
July 3rd, 2015 at 1:59 pm
Perfect as always 🙂
Great work !
July 3rd, 2015 at 2:10 pm
linux 17.1 has a problem with bluetooth driver bcm43142, is it fixed in 17.2 so as I can upgrade???
July 3rd, 2015 at 2:12 pm
Ran it and it says I am still on Rebecca. Both in grub and System Profiler.
Edit by Clem: You need to reboot and then run “sudo update-grub”.
July 3rd, 2015 at 2:15 pm
I’m running into a problem: I have launched the installer and follow the instructions and input my password to begin the installation. At that point the installer fails telling me “The upgrade did not succeed. Make sure you are connected to the Internet and try again” And of course I’m solidly connected to the Internet.
In addition, immediately after this the Update Manager window displays the following when I click Refresh: “E: The value ‘rebecca’ is invalid for APT::Default-Release as such a release is not available in the sources”
So I open Software Sources, click “Restore Default Settings”, then click “Update the cache”. It updates fine, with no errors.
Then I try re-launching the 17.2 installer, and it fails again.
I’ll be happy to submit any logs or bug reports needed. Thank you!!
Edit by Clem: Can you cleanly “apt update” from terminal? Also, what does “inxi -r” tell you?
July 3rd, 2015 at 2:15 pm
Clem, upgraded to mint 17.2 mate this morning, but the GRUB menu still shows 17.1, and inxi shows 17.2 with mate 1.10.0. Also, started getting the unlock keyring message. I fixed that with seahorse. Other than these minor things, all seems great! and thanks!
Bill
July 3rd, 2015 at 2:20 pm
*Always* back up your data director(y)(ies) *before* doing an upgrade; in case the upgrade “fails”, for whatever reason, you can still do a fresh install, and restore the director(y)(ies) post-install.
Thanks for your cautionary tone in the opening paragraph!
July 3rd, 2015 at 2:22 pm
Thank you!
July 3rd, 2015 at 2:34 pm
All went well. Thanks! 🙂
July 3rd, 2015 at 2:40 pm
Hello!
I have upgraded from 17.1 to 17.2 in Cinnamon and Mate this morming.
Everything went smooth and very quick but I found two bugs. One in Cinnamon that was already present in 17.1 related to background thumbnails and the other in Mate in which some system setting are duplicated (English and spanish).
How can i report them and eventually fix them?
Thank you very much!
Edit by Clem: You can remove mate-system-tools (it’s discontinued in 1.10), replaced with gnome-system-tools.
July 3rd, 2015 at 2:44 pm
Not able to update mintupdate, unfortunately. 🙁
“W: Die Datei »« konnte nicht heruntergeladen werden
404 Not Found [IP: 68.235.39.11 80]”
Any suggestions?
Edit by Clem: Hi Andy, click the refresh button (we’re at mintupdate 4.9.2 already).
July 3rd, 2015 at 2:48 pm
Hi Clem and Linux Mint Dev Team,
Thank you very much for the update! Already applied it, and it works like a charm! (Did not upgrade the Kernel though).
The only issue that started happening after the upgrade is that the Update Manager icon is now bugged:
Any fixes for this?
Thanks again!
Edit by Clem: Not yet, it’s a Cinnamon bug.. we’ve been looking into it for a while, but we don’t have a fix for it yet.
July 3rd, 2015 at 2:57 pm
Just finished the upgrade. Nothing dramatic append, went smoothly. Haven seen any regression so far. All themeing is preserved. Small thing like mentioned above, the boot menu still shows 17.1. I also try to the suggested new kernel (3.16.0.38), even if it install it, it keeps booting with the previous one. Using the boot customizer program, it shows correctly 17.2 entries but even after a writing to grub, the menu still show 17.1. Anyway great job as always from the Mint masters.
Tx
Edit by Clem: sudo update-grub
July 3rd, 2015 at 3:15 pm
Just upgraded my Dell 7537: EVERYTHING works (actually, everything did work on 17.1 too!). The 17.x series have been the most stable I’ve seen so far, I think because of the Mint Dev Team concentrating on the existing base. Great idea!
I backed up the /home/user folder, upgraded to 17.2, upgraded the kernel to the recommended on, updated grub.
Just awesome! Thank you to the whole LinuxMint Team: great work!
Thanks again!
July 3rd, 2015 at 3:31 pm
No issues upgrading. I did follow your final step “sudo update-grub” after the first reboot and now grub shows 17.2.
As always… your work is very much appreciated.
Scott
July 3rd, 2015 at 3:45 pm
I can’t quite figure out how to upgrade the kernel.
Can someone help me please?
Edit by Clem: You can install multiple kernels (i.e. you don’t upgrade per se, you install a new one). Kernels are available from the Update Manager -> View -> Linux Kernels menu.
July 3rd, 2015 at 3:58 pm
Gee I miss that part about manual grub update. Still after the “sudo grub-update” cmd, it won’t do it. It does mention 3.16 with no error. I use the standard way from the update manager/view kernels menu. It shows installed but no go on reboot.
July 3rd, 2015 at 4:09 pm
Again, thank you for your work, congrats on another great release, and i hope you continue with this policy of upgrading on a lts release. It always feels up to date, safe to upgrade and it’s lts. (Only good reasons to continue like this)
Small bugs, the rating numbers on themes are hidden by the scroll bar (also i’m getting server errors right now, but this is probably because of lots of users testing):
Btw, file operations need work, specially because deleting files go to queue, moving files to other places should also have options to star right away…
Also now, nemo is quitting/crashing lots of times with mounting/unmounting of samba/smb shares (at least for me with bookmarked smb shares this happens most of the times).
July 3rd, 2015 at 4:09 pm
Upgrade went well!
Thanks to the Linux Mint team for the outstanding work.
Cheers
Daniel
July 3rd, 2015 at 4:13 pm
Everything went ok in my upgrade, but i found a problem: when i try to change the old nvidia driver 331 to the new 346 nothing happens, the combo box just uncheck 346 and check 331.. What can i do?
July 3rd, 2015 at 4:46 pm
still digicam won´t run
July 3rd, 2015 at 4:49 pm
sorry, digikam
Edit by Clem: apt install kdelibs-bin kdelibs5-data kdelibs5-plugins ()
July 3rd, 2015 at 5:00 pm
Guess I need to RTFM aye?
Your grub menu won’t be automatically updated on your behalf. After you rebooted the computer, you can trigger that update with the following command: “sudo update-grub”.
All is well! heh….
Bill
Edit by Clem: It’s ok, we’re only human 🙂
July 3rd, 2015 at 5:11 pm
you need to goto the update manager, view | kernels and scroll down to you find the kernel that has the recommended check mark. install that.
bill
July 3rd, 2015 at 5:22 pm
I did that Clem. Also tried to reinstall grub from recovery. It sat for 20 minutes and did nothing. Neither SBM or Grub Customizer sees 17.2.
July 3rd, 2015 at 5:24 pm
And from Mint 16 XFCE?
I tried from apt-get dist-upgrade
and apt-get install mint-upgrade-info because I don’t have mint-upgrade-info and I can’t download, I did apt-get upgrade too.
Edit by Clem: From 16 you’ll need a fresh install or an APT update (i.e. change the base sources to point to trusty and the mint ones to rafaela).
July 3rd, 2015 at 5:28 pm
Beautiful, a much appreciated update! The update installed with out any issues and the menu artwork is looking very nice. Thanks for all the teams efforts.
July 3rd, 2015 at 5:33 pm
July 3rd, 2015 at 5:37 pm
> Edit by Clem: Can you cleanly “apt update” from terminal? Also, what does “inxi -r” tell you?
Thanks for your help Clem! Yes, I can run apt update from terminal, with no errors. Everything is up to date.
Here’s the output from inxi -r:
Thanks!
July 3rd, 2015 at 5:40 pm
Thank you from Portugal.
July 3rd, 2015 at 5:42 pm
If you install the new kernel after upgrading but before rebooting the grub-menu is updated already 🙂
rg,rg
July 3rd, 2015 at 5:44 pm
Addendum to above comment… Here is the output from inxi -r right after my installer fails:
This is the output BEFORE my installer fails:
July 3rd, 2015 at 5:56 pm
I tried to update today from 17.1 to 17.2, and in the process of downloading the packages (with the update manager as recommended) I left my desk. I found my computer “frozen” on the old (17.1) screensaver, but the system was ok. I went to a terminal with ctrl+F1, and restarted the machine. The system starts cinnamon, but I can’t access the settings, applets windows, themes, etc.
I ran cinnamon-settings on the terminal and got
$ cinnamon-settings
Traceback (most recent call last):
File “/usr/lib/cinnamon-settings/cinnamon-settings.py”, line 12, in
from gi.repository import Gio, Gtk, GObject, GdkPixbuf, GLib, Pango, Gdk, cairo
ImportError: No module named gi.repository
Is there any way of “forcing” a reinstall of the update to 17.2?
Thanks in advance for the help
July 3rd, 2015 at 5:56 pm
Upgrade went well – will try the kernel update another time. I see no need for it yet, in my environment.
Thanks!
July 3rd, 2015 at 5:57 pm
I’m sorry Clem… refresh solved the problem. Next time, I promise to read before posting. 😉 Thanks, and I’ll inform three other users on facebook who’re having the same problem.
July 3rd, 2015 at 6:30 pm
Re: Linux Mint 17.2 Rafaela MATE 64-bit
When clicking on MATE’s ‘Help’ in right-click and context menu and also many of the ‘Help’ buttons in tools in ‘Control Center’ such as ‘Screensaver Preferences’ or ‘Windows’, I get a ‘Page Not Found’ error in the resulting ‘Help’ window with various sub-error messages?
Example error message when I right click on the MATE Panel and click ‘Help’ in the context menu:
” Page Not Found
The page ‘gospanel-1’ was not found in the document ‘help:mate-user-guide’.”
Both ‘mate-user-guide’ and ‘mint-user-guide-mate’ installed. I tried re-installing both of these packages but no joy, same error when opening MATE’s ‘Help’.
Anyone got a fix or workaround for this? BTW, I’m seeing this issue on a machine with a fresh install and also on a machine just upgraded from 17.1.
.
July 3rd, 2015 at 6:36 pm
How I do this, I must edit any file with an text editor or from Synaptic, Software manager…?
July 3rd, 2015 at 6:50 pm
Here?
July 3rd, 2015 at 6:57 pm
Thank you Clem!
By removing mate-system-tools (User and Groups) and (Date and Time) are not duplicated anymore. These two settings are now in english and not in spanish. I can live with that.
There is also another duplicated setting (Network connections). I can’t find which package I should remove.
Thanks again!
July 3rd, 2015 at 6:59 pm
Hm, for some reason I’m completely unable to reach security.ubuntu.com, regardless of which mirror I choose.
Consequently updating currently seems not possible for me.
July 3rd, 2015 at 7:09 pm
I have to add: Currently at least, I guess it will resolve itself eventually, still a bit strange.
July 3rd, 2015 at 7:17 pm
Hi, i’ve updated from 17.1 to 17.2 and everything works like a charm. Thank you verry much !
July 3rd, 2015 at 7:18 pm
Thank you LM Team and Clem!
You do a trmendous job…
43# @Horacio: Some accessories like Calculator are also dublicated.
But you can remove it by removing mate-calc and mate-calc-common
no problem.
I’m not sure if I have to remove something else, but wherever you see “qiana” in description maybe (I say mabe…) it is safe to remove
One more time thank you!
July 3rd, 2015 at 7:30 pm
Thank you Vassilis!
I was aware that it might happen with mate calculator. It’s in Mate 1.10 changelog.
Network connections is not duplicated. My mistake!
Thank you again Clem and the community!
July 3rd, 2015 at 7:50 pm
My laptop runs the main edition and I did the upgrade a few minutes ago. All went well of course. This is the first time I had seen the upgrade mechanism and I liked how it looked and worked.
My laptop runs best with the Ubuntu based edition because of it’s AMD E1 processor and on chip graphics. My desktop runs best with LMDE 2 Cinnamon because the NVidea 220 graphics work best with the open source drivers and I do not have to spend time trying to fix plymouth.
Cinnamon 2.6 is great on both releases! The added features and very refined look will no doubt continue to popularize the use and adoption of Cinnamon in many distributions.
I looked at github daily and saw all of the work that went into Cinnamon and Mate! Nice to see transparency in development! My sincere congratulations for the amazing work that has been done!
July 3rd, 2015 at 7:53 pm
Worked like a charm both Cinnamon and Mate
Thanks
July 3rd, 2015 at 8:55 pm
Thank you guys. Upgrade went smoothly
July 3rd, 2015 at 9:41 pm
updated my mint based on i3 desktop (mate edition), it required me to install mint-meta-mate to update o_O
installed it, now it works fine. The update didn’t seem to break anything, thank you guys :3
July 3rd, 2015 at 9:46 pm
Almost everything went okay, however the menu button is no longer responsive. When I click on it it does absolutely nothing. My quick launchers on the panel works but the menu button does not. Any suggestions? This is the cinnamon version btw. Thanks
July 3rd, 2015 at 9:53 pm
I realize this isn’t an issue with Mint per se, but the problem appeared since installing the upgrade this morning. Namely, half my fonts no longer appear in any of the libreoffice programs. This is maddening, and there doesn’t seem to be any logic whatsoever to which ones work and which ones don’t. Even within the same font family (such as my favourite, Gill) some varieties appear and others are missing!
This happens exclusively with libreoffice, all other programs are able to see all the fonts I have installed without an issue.
I’ve tried moving the fonts around to all the various locations where fonts can be installed in Linux but no dice: libreoffice simply fails to see them.
Is anyone else experiencing this??
July 3rd, 2015 at 9:59 pm
Clem, found my problem. For some reason /etc/apt/apt.conf.d/00local still contained ‘rebecca’ instead of ‘rafaela’ so I manually edited that file and now my installer is working fine. The files in /sources.list.d updated fine, but /apt.conf.d didn’t… not sure why BUT it’s probably my fault as I’ve done work in there in the past.
Thanks again for your help.
July 3rd, 2015 at 10:18 pm
i wanted to test out kernel 4.0.5 i put together following instruction in mint 17.1 MATE. I tried going back to a previous kernel through the dual boot (Win7.1 x64 and Mint 17.1 x64 Mate) and I ran into troubles with my AMD proprietary driver update to 15.200 and went back to the xserver for now.
I just wanted to try to upgrade to 17.2 Mate in one dual boot computer. it is amd, FX8120 cpu and sapphire hd7950 3gb ddr5/OC 925hz version.
I see that the kernel recommendation is 3.16.38 which i do have installed in the prior kernels.
since i already made troubles for myself and the amd driver update switching kernels backward, to a good kernel I am wondering what kinds of new problems i might have going back from my manual upgraded kernel 4.0.0 or 4.0.5?
I am only 10months into any/all kinds of linuxes , like it very much but still learing bit by bit which is why i want to tackle the upgraded 17.2 Mate for no particular reason other than experiences and surprises.
thanks
john
July 3rd, 2015 at 10:57 pm
There are 2 thing I do after installing Mint and that is use the 2 most popular extras 1/. Add the Weather app and 2/. Add the Void theme.
These are both the most popular items. Please can they be included in the next release.
Thanks and keep up the good work, I notice that even on an i7 computer that Cinnamon in 17.2 is snappier.
July 3rd, 2015 at 10:57 pm
I was able to get it working again by right clicking on the panel>trobleshoot>restore all settings to default.
Thanks for the great product.
July 3rd, 2015 at 11:00 pm
Updated 32bit MATE 17.1, Restarted and Updated GRUB but the default background is still displaying Version 7.1\whilst Added Sysinfo says it is Version 17.2 Rafaela which is worrying. Good news is Palatino carried over in LibreOffice Writer.
July 3rd, 2015 at 11:01 pm
Found a cosmetic bug. Have upgraded three boxes. On all three the Control Centre now has double entries for Time & Date and Users & Groups.
Otherwise mostly good. Biggest concern is the main box’s Driver Manager now shows I’m using an “alternative driver” and none of the six entries is marked “recommended”. (I tend to stick with “recommended”) So I’m off to Google.
July 3rd, 2015 at 11:42 pm
Finally was able to write the new kernel to grub.”sudo update-grub” was doing his thing but on reboot it was the same old 17.1. I have a dual boot with kubuntu and I suspect it protect the grub record. So did a grub-customizer in Kubuntu and there was 2 entries, for 17.1 and 17.2. Delete all 17.1, write the config, then on reboot 17.2 was presented with the new kernel … houra !
July 3rd, 2015 at 11:57 pm
Just upgraded to Rafaela on my Toshiba L300 laptop. Carefully read release notes, upgrade instructions and user comments before. The kernel was upgraded to the recommenden (3.16.0-38) version as well. Everything went smoothly as expected. No problem noticed so far.
Thank you Clem and Mint team: great job as usual!
July 4th, 2015 at 12:59 am
Спасибо вам из России !!! С удовольствием пользуемся линукс минт!!! Грох Александр город Ухта Россия
July 4th, 2015 at 1:26 am
Upgraded from 17.1 to 17.2 without a problem and all is well with the exception that there’s no access to Spices still. Can’t download themes, applets, extensions or refresh the indexes. The following error occurs now:
An error occurred while trying to access the server. Please try again in a little while.
Details: [Errno 104] Connection reset by peer
The real problem with this is that when clicking the “Add/Remove desktop themes” link in the Themes applet of Cinnamon settings, it does bring up the appropriate window but if I close the window, the Themes applet remains frozen and can’t be closed nor can I return to the main Cinnamon settings window by clicking the “arrow”. Several minutes later I get a dialog box with the above error call out.
Cinnamon settings can still be brought up again via the menu but the original Themes applet is still frozen in place and I have to log out and log in again to get rid of it. Restarting Cinnamon does not get rid of it.
This also occurred when I was testing the developer builds via Romeo before the 17.2 release.
July 4th, 2015 at 2:02 am
Just another minor MATE bug. All three upgrades here now have two Calculator entries in Menu. One summons mate-calc, and the other summons gnome-calculator. My remaining 17.1 install shows mate-calc was the previous default.
(Had no luck finding out why no video driver in Driver Manager is marked ‘recommended’. However tested the two newer Nvidias listed and the Nouveau and found no real difference, so decided ‘good enough’ and moved on. Why tempt fate.)
July 4th, 2015 at 2:12 am
I have full disk encrypt set up on my machine, after updating I don’t get the nice box to enter password, just a command line to type encryption password into, it boots fine when I enter the password but I want the nicer looking password box back, how do I do this?
July 4th, 2015 at 2:45 am
One funny thing, though – I installed the 17.2 Cinnamon RC on a spare laptop – all the xscreensaver screensavers showed up.
When I upgraded from 17.1 to 17.2 the only screensaver was “Stars”. I had to install all the xscreensaver screensavers from the repos (and then remove xscreensaver itself, so it wouldn’t potentially interfere with cinnamon-screensaver). Not a major thing, but…
Can I ask for a feature enhancement for the screensavers? A “Random” option, like the one that exists for the background slideshow.
July 4th, 2015 at 2:55 am
@armageddon51: Why should people install “closed source” on an “open source” operating system? Besides i didnt see a deb file, only an .exe installer from there download source 🙁
Besides an imaging system is already onboard -> look at “Disks” :O)
July 4th, 2015 at 2:57 am
at mohamed: look at my site,if you have a similiar setup or follow the link in the post to the English site
July 4th, 2015 at 3:04 am
Regarding last post (58), I got the proper password box back by pressing F11 or F12, I’m not sure which. (Could have been F10)
July 4th, 2015 at 3:35 am
Easiest upgrade yet!
Thanks… This is why I’ve been with Mint since 2008.
I need to send a gift of thanks!
July 4th, 2015 at 4:21 am
My thanks, as ever, for your wonderful work !
July 4th, 2015 at 5:40 am
@LM : I assume you are talking about Macrium. No, this is not a linux program but a windows one. No install necessary. A “created” boot disk suffice. The Linux imaging programs are very crude. As for the Linux “Disks” utility, I think the imaging function does not work on the system disk because the root has to be unmount first. I don’t think Linux has a shadowing function like windows. Sorry I think we are diverging from the topic here.
— update to 17.2 is fully operational now. Great work !
July 4th, 2015 at 7:07 am
Hello to everybody! I appologize for my bad English in advance. I’d like to report for a bug after upgrading to Rafaela 17.2. This issue might not be a bug, but may be due to my lack of competence (I am still a linux mint beginner – I have been using that OS for more than six months, but i still feel lame). The problem is that the shortcuts of open windows for running applications at the taskbar (panel) obscure the shortcuts of applets on the left side of the panel and it’s impossible to click on them and launch them. You can see some kind of reproduction of the issue here:
I must beg your pardon if this issue has already been reported. Please, give me an advice how to get rid of it. Otherwise I have to launch applications through the menu, which is a bit annoying.
Congrats and thanks to everything that Linux Mint team do. Great work!
Regards,
Yasen
July 4th, 2015 at 8:16 am
hi clem and linux mint team just want to say thankyou so much for all your hard work from everyone here we all appreciate everything you guys do your the best keep up the great work!!! linux mint 17.2 rocks!! cant wait for xfce edition!
July 4th, 2015 at 8:26 am
Upgrade was flawless, just like the last one. Sticking to a single LTS base was a really good decision. Kudos!
July 4th, 2015 at 9:39 am
Upgrade doesn’t work. I got update Mint update, then Mint update info. But there isn’t “Upgrade to Linux Mint 17.2 Rafaela in edit.
I have Rebecca x64.
July 4th, 2015 at 9:53 am
Sorry, I was wrong, a miracle happened here. I see in the sources and in the description for the menu Linux Mint17.2 Rafaela.
And also in system surveillance is: Version 17.2 Rafaela.
But I have not upgraded manually. I haven’t even seen that “upgrade to…” under edit. Funny
July 4th, 2015 at 9:57 am
Update: The problem has been solved after setting all panel settings to their defaults.
July 4th, 2015 at 10:08 am
A big thanks to all for your hard work to get 17.2 out.
My Toshiba L840 upgraded without any problems.
Again many thanks…. Mint is the best
Regards
cs
July 4th, 2015 at 10:21 am
How do i get it updated to 2.6.12? This site says it is already available.
July 4th, 2015 at 10:28 am
Guys, I did a fresh install and I haven’t been able to access the System Settings ever since. I installed gnome-control-center from the Software Manager with the hopes that that would fix the issue but alas I still can’t open up the System Settings. Have you come across this problem too?
July 4th, 2015 at 11:05 am
I have a Dell Latitude D630 (don’t laugh – there’s a reason!). On this machine I have Windows XP, Peppermint 5, Linux Mint Cinnamon and (currently) Manjaro xfce which is bugged.
I have upgraded Mint from 17.1 to 17.2 successfully, apart from issues with grub and the kernel. It seems that on my machine, grub is ‘owned’ by Manjaro, as there is a Manjaro logo on the screen when grub loads. The result is that grub only offers Mint 17.1, although it comes up as 17.2, but although I have installed the recommended kernel 3.16.0-38 it still boots with the old 3.13.0-24. It seems I had to go into Manjoro and do [code: sudo update-grub /code] there. I’m now looking for a way out of this having two versions of grub.
Hope that helps others with similar issues.
July 4th, 2015 at 11:16 am
After a backup (using qt4fsarchiver) upgraded my LM 17 mate to LM 17.2.
Did not have any problems – the upgrade was smooth.
Finally Marco windows manager can display the status bar when changing the FN-brightness values.
Thank you for a nice and user-friendly Linux-based operation system.
(Ralink 3290 wifi is still working with a compatibility driver rt2x00pci, hopefully someday the developers will find a way to get to work at a full performance with authentic drivers).
July 4th, 2015 at 11:27 am
Update went smooth. Seems to be working faster than 17.1. Maybe it’s my imagination, but I don’t think so.
July 4th, 2015 at 11:39 am
Hi Clem and Mint Team,
thanks again for your awesome work!
I am at Linux Mint Cinnamon 64 bit and upgrade from 17.1 to 17.2 plus recommended kernel upgrade to 3.16.0-38 worked perfect.
Everything works fine!
Love your OS, for me the best OS I ever used.
Cinnamon 2.6 is a wonderful GUI, also works great with Amarok (from KDE) which is my fav music player now.
Intel i5-4690
AS Rock Z97 Killer Mainboard
MSI Geforce GTX 960 (nvidia-346 driver)
Games like Pillars of Eternity (native), The Witcher II (native) or Trackmania Valley (and so on) and PathOfExile with PlayOnLinux work great too.
Just can recommend your OS to everyone.
Cheers Tommi
July 4th, 2015 at 12:16 pm
Hi, i’m new in linux world and i ba ea few questions.
Where do i found a x64 version?
Does it have a maximum memory to use?
July 4th, 2015 at 1:09 pm
painless update … exceptional as ever
brilliant work, once again … thx to Clem and the Team
Cheers
Ajc
July 4th, 2015 at 1:48 pm
How do I upgrade from 17.0 to 17.2 with apt-get? In what way I need to change sources.list?
July 4th, 2015 at 2:22 pm
hi
Can I upgrade from 17.1 xfce to 17.2 ?
how or when it can possible?
thanks
July 4th, 2015 at 3:00 pm
I have upgraded to Rafaela from 17.1 32 bits
Everything was perfect but now my password si no more recognized (same problem on 2 Dell computers) to open a session
Any idea how it is due to the upgrade or how to change the pasword
Thanks
July 4th, 2015 at 3:55 pm
Another superbly polished release. Cinnamon is getting better and better. Many thanks, Clem and team.
July 4th, 2015 at 4:16 pm
Waiting for the KDE edition. Can we know when it is?
July 4th, 2015 at 4:22 pm
Btw, any update on the KDE version’s ETA (my workhorse) ? If it’s that a smooth update, I am anxious to jump.
July 4th, 2015 at 4:49 pm
With 17.2 both of my LUKS installs have no video signal at the initial unlock step. One is RS482 integrated with default driver, other is GT520 using either 331 or 346 or Nouveau.
Workaround is press ESC to view, or CTL-ALT-DEL because the next boot will start with a GRUB menu and for some reason everything works fine if you start from the GRUB menu. You can also just enter your passphrase blind, and video will return when it gets to startx.
With 17.1 only the GT520 box had this trouble.
July 4th, 2015 at 5:30 pm
Thanks for all of the hard work! Cinnamon is really nice. Are you going to bring back the ability to adjust the panel size? My eyesight is very poor and I have to hunch over too see things at the default size.
July 4th, 2015 at 5:38 pm
Hi Mint Team,
I’m trying to upgrade to Mint Mate Rafaela, but the Update Manager shows me a this message: “The packege mint-meta-mate requires to be installed before the upgrade”.
I push the button to install the package, but it seems that this operation is impossible, because I’should fix the damaged packages before.
How can I do this?
Thanks
July 4th, 2015 at 5:42 pm
Clem,
Thanks for the rolling upgrades. I have upgraded to 17.1 and then to 17.2. To the Linux Mint Team….Well Done !!!
July 4th, 2015 at 6:34 pm
85, I have this issue too see post 66. However on second boot it goes back to the text prompt too until I hit f11
July 4th, 2015 at 6:52 pm
Upgraded the last computer today, a P4 2.8 GHz system my kid’s use. No problems of any kind and the system runs great!
July 4th, 2015 at 8:19 pm
Made up some good reasons to try the update, truth was I was just fascinated to see what you have done. You shouldn’t do such a good job if you don’t want us to be insatiably curious.
Everything went well. My dropbox icon disapeared but was restored as soon as I installed the recommended Kernel.
Thank you. Another excellent job. Mint is a joy to use.
July 4th, 2015 at 9:05 pm
From 17.1 to 17.2 with no problem.
Wonderful! Thanks so much!
July 4th, 2015 at 11:29 pm
My Asus X73 with Nvidia 540M with nvidia 346 series drivers, installed by driver manager.
-performance mode: useless, much slower then on integrated graphic chipset.
-external monitor: not found, not working.
-mate-settings-daemon: not working on nvidia drivers. On Intel drivers works perfectly.
-Blender: rendering on GPU not working.
Of course I tried hints form Google (run Blender as superuser for example) but still not working. Goodbye mister Mint.
July 4th, 2015 at 11:39 pm
Ran into the “The upgrade did not succeed. Make sure you are connected to the Internet and try again” error.
Added myself to /etc/sudoers (assume it just needs apt/apt-get?) and it’s downloading now.
July 4th, 2015 at 11:41 pm
17.1 to 17.2 went well except sound. Xonar DG sound card works with 3.13 kernel and 17.2, but not with 3.16. every way I could think of to check it ( alsa, pulse audio as well as thru the terminal, said it was there and working, but no sound. Reverted to old kernel and all is well. Everything else is great!
July 5th, 2015 at 1:20 am
I have a Dell Inspiron 3000 with full disk encryption.
My first hard disk is Windows 8.1 (soon to be 10!)
My second disk is GNU/Linux Mint.
UEFI boot with Secure Boot on.
Upgrade from 17.1 to 17.2 went OK.
Updated kernel OK.
Did update-grub
Removed unused MATE items.
Seems to work OK.
I do have the problem that shows up on rebooting. The box to take the encryption password fails to display. However, it still works OK.
Good job!
July 5th, 2015 at 1:47 am
I have update but there is something with display. After reboot I can’t see anything. I tried to update from 17.1 to 17.2 and have done clean install of 17.2, but everytime after reboot (after installation complete) I see the black screen.
HP Pavilion G6
AMD A10-4600M APU with Radeon(tm) HD Graphics
8G RAM
A main (might be) point. In LM less then 17.2 the suspend mode didn’t wake up.
On 17.2 it become works, but I couldn’t be able to use the OS after reboot.
What can I do then?
Now I reinstall the 17.1.
I use the Cinnamon version.
Thanks.
July 5th, 2015 at 2:51 am
All 4 laptops in my household smoothly transitioned from 17.1 to 17.2 – average time per upgrade 14 minutes. Zero hiccups. A huge thank you to Clem and everyone on the team who contributed to this great success.
HP dv6 – x2
HP dv7 – x1
Toshiba – x1
July 5th, 2015 at 5:01 am
In spite of the “if it ain’t broke don’t fix it!” warnings, the lure of more efficient resource usage inspired me to upgrade to Mint 17.2 Rafaela. The the install was problem free, and the resource monitor window I keep on the MATE panel seems to indicate that it IS indeed much more efficient!
Kudos, Clement and team!!!!
The successful upgrade on the MATE installation inspired me to try the upgrade of the Cinnamon partition on my other computer. Again, no problems, and things seem to look subtly crisper (am I imagining that?) and perform snappier.
Thanks so much for all your hard work!
July 5th, 2015 at 5:58 am
🙁 Nemo has lost the “Copy/Move .. to other pane” option. Yes holding Ctrl while dragging works, but I was very used to this when moving an often complex selection of images between folders. 🙁
Is there a preferences setting or can this be re-enabled please.
Edit by Clem: Yes, in Edit->Preferences->Display->Context Menus
July 5th, 2015 at 6:08 am
Thanks guys. Upgrade from Mate 17 was piece of cake. Everything works perfectly. All too easy. Great piece of work.
July 5th, 2015 at 7:00 am
Just upgraded from 17.1 to 17.2 via the Update Manager. Also installed the new recommended kernel. All went smooth without any major problem. A big thank you to the Linux Mint team for another wonderful version of LM.
A couple of things to report though. No big issue really: 1) my workspaces’ names were reset to the default “Workspace 1” etc. Not a problem. Just rename them back to what they were before upgrade. 2) All I got on the new screensaver setting is “Screen Locker” and “Stars.” How do I get “Flurry,” “Flying Toasters,” etc. as shown in “New features in Linux Mint 17.2 Cinnamon” ?
Once again thank you for such an awesome work.
July 5th, 2015 at 7:37 am
I just noticed that Conky is not showing the temperatures for the CPU cores. The following error message is displayed when run from command line:
Conky: can’t open ‘/sys/bus/platform/devices/coretemp.0/temp2_input’: No such file or directory
please check your device or remove this var from Conky
Conky: can’t open ‘/sys/bus/platform/devices/coretemp.0/temp3_input’: No such file or directory
please check your device or remove this var from Conky
Conky: can’t open ‘/sys/bus/platform/devices/coretemp.0/temp4_input’: No such file or directory
please check your device or remove this var from Conky
Conky: can’t open ‘/sys/bus/platform/devices/coretemp.0/temp5_input’: No such file or directory
please check your device or remove this var from Conky
Anyway we can rectify this problem? Thanks.
July 5th, 2015 at 8:53 am
HAllo,
i tried to make the update, but i dont see the the menu entry for update to 17.2.
i can only make update of my version 17.1.
please help. thank you
July 5th, 2015 at 9:50 am
Upgraded from “Rebecca” to “Rafaela” Just like the names imply, I can say you cannot compare 100m men to 100m women, at least not yet!!! NO PEJUDICE!!!!!!!!
Rafaela is extremely faster than my previous version “Rebecca”
Im happy/pleased with the upgrade.
Mint, Congratulations on another excellent job, especially this improvement
July 5th, 2015 at 9:51 am
Forgot to say that UPGRADE WENT FLAWLESS on my laptop (Elitebook 8440P)
July 5th, 2015 at 10:01 am
Conky CPU cores temperature solved by replacing ${platform coretemp.0 …} with ${hwmon 1 temp …} in ~/conkyrc.
July 5th, 2015 at 11:06 am
Hi,
I would like to upgrade from 17.1 to 17.2 but after couple of refresh, I don’t have the “Upgrade to Linux Mint 17.2 Rafaela” in the menu Edit of the Update-Manager.
If I check the # of the package of Mintupdate I have 4.9.2.
Can someone explain to me how to upgrade ?
TIA
July 5th, 2015 at 11:17 am
ref #110 – thank you Clem, my Nemo is healed and I can work again as before. Great holiday photo you took and thanks for sharing them with the Mint world.
July 5th, 2015 at 12:17 pm
If I update to Linux Mint 17.2, will I be able to prevent a grub update? I had to add modifications for connectivity (b43) and mods for display (xforce vesa) to avoid white screen that was unreadable. I have an old computer with old legacy graphics.
July 5th, 2015 at 12:25 pm
I forgot to say that I also need to keep my Broadcom b43 driver for my wi-fi.
July 5th, 2015 at 1:11 pm
@Vitaly (post 107): I had the same prob (on a netbook with AMD C-60), but just unplugging the power cable did it (for whatever reason). Maybe this helps you too.
July 5th, 2015 at 2:06 pm
So far I love the new 17.2 but ran in to an odd bug. I’m dual booting alongside Windows on several machines and on one of the (HP DV-9000) there is a peculiar issue post shutdown. If I shut down from Windows I have no problem but if I shut down from Mint I have to physically remove the battery and cord and hard reset to power back on. It’s more of a nuisance than anything but figured you might like to know.
July 5th, 2015 at 2:06 pm
I gotta laugh at posters that say that they’re not going to upgrade to 17.2 – Mate 1.08 had so many bugs, it nearly drove me to distraction!
Mate 1.10 on the other hand rocks! – all of the things that drove me crazy seem to have been fixed, as does (fingers-crossed) Movie Player, which would regularly crash when it was minimised during playback.
I’m very happy so far with the results. Well done to the developers.
July 5th, 2015 at 3:44 pm
I’ve just upgraded from 17.1 Cinnamon to 17.2 via the Update Manager.
Also installed the new recommended kernel (3.16.0-38).
Only a minor issue detected: panel size reverted to default. Really great!
#89 Deth Vader asked: “How do I upgrade from 17.0 to 17.2 with apt-get? In what way I need to change sources.list?”
In /var/log/apt/history.log I see that the Update Manager first installed mint-meta-cinnamon package.
Then in /etc/apt/sources.list.d/official-package-repositories.list it set the following Linux Mint repositories (repos for Ubuntu were not changed):
deb rafaela main upstream import
deb rafaela main
I’d say that after that you can run
$ sudo apt-get update
$ sudo apt-get dist-upgrade
After reboot you can also update the kernel with
$ sudo apt-get install linux-kernel-generic
and update GRUB menu with
$ sudo update-grub
July 5th, 2015 at 3:49 pm
Hi Clem and thank you and linux mint team for the great works you have done.Today I upgraded from 17.1 to 17.2 flawlessly.The process was easy, fast and very user friendly as always.I upgraded the kernel to 3.16 as well.No problem so far.
The only question for me is that where is the search applet which was mentioned both here and in the segfault page in February, with the ability of searching the desktop, filesystem, repos and web as well.I was waiting for this but now I can’t find it in applets settings.
Thanks again.
July 5th, 2015 at 3:50 pm
Also, before upgrading it is recommended that you backup your /etc directory so you can revert some system settings if need be:
$ sudo tar cfz etc_backup.tgz /etc
July 5th, 2015 at 4:04 pm
WINE installs their icons all over the Mate Menu. For some reason, it splits between the WINE folder and Other. If you try to install Windows program, the shortcut in the menu doesn’t actually work and leaves an error message “File not found”. That’s a big usability issue for me. Doesn’t happen in Cinnamon so this is a Mate menu problem.
July 5th, 2015 at 4:04 pm
Hello, after upgrade from 17.1 to 17.2 highdpi stopped working. Everything is really small, icons, fonts, and so on. How can I go back to 17.1? My laptop is DELL XPS 9530.
July 5th, 2015 at 4:41 pm
Update went extremely smoothly, thank you very much.
One problem on Cinnamon – the Dropbox icon no longer appears on the panel. I tried setting a delay in Startup Applications and that solved the problem until I rebooted, when the delay was reset to zero, and so the icon didn’t appear again. Do you know why the delay is being reset?
July 5th, 2015 at 4:47 pm
Upgraded to 17.2 on Dell XPS 1330. Went OK.
I’m running as single boot. When I boot and hold down shift, it says loading grub but it doesn’t.
One more thing. Clem, is it possible to add a way to show my password instead of just a series of splots? I saw and liked this feature when I tested Windows 10 which I since abandoned. I use a 15 character password and sometimes have trouble entering it (finger confusion at 70 years old). This would be handy and, as I live alone, secure.
July 5th, 2015 at 6:05 pm
Thank you! The update was very quick and easy. The update was great for my as I was waiting for a way to have an extra panel on my second monitor. Now I can finally really use my dual monitor setting to it’s full potential. Thanks so much!!
July 5th, 2015 at 8:49 pm
Upgrade from 17.1 64bits ran quickly and efficiently on an old Dell Core2 Duo PC. No issue to report. The main reason was to get the Cinnamon speed optimizations of the new version.
Congratulations to the dev team.
July 5th, 2015 at 9:19 pm
Thank You Mint Dev Team!
July 5th, 2015 at 10:30 pm
XFCE 17.2 Please!!!!
July 5th, 2015 at 10:48 pm
Switch from 32 to 64;
Thanks Clem & crew for the new release! Should I use the opportunity to switch from 32 to 64-bits now that Rafaela is out? I’m on a Intel Core 2 CPU T5600 @1,83Ghz and 2GB RAM (max)?
July 6th, 2015 at 2:00 am
Hi! I have only one problem with Linux Mint 17.2 cinnamon 64 bits, does not work dropbox. I hope you can correct the problem as soon as possible. thanks for the excellent work!
July 6th, 2015 at 6:22 am
When will be released the XFCE edition?
July 6th, 2015 at 6:57 am
Thank to all of the people behind this, thank you Clem! Everything worked like a charm :). I was really surprised when I saw Rila Lake Wallpaper in Rafaela, because I am from Rila and I go to that lake every year. Thank you again and have a nice day.
July 6th, 2015 at 7:47 6th, 2015 at 7:58 am
@ 97: I had a similar problem with mint-meta-cinammon. The trick was to remove apturl-common.
Marco
July 6th, 2015 at 11:17 am
** newbie alert **
I get:
‘Could not apply changes!
Fix broken packages first’
Please help me, also my machine can easily run 64bit but my rebecca is 32bit, would i be able to upgrade both to 17.2 and to 64bit?
Aidan
July 6th, 2015 at 1:27 pm
I am using Mint 17.1 Xfce. It works great! I like its responsiveness. Waiting for the 17.2 Xfce edition to come out!
July 6th, 2015 at 2:57 pm
Thanks for the new release. The upgrade from 17.1 was really fast and quite smooth.
– I moved first from kernel 3.13.x to the recommended 3.16 and found out that my DVBSky DVB-S card ist still not supported with this kernel. To avoid compiling media_build.git manually, I tried selecting the latest 3.19 kernel, and now the DVBSky card works out of the box. I still wonder if this kernel selection will have any drawbacks since it’s obviously not the recommended kernel for 17.2.
– Also (with both 3.16 and 3.19 kernel) I had the problem that during boot my screen was black with no boot logo, until the login screen appears. I was so far able to cure this my removing the “vt.handoff” parameter from GRUB_CMDLINE_LINUX in /etc/grub.d/10_linux. I am not entirely sure what this parameter was supposed to do since without the parameter the boot logo works again as it was working (also without this parameter) in Mint 17 and 17.1.
July 6th, 2015 at 3:12 pm
Thanks for the new release.
I could start waiting to upgrade, moreover there’s lots of positive comments here.
So just upgraded my LinuxMint to ran into these show-stoppers:
* Synergy (1.7.2) isn’t finding the SysTray any longer and refuses to launch (this is really nasty as I’m using two computer at work and this impacts directly into my daily workflow).
* Lots of programs don’t show up any longer in the SysTray (Skype, Gnome-Pie, the LinuxMint Updater, …). Bad, really bad.
* System Tray Collapsible applet, makes thinks even worse with the tray.
* BTW, nor this nor other applets leave any errors in looking glass, whereas three of my used extensions do.
I tried other themes (normally I’m using Void), but that doesn’t help.
Yes, I like the new version (things are much faster, updates from Spices now are really fast), but the above issues with the SysTray I hope will get fixes very soon, otherwise I’ll think about downgrading again.
July 6th, 2015 at 3:13 pm
Ah, just forgot to mention that
* Clementine Audio Player isn’t shown any longer in the sound menu.
July 6th, 2015 at 3:14 pm
Well: nvidia lock-up supposedly fixed, so I enabled the nvidia gpu (instead of the intel one) and system locked up as usual.
Back to the drawing board – and, for me, back to intel.
GeForce GT 650M (GK107M)
July 6th, 2015 at 3:37 pm
Thank you for the smooth update process. I use Mint every day at work and had been worried about losing my morning to upgrade troubleshooting. I’m very happy to report that no troubleshooting was required. 🙂
July 6th, 2015 at 6:39 pm
Same problem here as @SallyK with Dropbox. There is a thread here: Does this need fixing by Cinnamon or Dropbox team?
July 6th, 2015 at 6:42 pm
EDIT – Applied latest updates from Update Manager and it seems to be resolved
July 6th, 2015 at 7:52 pm
Actually, there is an overdue improvement that would be nice to address. Could the Update Manager be made to remember the User’s window adjustment? I like to check the changelog of the Updates — having to enlarge that mailslot-view every single time is kinda silly.
July 6th, 2015 at 9:29 pm
everything went fine (upgrade, grub and recommended kernel) on Thinkpad T510, thanks a lot.
July 6th, 2015 at 10:52 pm
ok, i’m currently running 17.1.
can i upgrade from command line? I mostly use this box via ssh. can I do a “do-release-upgrade” like i would on stock ubuntu? I’d have to install the “ubuntu-release-upgrader-core” package, but i’m afraid that would just upgrade the ubuntu part of mint.
i’m guessing i would have to change my apt sources from Rebecca to Rafaela, but is there a script that already does this?
July 7th, 2015 at 12:01 am
The update manager is not showing me the option under Edit to upgrade to 17.2. I am running the cinnamon version. I did get a new update manager at about the right time, so I don’t know what to think.
July 7th, 2015 at 1:18 am
oups!! broke everything: couldn’t boot after the upgrade. i don’t recall exactly the error message, something like “trying to write outside a drive?!”
Anyway i got a backup of my data so… The only pain in the ass is to reinstall all the softs i can’t live without!
July 7th, 2015 at 1:39 am
Thank u Mint, Dev Team
July 7th, 2015 at 2:52 am
I am using 17.1 xfce. It works great! Can’t wait for xfce 17.2 to come out.
July 7th, 2015 at 6:36 am
Install was easy. Updated grub (sudo: update-grub) after rebooting. Still having problem when booting. When I try to boot, I see my bios screen flash on the screen, then the screen goes blank and everything stops. When I try booting again, I then get the grub screen giving me boot options. I can either boot in recovery mode or I have to select boot from a previous version of mint (this is the one I choose). I then get the option of Mint 17.2 or Mint 17.2 recovery. After this it boots fine. I am using an HP mini that I have converted to a linux Mint system (no other OS). Any ideas on how I can resolve the boot issue?
July 7th, 2015 at 6:39 am
Hey guys, just to say that update 17.1 -> 17.2 went okay. But after applying new kernel 3.16.0-38 and updating grub, I lost access to my LUKS-encrypted system drive and home partitions.
To get it back working, I had to reboot with a 14.04 liveUSB and use a chroot to re-apply (without reformat or new keys, of course) the procedure outlined here:
July 7th, 2015 at 6:40 am
BTW, I am very new to linux. Have some experience with Windows but started using linux about a month ago. Be gentle…
July 7th, 2015 at 7:40 am
Hi,
just found another minor issue:
* workspace names get lost during upgrade
BTW, I like the new window effects themes, good idea.
July 7th, 2015 at 7:57 am
About what I mentioned earlier with Clementine:
It appears in the sound menu once executed, so I think this isn’t an issue.
But why are Banshee (which I never use) and VLC shown right away?
And others like SMPlayer never enter the sound menu.
Maybe there should be some kind of configuration, where I can hide or add sound/video applications.
July 7th, 2015 at 8:22 am
Hi Clem,
please, just delete comment 125, about my SysTray problems.
Just found out that the systray applet got disabled/removed from the panel during the update, that’s why I had all this trouble.
Sorry to bother you with this.
July 7th, 2015 at 10:46 am
I’m trying to upgrade to Mint Mate Rafaela, but the Update Manager makes me install mint-meta-mate. When I try to install it I get that some packages are broken. I go to the Package Manager and Fix Packages fine. Then try I try to install mint-meta-mate, but I still get the same error about fixing packages. It seems like it is an error loop that cannot be resolved. Could you please help or push it with the Update Manager to do things properly?
July 7th, 2015 at 1:35 pm
Thank you for the information, I succeed to upgrade my Linux Mint 17. I am looking forward to read new useful info on your blog.
July 7th, 2015 at 2:14 pm
I am having problems with the Configurable menu applet. After the upgrade to 17.2 it is unresponsive. Is there a way to correct this? If not how do I revert back to the original Mint Menu? Tried going to the Settings, applets and downloading classic menu but am getting an error. Any Help?
Thanks
Jon
July 7th, 2015 at 2:23 pm
I was installed Linux Mint 17.2 RC Mate.
Now, I don’t view the option for upgrade to stable version of 17.2.
The upgrade its automatic or I can’t upgrade from RC to stable?
Regards.
July 7th, 2015 at 3:27 pm
Running Rebecca, update manager shows ‘your system is upto date’ I can not find how to update, please advise.
Many Thanks!!
July 7th, 2015 at 4:55 pm
With upgrading kernel have I install or upgrade some drivers manually, or it all makes automatically?
I’m on Mint over 3 years, but only few months using terminal and trying to do something myself.
July 7th, 2015 at 5:45 pm
Thank you very much. Again, Linux Mint is #1. I’ve installed Linux Mint MATE 17.2;
One bug I’ve noticed with ‘The MATE Image Viewer’: unlike ‘The GNOME Image Viewer’, it doesn’t scroll images properly in full-screen view after zoom-in (+). I’ve checked it with many images, and it was impossible to scroll normally (on my Acer laptop).
July 7th, 2015 at 5:58 pm
I have been having a little problem with linuxmint 17 & 17.1 cinnanon since the time I started using linuxmint.
when I use the suspend buttom , the system crashes and wont resume.
systems resumes but the screen doesn’t display anything jxt like the screen is not working.
but when I remove the battery and plugs it back. it now boots.
am using hp G61-336NR.
this suspend issue has made me lose an important document which I have not saved.
I will be happy if linuxmint team address this problem for me.
by the way,gud work done so far.
July 7th, 2015 at 6:04 pm
with regards to this, I have not used the suspend button for a long time.
but suspend. ( which is “sleep” in windows) was very helpful to me when I was on the windows operating system.
please help me solve this problem.
aside this issue, I think linuxmint is the best operating system I have ever met and haven’t regretted joining the linuxmint world
July 7th, 2015 at 6:17 pm
am using amd dual core procesaor.
3gig ram
July 7th, 2015 at 6:42 pm.
Thanks Clem for your help.
July 7th, 2015 at 6:45 pm
The update went very smoothly. I did a home folder backup, updated from Linux Mint 17.1 Cinnamon to 17.2, updated to the new kernel, and then updated grub. So far so good!
You helped breathe life into a very old computer of mine, an 11 year old Pentium 4 single core. Freeing it from the bloat of a typical proprietary operating system has done wonders. We use it for everyday web browsing, word processing, storing and playing a very large music library, and other light media applications. I’m shocked at how well it runs now!
Great work, Mint team!
July 7th, 2015 at 8:57 pm
Hi Comunity!
I am proving the Live ISO of Linux Mint 17.2 in cinnamon, in one portable computer of 64 bits with UEFI activated in Secure Boot. The mark of the Laptop is ASUS, i decided to update the UEFI/BIOS to the latest version and everything works perfect.
Thank you team of Linux Mint, I’m very happy without systemd.
July 7th, 2015 at 9:45 pm
For the last couple of days I cant go on youtube
July 7th, 2015 at 9:46 pm
Can someone please help me
July 8th, 2015 at 12:48 am
Flawless upgrade from 17.1 to 17.2, with a definite speed increase using the MATE system.
Excellent work, and best distro by far!
Only error noted is that when entering the full disk encryption password, no prompt is visible (due to startx?) as noted by many others.
Also, between entering this password and waiting for the next login screen, PARTS OF THE PASSWORD COULD BE SEEN IN PLAIN TEXT momentarily on the screen as it continued to load.
Surely this is an error with the /passwd configuration in Mint or else I have ‘Hacking Teams’ finfisher style program installed on my system?? 😉
July 8th, 2015 at 2:06 am
Does Mint 17.2 work on Intel NUC5i5RYK or NUC5i5RYH?
July 8th, 2015 at 4:57 am
How much longer till the 17.2 XFCE version comes out?
July 8th, 2015 at 8:45 am
=== hplip ===
Are there any known issues with hplip? I observe for the HP printer M176n the “symptoms” (“hplip-3.15.2-plugin.run file does not match its checksum. File may have been corrupted or altered”) as described in for Ubuntu 15.04, but LinuxMint is based on 14.04. Has LinuxMint 17.2 now the hplip from 15.04? I jusk ask before proceeding as described in section 4 of the a.m. site (excellent page in French).
July 8th, 2015 at 9:24 am
I am running 17.1 for a little while now, after “Maya” and “Nadia” (and I will listen to Clem and not update to 17.2 as long as 17.1 works fine, which it does).
To Clem @ Co:
please know that you are all doing a GREAT job. Know that all the work you do with Linux Mint is not useless, and I dare say that we all appreciate it very much. Coming from Ubuntu, until Canonical started with Unity, I just *love* Linux Mint (too).
Oh, and since XP became obsolete, I got my parents on Mint too 🙂 So, know that Mint is not just for the Linux enthousiasts 🙂
July 8th, 2015 at 10:50 am
=== hplip ===
As this is not urgent, I’ll wait for the hplip-3.15.6-plugin .
July 8th, 2015 at 2:00 pm
Sadly the Mint17.2 MATE version, installed as a BrucesWay USB3key didn’t behave at all well on a different C2Q Intel 8200 host, whereas there are no such problems with Mint17.1 so I am reverting to that to use as a transportable, transferable ownership troubleshooting tool.
July 8th, 2015 at 2:56 pm
ITALIANO : Salve.Ho la versione 17.1 di Linux Mint mate e vorrei aggiornarla alla versione 17.2.Il problema è che quando devo istallare “mint-meta-mate” mi da un errore dicendomi che ho dei pacchetti danneggiati e che devo sistemarli prima di continuare.Allora vado su Synaptic—>Stato e mi dice che lo stesso “mint-meta-mate” è danneggiato….provo a correggerlo però mi continua a dare errore…cosa devo fare???
ESPAÑOL : Hola.Tengo la versión 17.1 de Linux Mint mate y quisiera actualizarla a la versión 17.2.El problema es que cuando tengo que instalar “mint-meta-mate” me da un error diciéndome que tengo unos paquetes dañados y que primero tengo que arreglarlos.Entonces voy en Synaptic—>Estado y me dice que el mismo “mint-meta-mate” está dañado…intento corregirlo pero me sigue dando error…que tengo que hacer???
ENGLISH : Hi.I’ve Linux Mint 17.1 mate version installed and I would to switch to 17.2.When I try to install “mint-meta-mate” it show me an error who say me that I’ve packages demaged and i must correct it before continuing with installation.So I go to Synaptic—>Packages State and it say me that the same “mint-meta-mate” is demaged…i’ve tried to correct it but follow say me that have an error…What I have to do???
Please answer me by mail in simple english ;D I only know italian and spanish.THANKS ;D
July 8th, 2015 at 4:22 pm
I have been using Mint 17.2 for several days now, and it works perfectly.
Just one request: would it be possible to limit the non-critical software updates to once a day? It is a bit annoying to see the update icon change every few hours.
Of course this is a very minor issue, and my overall experience with Linux Mint is absolutely great.
Thanks!!!
July 8th, 2015 at 4:30 pm
Hi Clem,
linux mint 17.2 still unable to detect Broadcom Bluetooth Deivce, The issue was also there in linux 17.1. Is there any resolution?
July 8th, 2015 at 5:32 pm
I ran the upgrade process just now, but my kernel did not update? The system info control panel reports 17.2 with Cinnnamon 2.6.11 and kernel 3.13.0-37.
July 8th, 2015 at 5:47 pm
Nevermind. I finally saw the note up top.
July 8th, 2015 at 8:06 pm
when I backup my /etc directory
sudo tar cfz etc_backup.tgz /etc
how do I revert some system settings if need be?
July 8th, 2015 at 8:35 pm
Please, checking all my good efforts on each website I had chosen by 10 o’clock and I will find a big solution in illustrating many requestions.
July 8th, 2015 at 9:23 pm
Do you plan to release Linux Mint with KDE 5? For example, as test option, like Kubuntu already did. I`ve tried to build and fail(
July 9th, 2015 at 4:31 am
HI Clem and Mint Team
I tried to upgrade to Rafaela from Qiana Mate
All the process was smoothly done except “Window”
Control Center – Window
It doesn’t seem to work properly when activating it
it shows this message ‘Window manager doesn’t work….’
I hope it could be done perfectly
Thanks
July 9th, 2015 at 5:51 am
Excellent! But one bug so far:
Startup Applications is broken:
:$ cinnamon-settings startup
Python module
Traceback (most recent call last):
File “/usr/lib/cinnamon-settings/cinnamon-settings.py”, line 600, in
window = MainWindow()
File “/usr/lib/cinnamon-settings/cinnamon-settings.py”, line 89, in wrapper
res = func(*arg)
File “/usr/lib/cinnamon-settings/cinnamon-settings.py”, line 315,_startup.py”, line 44, in on_module_selected
if app.shown and not app.no_display and not app.hidden:
AttributeError: AutostartApp instance has no attribute ‘shown’
PS: I’m starting one Perl program I wrote there. Worked fine in 17.1
July 9th, 2015 at 9:08 am
Hi All,
thanks for your job!!
I just want to ask about the TRIM BUG for Samsung SSD 8** (failed to get NCQ…) with latest firmware update EXT0DB6Q, on the Mint17.2 with Kernel 3.16*
Will be suggested to upgrade to the 3.16**** when released the Bug fix!
Thanks
July 9th, 2015 at 11:15 am
The Update Manager .. once every so often the icon is not a shield, but half of a white irregular quadrilateral in the panel next to the time. Only seen since the upgrade to 17.2.
July 9th, 2015 at 12:50 pm
I’m using Mint since about 3 years and to my mind it becomes more beautiful with every new version. Good job, thank you very much!
July 9th, 2015 at 2:33 pm
I’ve got an HP Mini 110-3700 with an Atom N455 processor and 1GB of RAM that was running Mint 17.1 Mate and the latest recommended kernel. Last night, I followed the instructions to upgrade both Mint and the kernel, and the upgrades were accomplished without a hitch. After rebooting, I did not notice any difference in performance, but now I am able to control the Mini’s back-light which I had not been able to do in 17 and 17.1. I don’t know which upgrade fixed that, 17.2 or the kernel, but the upgrade was worth it just for that fix. A previous attempt to fix it almost broke the system. There is still a noticeable lag the first time the menu is activated and I still have a little overheating (even with TLP installed – which doesn’t seem to help much, if at all) – I was hoping for improved power management, a problem that is worse on my Fujitsu T4215 (TLP hasn’t helped much here either) than it is on the HP Mini. Like others have mentioned in these comments, I see duplicate Calculator and Network entries in the menu. Seems like there was a third duplicate item too. Is it safe to uninstall one of each duplicate and does it matter which ones get uninstalled? Regarding updating the GRUB menu, even though the instructions say it won’t be automatically updated, mine was – I didn’t have to do anything. The GRUB menu is where you choose between OS’s on boot-up, right? (I’ve messed kind of piece-meal with Linux for probably 5 years or so, but I’m still very much a newb).
July 9th, 2015 at 2:42 pm
BTW – The HP Mini is dual booting Linux Mint and Windows 7 Starter Edition, the original OS on the machine.
July 9th, 2015 at 3:30 pm
Sure a lot of MINT updates this morning(this week). What is new Clem?
July 9th, 2015 at 4:48 pm
I just upgraded from Linux Mint 17.1 to Linux Mint 17.2. The upgrade went well. Did not have any problem. I use multi monitors (4 monitors). But upon booting on Linux Mint 17.2, Klondike opens up in one of the monitors. It works fine other than I have to close Klondike every time I boot up. It gets annoying sometime. How do I fix this? Thanks.
Here’s the overview of my system:
billy@Billy-LinuxMint ~ $ inxi -Fxz
System: Host: Billy-LinuxMint Kernel: 3.13.0-37-generic i686 (32 bit, gcc: 4.8.2)
Desktop: Gnome Distro: Linux Mint 17.2 Rafaela
Machine: Mobo: MSI model: X58A-GD65 (MS-7522) version: 4.0 Bios: American Megatrends version: V23.1 date: 03/19/2011
CPU: Hexa core Intel Core i7 CPU 980 (-MCP-) cache: 12288 KB flags: (lm nx sse sse2 sse3 sse4_1 sse4_2 ssse3 vmx) bmips: 40099
Clock Speeds: 1: 1600.00 MHz 2: 1600.00 MHz 3: 1600.00 MHz 4: 1600.00 MHz 5: 1600.00 MHz 6: 1600.00 MHz 7: 1600.00 MHz 8: 1600.00 MHz
Graphics: Card-1: Advanced Micro Devices [AMD/ATI] Barts XT [Radeon HD 6870] bus-ID: 03:00.0
Card-2: Advanced Micro Devices [AMD/ATI] Barts XT [Radeon HD 6870] bus-ID: 06:00.0
X.Org: 1.15.1 drivers: ati,radeon (unloaded: fbdev,vesa) Resolution: 1920×1080@60.0hz, 1920×1080@60.0hz, 1920×1080@60.0hz, 1366×768@60.2hz
GLX Renderer: Gallium 0.4 on AMD BARTS GLX Version: 3.0 Mesa 10.1.3 Direct Rendering: Yes
Audio: Card-1: 2x Advanced Micro Devices [AMD/ATI] Barts HDMI Audio [Radeon HD 6800 Series] driver: snd_hda_intelsnd_hda_intel bus-ID: 06:00.1
Card-2: Intel 82801JI (ICH10 Family) HD Audio Controller driver: snd_hda_intel bus-ID: 00:1b.0
Card-3: Creative driver: USB Audio usb-ID: 041e:3f19
Sound: Advanced Linux Sound Architecture ver: k3.13.0-37-generic
Network: Card: Realtek RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
driver: r8169 ver: 2.3LK-NAPI port: c800 bus-ID: 07:00.0
IF: eth0 state: up speed: 1000 Mbps duplex: full mac:
Drives: HDD Total Size: 1128.2GB (0.5% used) 1: id: /dev/sda model: WDC_WD1002FAEX size: 1000.2GB
2: id: /dev/sdb model: C300 size: 128.0GB
Partition: ID: / size: 610G used: 5.5G (1%) fs: ext4 ID: swap-1 size: 1.07GB used: 0.00GB (0%) fs: swap
RAID: No RAID devices detected – /proc/mdstat and md_mod kernel raid module present
Sensors: System Temperatures: cpu: 41.0C mobo: N/A gpu: 64.0,63.5
Fan Speeds (in rpm): cpu: N/A
Info: Processes: 217 Uptime: 3 min Memory: 545.3/6053.0MB Runlevel: 2 Gcc sys: 4.8.4 Client: Shell inxi: 1.8.4
July 9th, 2015 at 6:06 pm
“If it ain’t broke, don’t fix it”. – DON’T TELL ME WHAT TO DO!!!
I upgraded to 17.2 althogh everything was working fine in 17.1. You know what? It still works fine!
Awsome work! @all who are involved in making Linux Mint possible: THANK YOU!
July 9th, 2015 at 7:11 pm
After upgrade, to get rid of duplicates and unnecessary packages, it’s safe to remove at least:
mate-calc mate-calc-common (replaced by gcalctool)
mate-dialogs mate-dialogs-common (replaced by zenity)
mate-icon-theme-faenza
mate-system-tools mate-system-tools-common (replaced by gnome-system-tools)
if these are still installed on Raphaela. You may need to manually remove the duplicate menu entries.
Correct me if I’m wrong.
July 9th, 2015 at 9:03 pm
Hey Clem, I’d like to take this opportunity to thank you guys at Linux Mint for all your hard work. That being said, I have just one question. Is it possible to load 17.2 on an older machine with a P4 single core processor and 256G ram. I have an older laptop at home, which used to have Windows XP on it and was just wondering.
July 9th, 2015 at 9:47 pm
According to my post #107.
I’ve tried to clean install again.
It seem to be works well.
This time I install every updates separately: level 1, level 2, level 3.
I’ve read about the same issue. It might be causeswith my video card – ATI.
Btw, it works and I’m happy.
Thanks for this OS and the 17.2 version.
July 9th, 2015 at 11:45 pm
I had a wierd problem:
The following packages have unmet dependencies.
apturl : Depends: apturl-common (= 0.4.1ubuntu4.1mint1) but 0.5.2ubuntu4 is to be installed
E: Unable to correct problems, you have held broken packages.
To work round this, I did:
# apt-get install apturl-common=0.4.1ubuntu4.1mint1
Then apturl installed fine.
July 10th, 2015 at 12:26 pm
Hi Clem,
I upgraded my linux mint(cinnamon) 7.1 to 7.2…everything is good except that when i check SYSTEM SETTINGS-STARTUP APPLICATIONS there were
two “ON” word that appear in each application that i turn-on…It also appear in THEME, PANEL, etc that has ON and OFF.
July 10th, 2015 at 1:35 pm
@Linny #199
This lag when opening the Menu for the first time in MATE is noticeable even for my i5-3570K with 8gb of DDR3 1600Mhz and Nvidia 650. It’s probably not restricted to your setup.
Concerning the calculator, for some reason I have problems when pressing the calc button in my MS Keyboard. The calculator does not open, and a dialog saying it wasn’t possible to execute gcalctool pops up.
July 10th, 2015 at 2:15 pm
What would happen if you start to upgrade and the process is interrupted, for example, because of a power cut or loss of your internet connection? Can you just reboot to the existing version of Linux Mint, restart the upgrade, and resume the process from the point where it failed? Or what?
July 10th, 2015 at 2:35 pm
Did a clean install of 17.2 Rafaela. Install went smooth with no complications. Clicked on “Multimedia Codecs” and get nothing on the welcome page. Went to the search bar to research the problem and get nothing there either. Not sure how to fix it, so I went back to Rebecca. No problems at all. Using Cinnamon 2.4.8 and Kernel 3.13.0-37. Anyone experiencing this? Still love MINT!
July 10th, 2015 at 2:57 pm
re calc button on MS Keyboard.
Here it fails on the 17.2 LiveISO with the dialog “Couldn’t execute command: gcalctool. Verify that this is a valid command.” Same laptop running 17 works with the button. My other box with the upgrade to 17.2 and the two-calculator-problem spawns the mate-calc for that button-press.
July 10th, 2015 at 4:23 pm
The upgrade was flawless but this note is directly after the first reboot, so I can’t speak to usability. However, I do recommend a warning to laptop users. I know that most in the Linux community will already take this specific precaution, but it should reiterated.
If you are upgrading laptop, make sure you are on DC power. Do not attempt an upgrade on battery power.
You KNOW there are people that will upgrade on battery power that is less than minimum. The power will die half-way through the upgrade and they won’t blame themselves. Just a friendly reminder.
July 10th, 2015 at 6:18 pm
There was no “Edit->Upgrade to Linux Mint 17.1 Rebecca” on my 17.0 XFCE, even with Mint update 4.9.2.
I took
So, I edited /etc/apt/sources.list.d/ to Rafaela sources and it’s OK.
On the other side, upgrade 17.0 to 17.1 to 17.2 went fine on Cinnamon Mint.
July 10th, 2015 at 6:37 pm
Excellent job guys!
I migrated to the Mint when Ubuntu adopted Unity, and now I have no intention of changing distro.
Congratulations.
July 10th, 2015 at 7:00 pm
Update speed is very very very slooooooooooooooooooooooooooooooooow
July 10th, 2015 at 7:29 pm
Recently used 17.1 64 bit Cinnamon via ultra HD USBs (kind closest to SSD), a few early issues with internet, then great; re-installed new 17.2 64 bit Cinnamon same USBs other day…tremendous, as if native OS out-of-box on both 2010 Acer Aspire dual core notebook and new Dell Inspiron 17 i5 dual core (here, Mint 17.2 just shows up as boot option in secure boot list and runs like butter). All HP printers/other devices capable of running on Windows 7/8.1 no problem; for me, Mint 17.2 is the perfect alternative OS. Thanks, and congratulations!
July 11th, 2015 at 1:32 am
Hi, i have toruble with the HPLIP tool GUI; does not work in linux mint mate (x32) and cinnamon 17.2 (x64). especify, detect my hp mfp 1132, but not print or scan! The program say “install plug-in required”. but when i tried, send error message saying “don find required plug-in”.
sombody know the solution? help me please!
July 11th, 2015 at 3:37 am
Upgraded a Dell620 laptop from 32-bit MATE 17.1 to 17.2, undoubtedly the cleanest upgrade ever. Had to use the system utilities to verify the difference, no problems even with the NVIDIA video adapter. Thank You Clem!
July 11th, 2015 at 6:39 am
@riggoprerez
You need to install the latest HPLIP. The linuxmint forum is a good place to get help:
July 11th, 2015 at 1:19 pm
Hi, I must to deactivate Compiz otherwise the menu panel take a very long time to be available.
July 11th, 2015 at 3:55 pm
I upgraded a friend’s LM17.1 (Mate 64-bit) to LM17.2 on a Windows 7 dual boot laptop (I had done clean installs of 17.2 RC in my own computers, but I manage a half a dozen computers for older friends that are horrified of computers and I am upgrading them not that 17.2 is done – this was the first upgrade I did from 17.1 to 17.2 using update manager). Things did not go completely right; at first everything looked fine but then all sorts of errors popped up and a message saying that upgrade could not be done because there was no internet connection kicked me out of the upgrade manager (I think the problem was with the wifi connection where I was doing upgrade – not the computer or the OS). What I found truly amazing was that once I re-booted the computer actually upgraded and everything went perfect after that. I love the update manager – it seems like it fixes any problems that get created all by itself!
I do have an issue that does pop up on my 15 year old pentium M laptop (non PAE) since I installed Rafaela 17.2, the update manager fails (every day or every other day) and gives the red X flag – it says that another application is using APT, even when I know that nothing is running, nothing big. I will wait to see if this goes away as updates come in, but if it continues I’ll search for a solution to this minor annoyance.
Thank you, merci beaucoup, gracias, obrigado, gracies, danke schoen, etc. etc. I can’t find enough way to thank the teams that bring us Linux Mint (I guess it’s time for another donation to support the cause).
July 11th, 2015 at 3:57 pm
BTW, I had been having trouble with printer drivers in my friend’s computer before, but HPLIP took care of that.
July 11th, 2015 at 4:51 pm
When I first boot and it starts, Update Manager will fail to check for updates because it complains with this:
Could not refresh list of updates
E:Opening /etc/apt/sources.list.d/official-package-repositories.list – ifstream::ifstream (13: Permission denied)
I have to manually open Update Manger, click “Refresh,” and then it will work from then on. This is really annoying because until I do this step, I miss important updates (the shield stays with a red X). I’ve never had a problem before, and I saw this when mintUpdate 4.9.2 for Raphaela was released. It is still present in 4.9.3. Where are bugs normally reported? I would like this to please be fixed.
July 11th, 2015 at 5:34 pm
Hi! I’ve update yesterday from Linux Mint 17.1 and everything works fine! Excellent work 😀
July 12th, 2015 at 1:40 am
Yet more double menu entries — sometime in the last few days I’ve acquired double entires for Software Manager in both the Menu and in Control Centre.
This time both entires have the same command, ‘gksu mintinstall’. Checking ‘Edit Menu’ I see the un-toggled plain ‘mintinstall’ entry is also duplicated.
This time also only one of my three upgrade machines is affected. The only difference I can think of is this machine is the daily-box that gets updates as they come in. The other two have been offline since last week, so have done the whole week’s worth of updates at once.
[Also just noticed a very minor item — the Control Centre is ‘centRE’ in the Menu, but ‘centER’ on the app itself. …oh, perhaps because this box is set for Canadian English; we swing both ways.]
July 12th, 2015 at 7:03 7:06 am
Please Do not censor a Valid comment.As you did several weeks ago. Cheers bmad. 10:10 am
Upgraded from 17.1 XFCE to 17.2 using apt without issue. Just edited /etc/apt/sources.list.d/official-package-repositories.list and ran apt.
July 12th, 2015 at 11:22 am
I made the upgrade from 17.1 to 17.2 about a week ago and also noticed the duplications, about which others have written. I’ve been using Mint since ‘Helena’ and have noticed similar duplications immediately after ‘upgrades’ from time to time. I have to admit they were not critical to me but I did find that running and using the system for a while caused them to disappear ‘of their own accord.
July 12th, 2015 at 4:28 pm
To agatha:
“agha Says:
July 4th, 2015 at 2:22 pm
hi
Can I upgrade from 17.1 xfce to 17.2 ?
how or when it can possible?
thanks”.
**I changed the female names to Rafaella and the ***y names to trusty**
July 12th, 2015 at 4:38 pm
Is there a way for me to convert my 17.1 KDE edition to Cinnamon edition without having to reinstall from disk/usb ?
July 12th, 2015 at 8:28 pm
Thanks Clem & Co.! Installed with only a small prob: As noted by others, there are now duplicate apps in the main menu. These are the apps that I’ve found to be duplicated:
calculator Vs. mate-calc
network-admin Vs. mate-network-admin
time-admin Vs. mate-time-admin
users-admin Vs. mate-users-admin
Which version of each do we use? From other comments here, I assume that we’re to use the NON-MATE versions, correct?
BTW, for those preferring a more conservative solution, you don’t need to uninstall anything to resolve this–simply uncheck the unwanted apps in the menu editor and you should be all set. That way, there’s no risk of messing something up. 😉
July 12th, 2015 at 8:43 pm
Hey Clem…
GREAT JOB on the 17.2 release …. thank Team
One thing to ask/point out…. expo keeps freezing in Cinnamon. Has anyone else reported this issue?
July 12th, 2015 at 10:36 pm
@theStreak — with version 1.10, the Mate project dropped mate-calc and replaced it with galculator, though apparently Clem prefers gnome-calculator for Mint. Mate also dropped mate-system-tools and we now use gnome-system-tools.
For myself I’m waiting for Mint to issue the fix – I don’t believe using any of the mate-system-tools will cause trouble. These are just interfaces.
I’m guessing the fix will be issued in the days after the XCFE 17.2 is announced. The team can only handle so many things. One I notice the double icons are gone from Menu, I’m taking that as the signal that loose-ends have been sorted, and I’ll upgrade the remaining boxes here to 17.2.
July 13th, 2015 at 8:46 am
218 riggoperez. I have had that problem a number of times, and each time it has been because I was not running the HP program with enough privilege. The error message is most unhelpful in that respect. Suggest sudo-ing the command in question, sudo hplip etc.
July 13th, 2015 at 11:26 am
I have three computers currently running Linux Mint and all three are fully upgraded to 17.2. All are VERY different machines and I’m glad to see a smooth, simple OS that works so well on all of them. The upgrade went perfectly every time thanks to very carefully written directions. Thank you so much.
One side question, is there a snail mail way to donate to the Mint project?
July 13th, 2015 at 12:30 pm
Hi
Trying to uprade to 17.2,but have a problem with Error, anyhelp appreciated. Could not refresh list of updates
E.Encountered a section with no package: header,E:problem with mergelist
/Var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_main_i18n_Translation-en,E:The package lists or status file could not be opened.
Thanks
July 13th, 2015 at 7:49 pm
The nvidia-173 driver used for the GeForce FX graphic-card series does not work with the 3.16 kernel anymore but it still appears as the recommended driver. Upgrading from kernel 3.13 to 3.16 leads to a not working X-server.
July 13th, 2015 at 8:38 pm
Last Friday I bought a new laptop with Ubuntu preinstalled. It turned out to be 12.04 with the dead Ubuntu One still there so, for the sake of purity and because it was prompted by the system, I decided to upgrade to 14.04.2. The upgrade got numb frozen at updating the fonts, I rebooted the laptop and started it over again. Then again, and again. All in all it counted four failed attempts which took all my weekend. So I, feeling quite angry, decided to install my beloved Linux Mint. Again, for the sake of integrity of test, I took Maya, installed it and upgraded to Rafaela. Needless to say, it all worked like charm and took around 20 minutes. To cut it short, my heartfelt thank you to Clem and Mint Team for the best Linux distro ever!
July 14th, 2015 at 8:09 am
Ooopsie – printing is broken. Both hp-check and hp-doctor can’t fix is and say “17.2 is deprecated or not yet supported”. Only way to print anything right now is sneakernet to Windows 🙁 ..for those who still even have a legacy Windows.
July 14th, 2015 at 3:50 pm
Upgrading to 17.2, received this error msg:
E: The value ‘rebecca’ is invalid for APT::Default-Release as such a release is not available in the sources
E: _cache->open() failed, please report.
The msg popped up twice. Retrying had the same results.
I did the required updates before trying the upgrade.
Tks,
John
July 14th, 2015 at 4:20 pm
I performed the upgrade to 17.2 via the apt-get route. Worked fine, no reboot required to incorporate the upgrade (Thank you). After the upgrade I looked at the Update Manager, which still showed the upgrade as being available, but choosing Refresh also gave the previous error message, then showed no updates required.
John
July 14th, 2015 at 6:44 pm
17.2 still has the USB stick read-only bug.
Basically Caja remembers that a stick was a read-only liveISO a moment ago, and won’t drop that identity after it’s been reformatted to ex4/fat. You can mess with Permissions in Properties all you want, Caja won’t retain the new information and steadfastly refuses to let you copy to the ‘read-only’ stick. But things will be fine if you just reboot.
For further information, Grsync has no problem writing to the stick while Caja won’t. In the above example, the stick was formatted with USB Stick Formatter. However I recall similar USB frustration in Disks a year ago while helping someone on the forum, so this may not be limited to Caja.
July 14th, 2015 at 7:58 pm
upgraded works like a charm no problems grub updated manually
thank yo for god work
July 14th, 2015 at 9:05 pm
@J.K. too 🙂
Again: Those who face trouble with HP-printers should install the latest HPLIP. Even though Mint 17.2 isn’t supported, the HPLIP installer does a good job. The linuxmint forum is a good place to get help:
July 14th, 2015 at 10:47 pm
why i can’t upgrade it 🙁
July 14th, 2015 at 11:18 pm
@238 – I used this post to solve the problem:
July 14th, 2015 at 11:18 pm
July 15th, 2015 at 11:27 am
@Clem,for the first time that I can remember, I’ve found a fault with Linux Mint Cinnamon. It’s not a bug type of fault, it’s more of a design/implementation fault. The cued copying, though useful at times, can slow down productivity. A few minutes ago, I wanted to copy a few GBs worth of music files onto my flash drive to copy them across to my secondary computer. I also wanted to copy a few other little assorted files from my backup drive to my working drive. That would normally take literally a couple of seconds, but because it’s in the queue, I have to sit and wait for all the music files to finish copying first before I can work on those other few files. Someone did mention this or something similar in a Youtube video review, but I can’t remember which video it was or who it was. They suggested making the queued copying configurable so you can select that option or select simultaneous copying. As I’m not a programmer, I don’t know if that is at all possible. Could you possibly look into that to see if it’s a viable option? Other than that – which although I’d rather not, I could learn to live with – I’m absolutely loving Mint Cinnamon 17.2. Keep up the good work.
July 15th, 2015 at 11:33 am
@Clem, Ignore my last post. I Just realised that it is possible to copy batches of files simultaneously that are waiting in the queue. I got curious about what would happen if I clicked the little triangle in the queued files dialogue, and what do you know? It copied the little batch I was waiting on. Kudos to you guys, for thinking of that. Well, that’s me happy again. Thanks. 🙂
July 15th, 2015 at 11:42 am
Hello, i tried to upgrade, but in the middle of the upgrade process, this message appeared:
“Some of the packages could not be retrieved from the server(s).
Do you want to continue, ignoring these packages?”
What should i do?
Thanks.
July 15th, 2015 at 3:00 pm
@Clem,
While I was deleting a massive amount of files on a remote CIFS-drive I saw that the status-bar in Nemo is constantly updated.
Doesn’t this slow things down ?
Apart from randomly showing one of the files being deleted it also shows the free space on that device.
I don’t know if the latter has to be requested from that device but if it does it’s not really meaningful while it’s deleting.
Maybe an idea might be to show that’s it doing something (like deleting) when you have that specific directory open or showing the paths of the files that are deleted (or copied/moved).
That would indicate something’s happening if the deleting window is covered.
rg,rg
July 15th, 2015 at 5:47 pm
Trouble with shockwave player
July 16th, 2015 at 7:58 pm
Installed Rebecca (Cinnamon) to Rafaela (Cinnamon), updated kernel, update-grub, dist-upgrades, apt-get updates; all today on a Dell Latitude E5400 laptop without any apparent glitches.
Thank you! 🙂
July 16th, 2015 at 10:34 pm
Whoops. I love being bleeding edge, but I ran the 17.2 update (cinn x64 17.1 previous), and now I have a TON of CPU usage from cinnamon. I have 8 processes between 8 and 40% CPU usage, and 1 process that is between 100 and 400% CPU usage, all labelled cinnamon.
Ideas?
July 16th, 2015 at 10:35 pm
Radeon HD 5430, btw, and 3 monitors. Worked perfectly before. I’m using the xserver-xorg-video-ati. Can’t get all 3 monitors with the fglrx ones (well, I couldn’t before anyway, have yet to try that now). Will try and report back.
July 16th, 2015 at 10:47 pm
When I try to reinstall cinnamon I get:
W: pycompile:246: No such file or directory: /usr/lib/cinnamon
cinnamon start/running, process 13930
Processing triggers for libc-bin (2.19-0ubuntu6.6) …
July 16th, 2015 at 11:03 pm
OK, so I got cinnamon to reinstall, by su and cd /usr/lib and mkdir cinnamon. But now Under Driver Manager I only have Continue to use manually installed drive, and can’t get back to xserver-xorg-ati. My monitor is duplicated, and it says laptop, and it’s the wrong resolution. How do I get back to xorg? I did not manually install a driver, by the way. I just switched to fglrx and tried to switch back to xorg.
July 16th, 2015 at 11:55 pm
Well, I ended up doing a quick reformat of that drive and installing LMDE 2 x64 Mate edition, which in general runs a lot better anyway. Sorry for all the spam.
July 17th, 2015 at 2:22 pm
Muchas gracias! Me resultó muy fácil actualizar mi cinnamon 17 a esta nueva distro, me va de maravilla en mi viejo AMD.
July 17th, 2015 at 5:50 pm
Problem with recognising the monitor after updating from 17.1 to 17.2: monitor no longer recognised and full resolution not attainable. Nvidia card.
Coincidentally, the machine died and I will try a clean install of 17.2 first when I have built the new one.
July 18th, 2015 at 4:31 am
Wow Clem, Mint 17.2 looks amazing! I like the changes made in Cinnamon. Upgrade was smooth sailing for our computers here. Your team is doing a great job with Mint.
Thanks for making an awesome distro! 🙂
July 18th, 2015 at 3:49 pm
Why does /gnome-terminal require user password on launch?
How to stop it asking for my user password?
Adding the line ian ALL=NOPASSWD:/usr/bin/gnome-terminal does not work
Changing owner doesn’t work either, something about a policy setting
Huh? Why?
Where is the remedy to stop gnome-terminal asking for my user password?
July 19th, 2015 at 12:38 pm
What about the update size? Is it possible to upgrade with iso file?
July 19th, 2015 at 3:25 pm
This is not a real update! You are not even using the latest version of Ubuntu anymore. Just watering the same LTS is not called pleasing everyone who wants to upgrade.
Mint has lost its way. Its not ready to evolve and just cares about those who have old, older, oldest computers. What about donors who use new computers?
Edit by Clem: Not at all. Different projects have different objectives. Sticking to LTS and favoring quality on the long-term over bleeding-edge made a lot of sense to us. It’s one of the best decisions we ever made, it pleases a lot of people and it’s more in line with our core values and the goals we set for ourselves. You’d see a lot more bugs and less innovation/development if it wasn’t for this. A 2 year base means we can engage into fixing it rather than constantly catch up with it, and focus on new features rather than regressions every 6 months.
July 19th, 2015 at 4:48 pm
Hi guys,
The new version is ok, except the HPLIP it comes with is a bugous version that’s unable to install the driver. Could you please fix it? (I put the link to the bug in the “Website” field) Thank you!
July 19th, 2015 at 5:10 pm
Love this distro more than any other !
Keep on (great) coding !
No update problem !
July 19th, 2015 at 10:26 pm
Oh great. hahaha updated to 17.2, cause it showed up on the mngr and was not a ‘5’ (super newbie,standalone mint pc) and the first few sentences here tell me its not necessary, or shouldn’t if not needed.
my outlook is running a tad slower, and some things dont work without re-starting firefox. read on one post to update “sudo update-grub”
Just did that and will know how worked next start up. But, some of them also did Kernal updates. I have two in the manager but listed as “5” so havent done them. So, should I ??
Kernal hdrs 3.13.0-57.95
Firmware kernal drivers 1.127.13
+++
July 20th, 2015 at 4:52 am
The charging graphic disappeared from battery icon but it came back after installing new recommended kernel. Then space between battery icon and percentage got corrected after restarting. 🙂
Now I can remove the old (3.13.0-37 / 3.13.11.7) kernel right?
July 20th, 2015 at 4:54 am
When I click on Edit in my Update Manager box, it only shows Preferences and Software Sources. How do I make the Upgrade to Linux Mint 17.2 show up?
July 20th, 2015 at 5:54 pm
Nice one!
Previously, on 17 and 17.1, I was experiencing random but frequent desktop freezes where only the mouse cursor movements got updated.
I could click on things but nothing would appear to happen until I un-froze things by unplugging the laptop’s AC adaptor – then the results of all the clicks became visible.
This has not occurred in the two weeks since I upgraded to 17.2 😀
Well done everyone!
July 21st, 2015 at 10:04 am
HI! I have a problem with my Linux Mint Rafaela (Portuguese edition): on the lower bar, the date displays properly (“Segunda” stands for “Segunda feira”, wich means monday). But on the calendar above it, it’s showing “Dom”, abbreviation of “Domingo”, wich means Sunday. Any idea how to correct this? The week days were not translated properly.
Congratulations for the new LM edition, it’s great!!
July 21st, 2015 at 3:23 pm
When I open up update manager and install all the available updates I dont see the Option to Upgrade to Linux mint 17.2 under the Edit menu. Please help I’m running Linux Mint 17.1 Xfce 32 bit and I have my update manager to version 4.9.2
July 21st, 2015 at 10:08 pm
I Clem and the development Team and the Linux community for a great job on linux Mint The Best Distro Off the Year.
One Thing;
After booting the computer with two monitors. On both monitors the Logon field. Can you make One Login field on the left monitor.
Best regards,
froot.
July 22nd, 2015 at 4:42 am
Clem, Thanks a lot for your work with Linux Mint. Absolutely my favourite distro!
One comment though – why don’t you setup a proper threaded discussion forum on the blog.linuxmint.com such that you can reply against a comment without editing someone else’s reply? That would allow us to see your responses a little more easily.
What do you think? Let me know if you need any help with this and I would love to set up something for you.
July 22nd, 2015 at 1:17 pm
i would like to know if i update my Mint 17.1 to 17.2 through the update manager will i need to install the apps that i had installed manually?
Thank You!
July 22nd, 2015 at 1:35 pm
what i wanted to ask is if i will have to install AGAIN all the apps that was already installed?
July 22nd, 2015 at 2:40 pm
Earlier I wrote about my issues with upgrading my MATE 17.1 to 17.2. the Update Manager wanted me to install mint-meta-mate. When I tried to install it I get that some packages are broken. I go to the Package Manager and Fix Packages fine. Then try I try to install mint-meta-mate, but I still get the same error about fixing packages.
So I tried to install mint-meta-mate via Terminal and then I saw the real dependency. It was some library, which also depended on uinstalling my Chrome. I uninstalled Chrome and then I was able to install mint-meta-mate. Upgrade went fine. Quite strange, but Chrome was the issue :O
Hope this helpssomeone else.
July 22nd, 2015 at 8:56 pm
BorisXp, AFAIK you won’t have to install your apps again because of update. My all apps remained.
July 22nd, 2015 at 8:59 pm
The update has messed up with the battery icon on my taskbar 🙁
After updating the kernel it seemed to have corrected, but now the problem is back. Looks that I shouldn’t have updated.
July 22nd, 2015 at 9:41 pm
xor10 thankx for the answer!
July 23rd, 2015 at 9:49 pm
Is anyone else facing missing nvidia indicator? I just upgraded because of it but I don’t have it in Panel -> Add New Item. Halp.
Edit by Clem: It should show if the two following conditions are met: 1. nvidia-settings & nvidia drivers are installed (both get installed if you install the NVIDIA drivers via the Driver Manager) 2. your chipset supports NVIDIA Prime (you can test that by running “sudo prime-supported”, which should say “yes”. Check /var/log/prime-supported.log if it doesn’t.). Also don’t hesitate to give us the output of inxi -Gxx. Last but not least, make sure nvidia-prime-applet is installed.. that’s what provides the applet.
July 24th, 2015 at 8:45 am
#283
Clem, thank you for your help. It was indeed missing nvidia-prime-applet pakage. | http://blog.linuxmint.com/?p=2871 | CC-MAIN-2017-39 | refinedweb | 17,926 | 75.61 |
’re going to look at a very small, and sometimes helpful static method of the object class. Of course, we know most of the key methods of the object class by heart, especially the ones we tend to override often such as Equals(), GetHashCode(), and ToString().
But there’s one static method which doesn’t tend to get the respect it deserves very often. It’s really quite trivial, yet it can help boost readability and maintainability of code. It’s a very simple method which makes it easy to tell if two references refer to the same object.
Now, this may sound like a trivial feat to you and not one very worthy of attention, but read on and see if you still think so after this discussion.
As you probably know, the == and != operators are defined between reference types to check to see if two references refer to the same instance of an object.
Note: For value types (primitives and struct types), == and != operators are disallowed unless they are defined explicitly for the value types being used as arguments. This means that they can be used for all numeric primitives, and for struct types that explicitly overload the operators directly.
So let’s concentrate on == and != between reference types by starting with a quick example. Let’s say you have a simple class representing a Point:
1: public class Point
2: {
3: public int X { get; set; }
4: public int Y { get; set; }
5: }
And we initialize three references to two Point instances as follows:
1: // s1 and s2 refer to two separate instances of "equivalent" objects
2: var s1 = new Point { X = 5, Y = 13 };
3: var s2 = new Point { X = 5, Y = 13 };
4:
5: // s3 and s2 refer to the exact same object
6: var s3 = s2;
So given that, we’d expect the following code to output the values indicated in the comments.
1: // false, s1 and s2 refer to different instances of Point
2: Console.WriteLine(s1 == s2);
3:
4: // true, s2 and s3 refer to same instance of Point
5: Console.WriteLine(s2 == s3);
And it works as expected! Since s1 and s2 refer to different instances, the result is false, whereas s2 and s3 refer to the exact same instance of a Point so the result of the == operator is true.
This is how the operator == (and in converse, it’s opposite operator !=) work by default for reference types. Since all types are derived from object, this means that unless you specify otherwise, this is the behavior you will get for any new class you create.
As you know, you can overload many operators in C# for your class or struct type. Bear in mind, as always, that operators are overloaded, not overridden. In particular, for this post we are most interested in overloading == and != and its effects.
For example, in the string type, the operators == and != have been overloaded to compare two strings to see if they have the same value, even if they point to different instances:
1: var s1 = "There";
2: var s2 = "here";
4: // T + here = There, but we are avoiding string interring here to prove a point.
5: var s3 = 'T' + s2;
6:
7: // This is true, because "There" is lexicographically equal to "There"
8: Console.WriteLine(s1 == s3);
Now, I did a trick here to make sure that s1 and s3 didn’t refer to the same instance of a string. If I would have set s3 directly to “There” as well, the two string literals would have been collapsed into one by the compiler and we’d have two references to the exact same object, which wouldn’t have illustrated the point. Thus building s3 at runtime prevented the string from being interred and we have two strings both with values of “There”.
Note that even though those two string references refer to different instances, they have the same value, and the == operator is overloaded for string operands to compare the string values instead of the references.
So what happens if you want to actually compare the references to see if they are the same instance, but the type has overloaded operators == and != so that you can’t use them directly?
Why would we ever want to do this? Well, let’s look at an example with our friend the Point class we implemented at the start of this post. Let’s say that we want to define == and != operators for Point so that it compares the X and Y values instead of the references. To do this we might try coding something like this:
1: public static bool operator ==(Point first, Point second)
3: // return true if both first and second are same reference, or both null
4: if (first == second) return true;
5:
6: // if either (but not both due to first check) is null, return false
7: if (first == null || second == null) return false;
8:
9: // both not null, compare values
10: return first.X == second.X && first.Y == second.Y;
11: }
Remember that == should return true if both arguments are null, so we first attempt to check first and second to see if they are the same instance (in which case there’s no sense checking values, must be same by definition!) or both null. If that test returns false, then either only one is null, or they are both not null but refer to different instances. We then check to see if either is null. If one is null and one is not, the result of == should be false by definition. Finally, now that we know both are not null and not the same reference, we can compare the values.
Because operator == and != must be defined in pairs for a given type, we must also provide operator !=, but we can easily do this by negating the result from operator == as follows:
1: public static bool operator !=(Point first, Point second)
3: return !(first == second);
4: }
Okay, now we have our pair of operators and we can try them out, so we exercise them in our program as follows:
1: var p1 = new Point { X = 5, Y = 13 };
2: var p2 = new Point { X = 5, Y = 13 };
4: // p1 and p2 are separate instances, but with equivalent values
5: Console.WriteLine(p1 == p2);
It all compiles fine, we then run it and after we see our screen hanging for a few moments, we get a StackOverflowException. What happened? Well, generally speaking a stack overflow happens when the call stack gets too deep and the stack runs out of memory. Typically, this is the result of runaway recursion.
Recursion? Where did we do recursion? Well, if you notice we did it in three spots:
3: // *** THIS RECURSIVELY CALLS THIS OPERATOR OVERLOAD FOREVER ***
6: // *** SO DO THESE TWO ***
9: return first.X == second.X && first.Y == second.Y;
10: }
Note that because we are using the == operator between two Point references, this will resolve to the operator == overloaded for Point, which is what we are currently defining! This means that for it to resolve operator == it must call operator == which must call operator == which must call operator == and so on for infinity or stack overflow, whichever happens first.
So maybe you get crafty and say, well, I can just use != instead and negate the result! But you’d then end up with the same issue because != would just call == which would call != and so on. So it’s clear that we need a way to get back to the original definition of == and != between object so that it does a strict reference comparison. So how do we do this?
The object class has a nice static method on it called ReferenceEquals() which makes it trivial to compare two instances of a reference type to see if they refer to the same object, or if both are null. We can use this to make our operator overload more readable and correct as follows:
4: if (ReferenceEquals(first, second)) return true;
7: if (ReferenceEquals(first, null) || ReferenceEquals(second, null)) return false;
The call to ReferenceEquals() prevents us from making a recursive call to our own operator == overload on Point and allows us to check the references directly!
Notice, we don’t have to say object.ReferenceEquals() because all types derive from object, hence ReferenceEquals() is always available inside any class without a need to prepend the object type qualifier.
Now, those of you who are crafty (or have access to a decompiler) will notice that ReferenceEquals() is actually defined as something like this:
1: public static bool ReferenceEquals(object objA, object objB)
3: return objA == objB;
Wait a minute! It’s just invoking operator ==, so why does this work and not our original definition?
Well, the answer is that the two parameters objA and objB are both references to object! Remember that operators are overloaded, not overridden! This means that the == operator used depends on the type of the reference operands, not the type of the objects being referred to. So since objA and objB are both object, it uses the == defined between object which is a reference comparison.
Now, of course this means we could have just done this instead:
3: // casting both to object forces the == to be a reference comparison
4: if ((object)first == second) return true;
6: if ((object)first == null || (object)second == null) return false;
7:
8: return first.X == second.X && first.Y == second.Y;
9: }
Personally, though, I much prefer ReferenceEquals() because it’s intention is quite clear. If you perform the object cast, obviously it works. But if you use == and forget the case, or if a developer who doesn’t understand the nuances of operator overloading comes along and thinks it’s redundant and removes it, this can lead to runtime errors (in the case of unintended recursion) or incorrect results (in the case of a value comparison where a reference was intended).
So remember, when you are defining operator == and != operator overloads, consider using ReferenceEquals() to make sure the reference comparisons are performed correctly and you are not accidentally generating an infinitely recursive call. Even if not defining operator overloads, it can be good to be explicit and use ReferenceEquals() for reference comparisons so that even if an operator == is ever defined at a later point on your type, your reference comparison still performs as intended.
Is the ReferenceEquals() method revolutionary? Probably not, but it was important enough for the .NET designers to make it a part of object, and thus it deserves consideration. After all, it can make your code safer, and easier to read by making the intention of the comparison very clear (comparing references not values) and thus, it’s a Little Wonder in my book.
Print | posted on Thursday, August 18, 2011 7:03 PM |
Filed Under [
My Blog
C#
Software
.NET
Little Wonders
] | http://blackrabbitcoder.net/archive/2011/08/18/c.net-little-wonders-the-referenceequals-method.aspx?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+BlackRabbitCoder+%28James+Michael+Hare%29 | crawl-003 | refinedweb | 1,814 | 59.64 |
In this post, I am going to introduce indexed monads, which generalize monads with additional type parameters carrying the information about the computational effects.
Motivation
The State monad represents computations with a state that can be queried and updated. For example, an
Int state is queried and updated during the computation of
c in the following example. While the value of the state is changed from
0 to
1, the type of the state remains the same during the entire computation.
import Control.Monad.State test1 = runState c (0::Int) where c = do v <- get put (succ v) return v -- (0, 1)
This is okay in most cases, but we sometimes want to express a computation where not only the value but also the type of the state can be changed. The vanilla State monad is not general enough to express this requirement.
Indexed Monads
Indexed monads are a generalization of monads that index each monadic type by an initial (type)state and a final (type)state.
m is a type constructor for three type arguments,
p,
q and
a. The argument
a is the type of values produced by the monadic computation.
p and
q represent the types of the state before and after the computation.
class IxMonad m where ireturn :: a -> m p p a ibind :: m p q a -> (a -> m q r b) -> m p r b
ireturn and
ibind must meet the monad laws as the ordinary monads do.
ibind is required to be associative and
ireturn to be the left and the right unit of
ibind.
All ordinary monads can be injected into
IxMonad with a newtype wrapper
MW. It is a phantom type as the type parameters
p and
q are not used on the right hand-side of
MW.
newtype MW m p q a = MW { unMW:: m a } instance Monad m => IxMonad (MW m) where ireturn = MW . return ibind (MW m) f = MW (m >>= unMW . f)
Here is an example of using the ordinary
State monad wrapped with
MW.
iget and
iput wraps the result with
MW newtype wrapper.
iget :: (MonadState s m) => MW m s s s iget = MW get iput :: (MonadState s m) => s -> MW m s s () iput = MW . put test2 = runState (unMW c) (0::Int) where c = iget `ibind` ( \v -> iput (succ v) `ibind` ( \_ -> ireturn v)) -- (0, 1)
Indexed State Monad
IxStateT defines an indexed state monad where
si and
so represents the input and the output state type respectively. The definition of
IxStateT is similar to that of
StateT except that the type of the state can be changed during the computation.
newtype IxStateT m si so v = IxStateT { runIxStateT:: si -> m (so,v) } instance Monad m => IxMonad (IxStateT m) where ireturn x = IxStateT (\si -> return (si,x)) ibind (IxStateT m) f = IxStateT (\si -> m si >>= (\ (sm,x) -> runIxStateT (f x) sm)) vsget :: Monad m => IxStateT m si si si vsget = IxStateT (\si -> return (si,si)) vsput :: Monad m => so -> IxStateT m si so () vsput x = IxStateT (\si -> return (x,()))
The following example gets an
Int from the state and puts a
String into the state. We can see that the type of the state is changed from
Int to
String.
test3 = runIxStateT c (0::Int) >>= print where c = vsget `ibind` ( \v -> vsput (show v) `ibind` ( \_ -> vsget `ibind` ( \v' -> ireturn (v,v')))) -- ("0",(0,"0"))
Do notation
The
IxMonad examples above looks ugly as we couldn’t use the do notation. Fortunately,
-XRebindableSyntax extension allows us to overload the do-notation by providing alternative definitions that are local to the module.
{-# LANGUAGE RebindableSyntax #-} import Prelude hiding ((>>=), (>>), return) import IxState return :: (Monad m) => a -> IxStateT m si si a return = ireturn (>>=) :: (Monad m) => IxStateT m p q a -> (a -> IxStateT m q r b) -> IxStateT m p r b (>>=) = ibind (>>) :: (Monad m) => IxStateT m p q a -> IxStateT m q r b -> IxStateT m p r b v >> w = v >>= \_ -> w c :: (Monad m) => IxStateT m Int String (Int, String) c = do v <- vsget vsput (show v) v' <- vsget return (v, v')
Other definitions
There are multiple ways to define indexed monads. The one used here is from Robert Atkey’s Parameterised Notions of Computation.
Other definitions include:
- McBride: Kleisli Arrows of Outrageous Fortune
- Orchard: Fun with indexed monads
References
- Oleg Kiselyov’s Parameterized `monad’
- Indexed Monad section of Stephen Diehl’s What I Wish I Knew When Learning Haskell | http://kseo.github.io/posts/2017-01-12-indexed-monads.html | CC-MAIN-2017-17 | refinedweb | 736 | 53.95 |
Letting your blocks know where they are
I’ve been fiddling around with how I could get information from the current content area when in the context of a block controller.
First of all, I wanted to know which tag was currently set in the content area. That was reachable through this:
1: var tag = ControllerContext.ParentActionViewContext.ViewData["Tag"] as string;
Then, I tried getting the actual content area, which I could retrieve by doing this:
1: var currentContentArea = ControllerContext.ParentActionViewContext.ViewData.Model as ContentArea;
By getting the current content area, I could get information on how many items it contained, and what those items were. I could also get the current index of the item. Knowing this, I could control which view to render, based on the current index. In the example below I’ve done just that, with the case being that the blocks rendered first, second and third in the list should have special views.
The block type that is being used:
1: [ContentType(GUID = "81D97CE8-AF88-41FB-B4FF-BFF5D53DDDDF",
2: DisplayName = "Football player block")]
3: public class PlayerBlock : BlockData
4: {
5: public virtual string Heading { get; set; }
6: [UIHint(UIHint.Image)]
7: public virtual Url Image { get; set; }
8: public virtual XhtmlString MainBody { get; set; }
9:
10: // This property will indicate the block’s position and will be set in the controller,
11: // which is why I've used the [Ignore] attribute. By doing this, EPiServer won't register it
12: // as an editable property.
13: [Ignore]
14: public int Index { get; set; }
15: }
In the PlayerBlock controller, I return a view based on the current block’s index in the content area:
1: public override ActionResult Index(PlayerBlock currentBlock)
2: {
3: string blockView;
4: // get the current content area
5: var currentContentArea =
6: ControllerContext.ParentActionViewContext.ViewData.Model as ContentArea;
7:
8: int index = 1;
9: // we'll need to check if it is actually rendered in a ContentArea.
10: if (currentContentArea != null)
11: {
12: // the index of the current selected block
13: index = currentContentArea.Contents.IndexOf(currentBlock as IContent) + 1;
14: }
15: switch (index)
16: {
17: case 1:
18: blockView = "first";
19: break;
20: case 2:
21: case 3:
22: blockView = "twoandthree";
23: break;
24: default:
25: blockView = "index";
26: break;
27: }
28: currentBlock.Index = index;
29:
30: // Example:if index is 2, return view "/Views/Blocks/PlayerBlock/TwoAndThree.cshtml".
31: // If in preview mode,
32: // the 'first' view will be return as we set the index initial value to '1'.
33: return PartialView(string.Format("~/Views/Blocks/{0}/{1}.cshtml",
34: currentBlock.GetOriginalType().Name,
35: blockView),
36: currentBlock);
37: }
The code along with the inline comments should be quite self explanatory, but to sum up: The first item in the content area will now be rendered using the First.cshtml view, while item two and three will be rendered using the TwoAndThree.cshtml view (I guess I could have found a better name for that one), while the rest of the views will be rendered with the Index.cshtml view.
And finally: Keep in mind that while I’ve used the currentBlock object in all three views, I could just as well create view models, and populated them only with the data needed in the view. Performance wise, that would probably be a good idea.
NIce!
Love the player names! Great blog post
Brilliant! A little bit disappointed with Michu's performance this month though.
Thanks! I'm sure Michu will be better next month. Saving a spot for him on my fpl team.
Nice work, thanks for sharing. The IndexOf method on the Contents property of ContentArea, did you write that yourself? Can't find it as part of LINQ, nor as an extension method in the EPiServer namespaces.
Yes, that is an extension I made:
(this IEnumerable source, T value)
.Default;
public static int IndexOf
{
int index = 0;
var comparer = EqualityComparer
foreach (T item in source)
{
if (comparer.Equals(item, value)) return index;
index++;
}
return -1;
}
How do you get the current ContentArea tag when using a page as a block?ControllerContext.ParentActionViewContext.ViewData["Tag"] as string; does not work.
Sigve, it works for me. Did a simple test:
[TemplateDescriptor(
TemplateTypeCategory = TemplateTypeCategories.MvcPartialController,
Inherited = true)]
public class TestPartialController : PageController
{
public ActionResult Index(SitePageData currentPage)
{
var tag = ControllerContext.ParentActionViewContext.ViewData["Tag"] as string;
return View(currentPage);
}
}
What if you had the same block added twice to the same ContentArea?
I guess you would need to some extra logic in order to get that working, Alf. Like saving some sort of index key in the TempData. However, with EPiServer 7.5, using DisplayOptions may be a better option than this approach.
Is it possible to get the actual ContentArea using webforms too?
Haven't tried it, but I suppose you could. You should be able to get the current page with:
();
var pageRouteHelper = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance
PageReference currentPageLink = pageRouteHelper.PageLink;
Hi Per
Can't figure out how to get the Name of ContentArea. I would like to render different html in the block depending on which area it is on the page. Would appreciate if you could share your ideas.
A solution to my problem, that I could find is to pass additional info (area name) into ViewData when rendering the area:
@Html.PropertyFor(m => m.SideArea, new { ContentAreaName="SideArea"})
Then it's accessible in the block controller as you described.
Andrew,
it sounds to me like you should rather use tags and template descriptors in your situations. If you are not familiar with template descriptors your should check out the TeaserBlockWide in the Alloy templates.
Hi! Thanks for a nice post!
I found that the ContentArea.Contents property is now deprecated so i did this instead using the Items.
index = currentContentArea.Items.Select(p=>p.ContentLink).IndexOf(CurrentData.ContentLink) + 1;
And that did the job for me! | https://world.optimizely.com/blogs/Per-Magne-Skuseth/Dates/2013/8/Letting-your-blocks-know-where-they-are/ | CC-MAIN-2021-39 | refinedweb | 976 | 56.35 |
Qtopia can be compiled in a number of ways. The two most common ways are:
There are a number of benefits to single-exec as follows:
The main idea behind single-exec is to make it possible to statically link the libraries to the programs. Normally if you did this, the size would be massive, each application having a copy of all the libraries. But by compiling all the application code in to a single binary, this is not a problem. Normally if one did this, you might just have one process, and in that process create new top level widgets of the different applications within that process, but this is not a very stable model, a single application fault brings down the whole system. Therefore it is necessary to run the applications as separate processes.
When an application is started in single-exec, we fork the server process, and execute the same binary again, but with an argv list that will inform the newly created process what application it should be. This model is very similar to that used by a UNIX tool called busybox which morphs in to different programs based on argv[0].
The size benefit of single-exec comes from static linking. When the linker combines together the code, it performs various size optimizations such as:
One important thing to be aware of when building single-exec with additional 3rd party components is that the symbols must not clash with those from other applications, use of C++ namespaces would be a very good idea to avoid potential problems caused by this.
To build Qtopia as a single-exec binary: | http://doc.trolltech.com/qtopia2.2/html/single_exec.html | crawl-001 | refinedweb | 273 | 55.37 |
>
Alright everyone I think I got a tricky one for ya. So im making a 2D platformer where the player has a small collider attached to his feet called groundCheck. Its your basic ground check where if the player is not on the "ground", they cant keep jumping or walking. Everything seems to work fine except when I test it on my phone. In the game, if you jump to a platform and miss it, the player falls for a second and then hits an empty game object with a "Hazards" script attached to it. It the player tagged "Player" hits this collider, they spawn back to the beginning of the level to restart. Again, this works well when testing in unity but not quite when tested on the phone.
On the phone, if the player misses a platform and falls onto the hazard border, they will die (like they should) but if they keep pressing the jump icon, the player will jump one time and then when they hit the hazard border the second time, they will die. The jump button works fine in all other parts of the game, they can not continuously jump in the air or anything, its just when they are hitting the hazard colliders. Its puzzling because the border hazards have no affiliation with "ground" and should not allow the player to jump one or two times before dying! Plus its hard to test because like I said, it works fine on the computer but not the phone. Could it be my Jump touch button from my canvas? Sorry Im typing so much, I will upload anything you guys need me to. Thanks for the help!
Answer by bgprocks
·
Jul 31, 2017 at 07:59 PM
are you using coroutines at all, how are you processing the jump request. It sounds like you have an order of operations issue. Like your jump is getting processed before the collision code. one trick you can do is disable jumping as soon as the user is lower that the platform, or have a trigger object below the platform but above the hazard, once the player hit the trigger disable processing jump request.
I think you may be on to something, its really the only thing I can think of that makes sense. Im going to put up some bits of code.
This is everything that has to do with jumping from my Touch code (this is the code for the jump button on the canvas that the player interacts with through the touch screen):
public void Jump()
{
player.jump = true;
}
This is all the jump related code attached to my Player:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
using UnityEngine.EventSystems; public class Player : MonoBehaviour {
public float maxSpeed = 3;
public float speed = 50f;
public float jumpPower = 150f;
public bool jump;//this was added
public float jumpheight;
public bool grounded;
void Update() { anim.SetBool("Grounded", grounded); //This Jump code is to jump when space bar is pressed in unity if (Input.GetButtonDown("Jump") && grounded) { rb2d.AddForce(Vector2.up * jumpPower);
}
if ((jump) && grounded)//for jumping with the touch screen button
{
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpheight);
jump = false;
}
} void FixedUpdate() { //Fake friction / Easing the x speed of our player if (grounded) { rb2d.velocity = easeVelocity; }
And possibly most importantly, this is my GroundCheck code:
public class GroundCheck : MonoBehaviour {
private Player player;
void Start()
{
player = gameObject.GetComponentInParent<Player>();
}
void OnTriggerEnter2D(Collider2D col)
{
player.grounded = true;
}
void OnTriggerStay2D(Collider2D col)
{
player.grounded = true;
}
void OnTriggerExit2D(Collider2D col)
{
player.grounded = false;
}
}
Let me know if anything stands out! :)
Nothing is jumping out at me (not a pun) but will look it over again when I reboot my.
My 2d player controller doesnt work very well. Any tips on fixing it?
0
Answers
I need help with a movement script
1
Answer
Inconsistent jumping with character controller
1
Answer
2D Charachter infinite jumping
0
Answers
Why is this code glitching?
2
Answers | https://answers.unity.com/questions/1387343/player-can-jump-on-invisible-non-ground-items.html | CC-MAIN-2019-22 | refinedweb | 665 | 63.8 |
On Fri, May 14, 2021 at 02:39:12PM +0300, Nir Soffer wrote: > On Fri, May 14, 2021 at 12:07 PM Richard W.M. Jones <rjones redhat com> wrote: > > > > On top of the previous commit which enabled multithreading but > > continued to use the synchronous libnbd API, this allows each thread > > to issue commands asynchronously. Because there is still a single > > handle, this introduces a single background thread to poll the file > > descriptor and dispatch the commands. > > This is only a little bit faster (compare to results in previous > > commit message): > > > > READ: bw=250MiB/s (262MB/s), 62.4MiB/s-62.4MiB/s (65.4MB/s-65.5MB/s), io=4096MiB (4295MB), run=16398-16411msec > > > > A future multi-conn version of nbdfuse would likely use multiple > > background threads (one per connection) to do the same job, but that > > is left for future work. > > --- > > fuse/nbdfuse.c | 5 ++ > > fuse/nbdfuse.h | 1 + > > fuse/operations.c | 181 +++++++++++++++++++++++++++++++++++++++++----- > > 3 files changed, 169 insertions(+), 18 deletions(-) > > > > diff --git a/fuse/nbdfuse.c b/fuse/nbdfuse.c > > index fa35080..f91ff7f 100644 > > --- a/fuse/nbdfuse.c > > +++ b/fuse/nbdfuse.c > > @@ -426,6 +426,11 @@ main (int argc, char *argv[]) > > if (nbd_is_read_only (nbd) > 0) > > readonly = true; > > > > + /* Create the background thread which is used to dispatch NBD > > + * operations. > > + */ > > + start_operations_thread (); > > + > > /* This is just used to give an unchanging time when they stat in > > * the mountpoint. > > */ > > diff --git a/fuse/nbdfuse.h b/fuse/nbdfuse.h > > index 1f8f703..016c325 100644 > > --- a/fuse/nbdfuse.h > > +++ b/fuse/nbdfuse.h > > @@ -36,5 +36,6 @@ extern char *filename; > > extern uint64_t size; > > > > extern struct fuse_operations nbdfuse_operations; > > +extern void start_operations_thread (void); > > > > #endif /* LIBNBD_NBDFUSE_H */ > > diff --git a/fuse/operations.c b/fuse/operations.c > > index 4da701e..1e81593 100644 > > --- a/fuse/operations.c > > +++ b/fuse/operations.c > > @@ -39,6 +39,7 @@ > > #include <assert.h> > > #include <sys/types.h> > > #include <sys/stat.h> > > +#include <pthread.h> > > > > #include <libnbd.h> > > > > @@ -47,14 +48,90 @@ > > > > #define MAX_REQUEST_SIZE (32 * 1024 * 1024) > > > > -/* Wraps calls to libnbd functions and automatically checks for error, > > - * returning errors in the format required by FUSE. It also prints > > - * out the full error message on stderr, so that we don't lose it. > > +/* Number of seconds to wait for commands to complete when closing the file. */ > > +#define RELEASE_TIMEOUT 5 > > + > > +/* This operations background thread runs while nbdfuse is running and > > + * is responsible for dispatching AIO commands. > > + * > > + * The commands themselves are initiated by the FUSE threads (by > > + * calling eg. nbd_aio_pread), and then those threads call > > + * wait_for_completion() which waits for the command to retire. > > + * > > + * A condition variable is signalled by any FUSE thread when it has > > + * started a new AIO command and wants the operations thread to start > > + * processing (if it isn't doing so already). To signal completion we > > + * use a completion callback which signals a per-thread completion > > + * condition. > > */ > > -#define CHECK_NBD_ERROR(CALL) \ > > - do { if ((CALL) == -1) return check_nbd_error (); } while (0) > > +static void *operations_thread (void *); > > + > > +void > > +start_operations_thread (void) > > +{ > > + int err; > > + pthread_t t; > > + > > + err = pthread_create (&t, NULL, operations_thread, NULL); > > + if (err != 0) { > > + errno = err; > > + perror ("nbdfuse: pthread_create"); > > + exit (EXIT_FAILURE); > > + } > > +} > > + > > +static pthread_mutex_t start_mutex = PTHREAD_MUTEX_INITIALIZER; > > +static pthread_cond_t start_cond = PTHREAD_COND_INITIALIZER; > > + > > +struct completion { > > + pthread_mutex_t mutex; > > + pthread_cond_t cond; > > + bool completed; > > +} completion; > > + > > +static void * > > +operations_thread (void *arg) > > +{ > > + while (1) { > > + /* Sleep until a command is in flight. */ > > + pthread_mutex_lock (&start_mutex); > > + while (nbd_aio_in_flight (nbd) == 0) > > + pthread_cond_wait (&start_cond, &start_mutex); > > + pthread_mutex_unlock (&start_mutex); > > + > > + /* Dispatch work while there are commands in flight. */ > > + while (nbd_aio_in_flight (nbd) > 0) > > + nbd_poll (nbd, -1); > > Just to make sure I understand this correctly - this runs all completion > callbacks? I wasn't sure if your comment refers only to nbd_poll or to the whole while() loop, so I'll talk about both. nbd_poll is tricky to understand without looking at the implementation: You can see that each call of nbd_poll first sleeps until the file descriptor is ready, then it runs [nbd_unlocked_aio_notify*] the state machine until it would block again once, then it returns. Now how many completion callbacks might run during one nbd_poll is not well defined. It's possible to have a scenario where you have 2 or more commands in flight waiting for the server to reply, and then in the single call to nbd_unlocked_aio_notify* both commands would complete. It's also possible no commands will complete. As for the while loop, it continues until there are no more commands in flight (all have retired). After this we go back to sleeping on start_cond. Hopefully there isn't a race condition - I don't think there is ... > Would be nice to mention this in the comment. > > > + } > > + > > + /*NOTREACHED*/ > > + return NULL; > > +} > > + > > +/* Completion callback - called from the operations thread when a > > + * command completes. > > + */ > > +static int > > +completion_callback (void *vp, int *error) > > +{ > > + struct completion *completion = vp; > > + > > + /* Mark the command as completed. */ > > + completion->completed = true; > > I think changing this after locking the completion mutex will > be better. The mutx will ensure proper ordering of things and > it matches the code checking this flag while the mutex is locked. Yes, good point: > > + > > + pthread_mutex_lock (&completion->mutex); + completion->completed = true; <-- here I think. > > + pthread_cond_signal (&completion->cond); > > + pthread_mutex_unlock (&completion->mutex); > > + > > + /* Don't retire the command. We want to get the error indication in > > + * the FUSE thread. > > + */ > > + return 0; > > How retiring the command affects the error indicator? > > libnbd errors are stored in thread local storage - how does it > work when another thread is polling? nbd_aio_command_completed is called from the FUSE thread and sets the error, so I guess we're OK ... > > +} > > + > > +/* Report an NBD error and return -errno. */ > > static int > > -check_nbd_error (void) > > +report_nbd_error (void) > > { > > int err; > > > > @@ -66,6 +143,55 @@ check_nbd_error (void) > > return -EIO; > > } > > > > +static int > > +wait_for_completion (struct completion *completion, int64_t cookie) > > +{ > > + int r; > > + > > + /* Signal to the operations thread to start work, in case it is sleeping. */ > > + pthread_mutex_lock (&start_mutex); > > + pthread_cond_signal (&start_cond); > > + pthread_mutex_unlock (&start_mutex); > > + > > + /* Wait until the completion_callback sets the completed flag. > > + * > > + * We cannot call nbd_aio_command_completed yet because that can > > + * lead to a possible deadlock where completion_callback holds the > > + * NBD handle lock and we try to acquire it by calling > > + * nbd_aio_command_completed. That is the reason for the > > + * completion.completed flag. > > + */ > > + pthread_mutex_lock (&completion->mutex); > > + while (!completion->completed) > > + pthread_cond_wait (&completion->cond, &completion->mutex); > > + pthread_mutex_unlock (&completion->mutex); > > + > > + /* nbd_aio_command_completed returns: > > + * 0 => command still in flight (should be impossible) > > + * 1 => completed successfully > > + * -1 => error > > + */ > > + r = nbd_aio_command_completed (nbd, cookie); > > + assert (r != 0); > > + return r; > > +} > > + > > +/* Wrap calls to any asynch command and check the error. */ > > +#define CHECK_NBD_ASYNC_ERROR(CALL) > > + do { \ > > + struct completion completion = \ > > + { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, false }; \ > > + nbd_completion_callback cb = \ > > + { .callback = completion_callback, .user_data = &completion }; \ > > + int64_t cookie = (CALL); \ > > + if (cookie == -1 || wait_for_completion (&completion, cookie) == -1) \ > > + return report_nbd_error (); > > This runs in the fuse thread, but the error was detected in the operations > thread. Do we pass the error to the thread starting the async io request > in some way? Yes, I think so. When wait_for_completion (in the FUSE thread) calls nbd_aio_command_completed, the error is set. > Looks good, I'm not sure there is a better way to use a single handle from > multiple threads. > > It looks like a generic infrastructure that could be part of the library like > nbd_poll(). Yup - I think I'd want something which is a bit more efficient though, since there appears to be a lot of overhead from the conditions / thread switching. I'm still playing with this to see if more FUSE threads help. At the moment with 4 FIO jobs, FUSE runs about 4 threads (sometimes one more), but I know that 4 commands in flight is not nearly enough to keep the NBD server busy. Rich. -- Richard Jones, Virtualization Group, Red Hat Read my programming and virtualization blog: libguestfs lets you edit virtual machines. Supports shell scripting, bindings from many languages. | https://listman.redhat.com/archives/libguestfs/2021-May/msg00091.html | CC-MAIN-2021-31 | refinedweb | 1,237 | 56.05 |
Jun-ichiro itojun Hagino
KAME Project
Research Laboratory, Internet Initiative Japan Inc.
itojun@iijlab.net
We at the KAME project
are implementing IPv6 and IPsec support code on top of 4.4BSD.
To cope with the problems, we have introduced the following changes:
(1) a new function called
m_pulldown,
which adjusts the mbuf chain with a minimal number of copies/allocations, and
(2) a new calling sequence for parsing inbound packet headers.
These changes allow us to manipulate incoming packets in a safer,
more efficient, and more spec-conformant way.
The technique described in this paper is integrated into the KAME IPv6/IPsec
stack kit, and is freely available under BSD copyright.
The KAME codebase is being merged into NetBSD, OpenBSD and FreeBSD.
An integration into BSD/OS is planned.
The 4.4BSD network code holds a packet in a chain of ``mbuf'' structures.
Each mbuf structure has three flavors:
When processing inbound packets, 4.4BSD uses a function called
m_pullup
to ease the manipulation of data content in the mbufs.
It also uses a deep function call tree for inbound packet processing.
While these two items work just fine for traditional IPv4 processing,
they do not work as well with IPv6 and IPsec processing.
For input packet processing,
the 4.4BSD network stack uses the
m_pullup
function to ease parsing efforts
by adjusting the data content in mbufs for placement onto the continuous memory
region.
m_pullup
is defined as follows:
struct mbuf *
m_pullup(m, len)
struct mbuf *m;
int len;
(figure omitted from html version)
Figure 1: IPv6 extension header chain
IPv6 specification (Deering, 1998)
and IPsec specification (Kent, 1998)
allow more flexible use of protocol headers
by introducing chained extension headers.
With chained extension headers, each header has a ``next header field'' in it.
A chain of headers can be made as shown
in Figure 1.
The type of protocol header is determined by
inspecting the previous protocol header.
There is no restriction in the number of extension headers in the spec.
Because of extension header chains, there is now no upper limit in
protocol packet header length.
The
m_pullup
function would impose unnecessary restriction
to the extension header processing.
In addition,
with the introduction of IPsec, it is now impossible to strip off extension headers
during inbound packet processing.
All of the data on the packet must be retained if it is to be authenticated
using Authentication Header (Kent, 1998).
Continuing the use of
m_pullup
will limit the
number of extension headers allowed on the packet,
and could jeopadize the possible usefulness of IPv6 extension headers.
(NOTE:
In IPv4 days, the IPv4 options turned out to be unusable
due to a lack of implementation.
This was because most commercial products simply did not support IPv4 options.
)
Another problem related to
m_pullup
is that it tends to copy the protocol header even
when it is unnecessary to do so.
For example, consider the mbuf chain shown
in Figure 2:
struct ip *ip;
struct tcphdr *th;
ip = mtod(m, struct ip *);
/* extra copy with m_pullup */
m = m_pullup(m, iphdrlen + tcphdrlen);
/* MUST reinit ip */
ip = mtod(m, struct ip *);
th = mtod(m, caddr_t) + iphdrlen;
The problems can be summarized as follows:
(1)
m_pullup
imposes too strong restriction
on the total length of the packet header (MHLEN);
(2)
m_pullup
makes an extra copy even when this can be avoided; and
(3)
m_pullup
requires the caller to reinitialize all of the pointers into the mbuf chain.
Under 4.4BSD, protocol header processing will make a chain of function calls.
For example, if we have an IPv4 TCP packet, the following function call chain will be made
(see Figure 4):
If chained extension headers are handled as described above,
the kernel stack can overflow by a deep function call chain, as shown in
Figure 5.
IPv6/IPsec specifications do not define any upper limit
to the number of extension headers on a packet,
so a malicious party can transmit a ``legal'' packet with a large number of chained
headers in order to attack IPv6/IPsec implementations.
We have experienced kernel stack overflow in IPsec code,
tunnelled packet processing code, and in several other cases.
The IPsec processing routines tend to use a large chunk of memory
on the kernel stack, in order to hold intermediate data and the secret keys
used for encryption.
(NOTE:
For example, blowfish encryption processing code typically uses
an intermediate data region of 4K or more.
With typical 4.4BSD installation on i386 architecture,
the kernel stack region occupies less than 8K bytes and does not grow on demand.
)
We cannot put the intermediate data region into a static data region outside of
the kernel stack,
because it would become a source of performance drawback on multiprocessors
due to data locking.
Even though the IPv6 specifications do not define any restrictions
on the number of extension headers, it may be possible
to impose additional restriction in an IPv6 implementation for safety.
In any case, it is not possible to estimate the amount of the
kernel stack, which will be used by protocol handlers.
We need a better calling convention for IPv6/IPsec header processing,
regardless of the limits in the number of extension headers we may impose.
This section describes the approaches we at the KAME project
took against the problems mentioned in the previous section.
We introduce a new function called
m_pulldown,
in place of
m_pullup,
for adjusting payload data in the mbuf.
We also change the calling sequence for the protocol input function.
In the early days of IPv6/IPsec development,
the Japanese research community felt it very important to make
a reference code available in a freely-redistributable form
for educational, research and deployment purposes.
The KAME project is a consortium of 7 Japanese companies and
an academic research group.
The project aims to deliver IPv6/IPsec reference implementation
for 4.4BSD, under BSD license.
The KAME project intends to deliver the most
spec-conformant IPv6/IPsec implementation possible.
Here we introduce a new function,
m_pulldown,
to address the 3 problems with
m_pullup
that we have described above.
The actual source code is included at the end of this paper.
The function prototype is as follows:
struct mbuf *
m_pulldown(m, off, len, offp)
struct mbuf *m;
int off, len;
int *offp;
For IPv6 processing, our code does not make a deep function call chain.
Rather, we make a loop in the very last part of
ip6_input,
as shown in Figure 8.
IPPROTO_DONE is a pseudo-protocol type value that identifies the end of the
extension header chain.
If more protocol headers exist,
each header processing code will update the pointer variables
and return the next extension header type.
If the final header in the chain has been reached,
IPPROTO_DONE is returned.
With this code, we no longer have a deep call chain for IPv6/IPsec processing.
Rather,
ip6_input
will make calls to each extension header processor
directly.
This avoids the possibility of overflowing the kernel stack due to multiple
extension header processing.
Regardless of the calling sequence imposed by the
pr_input
function prototype, it is important not to use up the kernel
stack region in protocol handlers.
Sometimes it is necessary to decrease the size of kernel stack usage
by using pointer variables and dynamically allocated regions.
struct ip6protosw {
int (*pr_input) __P((struct mbuf **, int *, int));
/* and other members */
};
ip6_input(m)
struct mbuf *m;
{
/* in the very last part */
extern struct ip6protosw inet6sw[];
/* the first one in extension header chain */
nxt = ip6.ip6_nxt;
while (nxt != IPPROTO_DONE)
nxt = (*inet6sw[ip6_protox[nxt]].pr_input)(&m, &off, nxt);
}
/* in each header processing code */
int
foohdr_input(mp, offp, proto)
struct mbuf **mp;
int *offp;
int proto;
{
/* some processing, may modify mbuf chain */
if (we have more header to go) {
*mp = newm;
*offp = nxtoff;
return nxt;
} else {
m_freem(newm);
return IPPROTO_DONE;
}
}
Many BSD-based IPv6 stacks have been implemented.
While the most popular stacks include NRL, INRIA and KAME,
dozens of other BSD-based IPv6 implementations have been made.
This section presents alternative approaches for purposes of comparison.
The latest NRL IPv6 release copes with the
m_pullup
limitation by introducing a new function,
m_pullup2.
m_pullup2
works similarly to
m_pullup,
but it allows
len
to extend up to MCLBYTES, which corresponds to 2048 bytes in a typical installation.
When
the
len
parameter is smaller than or equal to MHLEN,
m_pullup2
simply calls
m_pullup
from the inside.
While
m_pullup2
works well for packet headers up to MCLBYTES with very little change
in code, it does not avoid making unnecessary copies.
It also imposes restrictions on the total length of packet headers.
The assumption here is that the total length of packet headers is less than
MCLBYTES.
The Hydrangea IPv6 stack was implemented by a group of Japanese researchers,
and is one of the ancestors of the KAME IPv6 stack.
The Hydrangea IPv6 stack avoids the need for
m_pullup
by modifying the mbuf allocation policy in drivers.
For inbound packets, the drivers allocate mbufs by using the
m_devget
function, or by re-implementing the behavior of
m_devget.
m_devget
allocates mbuf as follows:
This approach worked well in most cases, but failed for (1) loopback interface,
(2) tunnelled packets, and (3) non-conforming drivers.
With the Hydrangea approach, every device driver had to be examined
to ensure the new mbuf allocation policy.
We could not be sure if the constraint was guaranteed until we checked the
driver code,
and the Hydrangea approach raised many support issues.
This was one of our motivations for introducing
m_pulldown.
This section compares the following three approaches in terms of
their characteristics and actual behavior:
(1) 4.4BSD
m_pullup,
(2) NRL
m_pullup2,
and (3) KAME
m_pulldown.
Table 1 shows the assumptions made by each of the three approaches.
As mentioned earlier,
m_pullup
imposes too stringent requirement for the total length of packet headers.
m_pullup2
is workable in most cases, although
this approach adds more restrictions than the specification claims.
m_pulldown
assumes that the single packet header is smaller than MCLBYTES,
but makes
no restriction regarding the total length of packet headers.
With a standard mbuf chain,
this is the best
m_pulldown
can do, since there is no way to hold continuous region longer than MCLBYTES.
This characteristic can contribute to better specification conformance,
since
m_pulldown
will impose fewer additional restrictions due to the
requirements of implementation.
Among the three approaches, only
m_pulldown
avoids making unnecessary copies of intermediate header data and
avoids pointer reinitialization after calls to these functions.
These attributes result in smaller overhead during input packet processing.
At present,
we know of no other 4.4BSD-based IPv6/IPsec stack that addresses kernel
stack overflow issues,
although we are open to
new perspectives and new information.
To compare the behavior and performance of
m_pulldown
against
m_pullup
and
m_pullup2
using the same set of traffic and
mbuf chains, we have gathered simulated statistics for
m_pullup
and
m_pullup2,
in
m_pulldown
function.
By running a kernel using the modified
m_pulldown
function,
we can easily
gather statistics for these three functions against exactly the same traffic.
The comparison was made on a computer
(with Celeron 366MHz CPU, 192M bytes of memory)
running NetBSD 1.4.1 with the KAME IPv6/IPsec stack.
Network drivers allocate mbufs just as normal 4.4BSD does.
m_pulldown
is called whenever it is needed to ensure continuity in packet data
during inbound packet processing.
The role of the computer is as an end node, not a router.
To describe the content of the following table,
we must look at the source code fragment.
Figure 8
shows the code fragment from our source code.
The code fragment will
(1) make the TCP header on the mbuf chain
m
at offset
hdrlen
continuous, and (2) point the region with pointer
th.
We use a macro named IP6_EXTHDR_CHECK,
and the code before and after the macro expansion is shown in the figure.
/* ensure that *th from hdrlen is continuous */
/* before macro expansion... */
struct tcphdr *th;
IP6_EXTHDR_CHECK(th, struct tcphdr *, m,
hdrlen, sizeof(*th));
if (th == NULL)
return; /*m is already freed*/
/* after macro expansion... */
struct tcphdr *th;
int off;
struct mbuf *n;
if (m->m_len < hdrlen + sizeof(*th)) {
n = m_pulldown(m, hdrlen, sizeof(*th), &off);
if (n)
th = (struct tcphdr *)(mtod(n, caddr_t) + off);
else
th = NULL;
} else
th = (struct tcphdr *)(mtod(m, caddr_t) + hdrlen);
if (th == NULL)
return;
From these measured results, we obtain several interesting observations.
m_pullup
actually failed on IPv6 trafic.
If an IPv6 implementation uses
m_pullup
for IPv6 input processing,
it must be coded carefully so as to avoid trying
m_pullup
against any length longer than MHLEN.
To achieve this end, the code copies the data portion from the mbuf
chain to a separate buffer, and the cost of memory copies becomes a penalty.
Due to the nature of this simulation,
the comparison described above may contain an implicit bias.
Since the IPv6 protocol processing code is written by using
m_pulldown,
the code is somewhat biased toward
m_pulldown.
If a programmer had to write the entire IPv6 protocol processing with
m_pullup
only, he or she would use
m_copydata
to copy intermediate
extension headers buried deep inside the header chains,
thus making it unnecessary to call
m_pullup.
In any case, a call to
m_copydata
will result in a data copy,
which causes extra overhead.
In all cases, the number of length checks (second column) exceeds the
number of inbound packets.
This behavior is the same as in the original 4.4BSD stack;
we did not add a significant number of length checks to the code.
This is because
m_pulldown
(or
m_pullup
in the 4.4BSD case)
is called
as necessary during the parsing of the headers.
For example, to process a TCP-over-IPv6 packet, at least 3
checks would be made against m->m_len;
these checks would be made
to grab the IPv6 header (40 bytes),
to grab the TCP header (20 bytes), and to grab the TCP header
and options (20 to 60 bytes).
The length of the TCP option part is kept inside the TCP header,
so the length needs to be checked twice for the TCP part.
In the tests, the number of copies made in the
m_pullup2
case is similar to the number made in the
m_pulldown
case.
m_pulldown
makes less copies than
m_pullup2
against packets like below:
node A (source) = 2001:240:0:200:260:97ff:fe07:69ea
node B (destination) = 2001:240:0:200:a00:5aff:fe38:6f86
17:39:43.346078 A > B:
srcrt (type=0,segleft=4,[0]B,[1]B,[2]B,[3]B):
icmp6: echo request (len 88, hlim 64)
6000 0000 0058 2b40 2001 0240 0000 0200
0260 97ff fe07 69ea 2001 0240 0000 0200
0a00 5aff fe38 6f86 3a08 0004 0000 0000
2001 0240 0000 0200 0a00 5aff fe38 6f86
2001 0240 0000 0200 0a00 5aff fe38 6f86
2001 0240 0000 0200 0a00 5aff fe38 6f86
2001 0240 0000 0200 0a00 5aff fe38 6f86
8000 b650 030e 00c8 ce6e fd38 d553 0700
During the test, we experienced no kernel stack overflow,
thanks to a new calling sequence between IPv6 protocol handlers.
The number of copies and mbuf allocations vary very much by tests.
We need to investigate the traffic characteristic more carefully,
for example, about the average length of header portion in packets.
Van Jacobson proposed pbuf structure
(NOTE:
A reference should be here,
but I'm having hard time finding published literature for it.
)
as an alternative to BSD mbuf structure.
The proposal has two main arguments.
First is the use of continuous data buffer, instead of chained fragments
like mbufs.
Another is the improvement to TCP performance by restructuring
TCP input/output handling.
While the latter point still holds for IPv6,
we believe that the former point must be reviewed carefully before being used with IPv6.
Our experience suggests that we need to insert many intermediate extension headers into
the packet data during IPv6 outbound packet processing.
We believe that mbuf is more suitable
than the proposed pbuf structure for handling the packet data efficiently.
Using pbuf may result in the making of more copies than in the mbuf case.
In a cross-BSD portability paper (Metz, 1999),
Craig Metz described
nbuf
structure in NRL IPv6/IPsec stack.
nbuf is a wrapper structure used to unify linux linear-buffer packet management
and BSD mbuf structure, and is not closely related to the topic of this paper.
The
m_pullup2
example discussed in this paper is drawn from the NRL implementation.
This paper discussed mbuf manipulation in a 4.4BSD-based IPv6/IPsec stack,
namely KAME IPv6/IPsec implementation.
4.4BSD makes certain assumptions regarding packet header length and its format.
For IPv6/IPsec support, we removed those assumptions from the
4.4BSD code.
We introduced the
m_pulldown
function and a new function call sequence for inbound packet processing.
These innovations helped us to implement IPv6/IPsec in a very spec-conformant manner,
with fewer implementation restrictions added against specifications.
The described code is publically available, under a BSD-like license,
at.
KAME IPv6/IPsec stack is being merged into 4.4BSD variants like FreeBSD,
NetBSD and OpenBSD.
An integration into BSD/OS is planned.
We will be able to see official releases of these OSes with KAME code soon.
The paper was made possible by the collective efforts of researchers at
the KAME project and the WIDE project and of other IPv6 implementers at large.
We would also like to acknowledge all four BSD groups who helped
us improve the KAME IPv6 stack code
by sending bug reports and improvement suggestions,
and the Freenix reviewers helped polish the paper.
/*
* ensure that [off, off + len) is contiguous on the mbuf chain "m".
* packet chain before "off" is kept untouched.
* if offp == NULL, the target will start at <retval, 0> on resulting chain.
* if offp != NULL, the target will start at <retval, *offp> on resulting chain.
*
* on error return (NULL return value), original "m" will be freed.
*
* XXX M_TRAILINGSPACE/M_LEADINGSPACE on shared cluster (sharedcluster)
*/
struct mbuf *
m_pulldown(m, off, len, offp)
struct mbuf *m;
int off, len;
int *offp;
{
struct mbuf *n, *o;
int hlen, tlen, olen;
int sharedcluster;
/* check invalid arguments. */
if (m == NULL)
panic("m == NULL in m_pulldown()");
if (len > MCLBYTES) {
m_freem(m);
return NULL; /* impossible */
}
n = m;
while (n != NULL && off > 0) {
if (n->m_len > off)
break;
off -= n->m_len;
n = n->m_next;
}
/* be sure to point non-empty mbuf */
while (n != NULL && n->m_len == 0)
n = n->m_next;
if (!n) {
m_freem(m);
return NULL; /* mbuf chain too short */
}
/*
* the target data is on <n, off>.
* if we got enough data on the mbuf "n", we're done.
*/
if ((off == 0 || offp) && len <= n->m_len - off)
goto ok;
/*
* when len < n->m_len - off and off != 0, it is a special case.
* len bytes from <n, off> sits in single mbuf, but the caller does
* not like the starting position (off).
* chop the current mbuf into two pieces, set off to 0.
*/
if (len < n->m_len - off) {
o = m_copym(n, off, n->m_len - off, M_DONTWAIT);
if (o == NULL) {
m_freem(m);
return NULL; /* ENOBUFS */
}
n->m_len = off;
o->m_next = n->m_next;
n->m_next = o;
n = n->m_next;
off = 0;
goto ok;
}
/*
* we need to take hlen from <n, off> and tlen from <n->m_next, 0>,
* and construct contiguous mbuf with m_len == len.
* note that hlen + tlen == len, and tlen > 0.
*/
hlen = n->m_len - off;
tlen = len - hlen;
/*
* ensure that we have enough trailing data on mbuf chain.
* if not, we can do nothing about the chain.
*/
olen = 0;
for (o = n->m_next; o != NULL; o = o->m_next)
olen += o->m_len;
if (hlen + olen < len) {
m_freem(m);
return NULL; /* mbuf chain too short */
}
/*
* easy cases first.
* we need to use m_copydata() to get data from <n->m_next, 0>.
*/
if ((n->m_flags & M_EXT) == 0)
sharedcluster = 0;
else {
if (n->m_ext.ext_free)
sharedcluster = 1;
else if (MCLISREFERENCED(n))
sharedcluster = 1;
else
sharedcluster = 0;
}
if ((off == 0 || offp) && M_TRAILINGSPACE(n) >= tlen
&& !sharedcluster) {
m_copydata(n->m_next, 0, tlen, mtod(n, caddr_t) + n->m_len);
n->m_len += tlen;
m_adj(n->m_next, tlen);
goto ok;
}
if ((off == 0 || offp) && M_LEADINGSPACE(n->m_next) >= hlen
&& !sharedcluster) {
n->m_next->m_data -= hlen;
n->m_next->m_len += hlen;
bcopy(mtod(n, caddr_t) + off, mtod(n->m_next, caddr_t), hlen);
n->m_len -= hlen;
n = n->m_next;
off = 0;
goto ok;
}
/*
* now, we need to do the hard way. don't m_copy as there's no room
* on both end.
*/
MGET(o, M_DONTWAIT, m->m_type);
if (o == NULL) {
m_freem(m);
return NULL; /* ENOBUFS */
}
if (len > MHLEN) { /* use MHLEN just for safety */
MCLGET(o, M_DONTWAIT);
if ((o->m_flags & M_EXT) == 0) {
m_freem(m);
m_free(o);
return NULL; /* ENOBUFS */
}
}
/* get hlen from <n, off> into <o, 0> */
o->m_len = hlen;
bcopy(mtod(n, caddr_t) + off, mtod(o, caddr_t), hlen);
n->m_len -= hlen;
/* get tlen from <n->m_next, 0> into <o, hlen> */
m_copydata(n->m_next, 0, tlen, mtod(o, caddr_t) + o->m_len);
o->m_len += tlen;
m_adj(n->m_next, tlen);
o->m_next = n->m_next;
n->m_next = o;
n = o;
off = 0;
ok:
if (offp)
*offp = off;
return n;
} | http://static.usenix.org/publications/library/proceedings/usenix2000/freenix/full_papers/hagino/hagino_html/ | crawl-003 | refinedweb | 3,491 | 60.95 |
class Signal – control and sense external I/O devices¶
The Signal class is a simple extension of the
Pin class. Unlike Pin, which
can be only in “absolute” 0 and 1 states, a Signal can be in “asserted”
(on) or “deasserted” (off) states, while being inverted (active-low) or
not. In other words, it adds logical inversion support to Pin functionality.
While this may seem a simple addition, it is exactly what is needed to
support wide array of simple digital devices in a way portable across
different boards, which is one of the major MicroPython goals. Regardless
of whether different users have an active-high or active-low LED, a normally
open or normally closed relay - you can develop a single, nicely looking
application which works with each of them, and capture hardware
configuration differences in few lines in the config file of your app.
Example:
from machine import Pin, Signal # Suppose you have an active-high LED on pin 0 led1_pin = Pin(0, Pin.OUT) # ... and active-low LED on pin 1 led2_pin = Pin(1, Pin.OUT) # Now to light up both of them using Pin class, you'll need to set # them to different values led1_pin.value(1) led2_pin.value(0) # Signal class allows to abstract away active-high/active-low # difference led1 = Signal(led1_pin, invert=False) led2 = Signal(led2_pin, invert=True) # Now lighting up them looks the same led1.value(1) led2.value(1) # Even better: led1.on() led2.on()
Following is the guide when Signal vs Pin should be used:
- Use Signal: If you want to control a simple on/off (including software PWM!) devices like LEDs, multi-segment indicators, relays, buzzers, or read simple binary sensors, like normally open or normally closed buttons, pulled high or low, Reed switches, moisture/flame detectors, etc. etc. Summing up, if you have a real physical device/sensor requiring GPIO access, you likely should use a Signal.
- Use Pin: If you implement a higher-level protocol or bus to communicate with more complex devices.
The split between Pin and Signal come from the usecases above and the architecture of MicroPython: Pin offers the lowest overhead, which may be important when bit-banging protocols. But Signal adds additional flexibility on top of Pin, at the cost of minor overhead (much smaller than if you implemented active-high vs active-low device differences in Python manually!). Also, Pin is a low-level object which needs to be implemented for each support board, while Signal is a high-level object which comes for free once Pin is implemented.
If in doubt, give the Signal a try! Once again, it is offered to save developers from the need to handle unexciting differences like active-low vs active-high signals, and allow other users to share and enjoy your application, instead of being frustrated by the fact that it doesn’t work for them simply because their LEDs or relays are wired in a slightly different way.
Constructors¶
- class
machine.
Signal(pin_obj, invert=False)¶
- class
machine.
Signal(pin_arguments..., *, invert=False)
Create a Signal object. There’re two ways to create it:
- By wrapping existing Pin object - universal method which works for any board.
- By passing required Pin parameters directly to Signal constructor, skipping the need to create intermediate Pin object. Available on many, but not all boards.
The arguments are:
pin_objis existing Pin object.
pin_argumentsare the same arguments as can be passed to Pin constructor.
invert- if True, the signal will be inverted (active low).
Methods¶
Signal.
value([x])¶
This method allows to set and get the value of the signal, depending on whether the argument
xis supplied or not.
If the argument is omitted then this method gets the signal level, 1 meaning signal is asserted (active) and 0 - signal inactive.
If the argument is supplied then this method sets the signal level. The argument
xcan be anything that converts to a boolean. If it converts to
True, the signal is active, otherwise it is inactive.
Correspondence between signal being active and actual logic level on the underlying pin depends on whether signal is inverted (active-low) or not. For non-inverted signal, active status corresponds to logical 1, inactive - to logical 0. For inverted/active-low signal, active status corresponds to logical 0, while inactive - to logical 1. | http://docs.openmv.io/library/machine.Signal.html | CC-MAIN-2018-22 | refinedweb | 717 | 52.7 |
Adding Events
A natural part of control development is for the control to expose events that make it easier to interact with the control. The constituent controls of a control are not automatically exposed to users. To expose events, you can define an event for the control and raise that event in response to a change in state or an event of constituent controls. The code in Listing 4 shows how to raise a new event when the user clicks the "Visit Jane Doe's Web Site" link shown in Figure 1.
Listing 4 A Control Event
// notify user that site link was clicked public event EventHandler Click; // callback on Author's Site link click protected void AuthorSite_Click(object sender, EventArgs e) { EnsureChildControls(); // raise event if (Click != null) { Click(this, EventArgs.Empty); } // move to author's site Page.Response.Redirect(AuthorSite); }
As Listing 4 shows, there's nothing special about the basic code required to raise an event. Because the Click event of the AuthorBio control is public, it will appear on the Events tab of the Object Inspector, making it easy for web forms to hook up callbacks.
Recall that controls in a designer normally have a default event, and C#Builder generates code if you double-click the control on the design surface. You can achieve the same behavior by adding a DefaultEvent attribute to the AuthorBio control's class definition. Also, handlers for controls are not invoked automatically, as you would normally expect. You must add the INamingContainer interface to the class definition. The following code shows how to add both a DefaultEvent attribute and the INamingContainer interface.
[DefaultProperty("Text"), DefaultEvent("Click"), ToolboxData("<{0}:AuthorBio runat=server></{0}:AuthorBio>")] public class AuthorBio : System.Web.UI.WebControls.WebControl, INamingContainer { // class definition elided for clarity }
In the code snippet above, the DefaultEvent attribute identifies the Click event. In addition to letting the IDE generate code when the control is double-clicked, the default event gets the initial focus in the Object Inspector when you select the Events tab. The INamingContainer is a marker interface, meaning that it doesn't have members. When this control is rendered with its page, INamingContainer will let each item have a unique name and ensure that everything, including events, is processed okay. | http://www.informit.com/articles/article.aspx?p=170718&seqNum=5 | CC-MAIN-2017-43 | refinedweb | 378 | 52.7 |
CodePlexProject Hosting for Open Source Software
Here is some code that only fails (it compiles) when used in a WP7 project.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
using Test.Models;
using Newtonsoft.Json;
...
var tree = JObject.Parse(Json);
var temp =
from t in tree.Root["dates"].Children()
select new Schedule {DateString = (string) t["date_string"]};
...
It is a WP7.1 project and the JSON.NET dll I am using is:
...\packages\Newtonsoft.Json.4.0.7\lib\sl4-windowsphone71\Newtonsoft.Json.dll
Here is the exception I find inside temp:
'System.Collections.Generic.IEnumerable<Test.Models.Schedule>' does not contain a definition for 'System' and no extension method 'System' accepting a first argument of type 'System.Collections.Generic.IEnumerable<Test.Models.Schedule>'
could be found (are you missing a using directive or an assembly reference?)
The "var tree = JObject.Parse(Json);" line parses the json string and builds the tree with no problems.
The exact code runs perfectly in a Monodroid and C# library project (with appropriate JSON.NET builds).
Any ideas?
Thanks.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://json.codeplex.com/discussions/287738 | CC-MAIN-2017-13 | refinedweb | 216 | 55 |
For a Windows Phone 8 application, I always heard that data can be stored in the "isolated storage" of the phone.
After some research, I found two namespaces: LocalStorage (WinRT but supported too in WinPRT) and IsolatedStorage and they both seem to store data. This is what I understood so far :
In the IsolatedStorage, can data from various apps mix ?
I want a way to have a real safe isolated place to store data with no extenal interaction from other apps. This data could be settings preferences.
The problem is that I do not know very well those APIs and my testing programs
around them lead to new questions.
What is the real difference between those namespaces and which one could fulfill my need explained above ?
Both APIs are used to manipulate with an app file system and there is no a restriction for media files. The main difference between these two APIs is that
IsolatedStorage type is available just for Windows Phone applications and
ApplicationData type is available for Windows Phone applications as well as for Metro Windows 8 applications. So, if you are going to develop your app for both platforms: Windows Phone 8 and Windows 8, I would suggest you to use
ApplicationData API, so you can have a common services assembly that is used in both your projects, in WP8 and in Win8 too.
On the other hand, both APIs are completely safe. That's mean no any other application can access to the file system of your application.
But if you are going to develop an application for WP7.8 and WP8 then you have no choice and have to use
IsolatedStorage type. | http://m.dlxedu.com/m/askdetail/3/8122c96e9054d5def4084523899b05aa.html | CC-MAIN-2018-22 | refinedweb | 278 | 59.94 |
Getting, in 2013, nearly 2 years since the release of Rails 3.1, we no longer think about it. It has simply become part of our workflow when developing Rails applications. For no extra effort, we receive a performance boost on the client side of our applications. We are writing far better, best practice JavaScript by the virtue of CoffeeScript and no longer configuring asset packagers to concatenate and minify JavaScript and CSS. It just happens.
I also like to think it changed the way look at developing the client side of our applications. In the past year, I have probably spent more time working with JavaScript than ever before. Simply because it is no longer a pain to set up the way way I want it. I can keep it organized and, more importantly, these days it’s really easy to test.
Exponential improvements in the JavaScript engines that are plumbed into modern browsers has allowed sophisticated JS frameworks to evolve and flourish in the form of beautiful, snappy and responsive web applications.
This series is a kind of lessons learned from the frontline creating rich JS powered UI’s with Rails and focusses how to keep our client side code under control and never reverting to the “junk drawer” development days of yore.
With Great Power, yada, yada, yada
I say it flippantly, but as the client side of our applications become larger and exponentially more complex we really should be adopting the same practices we have adopted for our Ruby code.
Hands up if test drive your JavaScript?
These days I still expect to only see a few hands. I certainly didn’t test drive about a year ago. I had tests, but usually written long after the code. They were brittle and unmanageable, at best, when I did write them. Then came the day I got stung by a nasty bug amidst a mess of a jQuery and various (and not to mention numerous) associated plugins. I was well past the point of unmanageable. The most humane thing to do was put the poor thing down.
I opted to embrace some sort of framework (Backbone) and test framework (Jasmine). Even for trivial tasks I would create the Backbone view or model, drive it through tests and apply. The beauty of something like Backbone was, through it’s employ at will ethos, I could apply it to all the use cases regardless of how complex (or not) the scenario. I could also chip away one logical chunk at a time instead of an all out flame war.
I am not saying this is definitively the right way to approach your new or existing applications, but it’s certainly a right way.
Lets take a really simple, stupid scenario to illustrate. What springs to mind is one of the simple, free things that made me love rails, the flash. We want our flash to appear with a closing “X” control, if we hover over the flash it fades, clicking on the “X” it makes it disappear, it’s all very growl-like. The first thing we do is write a test.
Since we will be using Jasmine as our test framework, we’ll use the jasminerice gem. This removes the grunt of the pain we can feel dealing with the asset pipeline. To get jasminerice up and running you simply include the gem in your
Gemfile
group :development, :test do gem "jasminerice" end
And run the generator
rails g jasminerice:install which will set up a
javascripts directory within your
spec directory (assuming you are using rspec) and some helper files, a dummy test and some fixtures. Fixtures are very important when testing our backbone views. You will see how we use these in a minute.
Once you have jasminerice set up in your application, delete the dummy tests that were installed and create a fixture called
spec/javascripts/fixtures/flash.html with the following content
<div class="flash"><p>There is a message for the user <span class="close-alert">X</span></p></div>
This fixture is essentially the markup we will use in our application. It may differ slightly or alot but the essential ingredients are the class
flash on the outer
div and
close-alert on the
span within. Now we have enough to write a test.
Create a file
spec/javascripts/flash_spec.js.coffee with the following content.
describe "Closing the alert box", -> beforeEach -> loadFixtures 'flash' it 'will close on a click of the cross', -> view = new App.Flash() $('.close-alert').trigger('click') expect(view.$el).not.toBeVisible()
In the above spec we first load the fixture into the DOM, meaning, we place it on the spec runner page for the un-initiated. Jasminerice includes the helper
loadFixtures which creates a container
jasmine-fixtures and appends the loaded fixtures within it. When the spec is complete, it deletes the fixture from the DOM, a rather nifty helper.
The rest of the spec sets up a new instance of the flash, triggers a click on the close element and asserts that the DOM element is no longer visible.
For those who do not have a lot of experience with Backbone,
$el is the container for the view. By default it is a plain old
div, but you can set it to whatever you wish. I wont dwell on it too much but just be aware the
$el property you see in the above tests is a Backbone helper to pass the selector for the container element, it is equivalent to
$('<your-selector') in jQuery. But as we may never know the
<your-selector> of a view (dynamically set, or multiple elements on a single view in a collection) it is preferred to use
$el.
Run the suite by pointing the browser at. As expected we get a red suite with a valid enough failure. If we cheat a bit our first pass of getting green, create a file
app/assets/javascripts/app.js.coffee that looks something like:
window.App = {} App.Flash = Backbone.View.extend el: '.flash' events: { 'click .close-alert': 'closeAlert' } closeAlert: -> this.$el.fadeOut()
Here we setup a namespace for the application. This is good practice in the sense we are isolating our code in the global namespace. It is still a global, but we will be restricting our usage to a known sensible namespace,
App.
We then extend a Backbone view by setting the
el property and binding the click event to it’s handler. You have to love the simplicity of Backbone (especially when viewed in it’s CoffeeScript form). I especially love how the events are bound within the realms of the views
el so no more adding unique id’s to everything on
e.currentTarget handlers.
Running the test again, bummer, we still get red. What’s going on? Is jQuery broken? Of course not, remember we are dealing with a test on an event. The jQuery default animation time on
fadeOut is 400ms. Our test triggers the event, and almost immediately runs the expectation. Let’s fix that using the ignorant sleep equivalent approach:
it 'will close on a click of the cross', -> view = new App.Flash() $('.close-alert').trigger('click') waits 410 runs -> expect(view.$el).not.toBeVisible() it 'will close on a click of the cross', ->
Ok, the suite should now be green but we have injected a 410ms delay into it. We know that cannot be good.
Great Scott
It is time to introduce the best thing to happen to testing JavaScript sinon.js. It is chocolate to the peanut butter. Sinon is a real utility belt for testing JS. You can mock, spy, stub and call matcher assertions. Best of all, it plays very nicely with Jasmine (and all the other test frameworks as far as I’m aware). We are going to use sinon to bend time itself and remove that nasty wait/runs combo slowing up our test suite.
To include Sinon in the application simply download sinon.js into the freshly created
spec/javascripts/support directory. And include the following in the spec:
it 'will close on a click of the cross', -> clock = sinon.useFakeTimers(); view = new App.Flash() $('.close-alert').trigger('click') clock.tick(410) expect(view.$el).not.toBeVisible()
And just like that, we have our lightning quick test suite back. Sinon really blows me away to be honest, set the clock tick to 110 and you see the spec fail as the opacity is still mid transition. Truly a beautiful piece of work in my opinion.
Next up, we want the flash to fade slightly when we hover over it. It’s a strange piece of UI at first. The notifications actually annoyed me a bit when I first started using Ubuntu, but I have become accustomed to it, especially when the notification is layered over other parts of the UI which may hold important info. In any case, at the moment we are just illustrating an example.
Testing this is very much the same as fading out the flash, only we get to use a new matcher.
it 'will fade slightly when the mouse hovers over it', -> clock = sinon.useFakeTimers(); view = new App.Flash() view.$el.trigger('mouseenter') clock.tick(110) expect(view.$el.css('opacity')).toBe(0.1)
Using the above spec with the implementation of the following just simply won’t work.
App.Flash = Backbone.View.extend el: '.flash' events: { 'click .close-alert': 'closeAlert', 'mouseenter': 'mouseOver' } closeAlert: -> this.$el.fadeOut() mouseOver: -> this.$el.fadeTo(100, 0.1)
Basically the precision of the opacity value will be off by some tiny fraction. As such, we will use the
toBeCloseTo matcher to specify the precision of the value under test, in this case 0.01 is good enough for me.
expect(view.$el.css('opacity')).toBeCloseTo(0.01, 0.1)
The fade back in is trivial. However, a thing to watch out for is, as we will be fading back up to an opacity value of 1, Jasmine will actually read the css attribute as a string. You can use good old
parseInt for consistency.
expect(parseInt(view.$el.css('opacity'))).toBe(1)
Red, Green, Refactor, Refactor Tests
So far, we have written some pretty ugly specs with lots of duplication. Duplication is my favourite code smell, as it’s easy to refactor. With duplication removed we end up with a spec looking like:
describe "flash alert box", -> beforeEach -> loadFixtures 'flash' @view = new App.Flash() @clock = sinon.useFakeTimers() @fireEvent = (event, element, clockTick=500)-> element.trigger(event) @clock.tick(clockTick) it 'will close on a click of the cross', -> @fireEvent('click', $('.close-alert')) expect(@view.$el).not.toBeVisible() it 'will fade slightly when the mouse hovers over the container', -> @fireEvent('mouseenter', @view.$el) expect(@view.$el.css('opacity')).toBeCloseTo(0.01, 0.1) it 'will fade back in when the mouse leaves the container', -> @fireEvent('mouseleave', @view.$el) expect(parseInt(@view.$el.css('opacity'))).toBe(1)
As you can see from the refactored test, ( just like we would refactor rspec tests) we are moving all the duplicated setup into the
beforeEach function. We have also created a helper
@fireEvent which takes the event, the DOM element and a clock tick. The clock tick I have made optional and defaulted to 500, as we are using sinon to fake out the clock we needn’t worry too much about it but it’s certainly worth bearing the default in mind.
Wrapping Up
Now we have a couple of tricks up our sleeves to get test driving our client side code. I would be pretty shocked if you were not thinking “that’s alot of code to write for a simple flash banner” and, to some extent, you are correct. As developers we all need to get stuff done. But why do we question tests for simple JavaScript and not things like rspec shoulda-matchers,
it { should belong_to other_object }. If you are questioning it, cool. At the end of the day we have to evaluate and trade off against what value the test gives us.
I took approx 10 minutes test driving and refactoring the example here. I’ve had plenty of practice writing ‘dumb’ tests over the last year, so 10 minutes to write some specs for an element that will appear about my app at almost random intervals is acceptable.
At some point I may wish to ajax-ify the flash on a form submission, having it already within a nice Backbone structure will make that transition easier. Also, there is a bug in the demo code. It’s a small one but I know having tests in place it will be straight forward to quash (mouseenter-close-wait-mouseleave).
The next part of the series will focus some more on testing techniques and tips as well as finally getting our JavaScript under Continuous Integration (CI). Then we will round off the series catering for (DUN DUN DUN) Internet Explorer and by that I mean testing our JavaScript cross browser/platform.
- Victor | http://www.sitepoint.com/getting-your-javascript-under-control/ | CC-MAIN-2013-48 | refinedweb | 2,174 | 72.26 |
<!—.
Destruct.
Symbolic expressions, or, more commonly, S-expressions, are a rarity found almost exclusively in the land of Lisp. Here’s are some examples:
(+ 8 (- 4 2)) (if (not nil) t (and nil t))
Both of these s-expressions are Lisp code. The first is just math expressed in prefix notation common to Lisp code. The second uses an if statement and some logical operators. The if statement is not so different from a ruby statement, though the use of ‘t’ for truth and ‘nil’ for false may seem a bit strange a first.
And here’s a more complicated example of S-expressions used as data, not code:
(content (title "S-Expression Demo") (rated 5.0))
In it’s simplest form, an S-expression is a list of symbols. Lists look like the contents of parenthesis separated by spaces. Symbols are barewords. So:
(this is an sexpression)
is a list containing the symbols ‘this’, ‘is’, ‘an’, ‘sexpression’. Most Lisp implementations also accept string and number literals, so we can write things like in the example s-expressions above.
Ruby gives us everything we need to represent S-expressions. Ruby list literals are written in enclosing brackets ([...]) and use commas as separators. Symbols are written as barewords proceeded by a colon (:).
Given that information, what does our simple example look like in Ruby?
[:this, :is, :an, :sexpression]
Not nearly as pretty, especially when things get more complicated.
[:content, [:title, "S-Expression Demo"], [:rated, 5]]
The commas are what really kill it for me, but the colons aren’t so hot either. Luckily, there’s a Ruby gem to let us write Ruby S-expressions in Lisp syntax.
First install the gem:
$ gem install -r sexp
Then, remember to require the gem:
#!/usr/bin/ruby -w require 'rubygems' require 'sexp'
Now let’s take it for a test run:
"(this is an sexpression)".parse_sexp ===> [:this, :is, :an, :sexpression] '(content (title "S-Expression Demo") (rated 5))'.parse_sexp ===> [:content, [:title, "S-Expression Demo"], [:rated, 5.0]]
Can it also do the reverse?
[:this, :is, :an, :sexpression].to_sexp ===> "(this is an sexpression)"
It sure can.
The S-Expression parser is built almost entirely using the smulti mechanism we talked about earlier. It uses regular expressions to tear chunks off the front of strings and builds objects out of them. As described above, it parses lists, symbols, strings, and numbers. Let’s look at the parse() method for SExpressionParser::Main.
smulti(:parse, /\s+/) {|c, rest| parse(rest) } smulti(:parse, /\(/) {|c, rest| @res = List.new(rest) } smulti(:parse, /\"/) {|c, rest| @res = String.new(rest) } smulti(:parse, NumberRE) {|c, rest| @res = Number.new(rest, c) } smulti(:parse, SymbolRE) {|c, rest| @res = Symbol.new(rest, c) }
The top dispatch says if the first character is any whitespace character, to ignore it and parse the rest of the string minus that character. However, the second and third dispatch are much more interesting. They match the opening character for lists and strings accordingly. If they are triggered, then the text after the opening character will be passed into a specialized parser. The same happens for Numbers and Symbols, although their regexps are seperated out for readability.
While the leading characters to lists and strings are typically thrown away, we identify symbols and numbers when we see a character or a digit accordingly. Well, actually a digit or a leading period for decimal numbers. These first characters are part of the symbol or number, so we can’t just throw them out. That’s why there are passed in to their specialized parsers, unlike the others.
smulti(:parse, NumberRE) {|c, rest| @res = Number.new(rest, c) } smulti(:parse, SymbolRE) {|c, rest| @res = Symbol.new(rest, c) }
We don’t need to look at all the sub parsers, but let’s peak into the List parser class. It’s parse method is very simple.
smulti(:parse, /\)/ ) {|s, rest| leave(rest) } smulti(:parse, /\s+/ ) {|s, rest| parse(rest) } smulti(:parse, // ) {|s, rest| item = Main.new(rest) add(item.value) parse(item.unwanted) }
As in the main parser, white space is thrown away and parsing continues.
smulti(:parse, /\s+/ ) {|s, rest| parse(rest) }
If at any point we find the closing parenthesis, we call the inherited leave() method. leave() is our way of telling the List parser that we’re done. It stores the remaining text in an instance variable where it can be retrieved by someone else (in this case the Main parser that called us) and returns.
smulti(:parse, /\)/ ) {|s, rest| leave(rest) }
However, in all other situations, the text is actually passed of to a new Main parser that can handle any of the basic s-expression types that we could encounter anywhere, even inside a list. This parser’s task is to make sense of the numbers, strings, symbols, or nested lists that this list might contain. And when the Main parser completes, we add the newly created item to our list of contents and continue parsing whatever comes next.
As parsing goes, s-expressions are not a difficult exercise. But it’s nice to see we can use multiple dispatch to quickly throw together a parser. And the fact of the matter is, the real fun of s-expressions is not parsing them, but using them.
So shall we put our previous heists to work for us and steal just one more thing?
DLSs, or domain specific languages, are hot. Sometimes a general-purpose programming language just isn’t the clearest or shortest way to solve some problem. Creating a sub-language that can solve the problem more elegantly is one of the best ways to get around this.
Martin Fowler, an advocate of object-oriented programming, patterns, and agile software development, divides DSLs into two types. In his own words [1], “External DSLs are written in a different language than the main (host) language of the application and are transformed into it using some form of compiler or interpreter… Internal DSLs morph the host language into a DSL itself.”
Most Ruby DSLs are Internal DSLs. Here’s an example from the Dwemthy’s Array DSL in the infamous and terrifying Chapter 6 of Why’s Poignant Guide to Ruby2:
class TeethDeer < Creature life 655 strength 192 charisma 19 weapon 109 end
This code describes the fearsome TeethDeer creature, known for it’s deadly bite. There’s no magic here, just some class methods. It’s nice that this code is only Ruby. Ruby on Rails also uses some small Internal DSLs in Ruby. David Heinemeier Hansson extends some of the core Ruby classes to let you write 3.days.ago and have it do the right thing. Unfortunately, coding these kinds of DSLs can get complex, and the Ruby syntax may ultimately feel limiting.
External DSLs aren’t as common in Ruby, but they do show up. For example, the Ruby DBI library uses embedded SQL:
sth = dbh.prepare("SELECT * FROM users");
So, as a point of comparison, 3.days.ago is still all Ruby code, but “SELECT * FROM users” is not.
Okay, enough talk, let’s implement a simple version of the Logo programming language in Ruby. Remember Logo3? That language with the silly turtle that draws? Logo code is very simple and traditionally looks like this:
repeat 4 [ forward 100 right 90 ]
This produces:
Our logo will differ only in that instead of square brackets for blocks, we’ll use parenthesis:
repeat 4 ( forward 100 right 90 )
The “good old days” of just flipping bits in video memory are long gone, so let’s draw SVG (scalable vector graphics) images instead. SVG is an XML drawing format, and since it’s just text, it should be relatively easy for us to generate. We’ll start by creating a Logo class, and giving it a render() method
def render return <<-END <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" ""> <svg width="100%" height="100%" xmlns=""> <g stroke="black" stroke- #{@buffer}</g> </svg> END end
This is an alarming snippet, but it just creates the headers and root element destined for our SVG file, and dumps the instance variable @buffer as part of the output. The real trick is going to be turning the Logo commands into SVG lines and storing them in that buffer.
Just to refresh your memory, the little Logo turtle drags a pen with him, so every time he moves, he draws a line. The most basic commands he listens to are ‘left’, ‘right’, and ‘forward’. Left and right ask him to turn some number of degrees left or right, and forward tells him to walk some number of pixels forward.
Therefore, we’ll have three other instance variables: @x, @y, and @angle. In order to keep @angle between 0 and 360 (not strictly necessary, but it’s cleaner this way), let’s make a setter for angle.
def turn(num) @angle = (@angle + num) % 360 end
Now, when the turtle moves forward, we’ve got to actually draw a line. Using the standard polar to cartesian conversion, the move() method computes the turtle’s new position and draws a line between there and his old position (so long as the @pen instance variable is set). Of course, he doesn’t actually draw the line, he just puts the text representing it into our @buffer.
def move(distance) oldx, oldy = @x, @y radians = @angle * Math::PI / 180 @x += distance * Math.cos(radians) @y += distance * Math.sin(radians) return unless @pen @buffer += <<-END <line x1="#{oldx}" y1="#{oldy}" x2="#{@x}" y2="#{@y}"/> END end
We’d have enough now to actually render something if we had an initialize() method to setup @x, @y, @angle, and @pen. Then we could write:
logo = Logo.new logo.move(100) logo.turn(90) logo.move(100)
That’s just Ruby though, so let’s add an
eval method. Note that we wrap the string in parenthesis, so that the ‘sexp’ library will return us a list of all the commands.
def eval(string) run("(#{string})".parse_sexp) end
Okay, let’s put multi to use again and build a method to run Logo S-expressions. We can put this in the initialize method along with the code to initialize our instance variables.
def initialize @x, @y = 100, 100 @angle = 0 @buffer = "" @pen = true amulti(:run, :right, Numeric) {|sym, r, rest| turn(r) ; run(rest) } amulti(:run, :left, Numeric) {|sym, l, rest| turn(-l) ; run(rest) } amulti(:run, :forward, Numeric) {|sym, f, rest| move(f) ; run(rest) } amulti(:run, :penup) {|sym, rest| @pen = true ; run(rest) } amulti(:run, :pendown) {|sym, rest| @pen = false ; run(rest)} amulti(:run, :repeat, Numeric, Array) do |sym, i, code, rest| i.to_i.times{ run(code) } run(rest) end amulti(:run) {} end
So what’s going on here?
The ‘run’ function takes a list of commands and arguments and consumes them as appropriate. The first two definitions pull the :right or :left command off the list along with a number of degrees to rotate. The turn() function does the dirty work. Note that all of the ‘run’ bodies recurse on the remaining arguments.
The definition that matches
:forward moves the turtle,
:penup and
:pendown sets the value of
@pen, and, finally,
:repeat takes a number of times to repeat and an array of code to run. So let’s try this out.
(You can download the complete source here)
Running this code …
logo = Logo.new logo.eval %q{ repeat 4 (forward 100 right 90) forward 50 right 90 forward 100 } puts logo.render
... gives us:
Looks right!
Pattern-matching multiple dispatch, S-expressions, and Logo, that’s a pretty good haul. So next time you’re missing Haskell, or Lisp, or something really weird like Logo, why not just stick with Ruby? Of course, you might have to steal a few things first …
[0] DSLs in OCaml
[1] Internal versus External DSLs
[2] Why’s (Poignant) Guide to Ruby
[3] Introduction to Logo
Topher Cyll is a software engineer in Portland, Oregon, who’s lucky enough to write about half of his projects in Ruby. Topher wrote the Multiple Dispatch and S-Expression RubyGems used in this article. He also volunteers on the Tech Team of the progressive political group The Oregon Bus Project and is an active member of the Portland Ruby Brigade. | http://www.artima.com/rubycs/articles/patterns_sexp_dslsP.html | crawl-003 | refinedweb | 2,052 | 63.39 |
A couple of years ago I started on a project to create a Qt language binding using the Gnome GObject Introspection libraries to generate QMetaObjects, so that it would be possible to base a language binding on a dynamic bridge between the two toolkits. I started a project in the KDE playground repo, and then Norbert Frese joined in with a companion project called go-consume that was based more on static C++ code generation. I wrote some blogs about how the QMetaObjects creation worked; Creating QMetaObjects from GObject Introspection data, QMetaObject/GObject-introspection inter-operability progress and QMetaObject::newInstance() in Qt 4.5.
We were hoping to give a talk at the Gran Canaria Summit about GTK bindings for Qt, but it didn't get accepted. At the time, I was so busy doing other things that I never managed to follow through and complete the bindings. So the project had languished for the past couple years. Recently I've got going with it again and the project is now being actively developed on Launchpad as smoke-gobject.
I went to the recent Ubuntu UDS conference in Budapest, which was great. The were loads of talks, meetings and other events and I was amazed that Canonical and the Ubuntu community apparently manage to put on an event of this size every six months.
My connection with Ubuntu was that I had been doing some work on fixing bugs with the Unity-2d desktop shell, and had made a start with understanding the code. That project is written in Qt C++ with a lot of QML too. What I found interesting was that it also used Gnome libraries and needed to wrap them in a more Qt-developer friendly Qt/C++ layer. That made me think of the bindings project I never finished a couple of years ago. I discussed doing a binding with the Unity-2d guys at UDS, and they seemed keen on the idea. There are two desktop shell projects for Ubuntu, one called 'Unity-2d' which is the Qt C++/QML one, and a pure Gnome project called 'Unity-3d' which is similar but has more advanced graphics requirements. The Ubuntu guys wanted to create a library that would be written using Gnome apis that could be shared by both Unity-2d and Unity-3d. So it sounded like a perfect test project to see if an automatically generated binding would be possible.
It is now possible to create instances, call instance methods, call methods that are in a namespace, get and set Qt properties that map on to GObject properties, connect to slots and signals in the Qt manner. The marshalling code is pretty complete, although the GObject Introspection marshalling options are pretty large and complex, and it has taken a fair bit of time to get it working.
All that stuff happens inside the QMetaObjects via arcane methods such as QObject::qt_metacall(), and it isn't very easy to write about 'black boxes' of code that do all this exotic stuff. Just recently though, I have finally got as far as the C++ code generation and there is finally something I can point to and describe, that makes it relatively easy to follow what the project is about.
So on principle of 'a code snippet is worth a thousand words', here is a sample of what you get if you run the GObject Introspection description for 'Gtk' through the smoke-gobject runtime. This is the header for the Gtk::Button class:
#ifndef GTK_BUTTON_H
#define GTK_BUTTON_H
#include "gtk_bin.h"
namespace Gtk {
class Button : public Gtk::Bin {
Q_OBJECT
Q_PROPERTY(bool focusOnClick)
Q_PROPERTY(Gtk::Widget* image)
Q_PROPERTY(Gtk::PositionType imagePosition)
Q_PROPERTY(QString label)
Q_PROPERTY(Gtk::ReliefStyle relief)
Q_PROPERTY(bool useStock)
Q_PROPERTY(bool useUnderline)
Q_PROPERTY(float xalign)
Q_PROPERTY(float yalign)
public:
Button();
Button(QString label);
Button(QString stock_id);
Button(QString label);
public slots:
void pressed();
void released();
void clicked();
void enter();
void leave();
void setRelief(Gtk::ReliefStyle newstyle);
Gtk::ReliefStyle relief();
void setLabel(QString label);
QString label();
void setUseUnderline(bool use_underline);
bool useUnderline();
void setUseStock(bool use_stock);
bool useStock();
void setFocusOnClick(bool focus_on_click);
bool focusOnClick();
void setAlignment(float xalign, float yalign);
void alignment(float& xalign, float& yalign);
void setImage(Gtk::Widget* image);
Gtk::Widget* image();
void setImagePosition(Gtk::PositionType position);
Gtk::PositionType imagePosition();
Gdk::Window* eventWindow();
signals:
void activate();
void clicked();
void enter();
void leave();
void pressed();
void released();
};
}
#endif // GTK_BUTTON_H
To me it doesn't look bad - you have some understandable camel case method names, slot, signals and properties that all do what you would expect them to do. There are a couple of problems with this particular code snippet that need sorting out.
Firstly, notice that there are two constructors with exactly the same arguments, and that wouldn't compile. This is because in the underlying library there are two constructor functions for Gtk::Button that have the same arguments; new_with_label() and new_with_mnemonic() both taking a 'gchar*' utf8 argument. How is a bindings author supposed to sort that out? I'm not sure yet. Certainly many languages like Ruby or Python will have the same issue where the constructors are named after the class instances they construct.
A second problem is with enclosing classes in namespaces like 'Gtk::' or 'GObject::' where there are already C structs called the same thing. So I could call them something like 'Qt::Gtk::Button' or lowercase the namespace to 'gtk::Button' - I haven't decided what to do yet.
The generated code for the .cpp part of the Gtk::Button class looks like this:
#include "gtk_button.h"
namespace Gtk {
static QMetaObject *_staticMetaObject = 0;
const QMetaObject *Button::metaObject() const
{
if (_staticMetaObject == 0)
_staticMetaObject = (QMetaObject*) Smoke::Global::findMetaObject("Gtk::Button");
return _staticMetaObject;
}
void *Button::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, metaObject()->className()))
return static_cast<void*>(const_cast< Button*>(this));
return Gtk::Bin::qt_metacast(_clname);
}
int Button::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
return Smoke::GObjectProxy::qt_metacall(_c, _id, _a);
}
Button::Button()
{
Button *_r = 0;
void *_a[] = { &_r };
metaObject()->static_metacall(QMetaObject::CreateInstance, 0, _a);
takeIdentity(_r);
}
Button::Button(QString _t1)
{
Button *_r = 0;
void *_a[] = { &_r, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
metaObject()->static_metacall(QMetaObject::CreateInstance, 1, _a);
takeIdentity(_r);
}
...
void Button::clicked()
{
void *_a[] = { 0 };
qt_metacall(QMetaObject::InvokeMetaMethod, 314, _a);
}
...
void Button::setRelief(Gtk::ReliefStyle _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
qt_metacall(QMetaObject::InvokeMetaMethod, 317, _a);
}
...
If you're familiar with code generated by the moc tool, it should look pretty similar. However, with the standard moc, a qt_metacall() function is generated which calls all the slots and properties in the class via a big case statement. Instead in the code above, each slot calls qt_metacall() - ie it works in reverse. No code needs to be generated for the signals and properties as that is all handled by the smoke-gobject runtime.
There is plenty for scope for optimization such as calling the GObject C functions directly where the marshalling is pretty simple. So I think in the long term in can be made efficient although the first version might be slow. I haven't adding virtual method overrides yet, but that shouldn't be too hard as all the info to generate the code can be got from the G-I typelibs.
I you want to checkout and build the project you will need have a GObject Introspection and GObject/Gtk development environment. It is built with cmake, and so it should be just a matter of creating a 'build' directory in the project and typing 'cmake ..' in there. There is a test for the runtime that uses a library that is part of G-I called 'libeverything' and is intended to be a torture test for bindings authors to use to test their code. In the initTestCase() method in tests/everything/tst_everything.cpp you will see this:
void tst_Everything::initTestCase()
{
int id = qRegisterMetaType();
Smoke::Global::initialize();
everythingNamespace = new Smoke::GObjectNamespace("Everything");
}
It will generate the .h/.cpp sources for the Everything namespace. If you want to have a look at what it does with a namespace like Gtk or Gst you can add a 'Smoke::GObjectNamespace * gtkNamespace = new Smoke::GObjectNamespace("Gtk");' line to the above method.
I am going to the Qt Contributor's Summit this week, and one of the topics for discussion is Interoperability with non-Qt code - Should Qt have better interoperability with (GTK+, Boost, ..)?' run by Jeremy Katz. I'm looking forward to getting some feedback..
glibmm an gtkmm (the C++ wrappers to resp glib and gtk) use the Glib and Gtk namespace - you might want to use different ones to avoid potential conflicts in applications using (even indirectly) either of the two and your bindings.
OK interesting. I didn't mention it in the blog, but another way of fixing the problem is to ensure that you don't need to include any glib or gtk C headers when you use the smoke-gobject Qt/C++ bindings. I wasn't sure if that was a good idea because it would stop you from using any direct C function calls in applications using the bindings. So for gtkmm, that must mean they assume you don't need access to the C apis directly.
I suppose the issue with gtkmm vs smoke-gobject namespace clashes would be are there any use cases where you would need to combine application code written using both bindings? I don't know really.
More than a direct usage of gtkmm, it could be some case of plugin system with a plugin written in gtkmm, or something like that.
I agree, not a very big case, but something to keep into account while the API is still not set yet.
Tomeu Vizoso: "tried to comment on your blog post but wasn't able to register in blogs.kde.org.).
About what to do with the foo_new_bar() C constructors, we just treat them as class methods."
"tried to comment on your blog post but wasn't able to register in blogs.kde.org."
I'm sorry to hear about that. I look forward to getting comments like
yours on a blog, and it's really annoying when the system makes it
hard to do. Lots of people have complained they can't comment on the
kde developers blogs. Perhaps I will add this mail and the original
question to the blog so that at least we can have some public record.
I'll try and find out whether the system can be changed.
)."
Ok, I will need to think how that will affects C++. I was assuming
that you would only be calling constructors for the class that
implements the constructor function.
"About what to do with the foo_new_bar() C constructors, we just treat them as class methods."
Yes, I think I will do that in C++ too. I will rename something like
gtk_button_new_from_stock() as a static C++ method called
Gtk::Button::createFromStock(). I don't think
'Gtk::Button::newFromStock()' seems quite right in C++ and
'createFoo()' is more usual.
I think I should subscribe to the G-I mailing list now I've got a few
questions like this one to ask about.
This place is a blogging platform for KDE contributors. It only hosts a fraction of KDE contributor's blogs. If you are interested in all of them please visit the agregator at Planet KDE. | https://blogs.kde.org/node/4444 | CC-MAIN-2017-13 | refinedweb | 1,895 | 58.52 |
I would like to be able to produce a stacked line graph (similar to the method used here) with Python (preferably using matplotlib, but another library would be fine too). How can I do this?
This similar to the stacked bar graph example on their website, except I'd like the top of bar to be connected with a line segment and the area underneath to be filled. I might be able to approximate this by decreasing the gaps between bars and using lots of bars (but this seems like a hack, and besides I'm not sure if it is possible).
I believe Area Plot is a common term for this type of plot, and in the specific instance recited in the OP, Stacked Area Plot.
Matplotlib does not have an "out-of-the-box" function that combines both the data processing and drawing/rendering steps to create a this type of plot, but it's easy to roll your own from components supplied by Matplotlib and NumPy.
The code below first stacks the data, then draws the plot.
import numpy as NP from matplotlib import pyplot as PLT # just create some random data fnx = lambda : NP.random.randint(3, 10, 10) y = NP.row_stack((fnx(), fnx(), fnx())) # this call to 'cumsum' (cumulative sum), passing in your y data, # is necessary to avoid having to manually order the datasets x = NP.arange(10) y_stack = NP.cumsum(y, axis=0) # a 3x10 array fig = PLT.figure() ax1 = fig.add_subplot(111) ax1.fill_between(x, 0, y_stack[0,:], facecolor="#CC6666", alpha=.7) ax1.fill_between(x, y_stack[0,:], y_stack[1,:], facecolor="#1DACD6", alpha=.7) ax1.fill_between(x, y_stack[1,:], y_stack[2,:], facecolor="#6E5160") PLT.show() | https://codedump.io/share/Uqq7EO0b48qW/1/how-can-i-create-stacked-line-graph-with-matplotlib | CC-MAIN-2017-04 | refinedweb | 282 | 64.41 |
combo box code problem
combo box code problem in this my problem related to :
when i select state MP then i wil open the its corresponding city but in database it only stores the option value no like MP at option value 10 then it will stores the 10
populating the combo box - Struts
populating the combo box Hi
I am having problem populating the combo box with a table in MS SQL Server 2005 Management Studio Express.
Belo...;
}
==========================================================================
My problem is populating the combobox table
Sub combo box problem - Development process
Sub combo box problem Hi, In this code Sub-Combo box is not working. plz solve the problem
Search Page
var arr = new Array();
arr["Select"] = new Array("-select-");
arr["Dkn/Tmz"] = new Array
Combo box value Error - WebSevices
Combo box value Error
if($_SERVER['REQUEST_METHOD'] == 'POST' )
{
$visa =trim($_POST['hdVisa... details and source code to solve the problem. Combo Box dynamically
populate Combo Box dynamically Hi,
How to populate the Combo Box dynamically using Flex with Jsp's
combo box - JSP-Servlet
combo box how to get a combo box in jsp page which allows editing as well as list box
Store combo box value - Development process
Store combo box value Hi , this is my code. Here wen i click submit button combo values are stored like 1,2,3... but i want to store value . plz... = request.getParameter("Combo");
String Issue = request.getParameter("IssueName");
String
JCombo Box problem
JCombo Box problem I have three combo boxes
First combo box display the year
Second combo box display the month for the selected year.
Third combo box display number of week in a selected month for the year.
I am select year
Loading combo box from oracle how can i load values into a combobox from oracle database when a value is selected in another combo box
Code to store sub combo box value - Development process
Code to store sub combo box value Hi Deepak, In the following code i want to store subcombo box value instead of number. Already "Dkn/Tmz" ,"kungumam... etc are storing
but i want to store "Circulation,marketing
JavaScript Combo Box Validation
JavaScript Combo Box Validation
This application illustrates how to validate the combo box using JavaScript
validation.
In this example we create a combo box of different
Need to push the combo box to flash movie - Java Beginners
Need to push the combo box to flash movie Hi,
I need to push the combo box values to the flash movie. I am succusfull in pushing the textfield... in pushing the combo box values to the flash movie
two text box problem
two text box problem i have two text box in two different pages and same variable use in two text box when enter value in first text box it's reflection show in second text box , how i reduce it in jsf ?
Hi Friend
how can retrive value from combo box in servlet?
how can retrive value from combo box in servlet? i have a jsp page with combobox. And i want to get value from combox to servlet
Dynamic check box problem
Dynamic check box problem In my project i have used a dynamic table, in the each row of that table there is one check box [that i have created dynamically]. Now my problem is that i can't access those values from that dynamic
How to retreive data by using combo box value - JSP-Servlet
How to retreive data by using combo box value Hello friend ,
i am using only one form. U are using html form and jsp form. So get... I can print combo box values
How to retrieve data using combo box value in jsp? - JSP-Servlet
How to retrieve data using combo box value in jsp? Hi freind,
I already post this question. I need urgent help from u. pl response me.... All actions in the same page....... Hi Friend,
Please visit are satisfaction in this form.. What will i do. My code is following are satisfaction in this form.. What will i do. My code is following
Dynamic loading of Combo box list using servlet - JSP-Servlet
Dynamic loading of Combo box list using servlet I have the category and their sub categories in database. How can I load the sub category from...
I give theortical descrption read it!
Select a value from drop dwon box
combo program - Java Beginners
combo program I want to give DOB in combo box for that i have to give 1 to 30 for days and 1900 to 2010. Without giving all, using for loop i have to get the values. Please help me..
Hi Friend,
Please
my table should be reseted to new value upon the selection of the combo box..
my table should be reseted to new value upon the selection of the combo box.. import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Connection
Combo box In Java
Combo box In Java
This tutorial will help you to create a Combo box in java. Combo box
allow you to select one of the option which appear at the user request. It is
possible that combo box can be editable by which a user can type
jtable combo - Java Beginners
jtable combo i am using jtable (using defaulttablemodel) ,when i am click on a particular cell of jtable i want to display the combo box in that cell,plz provide program Hi Friend,
Try the following code:
import
retrieving from oracle database using jsp combo box
retrieving from oracle database using jsp combo box hi this is my code in this once i select the server type and version of the server the process name of the server has to display in the process name field from the oracle
Not Able to select an Item in Spark Combo Box control (Adobe Flex Object) using QTP
Not Able to select an Item in Spark Combo Box control (Adobe Flex Object) using QTP Hi,
I am trying to Automate a website developed using Adobe Flex controls. But i am not able to select any item from Spark Combo Box. I tied
base the value of first combo box, how i display the second combox - JSP-Servlet
base the value of first combo box, how i display the second combox
i have a combo box for classes. my requirement is when i select the class, if class is 11 or 12 the second combo box of subject should be appear.
please
Dojo Combo Box
Dojo Combo Box
... box and
how to create a combo box in dojo. For creating the Combo box you need "dijit.form.ComboBox".
Combo Box: A
combo box is a graphical user...);
}
function hide(){
if (document.getElementById) {
document.getElementById('combo
how i conditional access the data from database using combo box. - JSP-Servlet
how i conditional access the data from database using combo box.
i have combox box named class when i select its value 11 or 12, another combo box...){
document.getElementById('combo').style.visibility = 'hidden';
}
}
function call(class_name
coding problem - JSP-Servlet
the combo box you have to use AJAX
Box
| J2ME Record
Listener | J2ME
Audio Record |
J2ME Record Data Base...
Map | Business Software
Services India
J2ME Tutorial Section
Java
Platform Micro Edition |
MIDlet Lifecycle J2ME
|
jad and properties file
J2ME Text Box Example
J2ME Text Box Example
This application illustrates how to create the text box using TextBox class. The
TextBox class is a Screen that allows the user to enter and edit text
Flex Combo Box example
Flex Combo Box example
In this tutorial page you will be taught to utilize ComboBox... ComboBox
controls. The Example below shows combo boxes with nicely formatted string
j2me - MobileApplications
j2me Hi Deepak,
Thank for u earlier suggestion.But i need its date and time when the file was created.But i got solution for that problem as below:
import java.io.*;
import java.lang.
How to retrieve data from database by using combo box value in jsp? - JSP-Servlet
How to retrieve data from database by using combo box value in jsp? Hello friend i want use only one jsp page.. but u give 2 pages...
I want to work in one page...
Pl response.. I do not need getParameter...
Pl respose me
values of Combo boxes are not stored in database - JSP-Servlet
values of Combo boxes are not stored in database
i have some combo box values.
when i click the submit button after select combo box values...) {
document.getElementById('combo').style.visibility = 'hidden';
}
}
function call
problem with addactionlistener on JComboBox - Java Beginners
. You can use addActionListener() on Combo Box in the following way:
import...problem with addactionlistener on JComboBox ViewElements.java:225...[] = { "A", "B", "C"};
JFrame frame = new JFrame();
JComboBox combo = new
j2me coding - Java Magazine
j2me coding hi,
i am doing a project on text steganography in sms using j2me.
i have a problem in coding for sending and receiving sms .i have... sms using port no.please give me a solution for this problem............
give me
regarding J2ME - Java3D
regarding J2ME I have a problem. I have to write a 200line text in J2ME,for that i am using drawString(),but de problem... use textarea control ,in j2me has various controls textfield,combobox..etc so hi use
Navigation with Combo box and Java Script
Navigation with Combo box and Java
Script
... in Navigation with Combo box?
JavaScript is a 2-level combo box menu script... selection box. The navigation that requires absolutely no DHTML or JavascriptComboBox Display Problem - Java Beginners
combo boxes. If first combo box i am display all date. If i select one date from first combo box then the second combo box display some dates based on first combo box select date. Here is my full program
import java.awt.*;
import
J2ME count character into string
J2ME count character into string i am new in J2ME, my problem is how to count character into number, i had been research google for almost 2 days... with J2ME coding, tons of thx will be given :)
best regards,
Noob beginner
j2me - Java Beginners
j2me hai. i m villu here.
i have to do a project about adding audio and video file together in j2me coding.I have tried but cant get it.Can u...,
For solving the problem visit to :
Combo Box Using Ajax In JSP
Combo Box Using Ajax In JSP
... to
Select the Data from database using Ajax in combo box. We created two file...; run on browser then it will
having a Select Box Employee Id.On select emp | http://www.roseindia.net/tutorialhelp/comment/55411 | CC-MAIN-2014-42 | refinedweb | 1,776 | 62.48 |
I am new to Java and this is one of my first codes that I'm posting, its a 8ball that returns a random answer via the console. I was just wondering if there is anything on this code that I can improve to further my knowledge, any help would be great
Code :
import java.util.Scanner; public class 8ball { /** * Coded by Cody Reuille * */ public static void main(String[] args) throws InterruptedException { /** * adds Scanners to check if a question is asked and to see if you want * to ask another question */ Scanner question = new Scanner(System.in); Scanner repeat = new Scanner(System.in); // initiates the int used for the random number int rndoutcome; // while loop so you can ask more then one question without it // terminating while (true) { System.out.println("Please state you're question."); question.nextLine(); // sets rndoutcome to a random number 0-9 rndoutcome = (int) (Math.random() * 10); // switch statement for random outcomes switch (rndoutcome) { case 0: System.out.println("Nope."); break; case 1: System.out.println("Anything is possible!"); break; case 2: System.out.println("Never!"); break; case 3: System.out.println("Yes!"); break; case 4: System.out.println("Please try again later."); break; case 5: System.out.println("I dont feel like answering that..."); break; case 6: System.out.println("Not even in your dreams."); break; case 7: System.out.println("Whats the answer im looking for? oh, NO!"); break; case 8: System.out.println("Maybe someday, but not today."); break; case 9: System.out.println("This is correct."); break; } // 2 second pause before asking if you want to ask another question Thread.sleep(2000); System.out.println("Would you like to ask another question? (Yes/No)"); // checks to see if you enter yes or no if (!repeat.nextLine().equalsIgnoreCase("yes")) { // if you type yes then it will repeat, if not it will terminate break; } } } } | http://www.javaprogrammingforums.com/%20java-theory-questions/11596-ideas-what-else-add-printingthethread.html | CC-MAIN-2015-35 | refinedweb | 310 | 62.24 |
.NET Framework: Collections and Generics
The original release of the .NET Framework included collections as .NET was introduced to the Microsoft programming world. The .NET Framework 2.0 introduced generics to complement the System.Collections namespace and provide a more efficient and well performing option.
Introduction to Collections
A collection is a container to which objects can be added. This container offers a powerful flexibility and adaptability. Collections often hold data items that are traversed in a loop structure. All of the items stored in the collection are stored as objects. This means that whatever type you are putting in the collection is taken down to its root object form as it is put in the collection and put back to its native form as it is pulled out. The act of taking a static instance of a particular class down to its base object type and back again is referred to as boxing and unboxing. The example below demonstrates filling an ArrayList, which is a type of collection, and getting the items back out. Notice how the items have to be cast as they are retrieved to return them to their native type.
System.Collections.ArrayList testList = new System.Collections.ArrayList(); // Add some numbers to the list for (int i = 0; i < 20; i++) { // Go ahead and play here. You can add whatever type you want in here // without issue as you add. Will be an issue for you at runtime as you // retrieve items. testList.Add(i); } foreach (var item in testList) { // Go ahead and try something like item + 1 here without the cast // and see what happens! Console.Write("{0}", (int)item); }
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
There is a performance challenge with collections since they store everything as objects. There is overhead as items are added or removed from a collection because they are boxed and unboxed to a specific type. An additional drawback is that you lose compile time type checking to enforce consistent use of the same type within your collection. There is a workaround for the type check, which involves creating a wrapper class of your own that inherits from CollectionBase and limits the specific type that can be added or removed from the collection. However, if your C# programming is collection intensive, that increases the amount of code you need to write and maintain.
Generics
Generics were introduced in the version 2.0 of the Microsoft framework as a solution to the problems with collections mentioned above. Generics offer a combination of type safety, performance, and generality in the type. A generic is a type safe class that is declared without a specific type applied to its definition. The type is specified at the time the object is actually instantiated and used. The .NET Framework includes a number of generic objects in the System.Collections.Generic namespace. It is likely you will find that many of these will meet your needs. In the event they don't, you can always build your own generic classes as well. The C# tutorial code below is a rewrite of our prior example, but using generics this time. You'll see that you get the compile time checking as well as the automatic type recognition as you retrieve.
List
testGeneric = new List (); for (int i = 0; i < 20; i++) { // Go ahead and play here. You'll get a compile time error here // if you try to add anything other than an int. testGeneric.Add(i); } foreach (int item in testGeneric) { Console.Write("{0}", item); }
Summary
We have looked at the original collection that was introduced with the .NET Framework. We discussed the challenges in using it, and introduced Generics which offer a solution to the performance issues and lack of compile time check with collections. It is likely that most of the collection types you will use as a .NET developer going forward will be of the generic variety given the advantages.
compile errorPosted by ProgrammerA on 09/04/2014 02:18pm
Great article. I do finally understand what the difference is between collection en generics. The sample code gives a compile time error. "Using the generic type "System.Collections.Generic.List" requires 1 type arguments. Why is there a type needed as your explainations says there isn't a type required. Thanks in advanceReply
C#.Net applicationPosted by Mahesh on 02/28/2013 09:24pm
i have required c#.net project by using barcodeReply by on 10/12/2012 04:52am
Thanks for sharing your views. Great blog here.. It.Reply
forensic accountantPosted by forensic accountant on 10/06/2012 05:57am
I noticed your blog title !. Everything is very open and represents very clear explanation of issues. Really blogging is spreading its wings quickly. Your write up is a good example of it. Your website is very useful. Thanks for sharing.Reply by llzzmm on 06/25/2011 08:18pm
== ====,ACCEPT PYAPAL PAYMENT AND CREDIT CARDS DELIVERY TO YOU DOOR TO DOOR. == ====Reply | https://www.codeguru.com/csharp/article.php/c19001/NET-Framework-Collections-and-Generics.htm | CC-MAIN-2018-26 | refinedweb | 836 | 66.03 |
So far (Part 1, Part 2, Part 3), we’ve covered pretty much everything you need to know in order to use the ADO .NET connected layer for your day-to-day data access layer development needs. We’ve seen how to open a connection, run different types of queries, use transactions, and use prepared statements to parameterise our queries. We’ve also talked a bit about why ADO .NET is still useful today, and the general structure of ADO .NET data providers.
In practice, while ADO .NET is easy, useful and fast, it can also be quite tedious. You’ll find yourself having to write a lot of the same boilerplate over and over, and it’s quite common for different companies to have their own libraries with utility methods for some of the most repeated operations.
Some of the guys at Stack Exchange (the company behind Stack Overflow) have built one such library, called Dapper. It’s sometimes called a micro-ORM, but I prefer to distance it even more from the ORM idea and simply call it a thin layer over ADO .NET. As we shall see shortly, it simply provides extension methods over the usual ADO .NET connection objects.
You can learn more about Dapper from the following links:
In this article, we’ll see how to use Dapper to do the same things we’ve been doing so far with ADO .NET, and how it makes life easier.
I’ll be using a .NET Core console application for this one, although it should work as-is for .NET Framework. I’m using SQL Server as the database engine. The current version of Dapper at this time is 2.0.35.
A Musical Example
For this article, create a database called Music, and run the following script:
create table Song ( Id int not null primary key identity(1, 1), Name nvarchar(50) not null, Year int not null, ArtistId int not null ); create table Artist ( Id int not null primary key identity(1, 1), Name nvarchar(50) not null, ); insert into Artist (Name) values ('Caravan Palace'), ('Red Hot Chili Peppers'), ('The Cure'); insert into Song (Name, Year, ArtistId) values ('Dramophone', 2012, 1), ('Can''t Stop', 2002, 2), ('Just Like Heaven', 1987, 3);
We’ll use this as a playground to explore Dapper’s querying capabilities.
Opening a Connection
When using Dapper, there is no strange new way to open a connection. You simply open an ADO .NET connection exactly as we did in Part 1. So if you’re using SQL Server, follow three simple steps.
First, ensure you have a reference to
System.Data.SqlClient. If you’re using .NET Core, this means adding the System.Data.SqlClient NuGet package. Projects based on the older .NET Framework need only add a reference since this assembly is part of the framework.
Secondly, import this assembly with a
using statement:
using System.Data.SqlClient;
Finally, write the basic code to create and open an
SqlConnection. I’m using the async version since we’ve already covered this in Part 2.
const string connStr = @"Server=.\SQLEXPRESS; Initial Catalog=Music; Integrated Security=True"; using (var conn = new SqlConnection(connStr)) { await conn.OpenAsync(); Console.WriteLine("Connected!"); }
Querying for Row Data
Once we have an ADO .NET connection object, we can use Dapper’s extension methods to execute queries. First, install the Dapper NuGet package. Then, make sure you import Dapper via a
using statement:
using Dapper;
Finally, just use the
QueryAsync() extension method to execute a query and retrieve the results:
using (var conn = new SqlConnection(connStr)) { await conn.OpenAsync(); const string sql = "select Name from Artist"; var names = await conn.QueryAsync<string>(sql); foreach (var name in names) Console.WriteLine(name); }
Here’s the output for that:
Caravan Palace Red Hot Chili Peppers The Cure
“A-ha!” I hear you say, “It’s simple enough with strings. What if I want to retrieve a row and return it as a C# object/DTO?” Alright, so for Artist we have this class:
public class Artist { public int Id { get; set; } public string Name { get; set; } public override string ToString() => $"{Id}: {Name}"; }
Then, we make some small changes to the querying code to (a) retrieve the ID along with the name in the query, (b) have
QueryAsync() use a generic argument of type
Artist, and (c) rename all the variables so they make sense, given the updates.
using (var conn = new SqlConnection(connStr)) { await conn.OpenAsync(); const string sql = "select Id, Name from Artist"; var artists = await conn.QueryAsync<Artist>(sql); foreach (var artist in artists) Console.WriteLine(artist); }
Dapper is intelligent enough to automatically map the column names to the properties of the specified class. That’s right… the entire
SqlDataReader part of ADO .NET, incuding fetching and converting individual fields, is no longer necessary. Here’s the output:
1: Caravan Palace 2: Red Hot Chili Peppers 3: The Cure
Querying for Scalar Data
For single-value queries, you use
ExecuteScalarAsync() instead of
QueryAsync():
using (var conn = new SqlConnection(connStr)) { await conn.OpenAsync(); const string sql = "select Name from Song where Id = 2"; var songName = await conn.ExecuteScalarAsync<string>(sql); Console.WriteLine(songName); }
The output for this is:
Can't Stop
Executing Non Queries
For inserts, updates and deletes, just use
ExecuteAsync():
using (var conn = new SqlConnection(connStr)) { await conn.OpenAsync(); const string sql = @"insert into Song(Name, Year, ArtistId) values('Snow', 2006, 2);"; int rowsAffected = await conn.ExecuteAsync(sql); Console.WriteLine($"{rowsAffected} rows inserted."); }
The following is the output when running this program. If you query the Songs table, you’ll find the new row in there.
1 rows inserted.
Prepared Statements
When you need to run queries based on user input, you need to use prepared statements and pass the inputs as parameters. With Dapper, you provide an anonymous object where the property names match the parameters in the query. Here’s a full example:
static async Task Main(string[] args) { Console.Write("Search for artist: "); string searchQuery = Console.ReadLine(); var artists = await FindArtistAsync(searchQuery); foreach (var artist in artists) Console.WriteLine(artist); } static async Task<IEnumerable<Artist>> FindArtistAsync(string searchQuery) { const string connStr = @"Server=.\SQLEXPRESS; Initial Catalog=Music; Integrated Security=True"; using (var conn = new SqlConnection(connStr)) { await conn.OpenAsync(); const string sql = @"select Id, Name from Artist where Name like @searchQuery;"; var param = new { searchQuery = $"%{searchQuery}%" }; var artists = await conn.QueryAsync<Artist>(sql, param); return artists; } }
An example run of this could be as follows:
Search for artist: re 2: Red Hot Chili Peppers 3: The Cure
Another one shows that, as expected, SQL injection doesn’t work with this code (i.e. no results were returned):
Transactions
ADO .NET transactions are already based on ADO .NET connection objects, so there is no new extension method to start, commit and rollback transactions with Dapper. However, queries involved in a transaction need to specify the transaction. For this reason, Dapper methods such as
QueryAsync(),
ExecuteScalarAsync() and
ExecuteAsync() take a parameter of type
IDbTransaction where you can pass in the relevant transacton object.
Conclusion
As you can see, Dapper takes away the tedious parts of ADO .NET and provides methods that allow you to run queries with just a connection obect. There’s no need to set up command objects, spend a lot of time preparing parameters, or map and convert returned fields one by one.
We haven’t covered everything you can do with Dapper, so feel free to check out the links at the beginning of this article to learn more.
This is also the end of this mini-series on ADO .NET. Hopefully, by now you can see that it’s actually quite easy to run queries with this good old technology, and it doesn’t have to be tedious. You can still use ORMs like Entity Framework if you like, but you should be able to weigh the pros and cons of your choice. | https://gigi.nullneuron.net/gigilabs/2020/07/ | CC-MAIN-2021-25 | refinedweb | 1,320 | 64.51 |
pfm_get_event_encoding man page
pfm_get_event_encoding — get raw event encoding
Synopsis
#include <perfmon/pfmlib.h> int pfm_get_event_encoding(const char *str,int dfl_plm, char **fstr, int *idx, uint64_t *code, int *count);
Description
This function is used to retrieve the raw event encoding corresponding to the event string in str. The string may contain unit masks and modifiers. The default privilege level mask is passed in dfl_plm. It may be used depending on the event.
This function is deprecated. It is superseded by pfm_get_os_event_encoding() where the OS is set to PFM_OS_NONE. Encoding is retrieve through the pfm_pmu_encode_arg_t structure.
The following examples illustrates the transition:
int i, count = 0; uint64_t *codes;]);
is equivalent to:
pfm_pmu_encode_arg_t arg; int i; memset(&arg, 0, sizeof(arg)); arg.size = sizeof(arg); ret = pfm_get_os_event_encoding("RETIRED_INSTRUCTIONS", PFM_PLM3, PFM_OS_NONE, &arg); if (ret != PFM_SUCCESS) err(1", cannot get encoding %s", pfm_strerror(ret)); for(i=0; i < arg.count; i++) printf("count[%d]=0x%"PRIx64"\n", i, arg.codes[i]); free(arg.codes); The encoding may take several 64-bit integers. The function can use the array passed in code if the number of entries passed in count is big enough. However, if both *codes is NULL and count is 0, the function allocates the memory necessary to store the encoding. It is up to the caller to eventually free the memory. The number of 64-bit entries in codes is reflected in *count upon return regardless of whether the codes was allocated or used as is. If the number of 64-bit integers is greater than one, then the order in which each component is returned is PMU-model specific. Refer to the PMU specific man page. The raw encoding means the encoding as mandated by the underlying PMU model. It may not be directly suitable to pass to a kernel API. You may want to use API-specific library calls to ensure the correct encoding is passed. If fstr is not NULL, it will point to the fully qualified event string upon successful return. The string contains the event name, any umask set, and the value of all the modifiers. It reflects what the encoding will actually measure. The function allocates the memory to store the string. The caller must eventually free the string. Here is a example of how this function could be used: #include <inttypes.h> #include <err.h> #include <perfmon/pfmlib.h> int main(int argc, char **argv) { uint64_t *codes 0; int count = 0; int ret; ret = pfm_initialize(); if (ret != PFMLIB_SUCCESS) err(1", cannot initialize library %s", pfm_strerror(ret));]); free(codes); return 0; }
Return
The function returns in *codes the encoding of the event and in *count the number of 64-bit integers to support that encoding.>
See Also
pfm_get_os_event_encoding(3) | https://www.mankier.com/3/pfm_get_event_encoding | CC-MAIN-2017-17 | refinedweb | 452 | 58.79 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.