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
|
|---|---|---|---|---|---|
Docs |
Forums |
Lists |
Bugs |
Planet |
Store |
GMN |
Get Gentoo!
Not eligible to see or edit group visibility for this bug.
View Bug Activity
|
Format For Printing
|
XML
|
Clone This Bug
I think this is probably due to incompatibilities for c++.
libfwbuilder error:
ccache c++ -Wall -g -I.. -DHAVE_CONFIG_H -I/usr/include/glib-1.2
-I/usr/lib/glib/include -D_REENTRANT -I/usr/include/libxml2
-I/usr/include/libxml2 -c RuleElement.cc -o RuleElement.o >/dev/null 2>&1
FWReference.cc:106: syntax error before `&' token
make[2]: *** [FWReference.lo] Error 1
make[2]: *** Waiting for unfinished jobs....
unfortunately the ebuild gets installed without error message, but the libraries
are missing.
fwbuilder does not compile because of the missings libs.
okay thanks for the bug report.. i'll have a patch committed for this shortly.
Matt
OKay. fixed in -r1. If you could, please test it and let me know if you run
into
any problems.
Thanks!
Matt
no, this does nor work for me.
First I have some dependencies which I needed to meet manually:
for libfwbuilder:
this version was installed:
dev-libs/glib-2.0.6-r1 *
this one needs to be installed, otherwise configure complains.
dev-libs/glib-1.2.10-r4 *
for fwbuilder:
this have been installed;
dev-libs/libsigc++-1.1.13 *
x11-libs/gtkmm-1.3.18 *
this needed to be intalled, again otherwise configure bailed out
dev-libs/libsigc++-1.0.4-r2 *
x11-libs/gtkmm-1.2.9-r2 *
Finally I received the following errror during make of fwbuilder:
PolicyCompiler_ipf.cc: In member function `virtual void
fwcompiler::PolicyCompiler_ipf::compile()':
PolicyCompiler_ipf.cc:296: `cout' undeclared (first use this function)
PolicyCompiler_ipf.cc:296: (Each undeclared identifier is reported only once
for each function it appears in.)
NATCompiler_ipf.cc: In member function `virtual void
fwcompiler::NATCompiler_ipf::compile()':
NATCompiler_ipf.cc:177: `cout' undeclared (first use this function)
NATCompiler_ipf.cc:177: (Each undeclared identifier is reported only once for
each function it appears in.)
make[2]: *** [PolicyCompiler_ipf.o] Error 1
make[2]: *** Waiting for unfinished jobs....
make[2]: *** [NATCompiler_ipf.o] Error 1
In file included from TargetDialog_pf.hh:31,
from TargetDialog_pf.cc:30:
glademm_support.hh:14: parse error before `::' token
glademm_support.hh:15: parse error before `::' token
glademm_support.hh:17: parse error before `::' token
In file included from TargetDialog_pf.hh:31,
from TargetDialog_pf_glade.cc:11:
glademm_support.hh:14: parse error before `::' token
glademm_support.hh:15: parse error before `::' token
glademm_support.hh:17: parse error before `::' token
make[2]: *** [TargetDialog_pf.lo] Error 1
make[1]: *** [all] Error 2
make[1]: Leaving directory `/var/tmp/portage/fwbuilder-1.0.4/work/fwbuilder-1.0.4/src'
make: *** [all] Error 2
!!! ERROR: The ebuild did not complete successfully.
!!! Function src_compile, Line -15, Exitcode 2
!!! emake failed
!!! emerge aborting on /usr/portage/net-misc/fwbuilder/fwbuilder-1.0.4.ebuild .
I hope it's not my messed up installation ;-)
Dominik
gah!! this one runs deep. i see how the deps need fixing, thanks for pointing
that out. there are some minor c++ corrections which need to be done (upstream
or patched) in libfwbuilder and also fwbuilder itself. fwbuilder seems to depend
on glademm... glademm is broken on gcc3.2 (more upstream c++ problems). so to
fix fwbuilder, glademm might need to be fixed.
I've attempted this, but alas my C++ knowledge won't stretch far enough this time.
Seemant, do you think you could reassign this to someone with the uber-C++
knowledge?
>Comment By: Vadim Kurland (vkurland)
Date: 2002-08-28 01:00
Logged In: YES
user_id=6825
I know. Getting libfwbuilder and fwbuilder to compile with
gcc 3 is not a high priority because some libraries we
depend on are broken anyway (gtk--).
Nevertheless, some of the compile issues mentioned in this
Gentoo bug report have alrady been fixed in libfwbuilder and
fwbuilder code in CVS
thanks for pointing this out
----------------------------------------------------------------------
You can respond by visiting:
matt, perhaps this should be masked out of the 1.4 profile until upstream can
sort this out. (see previous comment). I guess upstream in this case is
ultimately gtk--
okies. i agree, we should remove this from the default-*-2.0 profiles.
Yesterday I succeeded building fwbuilder 1.0.4 after editing the files that
gave
compile errors. The problems were that, when using cout, you need to #include
<iostream>, and using namespace std;. Earlier versions of GCC were less picky.
Furthermore, I hand-edited some include files auto-generated by glademm, where
I
replaced the __STD:: by std:: (or just removed the __STD:: prefix, and added
using namespace std;
Problem here is that the glademm-generated header files explicitly state that
they should never be hand-edited.
If it is useful, I can try to create a diff, and post it (this is my first
experience reporting fixes for compile-problems)
upgrade to 1.0.6/0.10.10
|
http://bugs.gentoo.org/6926
|
crawl-002
|
refinedweb
| 808
| 52.66
|
Access Your APIs
The AWS Mobile CLI and Amplify library make it easy to create and call cloud APIs and their handler logic from your JavaScript.
Set Up Your Backend
Create Your API
In the following examples you will create an API that is part of a cloud-enabled number guessing app. The CLI will create a serverless handler for the API behind the scenes.
To enable and configure an API
In the root folder of your app, run:
awsmobile cloud-api enable --prompt
When prompted, name the API
Guesses.
? API name: Guesses
Name a HTTP path
/number. This maps to a method call in the API handler.
? HTTP path name (/items): /number
Name your Lambda API handler function
guesses.
? Lambda function name (This will be created if it does not already exists): guesses
When prompted to add another HTTP path, type
N.
? Add another HTTP path (y/N): N
The configuration for your Guesses API is now saved locally. Push your configuration to the cloud.
awsmobile push
To test your API and handler
From the command line, run:
awsmobile cloud-api invoke Guesses GET /number
The Cloud Logic API endpoint for the
Guesses API is now created.
Customize Your API Handler Logic
The AWS Mobile CLI has generated a Lambda function to handle calls to the
Guesses API. It is saved locally in
YOUR-APP-ROOT-FOLDER/awsmobilejs/backend/cloud-api/guesses. The
app.js file in that directory contains the definitions and functional code for all of the
paths that are handled for your API.
To customize your API handler
Find the handler for POST requests on the
/numberpath. That line starts with
app.post('number',. Replace the callback function’s body with the following:
# awsmobilejs/backend/cloud-api/guesses/app.js app.post('/number', function(req, res) { const correct = 12; let guess = req.body.guess let result = "" if (guess === correct) { result = "correct"; } else if (guess > correct) { result = "high"; } else if (guess < correct) { result = "low"; } res.json({ result }) });
Push your changes to the cloud.
awsmobile push
The
Guesses API handler logic that implements your new number guessing functionality is now deployed
to the cloud.
Connect to Your Backend
The examples in this section show how you would integrate AWS Amplify library calls using React (see the AWS Amplify documentation to use other flavors of Javascript).
The following simple component could be added to a
create-react-app project to present the number guessing game.
Make a Guess
The
API module from AWS Amplify allows you to send requests to your Cloud Logic APIs right
from your JavaScript application.
To make a RESTful API call
Import the
APImodule from
aws-amplifyin the
GuessNumbercomponent file.
import { API } from 'aws-amplify';
Add the
makeGuessfunction. This function uses the
APImodule’s
postfunction to submit a guess to the Cloud Logic API.
async makeGuess() { const guess = parseInt(this.refs.guess.value); const body = { guess } const { result } = await API.post('Guesses', '/number', { body }); this.setState({ guess: result }); }
Change the Guess button in the component’s
renderfunction to invoke the
makeGuessfunction when it is chosen.
<button type="submit" onClick={this.makeGuess.bind(this)}>Guess</button>
Open your app locally and test out guessing the number by running
awsmobile run.
Your entire component should look like the following:
Next Steps
Learn how to retrieve specific items and more with the API module in AWS Amplify.
Learn how to enable more features for your app with the AWS Mobile CLI.
Learn more about what happens behind the scenes, see Set up Lambda and API Gateway.
|
https://docs.aws.amazon.com/aws-mobile/latest/developerguide/web-access-apis.html
|
CC-MAIN-2018-26
|
refinedweb
| 588
| 64.71
|
Interfacing GPS module with Arduino: Today’s tutorial is about the interfacing of GPS module with Arduino. We will learn what is GPS module? How it is used? How it is interfaced with Arduino to locate position? Today’s tutorial will comprise of following section:
- Introduction to GPS
- Components Required
- Pin out of GPS module
- Key Features
- Wiring Connections
- Note
- Arduino Code
- Applications
Introduction to GPS:.
Let’s assume that the receiver determines that it is 20,000km from a particular satellite. This means that the receiver could be anywhere on an imaginary sphere with the satellite as its center. If it also determines that it is 25,000km from a second satellite this narrows its location down even further. The only location in space where it can be both 20,000km from the first satellite and 25,000km from the second is where these two spheres intersect. That intersection is a circle of points. A third measurement adds another sphere which intersects the circle formed by the first two. This intersection occurs at two points, and so, with these three measurements, the GPS receiver has narrowed down its location to just two points in the entire universe.
A fourth measurement will intersect exactly with one of the two points. In practice, however, you may not need this fourth measurement as one of the two points will normally be located thousands of kilometers out into space, and therefore is unlikely to be your position! However a fourth measurement is used to calculate altitude. It also ensures that the receiver’s clock is truly synchronized with universal time.
Although this example demonstrates the use of four satellites, many receivers are capable of tracking more than four satellites at a time. In some cases this improves the positional accuracy of the receiver.
Components Required
Following is the list of components required for this project.
- GPS module
- GPS Antenna
- Arduino UNO
- LCD 16 x 2
- Breadboard
- Potentiometer 10kohm
- Connecting wires
Pin out of GPS module
GPS module has 4 pins provided out of module for connections.
Key Features:
- Small form factor: 25.4 * 25.4 * 3.
Interfacing GPS module with Arduino
Connect the circuit as follows
- GPS GND to Arduino GND
- GPS Vcc with Arduino 5V
- GPS Rx with Arduino Tx
- GPS Tx with Arduino Rx
- LCD Rs with Arduino digital pin 4
- LCD En with Arduino digital pin 5
- LCD D4 with Arduino digital pin 6
- LCD D5 with Arduino digital pin 7
- LCD D6 with Arduino digital pin 8
- LCD D7 with Arduino digital pin 9
These are the connection which will be used in program. For rest of the LCD connection see tutorial on LCD interfacing with Arduino.
- Connect GPS Antenna with GPS module..
Video Interfacing GPS module with Arduino
Arduino Code of Interfacing GPS module with Arduino
// Creating a Simple GPS Receiver
#include <TinyGPS.h> #include <LiquidCrystal.h> LiquidCrystal lcd( 4, 5, 6, 7, 8, 9 ); // Create an instance of the TinyGPS object TinyGPS gps; void getgps(TinyGPS &gps); void setup() { Serial.begin(4800); lcd.begin(16, 2); } void getgps(TinyGPS &gps) // The getgps function will display the required data on the LCD { float latitude, longitude; //decode and display position data gps.f_get_position(&latitude, &longitude); lcd.setCursor(0,0); lcd.print("Lat:"); lcd.print(latitude,5); lcd.print(" "); lcd.setCursor(0,1); lcd.print("Long:"); lcd.print(longitude,5); lcd.print(" "); delay(3000); // wait for 3 seconds lcd.clear(); } void loop() { byte a; if ( Serial.available() > 0 ) // if there is data coming into the serial line { a = Serial.read(); // get the byte of data if(gps.encode(a)) // if there is valid GPS data... { getgps(gps); // grab the data and display it on the LCD } } }
Result:.
After successfully uploading the program the LCD shows the longitude and latitude of your current position. Write these positions in Google map search bar such that first is latitude and second is longitude separated by a comma and space. Now Google map will display your current position
Applications:
- Automotive and Marine Navigation
- Automotive Navigator Tracking
- Emergency Locator
- Geographic Surveying
- Personal Positioning
- Sporting and Recreation
- Embedded applications: Smart phone, UMPC, PND, MP
4 thoughts on “Interfacing GPS module with Arduino: GPS coordinates on Lcd”
I don’t want co ordinates on lcd and I m using Intel gallio and S1216F8 GPS module.Help me to achieve co ordinates on Serial monitor.Thank you in Advance.
Im using the same connections and the same code. But, “Serial.available()” is always returning “0”. Plz Help.
Your GPS module is not working
Hello sir, can i use a battery and no computer after uploading?
|
https://microcontrollerslab.com/interfacing-gps-module-arduino/
|
CC-MAIN-2021-39
|
refinedweb
| 767
| 54.52
|
Some tips and tricks about the documentation system
I had some trouble to use the new documentation system. I'm putting here some tips and tricks. This page was build by gathering informations from the mailing list and irc. This may not be the right way to do. Please expand and correct...
It has been said on the mailing list that this page is of general interest for the sage community and should not stay hidden inside combinat. I would be happy to move it elsewhere, if someone suggest me a proper place and from where to link it. If you move it, please don't forget to update the link at the bottom of the sage-combinat home page -- Florent.
Contents
- How to write and compile Sage documentation
- Trouble shooting
- Do you want to know more ?
- Random tips and Tricks
1. How to write and compile Sage documentation
The format is called ReST for ReStructuredText and the doc builder is called Sphinx
1.1. For the impatient
- The two most important things to know are
``inline literal`` for sage raw code
`LaTeX interpreted text` for mathematics
Any line ending with :: means that the following indented things are a literal block (usually sage: commands)
1.2. The ReST Format
The link quickref gives a not so short description of the format
1.3. Step by step instruction for building the doc
- First issue a
sage -b
to make sure that the sage is up-to-date with your modifications. Then depending of the desired format you call
sage -docbuild reference <format>
For example, I use the html format so that I call
sage -b && sage -docbuild reference html
Then the compiled doc is found at
$SAGE_ROOT/devel/sage/doc/output/html/en/reference/index.html
You can use you browser to view it...
- You can get some help on the docbuild system by:
sage -docbuild -help
explains all the sage -docbuild options.
1.4. Setting hyperlink to modules, classes, methods, etc
The full explanation can be found at
It is not possible to define chapters and labels and things in the autogenerated documentation ("because of the way it is produced" according to Mike Hansen), but as you will see there should be no needs. Indeed, it is possible to generate a link to the documentation for any module, class, method, function, etc. The syntax is
:role:`title <target>`
or
:role:`target`
where
role is the kind of thing you what to link to (ie mod for module, class for classes, meth for methods, func for functions, etc;
target is the python name of the object (class, module, method...) which carry the doc to be linked to;
title is the name the link appear in the browser.
If you don't provide any title then target will be used.
For example, to link the dyck_word module, you'd do something like auto-generated.
Finally local name are handled. That is, for example, in the definition of a class (and any of its members or methods), you can link to any member or method of the same class by simply giving the name of it prepended by a dot ".". You dont need to give the full address of it. For example:
:meth:`.to_dyck_word`
set up a link of the .to_dyck_word() method of the current class if it exists. If not the doc builder search going up in the class/module hierarchy of python until it find a object under this name or reach the toplevel module without finding it. If it occur the title is typeset in boldface without any link produced and also without any error or warning. Note that without the prepended dot the object is searched starting from the toplevel to the innermost module/class.
- I don't know is it's possible and how to activate some report of the missing targets -- Florent
1.5. Adding a new file to the doc
If you write a new file say sage/combinat/family.py and you want your doc to be added to the system you have to add your file in the relevant index.rst file usually located in the tree:
$SAGE_ROOT/devel/sage-combinat/doc/en/reference
Going back to my example I have to add to the file
$SAGE_ROOT/devel/sage-combinat/doc/en/reference/combinat/index.rst
the following line
Combinatorics ============= .. toctree:: :maxdepth: 2 ../sage/combinat/combinat [...] ../sage/combinat/dyck_word + ../sage/combinat/family ../sage/combinat/finite_class [...]
1.6. How to find the unincluded docs ?
They are currently a lot of file that hasn't been referenced. They do not appear in the doc. You can generate the list of those files by
sage -docbuild reference print_unincluded_modules
2. Trouble shooting
2.1. Compilation fails with "Too many open files"
- On a machine I got the following error:
File "/home/combi/hivert/Sage/sage-3.4/local/lib/python2.5/subprocess.py", line 1003, in _execute_child errpipe_read, errpipe_write = os.pipe() OSError: [Errno 24] Too many open files The full traceback has been saved in /tmp/sphinx-err--kaK6F.log, if you want to report the issue to the author. Please also report this if it was a user error, so that a better error message can be provided next time. Send reports to [email protected] Thanks! Build finished. The built documents can be found in /home/combi/hivert/Sage/sage/devel/sage/doc/output/html/en/reference
I don't understand why but I nevertheless managed to build the doc using jsmath
sage -docbuild --jsmath all html
2.2. If you have deleted some doc file
Suppose that you added your file to some index.rst and then you delete it (e.g. by unapplying some patch). This cause some trouble because the build system left some garbage. Here there after unapplying the patch the file enumerated_sets.py does not exists anymore:
OSError: [Errno 2] No such file or directory: '/usr/local/sage/sage-3.4/devel/sage-combinat/doc/en/reference/sage/categories/enumerated_sets.rst'
Right now I don't know a good fix. Here are the methods I use:
Delete all the copy of enumerated_sets.py and enumerated_sets.pyc at the various positions of $SAGE_ROOT/devel/sage/build
Delete the enumerated_sets.rst file
If this still not work you can simply
Nuke the whole $SAGE_ROOT/devel/sage/doc/output tree !
3. Do you want to know more ?
Why was it decided to switch ?
The new format of doc is called reStructuredText it is hosted on sourceforge at ReST.
4. Random tips and Tricks
4.1. How to use "sage -t" outside sage tree
It does work, on has to use .py files. First do a
export SAGE_PATH=<path_to_your_files>
then for each function, import your functions from the appropriate module/file, e.g.,
from my_module import my_func
Here is what worked for me (John Cremona). Suppose that I have a stand-alone .py file, say myfile.py, containing various functions with doctests.
- No need to set any environment variables
- Put the line
from sage.all import *
at the top of the file.
- cd to the directory the file is in and type
sage -t myfile.py
4.2. Emacs mode for editing ReST files
It seems to be included in every major Linux distributions.
For Ubuntu 8.10 things worked out of the box with python-docutils.rpm installed.
For SuSE 11.1, the file is in docutils.rpm but not in emacs search path so you have to link it from
/usr/share/doc/packages/docutils/tools/editors/emacs/rst.el
to whatever place in emacs load path. To load it you have also to load lazy-lock before because is not automatically loaded since it is marked as obsolete:
(require 'lazy-lock) (require 'rst)
You can find informations on
Have a nice doc !!!
|
https://wiki.sagemath.org/combinat/HelpOnTheDoc
|
CC-MAIN-2020-05
|
refinedweb
| 1,299
| 65.62
|
Premier IT Outsourcing and Support Services within the UK
Problem, Formatting or Query - Send Feedback
Famous Bugs courtesy of Dave Curry (ecn.davy@purdue).
Originally From John Shore (shore@nrl-css)
Some time ago, I sent out a request for documented reports on
"famous bugs", promising to summarize the results for all who contributed. This is the promised summary.
I judge the effort as a failure. People encounter bugs and fix bugs
and talk about bugs, but they rarely document bugs. Those responding to my request were well meaning and helpful, but I was left feeling a little like my hair was being done by a gossip-laden ex-hacker.
I am, of course, no different. I didn't have documentation for
most of the famous bugs I knew about, and I don't have sufficient time, energy, and interest to follow all the leads. I should have known better.
One strong conclusion that I've reached is that many
computer system horror stories become known as bugs when in fact they are not – they're system problems that result from hardware failures, operator mistakes, and the like. Let me mention a few examples. In his book Software Reliablility, Glenford Myers mentioned a number of classical software errors. For example, he mentioned that a software error in the onboard computer of the Apollo 8 spacecraft erased part of the computer's memory. I happen to have a copy of a memo by Margaret Hamilton that summarized the conclusions of a detailed study of every Apollo bug (see below), so I looked under Apollo 8. The best I could find was this: "16. Illegal P01. P01 was selected during midcourse, illegally by the astronaut. This action destroyed W-matrix (several erasables in AGC)." The software did erase the memory, but it did so because the astronaut did something illegal, and not because the programmer goofed. This example is characteristic of the Apollo errors (see below), most of which show the need for better exception handling as part of the software specification. But weak specifications are not the same thing as bugs.
Here's another example, also from Apollo. It starts with a
note to me from Kaeler.pa at Xerox (via Butler Lampson):
I heard about the MIT summer student at NASA whose Apollo program filled up memory (with logging information) and flashed the red abort light a few seconds before the first moon landing. The student was in the control room, and after a little thought, said, "Go ahead, I know what it is, I will take responsibility". Luckily, he was right. He was awarded all sorts of medals for being willing to take the responsibility.
You should get this story from the horse's mouth before distributing it. I heard it from Neil Jacobstein (212-454-0212, in new york). He heard it from his advisor at the Johnson Space Center in Houston a few years ago. It might be interesting to trace this back to someone who really knows about it.
I called Jacobstein, and after some discussion he decided that the "bug" was probably the famous "1201 descent alarm" that I mention below. Again, this was caused by an astronaut error (a radar was turned on when it should have been off).
Lot's of people mentioned to me various NORAD "bugs" that
caused alerts. I got a copy of a Senate Armed Services Committee Report of 9 October, 1980, "Recent False Alerts From the Nation's Missile Attack Warning System." It deals primarily with the June 1980 alerts, but it contains the following summary:
Oct. 3, 1979 -- An SLBM radar (Mt. Hebro) picked up a low orbit rocket body that was close to decay and generated a false launch and impact report.
November 9, 1979 -- False indications of a mass raid caused by inadvertent introduction of simulated data into the NORAD Computer System.
March 15, 1980 -- Four SS-N-6 SLBMs were launched from the Kuril Islands as part of Soviet troop training. One of the lauches generated an unusual threat fan.
June 3, 1980 -- False indications caused by a bad chip in a communications processor computer
According to Borning@Washington (who by the way is studying computer problems in missile warning systems), the cause of the Nov. 1979 problem was as follows:
To test the warning system, false attack data was intermixed with data from actual satellite observations, put on tape, and run through the system. On November 9, the test tape of this sort was accidentally left mounted on a secondary backup computer. This machine was left connected to the system in use. When the primary computer failed, a backup computer was activated, which also failed. Then the secondary computer came into play, causing the alert.
All of these missile alerts were caused by real flying objects, hardware failures, or human error. I'm not saying that bugs didn't cause any missile alerts, just that the ones that are reputed to have been caused by bugs in fact were not.
Perhaps computer software -- as opposed to the combination of
hardware, software, and people – is more reliable than folklore has it. I would be interested in hearing your comments on this proposition.
Despite the foregoing problems, the assembly of responses makes
interesting reading. In the following, I'll mention a few well-documented bugs and then append various extracts from what I received. Thanks to all who responded. In most cases, I eliminated duplicates. Special thanks to Peter Neumann (SRI), who seems to be keeping better track of these problems than anyone else. Many of these don't qualify as bugs by anyone's definition, but they're interesting stories so I've included some of them anyway.
Space-Shuttle Bug
This may be the most famous of all -- the one that delayed at the last
minute the launch of the first space shuttle. The cause was was a bug that interfered with the communication between concurrent processes – an area of progamming that is among the least well in hand. John R. Garman wrote about the problem in detail in ACM SIGSOFT Software Engineering News (SEN), vol. 6, No. 5, pp 3-10.
The First Bug
Worth mentioning for the trivia folks, it was a moth that
was beaten to death by a relay in the Mark II. It was discovered by the Mark II staff, which included Grace Hopper. (Reports on this are a bit confusing. Many attribute the bug to her; in her own published account she refers to "we". I called and asked her. She said the machine operator actually pulled the moth out, and that it was found by the combined efforts of the staff.) Lots of people mentioned this bug to me; my favorite report attributed the bug to
"some little old lady who works for the Navy. She's the one who came up with Cobol, I think."
In fact, this is one of the better-documented bugs. You can even see its picture in the Anals of the History of Computing (vol. 3, July 1981, page 285). It's ironic that "modern" bugs have practically nothing in common with the first one (an exception being Dijkstra's well known remark about testing).
ARPANET Gridlock
In October 1980 the net was unusable for a period of several
hours. It turned out that the routing processes in all the IMPs were consuming practically all resources as the result of processing three inconsistent routing updates. It turned out that the inconsistency arose from dropped bits in a single IMP. Whether you choose to call this a bug or not, clearly it demonstrated a design failure. The details are reported well by Eric Rosen in SEN, January 1981.
APOLLO flight experiences
When Margaret Hamilton was working at the Charles Stark Draper
Laboratory in the early 1970s, she documented and analyzed in some detail the various "software anomalies" that occurred during several APOLLO flights. Apparently she did this at the request of Marty Shooman. I don't think that she ever published the results, but some years back she gave us a copy of "Shuttle Management Note #14" (23 October 1972), which summarized her analysis. It makes interesting reading.
One of her strongest conclusions was that 73% of the problems were
caused by "real-time human error". Translated roughly into 1983 computer-speak, this means that the APOLLO software wasn't user friendly. (I guess they didn't have icons or something.) Apparently, there was much debate about this during the design, but the software types were told that astronauts have the right stuff or something so there was no need to make the software robust.
One example is quite widely known, as it occured during the APOLLO
11 landing on the moon. In what was referred to as "1201-1202 Descent Alarms", the software kept restarting as the result of overloading. Turned out the radar switch was in the wrong position and used up 13% more computer time than had been anticipated.
Hamilton states that "pure software errors" were not a problem on
APOLLO flights. I guess she means that the software met its specifications, which is quite an accomplishment. But the specifications apparently did not say much about error detection and recovery. Hamilton states that "all potentially catastrophic problems would have been prevented by a better and/or known philosophy of providing error detection and recovery via some mechanism."
Nuclear Reactor Design Program
I don't know when the bug was first introduced, but
it transpired in 1979. From Jim Horning (Horning.pa@parc-maxc):
A belatedly-discovered bug in a stress analysis program (converting a vector into a magnitude by summing components–rather than summing absolute values; module written by a summer student) caused a number of nuclear reactors to be closed down for checks and reinforcement a about three years ago (not long after TMI). This was fairly widely discussed in the press at the time, but I never did see how the lawsuits came out (if, indeed, they have been completed).
From br10@cmu-10a came the following newswire stories:
a023 0026 16 Mar 79 PM-Topic, Advisory, Managing Editors: Wire Editors:
It all started in a tiny part of a computer program used by an
engineering firm designing nuclear reactors. It ended with the shutdown of five nuclear power plants at a time when President Carter is pushing oil conservation and the world oil market is in turmoil.
The computer miscalculated some safety precautions required by law.
The power from the closed plants now will have to be replaced by electicity generated with oil or coal. This may cost utility customers money and throw a curve at Carter's conservation program.
In Today's Topic: The Little Computer and the Big Problem, AP writer
Evans Witt traces this glitch in the system, from the obscure computer to its possible effect on the nation's energy problems.
The story, illustrated by Laserphoto NY7, is upcoming next. The AP
ap-ny-03-16 0328EST
*
a024 0044 16 Mar 79
PM-Topic-Glitch, Bjt,950
TODAY'S TOPIC: The . yyter and the Big Problem
Laserphoto NY7
By EVANS WITT
Associated Press Writer
WASHINGTON (AP) - Something just didn't add up.
And the result is: five nuclear power plants are shut down;
millions of Americans may pay higher utility bills; and a sizable blow
may have been struck to President Carter's efforts to reduce the use of
imported oil and to control inflation.
The immediate source of all this is part of the federal bureaucracy
- the Nuclear Regulatory Commission which ordered the shutdowns.
But in one sense, the ultimate culprit was
Shock II, a tiny
part of a computer program used by a private firm to design the power
plants' reactors.
Shock II was wrong and that means parts of the five reactors might
not survive a massive earthquake. Shock II was the weak link that
could have allowed the chain to snap.
In between Shock II and the shutdowns were a public utility, a
private engineering firm and the NRC staff. It was really the
judgments of the dozens of scientists and engineers, not elected or
appointed officials, that led to the shutdowns.
Perhaps as a result, the decision's impact on the nation's energy
situation was not even considered until the very last moment - when
the commission itself was faced with the final decision.
And at that point, the NRC said, it had no choice. It said the law
was clear: serious questions about the reactors had been raised and
the reactors had to be turned off until answers were found.
The specific questions are arcane engineering issues, but the
explanation is straightfoward: Will some of the systems designed to
protect the reactor survive an earthquake - or will they fail, and
possibly allow radioactive death to spew into the air?
The regulations say the reactors must be able to withstand a quake
equal to the strongest ever recorded in their area. The regulations
don't allow any consideration of the likelihood of a major quake. All
four states where the reactors are located - New York, Pennsylvania,
Maine and Virginia - have had minor quakes in this decade and
damaging quakes at least once in this century.
The only way to test them - short of having a massive earthquake -
is to test a model of the reactor. The
model is actually a set of
mathematical formulas in a computer that reflect how the reactor and
its parts will behave in a quake.
The model used for the five reactors came from Stone and Webster,
the large Boston engineering and architectural firm that designed the
plants. The Stone and Webster model indicated how strong and well
supported pipes had to be and how strong valves had to be.
The problem apparently cropped up after Stone and Webster suggested
within the last few months more pipe supports in the secondary
cooling system of the reactor at Shippingport, Pa., operated by
Duquesne Light Co. in Pittsburgh.
But why were the supports needed?
This was not clear to us,
looking at the calculations done by the models, said Gilbert W.
Moore, Duquesne's general superintendent of power stations.
So Dusquesne - and Stone and Webster - sent the computer models
through their paces again, having them calculate and recalculate what
would happen to the pipes in an earthquake.
We came out with some numbers which were not in the range we
would like, Moore said.
That made the problem clear - the model now said the pipes might
break in an earthquake. The previous analysis indicated an adequate
safety margin in the pipes, and Stone and Webster's explanation was:
One subroutine may not give uniformly conservative results.
The problem was in a
subroutine, a small part of the computer
model, called
Shock II, said Victor Stello, director of NRC's
division of reactor operations.
The facts were that the computer code they were using was in
error, said Stello.
Some of the computer runs were showing things
are okay. In some cases, the piping systems were not okay.
We didn't know the magnitude of the error or how many plants
might be affected,
he said.
It was on March 1 that Duquesne told the NRC of the problem by
telephone and asked for a meeting to discuss it. The same day, Energy
Secretary James R. Schlesinger was telling Congress that unleaded gas
might cost $1 a gallon within a year and service stations might be
ordered shut down on Sundays because of oil shortages.
The meeting took place on Thursday, March 8, in Washington with NRC
staff, Stone and Webster engineers and Duquesne Light people on hand.
Through the weekend, Stello said, engineers from NRC, Duquesne and
Stone and Webster worked at the private firm's Boston office,
analyzing the severity of the problem.
By the middle of Sunday (March 10) we begin to get a pretty good
idea of what it meant for the systems,
Stello said. Monday, we got
the latest information from our people at the Stone and Webster
offices. It became clear that there would be a number of the safety
systems that would have stresses in excess of allowable limits. The
magnitude of the excess was considerable.
Tuesday, members of the NRC were briefed by their staff of
engineers and scientists. They asked for an analysis of the economic
impact of the decision, and then ordered the plants closed within 48
hours.
And the five reactors shut down: Duquesne Light Co.'s Beaver Valley
plant at Shippingport, Pa.; Maine Yankee in Wiscasset, Maine; the
Power Authority of New York's James Fitzpatrick plant at Scriba, N.Y.;
and two Virginia and Electric Power Co. reactors at Surry, Va.
It may take months to finish the analysis of the potential problems
and even longer to make changes to take care of the situation.
Until the reactors start generating again, the utilities will have
to turn to plants using oil or coal. This may cost more, and that cost
may be borne by the millions of utility customers.
To replace the power from these nuclear plants could require
100,000 barrels of oil a day or more. And this at a time when
President Carter has promised to cut U.S. oil consumption by 5 percent
- about 1 million barrels a day - and when the world's oil markets are
in turmoil because of recent upheavals in Iran.
——————————-
Summary of various problems from NEUMANN@SRI-AI
Review of Computer Problems – Catastrophes and Otherwise
As a warmup for an appearance on a SOFTFAIR panel on computers and
human safety (28 July 1983, Crystal City, VA), and for a new editorial
on the need for high-quality systems, I decided to look back over
previous issues of the ACM SIGSOFT SOFTWARE ENGINEERING NOTES [SEN]
and itemize some of the most interesting computer problems recorded.
The list of what I found, plus a few others from the top of the head,
may be of interest to many of you. Except for the Garman and Rosen
articles, most of the references to SEN [given in the form (SEN Vol
No)] are to my editorials.
SYSTEM –
SF Bay Area Rapid Transit (BART) disaster [Oct 72]
Three Mile Island (SEN 4 2)
SAC: 50 false alerts in 1979 (SEN 5 3);
simulated attack triggered a live scramble [9 Nov 79] (SEN 5 3);
WWMCCS false alarms triggered scrambles [3-6 Jun 80] (SEN 5 3)
Microwave therapy killed arthritic patient by racing pacemaker (SEN 5 1)
Credit/debit card copying despite encryption (Metro, BART, etc.)
Remote (portable) phones (lots of free calls)
SOFTWARE –
First Space Shuttle launch: backup computer synchronization (SEN 6 5 [Garman])
Second Space Shuttle operational simulation: tight loop on cancellation
of early abort required manual intervention (SEN 7 1)
F16 simulation: plane flipped over crossing equator (SEN 5 2)
Mariner 18: abort due to missing NOT (SEN 5 2)
F18: crash due to missing exception condition (SEN 6 2)
El Dorado: brake computer bug causing recall (SEN 4 4)
Nuclear reactor design: bug in Shock II model/program (SEN 4 2)
Various system intrusions …
HARDWARE/SOFTWARE –
ARPAnet: collapse [27 Oct 1980] (SEN 6 5 [Rosen], 6 1)
FAA Air Traffic Control: many outages (e.g., SEN 5 3)
SF Muni Metro: Ghost Train (SEN 8 3)
COMPUTER AS CATALYST –
Air New Zealand: crash; pilots not told of new course data (SEN 6 3 & 6 5)
Human frailties:
Embezzlements, e.g., Muhammed Ali swindle [$23.2 Million],
Security Pacific [$10.2 Million],
City National, Beverly Hills CA [$1.1 Million, 23 Mar 1979]
Wizards altering software or
critical data (various cases)
SEE ALSO A COLLECTION OF COMPUTER ANECDOTES SUBMITTED FOR the 7th SOSP
(SEN 5 1 and SEN 7 1) for some of your favorite operating system
and other problems…
[Muni Metro Ghosts]
The San Francisco Muni Metro under Market Street has been plagued with
problems since its inauguration. From a software engineering point of
view, the most interesting is the Ghost Train problem, in which the
signalling system insisted that there was a train outside the
Embarcadero Station that was blocking a switch. Although in reality
there was obviously no such train, operations had to be carried on
manually, resulting in increasing delays and finally passengers were
advised to stay above ground. This situtation lasted for almost two
hours during morning rush hour on 23 May 1983, at which point the
nonexistent train vanished as mysteriously as it had appeared in the
first place. (The usual collection of mechanical problems also has
arisen, including brakes locking, sundry coupling problems, and
sticky switches. There is also one particular switch that chronically
causes troubles, and it unfortunately is a weakest-link single point
of failure that prevents crossover at the end of the line.)
———————
Problems mentioned in the book Software Reliability, Glen Myers
Myers mentions a variety of problems. One famous one (lot's of
people seem to have heard about it) is the behavior of an early
version of the ballistic missile early warning system in identifying
the rising moon as an incoming missile. Myers points out that, by
many definitions, this isn't a software error – a problem I discussed
a bit at the beginning of this message.
Other problems mentioned by Myers include various Apollo errors I've
already mentioned, a 1963 NORAD exercise that was incapacitated because
"a software error casued the incorrect routing of radar information",
the loss of the first American Venus probe (mentioned below in more
detail). Mentioned with citations were an Air Force command system that
was averaging one software failure per day after 12 years in operation,
deaths due to errors in medical software, and a crash-causing error
in an aircraft design program. I was not able to follow up on any of
the citations.
The rest of this message contains excerpts from things I received from
all over, in most cases presented without comments.
faulk@nrl-css (who got it elsewhere)
Today, I heard good story that is a perfect example of the problems
that can arise whe the assumptions that one module makes about another
are not properly documented. (The story is from a system engineer here
whose father got it from the Smithsonian Space people.)
Aparently, the Jupiter(?) probe to mars could have programs beamed to
it which it would load in internal memory. The system engineers used this
property to make mission changes and/or corrections. After the probe had
been on Mars for a while, memory started getting tight. One of the
engineers had the realization that they no longer needed the module that
controled the landing so the space could be used for something else. The
probe was sent a new program that overwrote the landing module. As soon as
this was accomplished, all contact was lost to the probe.
Looking back into the code to find what had gone wrong, the programmers
discovered that because the landing module had to have information on
celestial navigation, some or all of the celestial navigation functions
were inclded in the landing module. Unfortunately, the antenna pointing
module also required celestial navigation information to keep the antenna
pointed at earth. To do this, it use the navigation functions in the
landing module. Overlaying the module has left the antenna pointing in some
unknown direction and all contact with the craft has been lost forever.
Fortunately, all of the mission requirements had been fulfilled so it
was no great loss. It can live on as a great example of bad design.
————————-
mo@LBL-CSAM
The folklore tells of a bug discovered during the fateful
flight of Apollo 13. It seems that the orbital mechanics
trajectory calculation program had a path which had never been
excercised because of the smooth, gentle orbital changes
characteristic of a nominal Apollo flight. However, when
the flight dynamics team was trying ways to get them home with
the aid of much more creative maneuvers, the program promplty
crashed with a dump (running on IBM equipment, I believe).
The story goes that the fix was simple - something on the
order of a missing decimal, or a zero-oh reversal,
(Divide by zero!!!!!)
but there was much consternation and tearing of hair when this
critical program bought the farm in the heat of the moment.
This was related to me by an ex-NASA employee, but I have heard
it through other paths too. I guess the NASA flight investigation
summary would be one place to try and verify the details.
—————————-
jr@bbncd
One cute one was when the Multics swapper-out process swapped out the
swapper-in process. (recall that all of the Multics OS was swappable)
————————————
dan@BBN-UNIX
Here in Massachusetts we've recently begun testing cars for emissions. All car
inspections are carried out at gas stations, which in order to participate in
the program had to buy a spiffy new emissions analyzer which not only told you
what your emissions were, but passed judgement on you as well, and kept a
recorrd on mag tape which was sent to the Registry of Motor Vehicles so that
they could monitor compliance.
Well, on June 1 the owners of the cheaper ($8K) of the two acceptable analyzers
discovered that their machines could not be used; they didn't like the month of
June! The company which built them, Hamilton, had to apply a quick fix which
told the machines that it was actually December (!?). Lots of people were
inconvenienced.
Unfortunately all I know about this at the moment is what the Boston Globe had
to say, so I don't know what the actual problem was. The article said that the
quick cure involved replacing the "June" chip with the "December" chip; I don't
know what that means, if anything. Electronic News or Computerworld ought to
have more accurate information.
Don't forget about the rocket launch early in the space program which had to be
aborted because the Fortran program controlling it believed that the number of
seconds in a day was 86400 (rather than the sidereal time figure).
The recent issue of Science News with the cover story on when computers make
mistakes mentioned a story about a graduate student who almost didn't get his
thesis due to inaccuracies in the university computer's floating point
software. Not really earthshaking, except to him, I suppose.
—————————–
STERNLIGHT@USC-ECL
I don't have the data, but there were at least two "almost launches"
of missiles. The rising moon was only one. You
might try contacting Gus Weiss at the National Security Council–
he will be able to tell you quite a bit. Mention my name if you
like.
[I called Weiss, who didn't have much to say. He kept repeating
that the problems were fixed–js]
——-
mark@umcp-cs
The following is probably not famous except with me, but deserves to be.
True story:
Once upon a time I managed to write a check so that my
bank balance went exactly to zero. This was not so unusual an
occurance, as my checking account had an automatic loan feature
in case of overdraft, and I used this feature occasionally.
Negative and positive balances were therefore well known in this
account. Not so zero balances.
Soon after writing this check I attempted to withdraw
some funds using my money machine card. Unsuccessful. I
attempted to DEPOSIT money via the machine. Unsuccessful.
I talked to a person: they had no record of my account ever
having existed.
After several trips to the bank, each time up one more
level in the management hierarchy, I, the bank managers and me,
discovered the following: The bank's computer had been programmed
so that the way to delete an account was to set the balance to
zero. When I wrote my fatal zeroing check the computer promptly
forgot all about me. Only my passion for paper records, and the
bank's paper redundancy, enabled the true story to emerge and
my account to be restored.
Interestingly, no funds were ever in danger, since the
account was closed with NO MONEY in it. Nonetheless, the
inconvenience was considerable. Once the situation became
straightened out I immediately transferred my account to another
bank, writing a letter to the first bank explaining my reasons
for doing so.
——————————–
craig@umcp-cs
The most famous bug I've ever heard of was in the program
which caluclated the orbit for an early Mariner flight
to Venus. Someone changed a + to a - in a Fortran
program, and the spacecraft went so wildly off course
that it had to be destroyed.
——————————–
fred@umcp-cs
Some examples of bugs I've heard about but for which I
don't have documentation: (a) bug forced a Mercury astronaut
to fly a manual re-entry; . . .
There was something about this on the Unix-Wizards mailing list a
while back. The way I understand it, a programmer forgot that the
duration of the Mercury Capsule's orbit had been calculated in
siderial time, and left out the appropriate conversion to take into
account the rotation of the Earth beneath the capsule. By the end
of the mission the Earth had moved several hundred miles from where
it ``should have been according to the program in question. Sorry
I can't give you any definite references to this.
———————
KROVETZ@NLM-MCS
I've heard of two bugs that I think are relatively famous:.
2. I'm not sure where this error cropped up, but one of the earlier versions
of FORTRAN a programmer passed a number as an actual argument (e.g.
CALL MYPROC(2)) and within the procedure changed the formal argument.
Since FORTRAN passes arguments by reference this had the result of changing
the constant "2" to something else! Later versions of FORTRAN included a
check for changing an argument when the actual is an expression.
————————————-
uvicctr!dparnas
>From jhart Thu Jun 9 13:30:48 1983
To: parnas
San Fransisco Bay Area Rapid Transit, reported in Spectrum about two
years ago. "Ghost trains", trains switched to nonexistent lines,
and best of all the rainy day syndrome.
————————————-
uvicctr!uw-beaver!allegra!watmath!watarts!geo
One of my pals told me this story. One morning, when they booted,
years ago, the operators on the Math faculty's time-sharing system
set the date at December 7th, 1941 (ie Pearl Harbor). Well the
spouse of the director of the MFCF (ie Math Faculty Computing Facility)
signed on, was annoyed by this, and changed the date to the actual
date. Everyone who was signed on while this was done was charged
for thirty-something years of connect time.
I wouldn't know how to document this story.
Oh yes, didn't Donn Parker, self-proclaimed computer sleuth, call
the fuss made over UNIX and intelligent terminals some outrageous
phrase, like 'The bug of the century'? I am refering to the fuss
made over the fact that some of the terminals that berkeley had bought
were sufficiently intelligent, that they would do things on the command
of the central system. The danger was that if someone was signed
on to one of these terminals as root, an interloper could write
something to this terminal causing the terminal to silently transmit
a string back to UNIX. Potentially, this string could contain a
command line giving the interloper permissions to which they were
not entitled.
Cordially, Geo Swan, Integrated Studies, University of Waterloo
allegra!watmath!watarts!geo
—————————-
smith@umcp-cs
John, another bug for your file. Unfortunately it is a rumor that I
I haven't tried to verify. Recall that FORTRAN was developed on the
IBM 704. One of the 704's unusual features was that core storage used
signed magnitude, the arithmatic unit used 2's complement, and the
index regesters used 1's complement. When FORTRAN was implemented
on the IBM product that replaced the 704, 7094 etc. series, the
3 way branching if went to the wrong place when testing negative zero.
(It branched negative, as opposed to branhing to zero). I heard this
rumor from Pat Eberlein (eberlein@buffalo). Supposedly, the bug wasn't
fixed (or descovered) for two years.
—————————-
VES@KESTREL
1. In the mid 70's in a lumber provessing plant in Oregon a program was
controlling the cutting of logs into boards and beams. The program included
an algorithm for deciding the most efficient way to cut the log (in terms of
utilizing most of the wood), but also controlled the speed with which the log
was advancing.
Once the speed of a log increased to dangerous levels. All personnel
was scattered and chased out of the building, the log jumped off the track,
fortunately there were no casualties. This was caused by a software bug.
A reference to the event would be the former director of the Computer Center
at Oregon State University (prior to 1976), who at the time I heard the story
(Spring 1977) was President of the company which developed the software.
2. Abother rather amusing incident dates back to the mid 60's. It
was not caused by a software bug but is indicative of the vulnerability of
software systems particularly in those early days. It involved the Denver
office of Arizona airlines. Their reservation system was periodically getting
garbage input. Software experts were dispatched but failed to identify the
cause. Finally the software manager of the company which developed the system
went to study the problem on the spot.
After spending a week at the site he managed to identify a pattern
in the generation of garbage input: it was happening only during the shifts
of a paticular operator and only when coffie was served to her. Shortly
afterwards the cause was pinpointed. The operator was a voluminous lady
with a large belly. The coffie pot was placed behind the terminal and
when she would reach for it her belly would rest on the keyboard. Unfortuna-
tely, I don't have more exact references to that event.
—————————-
RWK at SCRC-TENEX
There's the famous phase-of-the-moon bug which struck (I believe)
Gerry Sussman and Guy Steele, then both of MIT. It turned out to
be due to code which wrote a comment into a file of LISP forms,
that included the phase of the moon as part of the text. At certain
times of the month, it would fail, due to the comment line being
longer than the "page width"; they had failed to turn off automatic
newlines that were being generated by Maclisp when the page width
was exceeded. Thus the last part of the line would be broken onto
a new line, not proceeded with a ";" (the comment character). When
reading the file back in, an error would result.
——————————–
gwyn@brl-vld
An early U.S. Venus probe (Mariner?) missed its target immensely
due to a Fortran coding error of the following type:
DO 10 I=1.100
Which should have been
DO 10 I=1,100
The first form is completely legal; it default-allocates a REAL
variable DO10I and assigns 1.1 to it!
————————————-
Horning.pa@PARC-MAXC
I have heard from various sources (but never seen in print) the story
that the problem with the wings of the Lockheed Electras (that caused
several fatal crashes) slipped past the stress analysis program because
of an undetected overflow. This one would probably be next to impossible
to document.
One of my favorite bugs isn't all that famous, but is instructive. In
about 1961, one of my classmates (Milton Barber) discovered that the
standard integer binary-to-decimal routine provided by Bendix for the
G-15D computer wasn't always exact, due to accumulated error from short
multiplications. This only affected about one number in 26,000, but
integer output OUGHT to be exact. The trick was to fix the problem
without using any additional drum locations or drum revoltions. This
occupied him for some time, but he finally accomplished it. His new
routine was strictly smaller and faster. But was it accurate? Milton
convinced himself by numerical analysis that it would provide the
correct answer for any number of up to seven digits (one word of BCD).
Just to be safe, he decided to test it exhaustively. So he wrote a loop
that counted in binary and in BCD, converted the binary to BCD, and
compared the results. On the G-15D this ran at something like 10 numbers
per second. For several weeks, Milton took any otherwise idle time on
the college machine, until his loop had gone from 0 to 107-1 without
failure. The he proudly submitted his routine to Bendix, which duly
distributed it to all users. Soon thereafter, he got a telephone call:
"Are you aware that your binary to decimal conversion routine drops the
sign on negative numbers?" This is the most exhaustive program test that
I've ever seen, yet the program failed on half its range!
Horning.pa
[Excerpts from a trip report by Dr. T. Anderson of the University of Newcastle upon Tyne.]
The purpose of my trip was to attend a subworking group meeting on the production of reliable software, sponsored by NASA, chaired by John Knight (University of Virginia), and organized and hosted by the Research Triangle Institute [Nov. 3-4, 1981]. Essentially, NASA would like to know how on earth software can be produced which will conform to the FAA reliability standards of 10^-9 failures/hour. Sadly, no one knew.
FRANK DONAGHE (IBM FEDERAL SYSTEMS DIVISION): PRODUCING RELIABLE SOFTWARE FOR THE SPACE SHUTTLE
Software for the Space Shuttle consists of about 1/2 million lines of code, produced by a team which at its largest had about 400 members. Costs were high at about $400 per line. . . . Between the first and second flight 80% of the mdoules were changed, such that about 20% of the code was replaced. Three weeks prior to the second flight a bug in the flight software was detected which tied up the four primary computers in a tight (two instruction) loop. .
Laws@SRI-AI
Don't forget the bug that sank the Sheffield in the Argentine war. The shipboard computer had been programmed to ignore Exocet missiles as "friendly." I might be able to dig up an IEEE Spectrum reference, but it is not a particularly good source to cite. The bug has been widely reported in the news media, and I assume that Time and Newsweek must have mentioned it.
I'll try to find the reference, but I must issue a disclaimer: some of my SRI associates who monitor such things more closely than I (but still without inside information) are very suspicious of the "bug" explanation. "Computer error" is a very easy way to take the heat off, and to cover what may have been a tactical error (e.g., turning off the radar to permit some other communication device to function) or a more serious flaw in the ship's defensive capability.
PARK@SRI-AI
From International Defense Review and New Scientist after the
Falklands war …
The radar system on the Sheffield that didn't report the incoming Exocet missile because it wasn't on the list of missiles that it expected a Russian ship to use.
The missiles fired over the heads of British troops on the Falklands beaches at the Argentinians, that could have gone off if they had detected enough metal below them (probably not really software).
The missile that was guided by a person watching a tv picture of the missile from a shipboard camera. A flare on the tail of the missile intended to make the missile more visible to the camera tended to obscure the target. A hasty software mod made the missile fly 20 feet higher (lower?) so that the operator could see the target.
A more general consideration is that in the event of an electromagnetic pulse's deactivating large numbers of electronic systems, one would prefer that systems like missiles in the air fail safe.
Laws@SRI-AI
I have scanned Spectrum's letters column since the original Exocet mention in Oct. '82, but have not found any mention of the bug. Perhaps I read the item on the AP newswire or saw a newspaper column posted on a bulletin board here at SRI. Possibly Garvey@SRI-AI could give you a reference. Sorry.
Garvey@SRI-AI Subject: Re: Falkland Islands Bug
The original source (as far as I know) was an article in
New Scientist (a British magazine) on 10 Feb 83. It suggested that the Exocet was detected by the Sheffield's ESM gear, but catalogued as a friendly (!) missile, so no action was taken. I have two, strictly personal (i.e., totally unsubstantiated by any facts or information whatsoever) thoughts about this:
1) I suspect the article is a bit of disinformation to
cover up other failings in the overall system; from bits and pieces and rumors, I would give top billing to the possibility of poor spectrum management as the culprit;
2) I wouldn't care if the missile had the Union Jack on
the nose and were humming Hail Brittania, if it were headed for me, I would classify it as hostile!
PALMER@SCRC-TENEX I was working for a major large computer manufacturer {not the one that employees me today}. One of the projects I handled was an RPG compiler that was targeted to supporting customers that were used to IBM System III systems. There had been complaints about speed problems from the field on RPG programs that used a table lookup instruction. The computer supporting the compiler had excellent micorocde features: we decided to take advantage of the feature by microcoding the capability into the basic machine. The feature was pretty obvious: it would search for things in ordered or unordered tables and do various things depending on whether the key was in the table. We made what we considered to be the "obvious" optimization in the case of ordered tables - we performed a binary search. Nothing could be faster given the way the tables were organized. We wrote the code, tested it on our own test cases and some field examples and got performance improvements exceeding sales requirements. It was an important fix… Unfortunatly, it was wrong. It isn't clear what "it" was in this case - Us or IBM. People loaded their tables in the machine with each run of an RPG program and they often wouldn't bother to keep their ordered tables ordered. IBM didn't care - it ignored the specification {most of the time}. Our code would break when people gave us bad data in ways that IBM's wouldn't. We had to fix ours. ——————————— Olmstread.PA@PARC-MAXC I can't supply any documentation, but I was told when I was in school with Ron Lachman (you might want to check with him at LAI – laidback!ron, I think) that IBM had a bug in its program IEFBR14. This program's sole job was to return (via BR 14, a branch through register 14, the return register); it was used by JCL (shudder!) procedures which allocated file space and needed a program, any program, to run. It was a one-line program with a bug: it failed to clear the return code register (R 15, I think). I submit you won't find any programs with a higher bugs-per-instruction percentage. ———————- hoey@NRL-AIC I got this at MIT…. From: ihnp4!zehntel!zinfandel!berry@ucb-vax In the April 1980 issue of ACM SIGSOFT Software Engineering Notes, editor Peter G. Neumann (NEUMANN@SRI-KL at that time) relays information that Earl Boebert got from Mark Groves (OSD R&E) regarding bugs in the software of the F-16 fighter. Apparently a problem in the navigation software inverted the aircraft whenever it corssed the equator. Luckily it was caught early in simulation testing and promptly fixed. In the July issue, J.N. Frisina at Singer-Kearfott wrote to Mr. Neumann, "concerned that readers might have mistakenly believed there was a bug in the flight software, which was of course not the case." [At least they fixed THAT one. Wasn't it Hoare who said that acceptance testing is just an unsuccessful attempt to find bugs?] Mr. Frisina wrote: "In the current search for reliable software, the F16 Navigation software is an example of the high degree of reliability and quality that can be obtained with the application of proper design verification and testing methodologies. All primary misison functions were software correct." In the April '81 Issue it is revealed that the F18 range of control travel limits imposed by the F18 software are based on assumptions about the inability of the aircraft to get into certain attitudes. Well, some of these 'forbidden' attitudes are in fact attainable. Apparently so much effort had gone design and testing of the software that it is now preferable to modify the aircraft to fit the software, rather than vice-versa! ——- Cantone@nrl-aic I've heard from Prof. Martin Davis, a logician at NYU, that Turing's Ph.D. thesis was just filled with bugs. His thesis was a theoretical description of his Turing machine that included sample computer programs for it. It was these programs that were filled with bugs. Without computers there was no way to check them. (Those programs could have worked with only minor fixes). [NOTE: I called Davis, who gave as a reference a paper by Emile Post on recursive unsolvability that appeared in 1947-8 in the Journal of Symbolic Logic – js] ———————- David.Smith@CMU-CS-IUS In simulation tests between the first and second Shuttle flights, a bug was found in the onboard computer software, which could have resulted in the premature jettison of ONE of the SRB's. That would have been the world's most expensive pinwheel! I read this in Aviation Week, but that leaves a lot of issues to scan. —————————— butkiewi@nrl-css In response to your request for info on bugs, here's one. We work with some collection system software that was initially deployed in 1974. Part of the system calculated the times of upcoming events. In 1976, on February 29th, some parts of the system thought it was a different julian day and it basically broke the whole system. Several subroutines needed leap year fixes. One software engineer was called in from home and worked all night on that one. How many sound Software Engineering Principles were violated? —————————- Stachour.CSCswtec@HI-MULTICS while i cannot cite any published documentation, and this could hardly qualify as a famous bug, a mail-system I once worked on (which ran with priviledge to write into any-one mailboxes) was discovered to have an incorrect check for message-length froma message coming from a file. The result was that a 'specially prepared msg' could arrange to overlay the test of the mail-system, and especilly restore the system 'change-access' program on top of the mail-system, which then gave the caller power to change access controls on any file of the system. This was for a university-built mail-system for a HOneywell GCOS3 ciria 1976. ——————– Sibert@MIT-MULTICS I imagine you've heard about this already, and, if not, I can't provide any documentation, but anyway: it is said that the first Mariner space probe, Mariner 1, ended up in the Atlantic instead of around Venus because someone omitted a comma in a guidance program. ————————– Kyle.wbst@PARC-MAXC TRW made a satellite in the late '50's or early '60's with the feature that it could power down into a stand-by mode to conserve electrical consumption. On the first pass over the cape (after successful orbital check out of all systems), the ground crew transmitted the command to power down. On the next pass, they transmitted the command to power up and nothing happened because the software/hardware system on board the satellite shut EVERYTHING down (including the ground command radio receiver). —————————- Hoffman.es@PARC-MAXC >From the AP story carried on Page 1 of today's Los Angeles Times: "Jet Engine Failure Tied to Computer: It's Too Efficient The efficiency of a computer aboard a United Airlines 767 jet may have led to the failure of both of the plane's engines, forcing the aircraft into a four-minute powerless glide on its approach to Denver, federal officials said Tuesday. . . . [The National Transportation Safety Board's] investigation has disclosed that the overheating problem stemmed from the accumulation of ice on the engines. . . . [I]t is believed that the ice built up because the onboard computer had the aircraft operating so efficiently during the gradual descent that the engines were not running fast enough to keep the ice from forming. . . . The incident raised questions among aviation safety experts about the operation of the highly computerized new generation of jetliners that are extremely fuel-efficient because of their design and computerized systems. "The question is at what point should you averride the computer," one source close to the inquiry said. . . . [T]he engines normally would have been running fast enough to keep the ice from forming. In the case of Flight 310, investigators believe, the computer slowed the engine to a rate that conserved the maximum amount of fuel but was too slow to prevent icing. A key question, one source said, is whether the computer-controlled descent might have kept the flight crew from recognizing the potential icing problem. Airline pilots for some time have complained that the highly computerized cockpits on the new jets – such as the 767, Boeing's 757 and the Airbus 310 – may make pilots less attentive. . . .
Kaehler.pa@parc-maxc Info-Kermit@COLUMBIA-20
On Wednesday, August 24, at 11:53:51-EDT, KERMIT-20 stopped working on many TOPS-20 systems. The symptom was that after a certain number of seconds (KERMIT-20's timeout interval), the retry count would start climbing rapidly, and then the transfer would hang. The problem turns out to be a "time bomb" in TOPS-20. Under certain conditions (i.e. on certain dates, provided the system has been up more than a certain number of hours), the timer interrupt facility stops working properly. If KERMIT-20 has stopped working on your system, just reload the system and the problem will go away. Meanwhile, the systems people at Columbia have developed a fix for the offending code in the monitor and have distributed it to the TOPS-20 managers on the ARPAnet.
The problem is also apparent in any other TOPS-20 facility that uses timers, such as the Exec autologout code.
The time bomb next goes off on October 27, 1985, at 19:34:06-EST.
Craig.Everhart@CMU-CS-A has put together a long file of stories that were gathered as the result of a request for interesting, humorous, and socially relevant system problems. They make fun reading, but most of them aren't really bugs, let alone well-docmented ones, so I decided not to include them. The file, however, can be obtained from Craig.
(end-of-message)
-Bob (Krovetz@NLM-MCS)
|
https://wiki.gen.net.uk/doku.php/archive:100:famous.bug
|
CC-MAIN-2020-29
|
refinedweb
| 8,552
| 60.35
|
From the documentation, Expo briefly introduces BackgroundFetch and Location as the only two options to handle background task. My scenario is triggering an API call every 10 seconds if there is a location change when the app is in the background.
I have followed the Location API "
startLocationUpdatesAsync" from:
I have also defined and been able to run:
import { TaskManager } from 'expo'; TaskManager.defineTask(YOUR_TASK_NAME, ({ data: { locations }, error }) => { if (error) { // check `error.message` for more details. return; } console.log('Received new locations', locations); });
And I am able to see the log in the terminal if the location changes. The location is also logged into the console when the app is in the background, however it only happens for a few seconds before the app just turns silently idle afterwards, even when the real location changes which should trigger the function call in the Task Manger.
At this time, only when I open the app to the foreground will it continuing to log new location. Otherwise, it will be as good as being killed.
Is there a way to keep background task running stably? Especially on Android 8 where BackgroundFetch from iOS is not supported and background tasks are generally restricted by the OS?
|
https://forums.expo.io/t/how-to-do-location-tracking-in-background-to-prevent-app-from-being-killed/22791
|
CC-MAIN-2019-22
|
refinedweb
| 203
| 53.21
|
First off, let me be perfectly honest, if you have any choice besides using JNI, do that other thing. Dealing with native libraries has been my number one source of pain when supporting Java applications. Now with that warning out of the way, sometimes you just can't avoid using JNI. For those who must go there, I hope this example helps and I salute your bravery and fortitude.
The Java and Scala examples do exactly the same thing. However, the byte code produced is slightly different since Scala doesn't have static methods.
Step 1 - Create a Java or Scala classWrite a Java or Scala class that will interface to the native library:
JavaIn Java, methods that will call the native code will use the native keyword in their method signature and have no method body. Create a file named Sample1.java and add the code below:
class Sample1 { // --- Native methods public native int intMethod(int n); public native boolean booleanMethod(boolean bool); public native String stringMethod(String text); public native int intArrayMethod(int[] intArray); // --- Main method to test our native library: " + sum); } }
The above code can be compiled using:
javac Sample1.java
Compiling Sample1.java will produce a single class named, Sample1.class
ScalaIn Scala, methods that call native code will use the native annotation and, like Java, have no method signature. Create a file named Sample1.scala and add the code below.
class Sample1 { // --- Native methods @native def intMethod(n: Int): Int @native def booleanMethod(b: Boolean): Boolean @native def stringMethod(s: String): String @native def intArrayMethod(a: Array[Int]): Int } // --- Code in App body will get wrapped in a main method on compilation object Sample1 extends App { // --- Main method to test our native library System.loadLibrary("Sample1") val sample = new Sample1 val square = sample.intMethod(5) val bool = sample.booleanMethod(true) val text = sample.stringMethod("java") val sum = sample.intArrayMethod(Array(1, 1, 2, 3, 5, 8, 13)) println(s"intMethod: $square") println(s"booleanMethod: $bool") println(s"stringMethod: $text") println(s"intArrayMethod: $sum") }
Sample1.scala can be compiled using:
scalac Sample1.scala
When you compile Sample1.scala you will get three classes: Sample1.class, Sample1$.class, and Sample1$delayedInit$body.class.
Step 2 - Generate a header file with javahThe next step is to have the JVM produce a header file that defines the function prototypes needed for the native implementation.
JavaCreating the native header is really simple for Java. You just need the compiled class, Simple1.class, created in step1. Use the javah program like so:
javah Sample1
Notice that you do not use the .class extension. javah will produce a file named Sample1.h.
ScalaCreating a native header from Scala code is slightly more involved in that you may need the scala libraries on the javah classpath. In our example, since we are using Scala's App class we definitly need the scala libraries. In this example, we only need scala-library.jar and scala-reflect.jar. I'm working on a Mac and installed Scala via homebrew and my classpath below reflects that. Your path will likely be different depending on your platform.
SCALA_LIB_HOME=/usr/local/Cellar/scala/2.10.2/libexec/lib/ SCALA_CP=$SCALA_LIB_HOME/scala-library.jar:$SCALA_LIB_HOME/scala-reflect.jar javah -cp $SCALA_CP:. Sample1
Output from javah will be Sample1.hThe Sample1.h file produced here using Scala looks exactly the same as the file produced using the Java class. Just for grins, this is the output of javah:
/ * DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class Sample1 */ #ifndef _Included_Sample1 #define _Included_Sample1 #ifdef __cplusplus extern "C" { #endif /* * Class: Sample1 * Method: intMethod * Signature: (I)I */ JNIEXPORT jint JNICALL Java_Sample1_intMethod (JNIEnv *, jobject, jint); /* * Class: Sample1 * Method: booleanMethod * Signature: (Z)Z */ JNIEXPORT jboolean JNICALL Java_Sample1_booleanMethod (JNIEnv *, jobject, jboolean); /* * Class: Sample1 * Method: stringMethod * Signature: (Ljava/lang/String;)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_Sample1_stringMethod (JNIEnv *, jobject, jstring); /* * Class: Sample1 * Method: intArrayMethod * Signature: ([I)I */ JNIEXPORT jint JNICALL Java_Sample1_intArrayMethod (JNIEnv *, jobject, jintArray); #ifdef __cplusplus } #endif #endif
Don't you just love C/C++?
Step 3 - Create the native implementationFor both our Scala and Java examples, the native implementation is exactly the same. You can write implementations in either C or C++, although the code will be different. The sample below implements all the methods defined in Sample1.h in C++. Copy and paste the code below into a file named Sample1.cpp:
Now the fun part, getting this to compile on your particular operating system. Since I'm working on a Mac here's the command line blurb I used to compile Sample1.cpp to a shared native library:Now the fun part, getting this to compile on your particular operating system. Since I'm working on a Mac here's the command line blurb I used to compile Sample1.cpp to a shared native library:
#include "Sample1.h" #include <ctype.h> #include <string.h> // Mutate array to uppercase void uppercase(char* str) { size_t n = strlen(str); for (size_t i = 0; i < n; i++) { str[i] = toupper(str[i]); } } JNIEXPORT jint JNICALL Java_Sample1_intMethod (JNIEnv* env, jobject obj, jint num) { return num * num; } JNIEXPORT jboolean JNICALL Java_Sample1_booleanMethod (JNIEnv* env, jobject obj, jboolean boolean) { return !boolean; } JNIEXPORT jstring JNICALL Java_Sample1_stringMethod (JNIEnv* env, jobject obj, jstring string) { const char* str = env->GetStringUTFChars(string, 0); char cap[128]; strcpy(cap, str); env->ReleaseStringUTFChars(string, str); uppercase(cap); return env->NewStringUTF(cap); } JNIEXPORT jint JNICALL Java_Sample1_intArrayMethod (JNIEnv* env, jobject obj, jintArray array) { int sum = 0; jsize len = env->GetArrayLength(array); jint* body = env->GetIntArrayElements(array, 0); for (int i = 0; i < len; i++) { sum += body[i]; } env->ReleaseIntArrayElements(array, body, 0); return sum; }
g++ -dynamiclib -G -Wall -O3 \ -I/usr/include -I$JAVA_HOME/include -I$JAVA_HOME/include/darwin \ Sample1.cpp -o libSample1.dylib
A few notes about this:
- Notice the -dynamiclib flag, this creates a shared library and is required. On linux use -shared instead.
- You have to include Java's jni headers which are always in at least 2 places.
- $JAVA_HOME/include
- $JAVA_HOME/include/<platform> . On Macs that's $JAVA_HOME/include/darwin, on Linux it's $JAVA_HOME/include/linux. I have no idea what it is on Windows.
- You may have to set the JAVA_HOME variable on your machine. You can do this on a Mac using: export JAVA_HOME=`/usr/libexec/java_home -v 1.7`
- Remember the line in our Java/Scala code that goes: System.loadLibrary("Sample1"). Although the name of the native library is referenced using "Sample1" in our code, it's actually looked up using a 'lib' prefix. So the native library is actually named libSample1.dylib on Mac or libSample1.so on Linux.
- If you're stuck developing for Java 6 on a Mac, change the native libraries extension to .jnilib or Java 6 won't find it. Java 7 on Mac requires .dylib extension. (I did try to warn you that JNI will test your strength)
Step 4 - Running the Code
Running either sample is straight-forward. However, you need to ensure that native library is on Java's or Scala's library path. The simplest way to do this is to add it to the java.library.path when you start your JVM.
Java
# Assumes all files are in the same directory. # If they are not, replace $(pwd) with the directory containing libSample1.so or libSample1.dylib java -Djava.library.path=$(pwd) -cp . Sample1
Scala
scala -Djava.library.path=$(pwd) -cp . Sample1
or
SCALA_LIB_HOME=/usr/local/Cellar/scala/2.10.2/libexec/lib/ SCALA_CP=$SCALA_LIB_HOME/scala-library.jar:$SCALA_LIB_HOME/scala-reflect.jar java -Djava.library.path=$(pwd) -cp $SCALA_CP:. Sample1
A Note about Deployment
It's not always feasible to set the java.library.path variable (e.g. when using Java Web Start). However, it is not particularly difficult to hack the path used internally by Java to add shared libraries at runtime. This is, however, a topic beyond the scope of this posting.
3 comments:
Really useful walkthrough - thanks!
Very well explained. Thanks.
Hello...i need a code to link scala with java. plse help
|
http://hohonuuli.blogspot.com/2013/08/a-simple-java-native-interface-jni.html?showComment=1454842670389
|
CC-MAIN-2018-05
|
refinedweb
| 1,339
| 58.58
|
Announcing Yesod 0.9.0 Release Candidate
August 23, 2011
Michael Snoyman
What's new?
You can get a taste for the new stuff in the 0.9.0 release from the ChangeLog page. In general, this is a very stable, well-tested release. The beta is being actively used in a number of production sites, including this one, with no reported ill effects. The Yesod team feels very strongly that this is an upgrade worth making as soon as possible.
The purpose of the release candidate is to try to get any last-minute input on bugs or bad decisions before they are set in stone with the official release. I highly encourage everyone using Yesod to install the release candidate and test it out on a few of your sites.
Get set up for Yackage
The 0.9 release candidate is available on the Yesod Yackage server. Note that the version numbers are the same as will be released with the final release. That means that, if you install the RC, it's highly recommended to wipe your .ghc folder after the official release comes out.
In order to install the release candidate, follow these steps:
- Add the following line to your
~/.cabal/configfile:
remote-repo: yesod-yackage:
- Run
cabal update
- Run
cabal install yesod-0.9.0
- Get a beer and congratulate yourself on a job well done.
Migration guide: Yesod 0.8 to 0.9
As has become a bit of a custom, we're going to go through the necessary changes to the Haskellers codebase to get it to work with the new release. Fortunately, there are many less steps in this release. You can see the entire commit on Github. To give you an idea of time investment, it took me about two hours to migrate Haskellers, write this guide, and apply a few minor tweaks to the framework in the process.
- Fix up your cabal file. For the most part, just change yesod to version 0.9 and watch the fallout. Pay particular attention to the version bounds on related packages like hamlet and persistent. Also:
- hamlet has been split out into multiple packages. You'll likely get build errors telling you to add shakespeare-css and shakespeare-js
- Due to issues with the newest aeson and Template Haskell, we had to create a fork. The API is identical, the only difference is in how doubles are rendered. Just updated any references to aeson to be aeson-native.
- Goodbye "Helpers" module namespace. This affects Yesod.Helpers.Static, Yesod.Helpers.Auth.*, Yesod.Helpers.Feed.* and others. All you need to do is remove the word Helpers.
- The datatypes from hamlet have been renamed. This likely doesn't affect much code, but just be aware of it.
- Forms have had a significant overhaul. This will be the most labor-intensive part of the migration. I'll address this later.
- In your Model.hs file, mkPersist now takes an extra parameter to give it settings. For now use sqlSettings, we'll have some more options in the future.
- Model.hs needs the GADTs language extension enabled.
- In your application file (e.g., Haskellers.hs), remove the type synonyms for Handler and Widget. This is now provided by the TH code. Also, instead of Widget (), just say Widget.
- In the YesodPersist instance, change "YesodDB" to "YesodPersistBackend".
- The other big change: the filter API for persistent became much simpler. Instead of using constructors like "PersonNameEq", we now just use operators. (Thanks to Boris for the groundhog inspiration here.) Some simple examples:There will be a bit of manual effort involved in this transition, but the result is well worth it.
- select syntax has changed. Instead of having those two hanging integers at the end, we have a list of options. An example should suffice:
- Old
- selectList [PersonNameEq "Michael"] [PersonAgeDesc] 5 10
- New
- selectList [PersonName ==. "Michael"] [Desc PersonAge, LimitTo 5, OffsetBy 10]
- Updates are similarly changed.
- Old
- update personId [PersonName "Michael"]
- New
- update personId [PersonName =. "Michael"]
- And a great sigh of relief was heard: polymorphic hamlet is gone. For the most part, this just means you'll need to preface a few hamlet calls with toWidget. Unfortunately, the error messages are confusing; just email the list if you get stuff on somthing.
- There have been some renames in the templates. It's best to just read the chapter for details.
- We added i18n support for form messages. You'll need to add this to your application file (e.g., Haskellers.hs)
instance RenderMessage Haskellers FormMessage where renderMessage _ _ = defaultFormMessageThis uses the default values, which are all English. You can modify these yourself if you want, expect some blog posts in the next few weeks focusing on how i18n works.
- Under some strange conditions, you'll have to give your ID variables explicit type signatures. This is exceedingly rare.
Forms
Forms got a huge cleanup in this release. I'm hoping to get the chapter up-to-date soon, but the migration guide isn't enough to fully explain what's happened. I'll just give a few quick translations that I've used in Haskellers:
|
http://www.yesodweb.com/blog/2011/08/yesod-0-9-release-candidate
|
CC-MAIN-2015-18
|
refinedweb
| 857
| 68.36
|
I recently did an interview with @terrybrock where I talked about my experience since I first joined Steemit, and my advise for new users on how to be successful. I talked about what it was like starting out as a new user with no followers (earning practically no rewards), and how I went from a 'nobody' on the platform, to one of the more well known users.
If you haven't watched the video yet, I highly recommend you check it out:
Steemit Success Series- @timcliff on Who To Target With Your Content
There have been a lot of thoughts spinning around in my head since the interview, and the recent spike in SBD prices to over $10 has reminded me of something that I should have talked more about in the interview. To me, this is really key for every user to keep in mind - and probably one of the most important things that we can teach new users to improve their experience.
Most users are looking at their rewards in the wrong way
The tokens that we earn today (through our blogging, commenting, and curating) have real value. That is part of what makes the Steem platform so amazing. Anybody can join, post content (about whatever they want) and earn rewards for the value they produce. Where else on the internet is this possible?
There is a lot of discussion about the rewards on the platform, and how we should not make rewards the main focus. While I totally agree that the Steem platform is SO MUCH MORE than just earning rewards, let's face it - most of us that are here do want to earn some money.
The three biggest complaints that I hear from new users are:
- The platform is unfair (other users are earning more, and they clearly don't deserve it).
- It is way to difficult to get noticed and earn significant rewards without putting in a ton of effort.
- My upvotes are worth practically nothing. After I upvote something, it only rewards the user a penny.
When users are so focused on rewards, it is easy to look at the small amount that they are earning and think it is not worth it.
Everyone seems to be focused on how much their rewards are worth today though. A 0.02 may not seem like a lot today (and it is not), but that 0.02 upvote may actually be worth a lot of money some day. (Seriously.)
The average user needs to be more informed about the investment side of Steem.
Any user can take 50% of their earnings and cash them out after 7 days. The other 50% can be left in the platform, or cashed out over a period of 13 weeks. When they cash out their rewards, where does that money come from though? It comes from an investor. Someone on the other side of the exchange (wherever the tokens are being sold) is buying those tokens. They are giving the user "real money" in exchange for the tokens. But why? Because they are expecting them to go up in value. Think about that. They aren't giving users free money out of the goodness of their hearts. They are paying for these tokens at the value they are being sold at, because they think/hope/expect that some day - they will be worth more.
I just went around to all of my friends accounts today and collected up all of the "loose change" SBD rewards that had collected in their accounts. Most of the accounts had around $0.10-$2.00 worth of SBD. While that may not seem like a lot - SBD is currently trading for over $10. It made for some very interesting conversations. Hey, remember that small amount of SBD that you left sitting in your account? It had actually gone way up in value. I just cashed it out for you. It was worth 19 bucks. It's really too bad you hadn't been more active on Steemit recently.. If you had just earned a few more dollars, you might have had over a hundred bucks.
Lots of little rewards can add up, and if those little rewards each go up in value - they can be worth a lot!
While SBD going from $1 to $10 was a pretty big surprise, STEEM going from $1 to $10 is something we should all start to consider a possibility. @steemitblog recently wrote an article comparing STEEM to Ethereum and it is pretty clear that the Steem blockchain blows Ethereum out of the water in many ways. ETH is currently sitting at $455.02 a token with a marketcap of $43,780,733,655. STEEM is sitting at $1.81 per token, with a marketcap of $445,703,080. Why couldn't STEEM be worth more? Why couldn't STEEM be worth a lot more?
With the plan to launch SMTs in early 2018, STEEM is going to be getting a lot more media exposure. It is not outside the realm of possibility that we could become one of the top 5 tokens. If that happens, STEEM tokens are going to be worth a lot more.
Users should really be asking themselves the question - do you want to be cashing out your rewards today, or would it be better to invest the money back into the platform? One of the easiest things to do with SBD rewards is to go to the internal market and use the SBD to buy STEEM. If the STEEM goes up in value, the same rewards will be worth more.
This info is not intended to be a price prediction, and it does not constitute investment advise. What it is intended to do is to point out that the rewards we earn today can be viewed in a much different light if we take a step back and look at what they could be worth several years down the line. Those few pennies that you earn today, really could be worth a lot.
Back in 2010, some guy bought two Papa John’s pizzas for 10,000 BTC. Assuming the pizza was about $20 USD, that puts the price of one BTC at $0.002 USD at the time. Today, BTC is sitting at around $15,000, and those same 10,000 BTC are worth about $150,000,000 USD. One penny worth of BTC from 2010 is now worth $150. Think about that for a second..
Closing Thoughts
While it is fun to think of STEEM tokens one day being worth $15,000 or more (and of course it is certainly possible), we do still have a ways to go. There are a lot of big improvements that need to be made, and our platform and community need to scale. My personal hope is that we can make 2018 the year that we get to $10 STEEM though, and I do think we can make that happen.
One thing that is important to keep in mind, is the token is not going to get to $10 (or $15,000) on its own. It is important that as members of the community, we take an active role in getting it there.
As yourself the question - what can you do to help increase the value of STEEM? Can you encourage local merchants to start accepting STEEM as a form of payment? Can you convince someone who will add a lot of value to join? Can you create an article that will start getting picked up by Google, and bring a lot more eye-balls to the site?
There are lots of ways to make the platform more valuable, and everybody has different talents and skills to offer. You might even have some way of adding value to the platform that nobody else can. I'm pretty confident that if we all work together to make this place as amazing as it can be - we really will reach the moon.
I (and maybe everyone too) have learned a lesson with SBD: HODL it as much as possible and wait for the next (abnormal) pump. SBD peaked at $22 last May, and here we are 6 months later with another massive pump. It's fair to say nobody could have anticipated another surge like that until today, thanks to those Korean exchanges. Who knows what could happen in another 6 months, or less!
And that's not all! I've been paying close attention to its price on Bittrex for a few months, and very often it got a weekly pump. For example, it would surge to $2-3 in the space of a few minutes! If you're lucky to have placed a sell order (which I did a couple of times), then you would get a nice little quick weekly profit!!!
As for STEEM, having it stored in Steem Power is the best incentive to hold it for the long term. After all, we NEED Steep Power to transact and increase our stake/influence. DASH and Ethereum were cheap last year, below $10, but once they got their recognition, they skyrocketed. Everyone who missed on those look back and slap themselves: Why oh why didn't I get some?
I think STEEM is the perfect opportunity, I can't wait to see its value in one year. It too is bound for a glorious moment. Almost every coin and altcoin had their 10x surges (whether by a pump or by slower growth). STEEM is no different. Get it now while it's still cheap. And finally, investors seek price stability. STEEM price remained relatively stable despite all the market volatility since this summer. Major coins got up and stayed up, shitcoins got pumped and dumped into oblivion, yet STEEM is still here unbudged! THIS is a good sign for the future. Things can only go up from this point on.
STEEM/USDT pair in most exchanges will provide more stability and more trading opportunity. LTC, DASH, XMR, and most top coins have USDT pair in top exchanges. For example, one did put a buy order in BTC, BTC fell 25% and STEEM fell 10% against BTC, therefore, it fell against USDT by 32.5%. It is hard to trade inter-day with STEEM against BTC. Hopefully, STEEM will be added to top exchanges and traded against USD sooner than later.
This is motivational.
Let's do this together, let's talk about it, let's show the world what is being done on blockchain already, on what scale, with what speed and how secure these wallets are.
It's game time.
Yes #fitzgibbon it is so much motivational, before reading this post i decided to withdraw my SBD but i will not do it not this time.@timcliff
I really needed to read this, thanks. As a new user to steemit (aged 10 days) I have come across other new users with similar complaints that you've pointed out here regarding rewards. While some of my posts are only generating between 2 and 8 cents, it is important to understand that as a new user with next to 0 followers, there will be some hurdles to cross in order to get noticed. As for putting too much effort in, absolutely! You always have to put in 110% in everything you do. This is what will build an audience for you, and while you might only be making 8 cents a post now, as you gain more followers, you will get more exposure and thus higher rewards for your posts. Not only that, but regarding @timcliffs point about 1 pennies worth of BTC in 2010 is now worth $150, the 8 pennies I made on my last article could be $80 within the next few years. People buy because they know it'll go up. I plan to hold as long as I can and together we can all make the value of steem go up. I see new users joining every day by the dozens if not hundreds. If anything, STEEM is getting quite a bit of recognition and that alone increases the value of STEEM.
Some really good points in this article. As a new user I feel like sometimes the platform isn’t “fair” , but then I look at what successful people do on here and for the most part it’s making solid, consistent posts and finding a niche. Over time it all adds up and I’m seeing now how it’s really done! Thanks for taking the time to post such a well thought out article. Really enjoyed it. Kudos!!!
I invested in Steem when I joined in September and am happy I did. I love that my vote can pay out those that interact with me. Looking at it with the long view perspective 2 years to 3 years goes by pretty fast in life and we will all benifit from being early here and starting out with nothing even my friends that just join have started there journey in crypto and blockchain. I think Steem is the best place for people to start as you have the most to gain with the least to loose. You are already posting and sharing on other social platforms and all you get is the value of using it but no investment in the platform. I see steem as a tool to empower community and empower the individual to have a place to speak there mind and share the unique point of view. When communities come together in an open way such as Utopian.io then we see the real power of empowering others. Investing in people is investing in steem when the value of this is realized then there is no limit to where the price can go. I am proud to be a part of this forward thinking self supporting community that runs on the steem blockchain. Thank you for taking the journey with me.
Allowistic Artist
Vincent Wilhelm Vaughn Strader
Creativity flows in the waves of now #allowistic
Really appreciate both the concise points and the infectious enthusiasm with which you convey them @timcliff
"I'm pretty confident that if we all work together to make this place as amazing as it can be - we really will reach the moon."
This statement alone speaks volumes as to the profoundly symbiotic nature of Steemit. I don't use the word "profound" lightly I use it because I believe the entire platform gives a tantalising glimpse at how our entire society could be structured. Working together as opposed to working against each other, helping each other to fuel the platform and in turn help ourselves. In many ways this concept is the antithesis of the ruthless dog eat dog structure our society so often morphs into. Baby steps? yes but even the smallest of acorns can grow into the mightiest of oaks!
Of course you're right. There were many articles on the subject of prospects of tokens steem and SBD. All experienced users and heavyweights talking about what we need to think about the future. It is absolutely true. But most new users don't read this information, I think. This is due to three reasons, which you also mentioned in your article.
Since many new users are focused only on receiving awards specifically in this moment, they do not see what is happening on the platform as a whole. They just votes and left comment "nice post".
And there is another reason, perhaps, many people think that all this may soon end. On the basis of this idea, they prefer to realize the funds received immediately. I'm not a hypocrite and I admit, I'm one of them.
Only recently have I seriously started to think about how to change my attitude to the platform and to think about the long term.
First and foremost, this is not due to belief in the success of this place (although I believe). The reason is simple, I got rid of the need to immediately change the crypto to real money. I received a financial stability that allows me to make long-term decisions.
This is a very important circumstance. Because it is difficult to get people, who are in dire need of money at the moment, to put aside their needs and think carefully about the future. Unfortunately.
I needed to read this! I have been wondering why my posts were not making any real money at all when others posting in the same challenge are making great rewards on their posts. I guess it all comes down to who follows you and if your followers are active or not. I went to the dead follower's website and found out that over a third of my followers have not posted or anything in months. I guess things happen for a reason and it was a learning experience for me.
i have been on steemit from 20 days ...this is the best blog i have ever read to help the newbie....today i get to the real importance of steemit....thankyou so much @timcliff ....lets
Your friends all left you with the keys to their accounts? I hope you at least bought them pizza with the $19 and had a little party!
Hehe, I figured someone would ask about that :)
Yes, I do actually offer all of my friends to hold on to their keys for them. I teach them about the security aspects of the platform, and if they want me to - I transfer their private keys to my backup securely. I also help a lot of them with the cash-out process, until they feel comfortable using an exchange themselves.
I wouldn't ever touch anyone's account without their permission, but most of my friends are happy having me provide them with that service. It helps them focus more on the 'fun' parts of the platform, and I do my best to slowly teach about crypto currency along the way.
Ha, I thought you had done an exercise of summin up what it would be worth, ha ha ha
That's a great idea. I'm not very good at getting friends involved with crypto.
I tried to get a coworker to open a coinbase account a couple of years ago and put $100 into it so we could both get the $10 bonus they were offering at the time. He didn't do it... and messaged me few weeks ago saying how much he regretted it.
That $10 bonus (assuming he cashed out the initial $100 right away)... would be worth over $1000 now.
You are so right @timcliff about Steemit requiring a long-term outlook. I must admit it is a little down-heartening sometimes to put a lot of time and effort into a post just for it to disappear with hardly a trace (and that has happened to me a lot!). However, taking the attitude you outline in your post eases the pain somewhat and hopefully, everything we do will pay us dividends in the future. Thank you for a dose of motivation to keep us going.
You should totally check out that video! I talk about my feelings on exactly the same thing :)
I will - thanks again.
@timcliff I totally agree with you in this. Even the tiny 1 cent SBDs count here. Many people that are here actively on steemit by now its because they found value on the platform, and they found they could contribute in something to make it a better place everyday.
As you mentioned several times, on steemit and steem you are in a never ending learning process of new things coming and going, and we are in something that never existed again. Earning rewards by creating, discovering and commenting on value content for the benefit of the community and the growth of the blockchain.
Many new ideas, concepts, developments start here everyday, many of which we here from them, some not yet, but all are efforts done by lots of people that trust on the platform.
What @aggroed mentioned if a site like Freelancer existed on a blockchain, I just wanted to let you know I thought of this idea, of developing a freelancer site with the steem blockchain. The only thing that kept me out of doing it, is that until know I do not know developers of the blockchain personally that would make a team with me to develop something like this. I have lots of ideas (in addition to the 14 ideas I already published to improved the steemit interface and in this way capture more visitors into signups), and ideas to capture big investors. My issue is I am not a developer, technical like you and many others are. If not I could have been adding much more value directly into it.
But you know you count on me and the steemit community, with my ideas, everyday, and will continue adding more ideas I have in qeue to publish.
Thanks for giving this motivation to new steemians, and minnows, since they are the highest percentage of signups. If we can make minnows grow, we will have the biggest spreading word power already stablished.
Regards, @gold84
Very good points, @timcliff. It was great having you on the interview. You did a great job.
Your points are very astute. Powering Up and putting more into Steemit makes a lot of sense right now. The future looks promising to me.
Keep up the good work, my friend. I look forward to hearing more from you.
Thanks @terrybrock - you do an amazing job as an interviewer. More users should be checking out your blog!! I really enjoyed working together, and I look forward to more collaboration in the future :)
Thank you for your post.
Since I make money for life another way than on Steemit, I just collect all rewards on my account and see what happens in someday.
Maybe, I become rich or lose, it's just a game, the same as our other life.
It's all the same as in real life we can try and do out best or just wait for nothing:)
I prefer to manage my own life but not to be a victim of circumstances
Totally agree !
since the first day here 6 months ago, I have invested my time and energy and bought steems with each sbds earned and powered up each with the intention to stay and grow, I have invested some euros here and there, not a lot,because I have not so much.. LoL... but considering I invest on me, on my time, on my skills, on my energy, I see much further and I trust in the cheerful energy that is mine and that pays off every day...
and because I'm having fun, I know that I am at the right place, at the right time ;-)
I remain very bullish on Steemit and Steem... and I feel very encouraged by the recent upwards movement.
Small rewards do add up... but you just have to keep plugging away at it; I remember doing so when Steem fell to 8 cents or less. Whereas I have had to cash out some for unforeseen personal financial reasons, I do believe we have a great gig here... and $10 Steem is totally in reach.
Hi @timcliff The No 2 witness at steemit [I just give you vote as witness cuz you deserve it]
In this blog post the most beautiful lines are as under:
That is part of what makes the Steem platform so amazing. Anybody can join, post content (about whatever they want) and earn rewards for the value they produce. Where else on the internet is this possible?
I bet no other channel is available at web who provides such opportunity. Also I do agree with your statement that in 2018 we can cross the value of steem on Ethereum. Yes we can make it happen. Thanks a lot for giving very positive vibes regarding this awesome platform. Steemit Community is growing everyday and people like you should take part and should boost the morale of newcomers. All the best dear @timcliff & stay blessed!
I watched this video the other day and it was very helpful - thank you! I'm new to the Steemit platform and as you can imagine - there's a lot to learn.
Moving forward I hope it doesn't get overrun with trolls and negativity. Steemit has a long way to go and I'm glad I'm here in the early days and able to help contribute in a meaningful way.
I intend to hodl for the long-term and can see no reason to power down for at least several years.
Excellent post, Tim, thank you. I've been trying to increase conversations lately about investors and how they ultimately drive the financial value here for everything we see. If we just focus on bloggers (who often want to extract rewards) and don't also talk about the investors who want to see a good financial return (or they'll take their investments elsewhere), then we could end up killing the goose that lays the golden eggs.
We could have a great social media platform with excellent content, but a token few care about because the investment value is pushed down but bloggers cashing out on a regular basis.
At the same time, we could have a nice speculative cryptocurrency increasing in value and a site full of useless spam and self-voting bots on junk, just to extract the highest investment return possible.
Neither scenario is very pretty. Posts like this will hopefully get more people thinking about the long-term value of creating valuable content and promoting actions which bring great financial returns to investors.
Thank you.
That's why I invest every SBD I earn to steem, steem has a promising future.
Wow, the most expensive pizza in the world hehehe, had to get in the guinness book
Yes, when I look at someone's decent post that earns $0.20, I remind myself that someday that may be $20... or $200. And if I upvote that to $0.24, I've just increased that by $4... or $40! Looking at the future value can have an affect on how we look at these pay outs today.
This post is worth over $1000... or $10K That's $7.41 per word or more!
@ironshield
i'm watching the episode right now. thanks for the advice man. i'm trying to get in on some of the action. i'm still somewhat new but i keep hearing your name pop up so i had to check you out brother. peace. take care man
ReSteem'd this one Tim! And Im voting/following all your Posts/Resteems much closer now :)
PEACE
of Fruit
I see that in life a lot of people can’t equal lots of small actions repeated regularly to reach a goal is actually easier than one bug action once.
I was just having this discussion with my boys yesterday.
I agree with most of what you put forth here, but I have to admit, it's still kind of hard to watch the gap increase between those who were here early and the rest of us, but I guess that's what we get for not getting in earlier.
That being said, I keep investing my sweat equity in hopes that I will be better off than those who come in after me. We are still pretty early in the advent of Steem and, in fact, still beta on steemit.com. I look forward to the day when the spell checker recognizes that "Steem" isn't a mispelling.
With regard to making the platform more valuable, I must have read your mind because I just started accepting Steem and SBD for payment for my side business selling Cinnamon Glazed Nuts. I made my first post about it an hour ago. I'm honestly not expecting a lot of business from it, but hopefully it will get people thinking about the things that could be done on the platform.
I know what you mean, but at the same time they are the reason we even have a platform today to complain about how little we are making :) If those early adopters didn't put their time, resources, and energy into getting the project from a dream to a reality - it would be nothing more than an idea. They have a lot, but IMO they are fully entitled to what they earn. I hope that we can earn them billions, because that means everyone that is here right now has the potential to earn millions :)
I had the same impression when I got here too, but I worked my tail off for a year and a half. Now 1.5 years later, I'm probably one of the people that the newcomers will point to as being way better off because I was here first. You will always be here first compared to everyone else that comes after - and if we continue to grow the platform and the value of STEEM, then no matter what time you join - you will always have the opportunity to work you way in for a slice of the pie, then work with the rest of us to grow the value of that share :)
Haha, I like that! Me too :)
That's pretty awesome! We totally need more of that. I just re-steemed your post.
Oh, I agree. They have put forth the investment and therefore reap their just reward. I also like the perspective you put forth regarding them paving the way. I do think that questioning algorithms is helpful nonetheless. There is room for improvement and voices (even the complainers) show perspective. Not saying we should all be trying to please everybody, but sometimes one change will improve aspects from many perspectives.
Thank you so much. I don't know why I didn't think about doing it sooner. Your resteem has certainly gained a lot of exposure for the post, and I am grateful for it.
Excellent work dear friend @timcliff, I share and support all your words, you have a lot of reason in what you say, there are many people out there crying in the corners, without making effort in their work, here the results are long term, ! A mountain of sand is formed by thousands and millions of granites. As my grandfather used to say, the tree does not stop you from seeing the forest
Thank you very much for your experience, words and conclusions
I wish you a happy Friday
I like this :)
Ethereum*!!!!
But seriously, Steem is a great investment in its infancy. It is such a blessing to be earning something that is continuing to grow every day
Ah, crap. Did my horrible spelling skills show through? lol. Thanks for catching that!! (fixed)
😀😀😀
Funny that you mentioned the value of friend's accounts. I convinced my buddy to join a year and a half ago and he did absolutely nothing with the platform since. Somehow his account is worth $25 today
Hehe, yep - exactly. It's a fun thought to think that someday these dormant accounts could one day be worth thousands. Hopefully he still has his keys, and keeps them safe! :)
I've been here for a while now and am active in the community most everyday. I say this due to not running across you before? I say this because what you've posted here is the type of stuff I like to read. Glad I stumbled over you today. I agree that the more active the members of the community are outside the platform the more exposure steem will get essentially growing into something very special in the future. Being active within' the community is very important and fun also as you are a great representation of this. One day just as with other cRyPtO's steem will rise to something extraordinary and people will look back and say, just as they are doing with BTC, "shoulda......'" coulda'..... woulda' !?!" Subbed and enjoyed!
I comment quite a bit, but I have a certain genera of posts that I usually hang out. Historically I'm a pretty active poster too, but recently I've been pretty busy with some projects "behind the scenes". Someone asked me recently to post more, so I'm trying to start up again :) Glad you ran into my post!
@stillwater - just curious, any relation to the city Stillwater, Minnesota? It's near where I live :)
No. I'm outside of the ATL
How true it all is. I completely agree with you. I joined just last October and yes i am new to the platform and yes I don’t get tons of money for my content (yet) but still... i have been able to cash out $300 ( it was originally around $90, but because i’’ve paid attention to the price changes during all this high peaks i turned it to $300 .
That was all from pennies like you said. That, and writing every day and interacting with others and making friends.
We can’t expect to have it all or be successful right a way . we gotta be patient and put some work into it.
Thanks for sharing your opinion and you advice!
I loved the article! Following you for more!
That's awesome! I'm happy to hear about your successful blogging, and how you have been able to turn it into even more through trading :)
thanks!! i am trilled! i did not expect such good results so soon! but that is to show that there is so much potencial here on Steemit!
this is very interesting writing, I am very detailed reading it, even we in Aceh there are already some coffee shops in Aceh have received payment with steem or sbd, imagine when this is done by all of them, steemit would be a fantastic platform. in these few days at a coffee shop in Aceh there are many who harvest sbd, because the price is skyrocketing. but, it's a natural thing for them small fish because of the economic situation and conditions that can not make them invest here. I think personally, this is a great investment opportunity for people who realize it, because One price sbd can get seven steam. people forget that steem will be the same as sbd. they are all negligent. and I also think that, it's better to buy a delegate as this will make the opportunity to print both steem and sbd. you have to pay that which with one sbd current value will get sp reaches 240 more sp. this is also an opportunity for all small fish who always expect an upvote from friends. thanks so much I like you
Very informative post, and some great advice. I need to get some money invested into Steem tokens, and resist the temptation to Power Up everything. lol
Like I keep telling... just enjoy the ride but one more thing before is find your niche.
Thank you for the information. This is very confusing for me. I am preparing myself to teach what I have learned from many different subjects. Personal Professional Development, Language and life experience.
I found new steemit users, learned a lot from your post. I will be of many benefits, to succeed, all the people like you were looking for. I think I have found it that I want your cooperation so that I can get some tips to succeed all the time. Thank you
writes post about earning low rewards Gets $93.20 In first hour.
Hehe, yes. You should really watch that video that I linked though (if you haven't already). I talk about the many months I spent when I first started out writing posts that didn't make money, and nobody knew who I was. I 100% understand the frustration involved with spending hours and hours on a post, only to earn 0.03 in rewards.
The dip in STEEM allowed me the opportunity to exchange the little sbd I had into triple the amount of STEEM. Had I waited one more day....
Keeping it all in the Steemit platform I powered up SP, but also kept 25 STEEM. I'm game for seeing it go up to $10.00.
The point you make about writing an article that gets Google's attention also feeds food for thought. I assume every post on the Steemit platform has the ability to get indexed by Google, Yahoo, Bing, and even Duck Duck Go.
Actually, I've already found some searching Google.
We should all be helping to drive organic traffic to Steemit.com. :)
Thanks for the reminder about value and solid advice.
Yep, totally! Just yesterday I spent several hours putting together a post on this new "CryptoKitties" craze, as I'm sure there will be tons of people searching for it in the coming months. I'm hoping the guide I put together can be one of the top results :)
Man I dig getting posts to the top spot. Whether it's on my own blog, or other's I write for. Good luck with the rankings and thanks again for the article. Gave me an idea for my next post. :)
Really these are very good advices for me as a beginer, i will change my vision on steemit, thank you
Thanks for these many good points you made. Everyone has something to contribute and make Steem profitable for all of us.
Will include the link to this post in the Crypto Growth Forum Transcript part-2... :)
well on my post i am not getting 50 % in sbd not sure what was the problem i have got so very small in return maybe my bad luck
Which post?
I have few post a.week ago. Setting was 50 50. And they give me .1 sbd and 25 .6 steem at pay out time. Really disappointed from that. .@timcliff
Please send me a link to one and I will review.
Here are the screen shots of payout
Here are the post link
@timcliff these are my higher post that time and they didnot give sbd i am not old one i am new user i need to learn . my setting was 50/50% always i never change rest posts are fine
Which interface did you post from? The blockchain shows that several beneficiaries (people besides you who share in the payout) were added.
utopian @timcliff but there is same setting 50/50
The problem was not that it didn’t split 50/50 (it did), but that it distributed the payout to lots of other people besides you. The amount you received was after the beneficiaries were paid.
Saying others don't deserve their likes is unfair. Each Steemer has their own interests.
What do you mean?
Exciting times. I am powering up as much as I can, it is time to invest!
I think Steemit is gonna rocket to the top of social media and crypto currency , but that will only happen when people promote Steemit and the community grows large enough . Good post @timcliff !
I think that you correctly write that one shouldn't expect big rewards from Steemit. Need to make more of an effort to promote BTC. It certainly can be a good posts that other people made them was circulated on the Internet. The more people know about Steemit, so it will be more expensive. As a result, all community Steemit will be able to earn good money.
We all need to make more of an effort to increase the strength of the voice. This will allow others to try to make more of an effort to create a good post
I literally do believe in Steemit and both the Steem and SBD(already gave a hint to us) will rise exponentially and will be worth a lot more than any of us could imagine .I am really seeing that day is nearer than we thought .
I so agree with this I got a lot of post that never get any vote yet I kept posting as these places food experiences ar too pretty hair to keep to myself so thumbs up @timcliff
Absolutely brilliant points and totally agree with those once @timcliff. Steemit platform really helpful for new users. This is the best blockchain system I have ever seen. More creative blogs, earn more rewards and establish great friendships all around the world here. Currently SBD price pumping more then we can earn multiple. I think it will be rise more and more. I am 02 months old to steem platform but i have checked pass cryptocurrency movements. So I can guess best ideas. In fact I convert to my SBD to steem then I have generated more steem.
I agreed totally about steemit platform. Its attractive one more users daily entire to this platform. Peoples ask from another then add much peoples. Be honest and honorable here. Thank you for giving more interesting one.
Do you ‘convert’ or trade/sell? If you are converting, you definitely should not under current market conditions. You would get a lot more by trading SBD for STEEM on the internal market, or through a service like BlockTrades or an exchange.
Thanks to your advice. Yup...agreed "timcliff. I knew now "convert" function is not useful now. I'll do with ur point.
I liked your post a lot...and i want to resteem it can i get your permission to resteem your post....
No permission needed. You are free to resteem whatever posts you want :)
Thanks for the post of yours.
I set a price target of $100 at the end of 2018....
I love seeing 20 cents coming into my account because I know it is $20.00 does the road.
Great post @timcliff...there is so much going on here that it will make peope's head spin.
That's funny I was thinking the same thing. Especially if bitcoin meets its' predictions. Even if not. This means by 2020 1 steem could be worth 1 grand. Definitely fun to speculate, and it would be nice to be right on this. I see 8 cents coming into my account and feel it's $80 down the road so I share your enthusiasm!
Haven't thought of it this way but it is interesting to speculate. You've given me new thoughts to ponder! I thank you for that.
Thanks for your reply @bitfiend.
I wont mention the $1,000 STEEM. If you read any of my posts, I am uber bullish but it overwhelms people. I try to justify my predictions in my posts and I feel I do a good job at $100. While I am sure I could give a great case for $1000 STEEM (I am not disagreeing with you, I think you might be more accurate than inaccurate), it would simply delve into stuff that people would be baffled by. SMTs are really going to cause an explosion and I am not sure that people fully grasp the potential that has.
Totally understand where you're coming from. I never even thought Litecoin would pass $100 but here we are. The possibilities and potential of cryptocurrencies has blown my mind on epic proportoins and I doubt we're done yet. While bitcoin was first of its kind, it is expected to gain most traction. The coins gaining the most traction are all bringing something very unique to the table. Steemit is the first of its kind in the sense of the social platform. This makes steem a major player for the future. One reason I think 1k for steem is because I thought I was in fantasy land when I imagined bitcoin being at 10 grand and we're passed that mark. I held off and missed out on great profits and here I am. The thing is, even now, I know I'm not too late.
My view is that in 10 years, most of the world economy will be on blockchain....that means $90 or $100 trillion worth of commerce being done...at that point, what is the value of all blockchains? $250T? $400T? $1QT?
I really dont think people have the ability to comprehend how much this is revolutionary. This is the Internet but 100 times stronger.
So yeah, a $2.5T blockchain isnt outrageous.
Thank you @timcliff
Happy holidays prise!
This is a magic course result a good command works!
Wait 130$+ =))
Congratulations @timcl post has been randomly Resteemed! To join the ResteemSupport network and be entered into the lottery please upvote this post and see the following rules.
Friends, Light, Friends Fear, Friends Power, Win Friends ...
|
https://steemit.com/rewards/@timcliff/don-t-sweat-the-small-stuff-why-earning-low-rewards-today-shouldn-t-be-a-big-deal
|
CC-MAIN-2018-47
|
refinedweb
| 7,508
| 80.62
|
picnic 0.0.0.4
Python packages creation made easy
Picnic.py helps you write python packages:
picnic.py new PackageName
This creates a directory with all the files you need to get started:
/PackageName_project /PackageName /setup.py /README.rst /packagename /__init__.py /packagename.py
Not enough ? Try this:
picnic.py new MyPackage --author=Zulko --sphinx --gitinit --dev
Now you have a new package with a Sphinx documentation and a git repository for your project. And your package has been installed on your computer in develop mode (meaning you can change the code directly from this folder, without needing to reinstall the project).
These commands also work on already-written packages. For instance if I go in the setup.py folder and type
picnic.py --remote= --ghpages
This will link my project to an existing Github repository and initialize the Github Pages for this project. Now I just need to push these on Github (see Cookbook below), which will give me this repo for the code, and this page for the online documentation (you can change the look afterwards).
Installation and customization
Picnic.py requires the awesome docopt package, that you can install with the classic
pip python install docopt
To install Picnic.py, get a zip of the code, for instance on Github, and unzip it in some folder. You can have a look at the file templates README.rst, setup.py etc in subfolder picnic/files, and customize them as you like.
Then, in the folder of the setup.py, type
sudo python setup.py install
or even better, use this command instead, it will enable you to change the templates even after the installation:
sudo python setup.py develop
And you are done ! Note that you can also install picnic.py with pip but it is not recommended as it doesn’t allow you to change the templates.
Contribute !
Picnic.py is an open source software originally written by Zulko and released under the MIT licence. Please help make picnic better, for instance by expanding the capabilities, providing advice for sounder standards if you are an experienced module-maker, reporting bugs, etc. We love forks and pull resquests !
And speaking about branches, there is another one being actively developed.
Picnic is being developped on Github. That’s where you should go for troubleshooting and bug reports.
Cookbook
In this section, which is meant for beginners in Python, Sphinx, git, and Github, we explain how the files created by Picnic.py are meant to be used. You can also get help from the console with
picnic.py --help
Creating a Python package
To start a new project, you type
picnic.py new PackageName
To install the package (you will be able to modify the code afterwards) type
python setup.py develop
or equivalently
picnic.py --dev
Now we can start to code: we go in directory PackageName/packagename and in the file packagename.py we write
def say_hello(): print "Hello world !"
To check that this worked, open a python console (in any folder) and type
>>> import packagename >>> packagename.say_hello() Hello World !
Creating a Sphinx documentation
To initialize the Sphinx documentation you type
picnic.py [new PackageName] --author="Your Name" --sphinx
The documentation source will be in the docs directory and the built (html) doc will be in the folder built_docs/html/. To preview the docs after you have made some changes you can go into the docs repository and type
make html firefox ../../built_docs/html/index.html
For convenience these two lines are already written in the docs/make_html.sh file, therefore you only need to type
./make_html.sh
Creating a git repository
To create a git repository the classic way, you generally add a .gitignore file to your folder (to specify what kind of files not to include in the repo) and type these lines
git init git add . git commit -m "Initial commit"
The --git option does exactly all this: it adds a .gitignore file to the folder and runs all these commands. Be sure to run it in the directory where your setup.py is.
Linking to a repository on Github
To put this git repository on a Github, first create a repo on Github (say no when they ask you whether to include a README file). Github should give you the url of the repo, something like. Then in a console type
git add remote origin
or equivalently
picnic.py --remote=
To commit the changes to the git repo I generally do
git commit -a -m "my description of the commit"
And after this, to push the changes on the online Github repo:
git push origin master
Creating Github-pages
Here we suppose that you have already linked your project to Github with
git add remote origin
or equivalently
picnic.py --remote=
Now all you have to do is
picnic.py --ghpages
This creates a special git repository for the Github Pages in the directory built_docs/html, which is the output directory of the documentation.
When you are happy with the way your documentation looks you go into folder built_docs/html and type
git commit -a -m "my description of the commit" git push origin gh-pages
That’s all there is to know !
- Author: Zulko 2014
- Keywords: python module package template engine setuptools
- License: see LICENSE.txt
- Package Index Owner: Zulko
- DOAP record: picnic-0.0.0.4.xml
|
https://pypi.python.org/pypi/picnic/0.0.0.4
|
CC-MAIN-2017-34
|
refinedweb
| 896
| 65.52
|
This article is the first part in my Mobile Game Programming for Beginners series. The series starts out with a super-simple game, but will continue to show how to implement a variety of different game types and the techniques used to code them.
The series is a four part series, where I'll go through the following games:
This part will show you how to implement a very simple game, which tools you'll need, and how to actually try it out on your handset.
In this game, the goal is to navigate your avatar to a target, no obstacles, and the target isn't even moving. There's no way to "die", no way to loose, but it's a good starting point to show the basics of game programming. The areas I'll cover in this first part are:
All the games in this series have been developed using three software packages:
The Java SDK (or JDK, Java Development Kit) is a collection of class libraries, tools, and documentation, used when developing Java applications. It is not to be confused with a JRE, Java Runtime Environment, which is something that is used to run Java based applications. I downloaded my JDK from here. You'll need a JDK installed to use the next tool on the list, NetBeans, so make sure this is the first thing you download.
NetBeans is an Integrated Development Environment, IDE, mainly for Java development. It is free, which is good, but the best thing about it is that it truly rocks. According to me, it's by far the best Java IDE around right now. NetBeans is the tool that you'll use to implement and test your game as it comes bundled with a neat emulator so that you don't have to install the game on your mobile phone before you know it works.
Go here and download the Mobility pack and get that installed. The Mobility pack includes the J2ME JDK (Java 2 Mobile Edition), which contains the class libraries required to write a MIDlet (which is a Java application that can run on a mobile device) and the tools required (such as emulators for testing the game without having to install it on an actual handset).
Almost all games need some sort of graphics to make them enjoyable. I prefer to use Paint.NET to create the graphics for my games (when it's not generated by the game itself, but more on that in the second part of the series). The reason I'm not using Paint that comes bundled with Windows is that it's simply not packed with all the nice features that Paint.NET has, such as support for transparent PNG files.
Head on over to Paint.NET's download page and download it.
Once you have these three tools installed, you're almost ready to start coding.
Almost all games rely on a central game loop, it is the loop that manages or controls the game. As the games you write become more and more complicated, the methods called from the game loop will have to contain more and more logic, but the actual game loop will still be a fairly simple loop. In its simplest form, it might look something like this:
while(gameShouldStillBeRunning) {
// Capture input
readInput();
// Update the game state
updateGameState();
// Present the game to the user, i. e. render or draw it to screen
renderGameState();
// Check for game over
checkGameState();
}
This method is responsible for reading or capturing the current state of the input. This includes, for example, checking which keys are pressed and how far the mouse has moved since the last check. The method typically stores the input that is relevant to the game in a place where the updateGameState method can access it.
updateGameState
Storing the game state can be as easy as setting a boolean value to true if a key is pressed, and to false it it's not pressed. The reason for checking the input and storing it first, instead of checking it when you actually need it (i.e., when updating the game state), is because it is often quite expensive CPU wise to read the input, and it is best to get all the input required at once. Otherwise, different parts of the code that updates the game state might query the OS several times for the same key input, which would be unnecessary. Making the games run smooth and fast is a major part of game development, and I will discuss this in a later part of this series.
true
false
You'll notice that the game included in this article doesn't read the input state in the game loop, that is because it's relying on a built-in functionality of javax.microedition.lcdui.Canvas; more on this later.
javax.microedition.lcdui.Canvas
Updating the game state includes all the actual processing of the game logic, such as moving the player's character according to the input captured, moving enemies according to their AI, updating the environment, checking for game over state, and many more things, all depending on what kind of game is being developed.
In this first part, updating the game state includes only moving the avatar and checking if the avatar has reached the goal.
When the game state is rendered, the state of the game (i.e., the location of the player, the map, and for example, the current score) is drawn to the screen. The Canvas class in the javax.microedition.lcdui package is used to render things to the screen in kind of the same way as java.awt or javax.swing components, by overriding Canvas.paint(Graphics graphics). Note that the Graphics parameter isn't the java.awt.Graphics object that you might recognize from desktop development, it is a javax.microedition.lcdui.Graphics object, which is like a cut down version of the AWT one.
Canvas
javax.microedition.lcdui
java.awt
javax.swing
Canvas.paint(Graphics graphics)
Graphics
java.awt.Graphics
javax.microedition.lcdui.Graphics
This is where the game primarily detects if the player has lost or beaten the game, but it will also detect and act on any major state changes. Such as completing a level and moving into a game state where the level summary is shown before the next level is started (yet another state).
The first thing to do to get started is setting up a project in NetBeans; it is important to pick the right type of project as the project type dictates the JDK that will be used (remember, we need the J2ME JDK to get this to run on a mobile device).
In NetBeans, select File->New Project... and select the project category Mobility and project type MIDP Application, then click Next.
Give your project a name; in this example, it is called Basics.GameLoop. Then, make sure to un-tick the Create Hello MIDlet as that will create a template designed to handle a control based UI (with buttons and lists), and for a game, all rendering is custom, so no standard controls will be used. Then, click Next.
The next screen shows the configuration options. The settings picked here must match the target device's capabilities. That means that a game written for MIDP-2.1 will not run on a mobile phone that only supports MIDP-1.0, for example. For now, leave this page with its default settings, and click Finish.
In your new project's source package, create a package (as keeping classes in the root package is discouraged). You can call the package whatever you want; in the example application, it is called com.bornander.games.basics.
com.bornander.games.basics
Create a class called BasicsMIDlet in the package you just created, this will be the entry point for the application. This is the class that the Java runtime on the mobile device will instantiate when the the user selects your MIDlet. Make sure the BasicsMIDlet class extends javax.microedition.midlet.MIDlet, as this class defines the interface used by the runtime to control a MIDlet. javax.microedition.midlet.MIDlet is an abstract class, and there are three methods that must be overridden:
BasicsMIDlet
javax.microedition.midlet.MIDlet
startApp()
This method is called by the runtime to start the MIDlet, either when a start is requested by the user by selecting the MIDlet in some menu, or when the mobile device decides to return the control back to a previously paused MIDlet.
pauseApp()
This method is called by the runtime to indicate to a MIDlet that it will lose focus, possibly due to an incoming call. It is entirely up to the MIDlet to actually pause something. The example game included in this article will ignore this method, which means the game would continue to run when a call comes in.
If a MIDlet decides to pause itself, after taking steps to suspend itself in a controlled manner, call the resumeRequest() method to notify the framework that it is interested to know when it can resume processing.
resumeRequest()
destroyApp(boolean conditional)
This method is called when a MIDlet is being destroyed (closed), to allow it to clean up its resources in a safe and controlled way.
Make sure your BasicsMIDlet implements these three, abstract methods, after which your class should look something like this:
package com.bornander.games.basics;
import javax.microedition.midlet.MIDlet;
public class BasicsMIDlet extends MIDlet {
public BasicsMIDlet() {
}
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
The next step is to add the the MIDlet to the Application Descriptor, which is a set of meta data that holds information about the mobile application. One mobile application can contain several MIDlets, but for this example, there's only going to be one.
Right-click Basics.GameLoop and click Properties, then select Application Descriptor, the MIDlets tab, and click Add.... This will let you select a MIDlet class, give it a name and icon, and add it to the descriptor. The dialog auto-detects classes that extends javax.microedition.midlet.MIDlet, so just click OK to accept the default proposal.
And that's it! The mobile application is created. Click Run Main Project to try it out on the emulator. This will launch a mobile phone emulator from where the MIDlet just created can be started. Note that since there's no actual implementation yet, it won't do anything. Add a System.out.println("Hello, world!"); to the BasicMIDlet.startApp method, and run the application again to see that it's actually started. The text will be printed to the NetBeans IDE, so do not expect to see it on the screen of the emulator.
System.out.println("Hello, world!");
BasicMIDlet.startApp
When writing MIDlets, there's a set of classes for labels, text fields, checkboxes and such, that are used in a similar way to the corresponding classes in Swing or AWT. As this article is about game programming, it won't discuss any of these controls as they're not very well suited for graphical games.
The class used to render to screen is javax.microedition.lcdui.Canvas. By extending this class, it is possible to override its paint method and implement custom rendering. Create a new class called MainCanvas and have it extend javax.microedition.lcdui.Canvas. Override paint to render red text on a blue background:
paint
MainCanvas
package com.bornander.games.basics;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class MainCanvas extends Canvas implements Runnable {
public MainCanvas() {
}
// The Graphics object is used to render images, lines, shapes and
// text to the screen using different draw methods.
protected void paint(Graphics graphics) {
// Get the width and height of the screen in pixels
int w = getWidth();
int h = getHeight();
// Set the current color to blue (hex RGB value ) and draw a filled
// rectangle the size of the screen
graphics.setColor(0x00007F);
graphics.fillRect(0, 0, w, h);
// Set the current color to red, the font to the default font and
// draw a string to the center of the screen.
graphics.setColor(0xFF0000);
graphics.setFont(Font.getDefaultFont());
graphics.drawString("Hello, world!", w / 2, h / 2,
Graphics.BASELINE | Graphics.HCENTER);
}
}
In order to get the MIDlet to use this Canvas, it has to be set as the current one for the display. Modify BasicMIDlet.startApp to create a MainCanvas, and set it to the default Display:
Display
public void startApp() {
MainCanvas mainCanvas = new MainCanvas();
Display.getDisplay(this).setCurrent(mainCanvas);
}
Run the MIDlet again; this time is should look something like this:
Now, it's time to start implementing the actual game.
Even though it would be possible to render all aspects of a game using the different draw methods in javax.microedition.lcdui.Graphics, it is more common to use images created in an image editing program (such as Paint.NET). This game will use two different images: one for the player or avatar, and one for the target.
When creating images, it is important to make use of transparent pixels; otherwise, the avatar image wouldn't appear to be round but square.
By adding the resources to a Java package, it is possible to load them into javax.microedition.lcdui.Image objects which can then be drawn onto javax.microedition.lcdui.Graphics. A convenient way of loading resources is to use the Class.getResourceAsStream method, as it allows for referencing resources using Java package names (but with forward slashes instead of dots). Also, since the easiest way to get a Class instance is to call Object.getClass, there's always a simple way to reference resources in the same bundle as the current class.
javax.microedition.lcdui.Image
Class.getResourceAsStream
Class
Object.getClass
Image resources can therefore be placed in the normal Java package structure:
By adding two javax.microedition.lcdui.Images as members to MainCanvas, and loading the resources in the constructor, the paint method can be modified to draw the avatar in the upper left corner and the target in the lower right. Notice that it's good practice not to use absolute coordinates (such as 100, 100), but instead calculate the coordinates based on the current screen width and height. Obviously, 0, 0 is always going to be the upper left corner, but the coordinates of the lower right will vary on different mobile devices. By finding the width and height of the screen, and then subtracting the width and height of the image, the target image is guaranteed to always appear in the lower right corner, regardless of screen resolution.
package com.bornander.games.basics;
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
public class MainCanvas extends Canvas implements Runnable {
// Declare members for the images
private Image avatar;
private Image target;
public MainCanvas() throws IOException {
// Load the image resources
avatar = Image.createImage(getClass().getResourceAsStream(
"/com/bornander/games/basics/resources/avatar.png"));
target = Image.createImage(getClass().getResourceAsStream(
"/com/bornander/games/basics/resources/target.png"));
}
protected void paint(Graphics graphics) {
int w = getWidth();
int h = getHeight();
graphics.setColor(0x00007F);
graphics.fillRect(0, 0, w, h);
// Draw the images
graphics.drawImage(avatar, 0, 0, 0);
graphics.drawImage(target, w - target.getWidth(),
h - target.getHeight();
graphics.setColor(0xFF0000);
graphics.setFont(Font.getDefaultFont());
graphics.drawString("Hello, world!", w / 2, h / 2,
Graphics.BASELINE | Graphics.HCENTER);
}
}
Always painting the Avatar in the upper left corner isn't going to make for a very interesting game. By declaring members for position, and also travel direction, it will be possible to control the Avatar using the keypad. Normally, I'd prefer to store the location of an Avatar in 2D space as some sort of Point object, but as the J2ME libraries is a cut down version of the J2SE, there is no such class. I could have written my own (as I have for the other games in this series), but decided to store the position as two separate integers. I store the direction as four separate booleans, for up, down, left, and right.
Point
boolean
public class MainCanvas extends Canvas implements Runnable {
// The two images
private Image avatar;
private Image target;
// The coordinates of the player.
private int x = 0;
private int y = 0;
// Flags indicating which buttons are pressed.
private boolean up = false;
private boolean down = false;
private boolean left = false;
private boolean right = false;
...
}
Moving the avatar (i.e., updating its X and Y coordinates according to the direction flags) is delegated to a method that also does constraint checking. By constraint checking, I mean the process in which the position is constrained to a valid one. In this example, it is invalid for the avatar to be outside the bounds of the screen.
public class MainCanvas extends Canvas implements Runnable {
...
private void moveAvatar() {
if (up)
--y;
if (down)
++y;
if (left)
--x;
if (right)
++x;
if (y < 0)
y = 0;
if (y > getHeight() - avatar.getHeight())
y = getHeight() - avatar.getHeight();
if (x < 0)
x = 0;
if (x > getWidth() - avatar.getWidth())
x = getWidth() - avatar.getWidth();
}
}
Notice again the use of getWidth/getHeight and avatar.getWidth/avatar.getHeight to make the constraint checking independent of screen size as well as image size. This method, MainCanvas.moveAvatar, will be called by the game loop for each iteration to update the position of the player. Obviously, this also requires a small change to the MainCanvas.paint method, as the avatar is no longer drawn at (0, 0), but at (x, y).
getWidth
getHeight
avatar.getWidth
avatar.getHeight
MainCanvas.moveAvatar
MainCanvas.paint
By extending Canvas, it's easy to capture the input by simply overriding some methods. Canvas exposes three methods related to key input:
void keyPressed(int keyCode)
void keyReleased(int keyCode)
void keyRepeated(int keyCode)
In this first example, I'm only going to use keyPressed and keyReleased, and to control the Avatar, the only thing the methods needs to do is to set up, down, left, and right according to which key was pressed or released.
keyPressed
keyReleased
up
down
left
right
The keyCode parameter passed to the key handling can be converted to key codes better suited for game programming using the aptly named function Canvas.getGameAction; this will convert the key code into one that can be checked for buttons such as up and down.
keyCode
Canvas.getGameAction
/**
* This gets called for us whenever a key is pressed.
* @param key The pressed key.
*/
protected void keyPressed(int key) {
int gameKey = getGameAction(key);
switch(gameKey) {
case Canvas.UP: up = true; break;
case Canvas.DOWN: down = true; break;
case Canvas.LEFT: left = true; break;
case Canvas.RIGHT: right = true; break;
case Canvas.FIRE: shouldRun = false; break;
}
}
/**
* This gets called for us whenever a key is released.
* @param key The released key.
*/
protected void keyReleased(int key) {
int gameKey = getGameAction(key);
switch(gameKey) {
case Canvas.UP: up = false; break;
case Canvas.DOWN: down = false; break;
case Canvas.LEFT: left = false; break;
case Canvas.RIGHT: right = false; break;
}
}
All games need to check the Game Over state; this can occur either when the player loses the game or when he beats it. In any case, it has to be checked, or the game can neither be won or lost.
In this first example, Game Over can only occur when the player has beaten the game. Yep, that's right. This is a game you can't fail at. You can choose not to win, but you can't lose. This implementation calls a method called isGameCompleted to check if the game is over. This method sets a member variable, completed. To change the behaviour of the game when the Game Over state is reached, the run method looks at the completed flag set when the Avatar has reached the Goal, and if it's true, then the Avatar isn't moved anymore, regardless of key presses. Also, the paint message draws a Game Over message at the center of the screen.
isGameCompleted
completed
run
/**
* Detects if the game has been completed
* (i.e. the avatar has navigated to the target).
* @return true if the game is completed.
*/
private boolean isGameCompleted() {
return x == targetX && y == targetY;
}
This method is called in the run method:
protected void paint(Graphics graphics) {
...
if (completed) {
graphics.setColor(0xA0A0FF);
graphics.setFont(Font.getDefaultFont());
graphics.drawString("Game Over", w / 2, h / 2,
Graphics.BASELINE | Graphics.HCENTER);
}
}
public void run() {
while(shouldRun) {
completed = isGameCompleted();
if (!completed) {
moveAvatar();
}
repaint();
try {
Thread.sleep(20);
}
catch (InterruptedException ex) {
}
}
owner.exit();
}
And that's it! That's the whole game. It's not the most addictive game in the world, but it is enough to show how to set up a NetBeans project and the basics of a game.
In the next part, I'll cover menus, simple AI, and basic collision detection as I demonstrate how to write a BreakOut style game.
As always, any comments on the article or the code are most welcome.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
import javax.microedition.lcdui.*;
public void run() {}
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
News on the future of C# as a language
|
http://www.codeproject.com/Articles/36060/Mobile-Game-Programming-for-Beginners-Part-of?msg=3044724
|
CC-MAIN-2014-10
|
refinedweb
| 3,569
| 63.7
|
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Saving Text Files3:20 with Jay McGavren
Our users can view pages that we've created for them. But a major feature of a wiki is the ability for users to create their own pages, and they can't do that yet. So let's fix that. Our next task is to set up a form so that users can create their own pages.
We've added another new method,
save_content, to the app. This one takes strings with a wiki page title and some content, and saves the content to a file:
def save_content(title, content) File.open("pages/#{title}.txt", "w") do |file| file.print(content) end end
We call
File.open with the name of a file we want to save our text to. The second argument is the mode to open the file in; a string of
"w" means we want to write to the file. If you provide a block to
File.open, it will pass a
File object to the block (that's the
file parameter), and automatically close the file when the block is done.
Within the block, we can call methods on the
File object to write data to the file.
File inherits a
IO class; whatever string you pass to
- 0:00
[MUSIC]
- 0:04
Our users can view pages that we've created for them.
- 0:08
But a major feature of a wiki is the ability for
- 0:10
users to create their own pages.
- 0:12
And they can't do that yet.
- 0:14
So let's fix that.
- 0:15
Our next task is to set up a form for new pages.
- 0:18
First thing we're going to need is the ability to save text files with
- 0:21
the contents of new pages.
- 0:23
We already have the page content method that takes a page title and
- 0:26
uses it to load the contents of a text file in the pages directory.
- 0:31
I've added another method called save_contents to the app
- 0:33
which saves a file to the pages directory.
- 0:36
Again if you launch a workspace from this video's page,
- 0:38
you'll get an updated wiki .rb file with this method already set up for you.
- 0:43
The save_content method takes two strings as parameters.
- 0:46
The first string holds the page title and
- 0:48
the second holds the page content, save_content calls the core rubyfile.open
- 0:52
method to open a file in the pages directory.
- 0:55
It uses the title string as a filename and adds an extension of the .txt.
- 1:00
The string w in the second argument tells the method to open the file in write mode.
- 1:05
File.open takes a block and
- 1:07
passes an object representing the open file to the block as a parameter.
- 1:12
Within the block,
- 1:13
we can call the print method on the file object to write strings to the file.
- 1:16
So we simply call print and write the entire page contents to the file at once.
- 1:22
When the block finishes, control returns to the file.open method
- 1:25
which closes the file for us automatically.
- 1:28
Just like before,
- 1:29
I'll copy the save content method to a new file to show you how it works by itself.
- 1:34
I'll create a test.rb file again.
- 1:40
And paste this method in there.
- 1:42
Then I'll add a call to it which will create a page titled Ben Deitch.
- 1:46
So we'll call save_content.
- 1:49
First argument is the title, Ben Deitch.
- 1:55
Second argument is the page content which will just say,
- 1:59
Treehouse Android teacher.
- 2:06
Let's save this and then go to our console and try running it.
- 2:10
Ruby test.rb.
- 2:14
If we right click in the sidebar and choose refresh,
- 2:18
we'll see a new file in the pages directory called Ben Deitch.txt.
- 2:23
And that file will have the contents that we specified when we called
- 2:26
the save_content method.
- 2:27
We can also use save_contents top update existing files.
- 2:31
Let's change the method call to update our Nick Pettit.txt file.
- 2:35
We'll set the title in our method call to Nick Pettit.
- 2:40
And we'll change the content in the file to Treehouse teacher and awesome guy.
- 2:49
Save that and now, we can go to the console and run the script again.
- 2:53
Then if we open Nick Pettit.txt, we'll see our updated content.
- 2:58
As before,
- 2:58
we should delete the test.rb file when we're done to keep our project clean.
- 3:04
Again, understanding the save_content method isn't essential to understanding
- 3:08
Sinatra.
- 3:08
But there's more info in the teacher's notes if you want it.
- 3:11
So we've got a method that can take a wiki pages data and save it for us.
- 3:15
Now we're going to need an HTML form that lets users enter that data.
- 3:18
We'll look at that next.
|
https://teamtreehouse.com/library/saving-text-files
|
CC-MAIN-2018-30
|
refinedweb
| 923
| 91.71
|
import "crypto/sha256"
Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
sha256.go sha256block.go sha256block_amd64.go sha256block_decl.go
The blocksize of SHA256 and SHA224 in bytes.
The size of a SHA256 checksum in bytes.
The size of a SHA224 checksum in bytes.
New returns a new hash.Hash computing the SHA256 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.
New224 returns a new hash.Hash computing the SHA224 checksum.
Sum224 returns the SHA224 checksum of the data.
Sum256 returns the SHA256 checksum of the data.
Package sha256 imports 6 packages (graph) and is imported by 25468 packages. Updated 2020-06-21. Refresh now. Tools for package owners.
|
https://godoc.org/crypto/sha256
|
CC-MAIN-2020-29
|
refinedweb
| 127
| 63.66
|
Details
- Type:
Bug
- Status:
In Progress
- Priority:
Major
- Resolution: Unresolved
- Affects Version/s: 1.7-rc-2
- Fix Version/s: None
- Component/s: ast builder
- Labels:None
- Environment:Groovy 1.7-RC-2 on jre1.6.0_04 on Windows Vista SP2
- Number of attachments :
Description
The following code produces class MyClass OK, but running the class produces error:
Exception in thread "main" java.lang.NoSuchMethodError: main
Here's the ASTBuilder code I used:
import static org.objectweb.asm.Opcodes.ACC_PUBLIC import static org.objectweb.asm.Opcodes.ACC_STATIC import org.codehaus.groovy.ast.builder.AstBuilder import org.codehaus.groovy.control.CompilerConfiguration import org.codehaus.groovy.control.CompilationUnit def classes= new AstBuilder().buildFromSpec{ classNode 'MyClass', ACC_PUBLIC, { classNode Object //superclass interfaces{ classNode GroovyObject } mixins{} genericsTypes{} method('main', ACC_PUBLIC & ACC_STATIC, Void.class) { parameters{ parameter 'args': String[].class } exceptions{} block{ methodCall { variable "this" constant "println" argumentList { constant "Hello, world!" } } } } } } def gcl= new GroovyClassLoader() def sec= null def ccfg= CompilerConfiguration.DEFAULT def cu= new CompilationUnit(ccfg, sec, gcl) cu.addClassNode(classes[0]) cu.compile()
Also tried this but same result: "Hello, world!" } } """) def gcl= new GroovyClassLoader() def sec= null //new CodeSource() def ccfg= CompilerConfiguration.DEFAULT def cu= new CompilationUnit(ccfg, sec, gcl) cu.addClassNode(classes[1]) cu.compile()
Activity
For the 2nd example (AstBuilder#buildFromString()), here is the working code: "Roshan here!" } } """) def su = classes[1].module.context def gcl = new GroovyClassLoader() def sec = null //new CodeSource() def ccfg = CompilerConfiguration.DEFAULT def cu = new CompilationUnit(ccfg, sec, gcl) cu.addClassNode(classes[1]) cu.addSource(su) cu.compile()
Regarding 1st example, the MethodNode (main) is not even getting added to ClassNode (MyClass)'s methods, so no wonder it is not coming in compiled class and then not able to run.
Slightly tweaked version of Roshan's example:
import org.codehaus.groovy.ast.* import org.codehaus.groovy.ast.builder.AstBuilder import org.codehaus.groovy.control.CompilationUnit import static org.codehaus.groovy.control.CompilerConfiguration.* import static org.codehaus.groovy.control.CompilePhase.* def classes = new AstBuilder().buildFromString(CONVERSION, """\ class MyClass { static main(String[] args){ println "Roshan here!" } } """) def su = classes[1].module.context def gcl = new GroovyClassLoader() def cu = new CompilationUnit(DEFAULT, null, gcl) cu.addClassNode(classes[1]) cu.addSource(su) cu.compile() MyClass.main()
I should have mentioned here for documentation sake what was the change introduced for the 2nd example.
The issue was that because there was no SourceUnit attached to the CompilationUnit, it was skipping all SourceUnitOperation(s) in the compilation phases - "resolve" being one such skipped operation.
Because "resolve" was not happening, main method was remaining as "main(LString;)V" instead of "main(Ljava.lang.String;)V" and that's why it was not being recognized as the standard main method.
I don't think there is any issue with the AST Builder. I wrote a Transformation called "Main" that adds main methods to classes and it works fine. There are two errors in the posted script:
1: You must use ACC_PUBLIC | ACC_STATIC for the correct modifiers. The & is not correct.
2: You must use Void.TYPE for the return type, Void.class is not the same.
I would commit this patch to the Groovy Example directory... what do you think?
Hamlet, isn't the transformation solution different from what is asked for in the example 1 - where classNode and method both are defined in AstBuilder?
It was noticed that methods defined under AstBuilder (in buildFromSpec) don't get added to the defining ClassNode. Since that has not been addressed, wanted to check if AstBuilder is not supposed to support that.
Yes, this solution is slightly different because I wanted to make something a little more useful. However, it did work in my testing. The problems were in the pipe character, the return type, and all that CompilationUnit/SourceUnit stuff, not in the AST builder. Maybe I should retest it after work though.
No, no, you missed my point. All other things you say are fine (modifier, return type, CompilationUnit/SourceUnit association, etc), except one.
This example is different from the issue #1 raised here because it is also doing the work of adding the MethodNode to the ClassNode - isn't that something that AstBuilder should also be able to do in its buildFromSpec()?
Does AstBuilder not support the following (because right now, methods from the builder don't get associated with ClassNode)?
def classes= new AstBuilder().buildFromSpec{ classNode 'MyClass', ACC_PUBLIC, { .... method('main', ACC_PUBLIC & ACC_STATIC, Void.class) { .... } } }
Following on from Roshan's comments, currently, I can only solve the original problem using something like:
import static org.objectweb.asm.Opcodes.ACC_PUBLIC import static org.objectweb.asm.Opcodes.ACC_STATIC import static org.codehaus.groovy.control.CompilerConfiguration.* import org.codehaus.groovy.ast.builder.AstBuilder import org.codehaus.groovy.control.CompilationUnit def classes = new AstBuilder().buildFromSpec { classNode 'HelloClass', ACC_PUBLIC, { classNode Object //superclass interfaces { classNode GroovyObject } mixins {} } } def methods = new AstBuilder().buildFromSpec { method('main', ACC_PUBLIC | ACC_STATIC, Void.TYPE) { parameters { parameter 'args': String[].class } exceptions{} block{ expression { methodCall { variable "this" constant "println" argumentList { constant "Hello, world!" } } } } } } def helloClass = classes[0] def mainMethod = methods[0] helloClass.addMethod(mainMethod) def gcl = new GroovyClassLoader() def cu = new CompilationUnit(DEFAULT, null, gcl) cu.addClassNode(helloClass) cu.compile()
It would be nice to have something like a {{methods{...}
}} node which allowed the two to be combined.
And even on this, without a SourceUnit, all SourceUnitOperation(s) of the compilation are not happening - so no "resolve" is happening - all types have to be explicitly resolved, as in "parameter 'args': String[].class"
Not sure whether such compile scenarios are supported by AstBuilder or not - once it goes beyond vanilla examples, differences from what compiler does normally may start coming in the way very fast - like ClassNodes not wrapped in a ModuleNode, no association with a SourceUnit, all SourceUnitOperation(s) getting skipped, etc.
In my opinion, using the "buildFromSpecification" requires the user to know the details of the ASTNode subtypes to use effectively. Similarly, using the SwingBuilder requires the user to know about the concrete Swing types as well. The builders are a nice convenience syntactically, but are not an abstraction hiding the details. Since this is the case, I would recommend not adding convenience methods to the builder. Instead, add the convenience methods to the ASTNode subtypes directly and then add the support for these to the builder. I think the builder should remain a syntatic shortcut over the ASTNodes and not start adding too much Api to it.
@Roshan
Your example should work fine with the AstBuilder. I guess I will have to look into it more. However, I'm still not convinced there is a bug in the AstBuilder. I think the error will come down to not using the API correctly.
For instance, use the same example and replace all the AstBuilder with direct ASTNode constructors... I will bet that it doesn't work that way either.
The test case for this needs to be an expected result created from ASTNode subclasses and an actual result created from AstBuilder... then compare the expected ASTNode to the actual ASTNode... all this wiring together and writing a class file is immaterial to the proper functioning of the builder.
Well, if I replace all AstBuilder with direct ASTNode constructors, then apart from creating ClassNode and MethodNode using their constructors, I will also have to do ClassNode.addMethod(MethodNode) manually - for the ClassNode to compile into a class that has that method.
That's the question - is AstBuilder supposed to do that internally or is that the responsibility of the AstBuilder user (as in Paul's example).
If it is supposed to be AstBuilder's responsibility, then it is a bug in AstBuilder curently. If it is not, then that means the following is not supported:
new AstBuilder().buildFromSpec{ classNode 'MyClass', ACC_PUBLIC, { .... method('main', ACC_PUBLIC & ACC_STATIC, Void.class) { .... } } }
Just trying to understand how much AstBuilder supports out-of-the-box.
@Roshan
OK, I understand now.
My reaction is that AstBuilder should not do this. But I could be convinced either way. How many edge cases like this are there, I wonder? How far in this direction do we go?
I am not really sure that these are edge cases. To start with, there are FieldNode (which need the owner ClassNode in their constructor and also need to be added to ClassNode with addField()). Similarly for PropertyNodes (owner ClassNode + addProperty).
First question to ask is about the purpose of AstSpecificationCompiler - whether it even wants to support the compile scenario as in this JIRA.
If AstSpecificationCompiler wants to give out ClassNodes that are compilable, then I don't think it can avoid the API - it will have to setup of hierarchy of ASTNodes as the compiler expects.
Yes, I see the point. Perhaps that would be a good improvement.
I agree here that the various edge case nodes have to be "added" to their respective parents, like method nodes, field nodes, property nodes to their class node parent.
(are we missing other nodes that need to be attached to their parent?)
so, to summarize:
we do want to auto-add these types to the parent. And this should be a minor improvement/enhancement that is part of a point release (7.1 most likely)
Auto-wrapping expressions into statements may also be considered (like wrapping a MethodCallExpression into an ExpressionStatement).
Currently, it has to be done manually as below
block{ expression { // we should see if this can be avoided at user level. methodCall { .... } } }
@Hamlet, yes, a must-have minor improvement/enhancement, good for a point release in a month or so
@Roshan, we not necessarily mandatory, but if there are some places / cases like these ones we can help further simplify, why not!
@Guillaume
>> If there are some places / cases like these ones we can help further simplify, why not!
I am a little worried about where this leads. Currently, the best documentation for the buildFromSpec is the ASTNode javadoc. This is good, as it is backed by something thoroughly unit tested and is executable in some sense. If we diverge from a a simple wrapper then we need to add some sort of documentation or risk leaving users confused. But re-document the buildFromSpec then it is a big task and duplicates much of what is there. For me, I would not make these simplifications.
@Hamlet, yes, you're certainly right, I guess it may be a bit confusing if the builder doesn't closely follow the AST Groovy generates. So let's not do such shortcuts, and keep the structure the same in the builder and in the ASTNodes.
Lost the thread a bit in the last couple of comments., right?
@Roshan
That is correct.
."
javap output of class:
|
http://jira.codehaus.org/browse/GROOVY-3971?focusedCommentId=205209&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
|
CC-MAIN-2013-48
|
refinedweb
| 1,770
| 50.33
|
01 June 2010 07:54 [Source: ICIS news]
SINGAPORE (ICIS news)--DSM Engineering Plastics has completed its takeover of Japan's Mitsubishi Chemical Corporation's (MCC) polyamide business, the Dutch producer said in a statement on Tuesday.
The acquisition was part of an agreement, which enabled DSM to acquire MCC’s polyamide business in exchange for its polycarbonate business, the statement added.
“Both businesses have an annual net sales level of approximately €90m ($111m) each. The parties have agreed not to disclose other financial details,” DSM said.
The deal would also enable DSM to “expand its position in ?xml:namespace>
A number of key employees of DSM's polycarbonate business were transferred to MCC as part of the deal, it added.
($1 = €0.81)
For more on polyamide, polycarbon
|
http://www.icis.com/Articles/2010/06/01/9363550/dsm-completes-takeover-of-mitsubishis-polyamide-business.html
|
CC-MAIN-2014-49
|
refinedweb
| 129
| 62.38
|
Today I came across a very nice Sencha Touch ux component: a sliding menu like…
Getting Started with Sencha Touch 2: Build a Weather Utility App (Part 1)! tutorial, you will start with coding the app. The next tutorials will focus on creating a cool Sencha Touch theme and how to port your app to a native app with PhoneGap.
This tutorial requires:
- Sen
Let’s start by creating a sencha folder somewhere on your hard disk. Download the Sencha Touch 2.3 framework and extract it into the newly created sencha folder. Now, create the folder for your app, I’ve called it dinmu since that is shorter than the name “DoINeedMyUmbrella” but it’s up to you.
Now, open your command line (MS-Dos Prompt or Mac OS X Terminal), navigate to the Sencha framework folder: (cd sencha/touch-2.3.x folder) and run the following command to generate your Sencha Touch MVC folder structure:
sencha generate app -name Dinmu -path ../dinmu
This command generates the full MVC structure for your application: Do I need my Umbrella. It takes the namespace Dinmu, to prefix all your classes. Review the folder structure it has created.
Now it’s time to start your web server via the command line — use the path to your sencha folder. (If you would rather use your own Apache web server, you are free to start it and skip this step.) On Mac OS X, you might need permissions for executing the next command: if you run into permission errors, prefix the above command with sudo.
sencha fs web -p 80 start -map /path/to/sencha/folder/
This will start your built-in Jetty web server. You need your CLI window open to keep the server running, so it makes sense to open a new CLI window for the next commands.
Test your generated Sencha Touch app. Open your modern browser (such as Google Chrome or Safari) and run:. You should see the Sencha demo app interface with a bottom tab panel and two demo slides:
The Data Package
In the next steps, you will Setting id,city,country,units,geo:boolean
This command generated the model for your application. It takes the classname Setting and one String with all the field names to define all the different fields. Let’s field id, will define id’s for every model record in your application. To have it behave as a unique id, you will need to configure it. Before the fields array, configure an idProperty and an identifier.
idProperty: 'id', identifier: 'uuid',
The logic for these unique IDs are in a Sencha class that we need to “import” into our app. We can use a requires for that, this requires the class Ext.data.identifier.Uuid.
requires: ['Ext.data.identifier.Uuid'],
The next step is to create some validations for our model. After the fields array, create a validations array. The array contains validation objects to validate whether the data for these fields is present:
validations: [{ type: 'presence', field: 'city', message: "Please provide a city." }, { type: 'presence', field: 'country', message: "Please provide a country." }],
Since we want to save the local settings data to the device, the last step is to add a client proxy.
We will use localstorage. The localstorage proxy will make sure that all the data persists into the browser localstorage. Define the proxy object directly after the validations array:
proxy: { type: 'localstorage', id: 'weathersettings' }
The View Components
The standard tabpanel interface that Sencha Cmd generates looks good, but it’s not what you need for a utility app. The Do I need my Umbrella app will need a carousel interface.
Open the code of app/view/Main.js in your IDE or text editor.
The current implementation of Dinmu.view.Main extends from the Sencha Touch Ext.tab.Panel class. It has a tabBarPosition property to add the tabs to the screen bottom.
We don’t need it, so remove tabBarPosition:bottom and change the extend to Ext.Carousel, to extend from the Sencha Touch Carousel class. From here, you can open your browser and run:. You should see the generated Sencha demo app. The tabpanel interface is replaced by a carousel interface. You can slide the views horizontally.
Let’s remove more default components. We won’t need the demo video, so let’s remove the Ext.Video from the requires array. We can also empty the items array, since we will replace it with two new items.
The first item object (container by default) has only the html property. This can be set to a placeholder text: Settings Form so you can code this later. The second item object has a property itemId: ‘mainview’ and a cls property (for styling) set to the value: textview. Also add a direction property, which will set the direction of the Carousel to ‘vertical’.
Ext.define('Dinmu.view.Main', { extend: 'Ext.Carousel', xtype: 'main', requires: [ 'Ext.TitleBar' ], config: { direction: 'vertical', items: [{ html: 'Settings Form' },{ itemId: 'mainview', cls: 'textview' }] } });
Viewed in the browser, the app looks pretty basic. Let’s add a top titlebar and a bottom toolbar. Before the Settings Form object, create a new object. This object will get the xtype: ‘titlebar’ to add a new instance of Ext.TitleBar to the Viewport (the screen). Set a class name on the titlebar with the CSS class property: cls: ‘title’. Set a docked: ‘top’ property to stick this titlebar to the top of the screen. Set the title to: Do I need my Umbrella? with the title property:
{ xtype: 'titlebar', cls: 'title', docked: 'top', title: 'Do I need my Umbrella?' },
You will do the same for the bottom toolbar. This time the xtype is not titlebar but toolbar. The cls can be set to footer. Dock it to the bottom of the screen. Instead of the title property, the toolbar needs an html property. Set this to some copyright string. We will add an ui property which is set to light to create a lighter look and feel. Don’t forget to add Ext.Toolbar to the requires array in the top of the file, so the correct framework class will be loaded into the memory.
{ xtype: 'toolbar', cls: 'footer', ui: 'light', docked: 'bottom', html: 'Powered by © Sencha Touch' },
The next step is to create some buttons in the top titlebar.
The titlebar should contain an items array, which contains two buttons. A back button, which will be displayed when you are on the settings screen, and a settings button which will be shown on the default screen. You don’t need to set the xtype to button, the default item of an Ext.TitleBar is a button. The back button, is by default hidden and it is left aligned in the titlebar. The settings button, shows an icon of a settings gear.
Confirm your code looks like this:
Ext.define('Dinmu.view.Main', { extend: 'Ext.Carousel', xtype: 'main', requires: [ 'Ext.TitleBar', 'Ext.Toolbar' ], config: { direction: 'vertical', items: [ { xtype: 'titlebar', cls: 'title', docked: 'top', title: 'Do I need my Umbrella?', items: [{ cls: 'back', hidden: true, ui: 'back', action: 'back', align: 'left', text: 'back' }, { iconCls: 'settings', action: 'settings', ui: 'plain', align: 'right' }] }, { html: 'Settings Form' },{ itemId: 'mainview', cls: 'textview' }, { xtype: 'toolbar', cls: 'footer', ui: 'light', docked: 'bottom', html: 'Powered by © Sencha Touch' }] } });
Open your browser and run:. You should see a button with a gear in the right corner of the Ext.TitleBar.
Forms
Now, we can start with creating a form. You know what? Let’s generate this too. Navigate to the dinmu folder on the command line and run the following to generate your Sencha Touch form:
sencha generate form SettingsView geo:toggle,units:select,city,country
Review the form class that has been scaffolded. Open app/view/SettingsView. The Dinmu.view.SettingsView class has an xtype set to settingsview. You can assign custom made classes to item arrays with the xtype property.
So let’s do so. Open Dinmu.view.Main (app/view/Main.js), find the settings item in your code. By default, if you don’t specify its xtype is set to container. You will need to refer to the new xtype: settingsview, so add xtype: ‘settingsview’ to the Main view code. You don’t need the placeholder html string anymore. Remove the html: settings property. Also don’t forget to add Dinmu.view.SettingsView to the requires array to make sure this class is loaded in memory.
To make it look better, you will add a fieldset to the Ext.form.Panel in the SettingsView. This fieldset contains the four new fields and the submit button. The fieldset will be a child of the formpanel and has its own children: the form fields and the button.
Create a second items array in the config object (after the title property). Nest the second items array as a child. The parent items array contains one fieldset xtype, with a title: ‘Your location’, and a line with instructions.
Make sure the child items array contains all the fields and the button. Verify your code looks like this:
Ext.define('Dinmu.view.SettingsView', { extend: 'Ext.form.Panel', xtype: 'settingsview', config: { items:[{ xtype: 'fieldset', title: 'SettingsView', instructions: 'In case you do not want the app to detect your location you can enter the city and country.', items: [ { name: 'geo', xtype: 'togglefield', label: 'Geo' }, { name: 'units', xtype: 'selectfield', label: 'Units' }, { name: 'city', xtype: 'textfield', label: 'City' }, { name: 'country', xtype: 'textfield', label: 'Country' }, { xtype: 'button', text: 'Submit', ui: 'confirm' } ] }] } });
Open your browser and run:. You should see the settings form with a title and some instructions. But there is something odd with the select unit field. It has no values.
Let’s add some values to the units selectfield.
Create an options array with two objects. One with the text: ‘Fahrenheit’ and a value: ‘f’ and one object with the text: ‘Celsius’ and the value: ‘c’.
The label GEO in the togglefield makes little sense. Change this label to: ‘ Auto detect?’ Since the text for this label takes much more space, we will set the labelWidth to ‘55%’. Set the value of the geo field to value: ‘1’ to enable geolocation by default.
Disable the units, city and country fields by adding disabled: true to all fields.
The button text, should be Refresh instead of Submit. Change this in the button component. Add a margin with the value ‘10 5’. Also add an action property to the button and set this to ‘refresh’. This way, we can reference the button later:
{ xtype: 'button', text: 'Refresh', action: 'refresh', margin: '10 5' ui: 'confirm' }
You might have noticed that the console outputs some warnings. The Ext.Loader, the mechanism that loads all' ],
You’ve finished the interface.
Here’s the complete code for the settingsview:
Ext.define('Dinmu.view.SettingsView', { extend: 'Ext.form.Panel', xtype: 'settingsview', requires: [ 'Ext.form.FieldSet', 'Ext.field.Toggle', 'Ext.field.Select', 'Ext.field.Text', 'Ext.Button' ], config: { items:[{ xtype: 'fieldset', title: 'SettingsView', instructions: 'In case you do not want the app to detect your location you can enter the city and country.', items: [ { name: 'geo', xtype: 'togglefield', label: 'Auto Detect?', labelWidth: '55%', value: '1' }, { name: 'units', xtype: 'selectfield', options: [ { text: 'Fahrenheit', value: 'f' }, { text: 'Celsius', value: 'c' }], label: 'Units', disabled: true }, { name: 'city', xtype: 'textfield', label: 'City', disabled: true }, { name: 'country', xtype: 'textfield', label: 'Country', disabled: true }, { xtype: 'button', text: 'Refresh', action: 'refresh', margin: '10 5', ui: 'confirm' } ] }] } });
But wait, what about the main view? Yes, you will dynamically inject this page with data. Therefore, you will need some logic to achieve this, so from the command line:
sencha generate controller Main
This command generates the Main controller. Open app/controller/Main.js with your editor. You will see a controller with an empty references object (refs) and an empty control object.]', fieldUnits: 'settingsview selectfield' },
Now that you have references to all the view components that should contain events, the events, you must hook the controller to app.js which is the MVC’s entry point. Open app.js, create a controllers array, right below the requires array and pass in the string ‘Main’ mapping the Main controller to the app/controller/Main.js file.
controllers: [ 'Main' ],
Now, we will add some logic. Go back to Dinmu.controller.Main and add the functions in the goodies-tutorial directory. You can find them in controller.txt.
Replace the launch function with the functions provided.
Setting Up Stores and Singletons. Define a new class: Dinmu.store.Settings. This class extends all methods and properties from the Ext.data.Store class. In the config object, create a property called: model. It should connect to the Setting model. Also, the settings store should load automatically:
Ext.define('Dinmu.store.Settings', { extend: 'Ext.data.Store', requires: ['Dinmu.model.Setting'], config: { model: 'Dinmu.model.Setting', autoLoad: true } });
Open controller/Main.js, in the config object create a stores array and add the Dinmu.store.Settings store to it:
stores: 'Dinmu.store.Settings',
Sometimes, it’s better to separate your business logic outside the MVC folders.
In the app folder, create a new folder utils. Create the file Functions.js, and define a class called: Dinmu.utils.Functions. This class has a property: singleton set to true. Now your class is a singleton, you cannot create more than one instance of it, but you can run the singleton methods from everywhere in your code:
Ext.define('Dinmu.utils.Functions', { singleton: true, //singleton methods here });
Add Dinmu.utils.Functions to the requires array of the app.js file.
Open the snippet: functions.txt from the goodies-tutorial folder and copy all the functions into the utils/Functions.js file.
This snippet contains the functions you will need for requesting weather data from. If you would rather request and use your own API_KEY, you can edit it on top of the Functions.js by changing the String for property API_KEY. It also contains logic for requesting geolocation on the device and injecting data in the template on the mainview. If you are really interested in this logic, I left complete comments in the functions.txt file which describes exactly what is going on.
To test the logic, open Google Chrome Developer Tools and switch to the Console tab and enter the following line: Dinmu.utils.Functions.getWeather(‘London’) it should return a weather object for London and display some text in the mainview.
Finally the Do I need my Umbrella app is finished! Open your browser and run:. The next steps for improving your application would be to apply a theme and a production build. This is something I will discuss in the next Sencha Blog tutorial.
If you found this tutorial helpful check out my book I wrote for O'Reilly: Hands-on Sencha Touch 2!
|
https://www.leeboonstra.com/developer/getting-started-with-sencha-touch-2-build-a-weather-utility-app-part-1/
|
CC-MAIN-2017-34
|
refinedweb
| 2,467
| 67.15
|
You don't need to create many types of thumbnails for images in your project.
You can create a thumbnail directly in the
View. Thumbnail will automatically cached. It's easy!
GDand
Imagick
Retinadisplays
GDor
Imagick
Note: Latest release and documentation are available from extension github page.
Extract the
EasyImage folder under
protected/extensions
Add the following to your config file
components section:
'components'=>array( //... 'easyImage' => array( 'class' => 'application.extensions.easyimage.EasyImage', //'driver' => 'GD', //'quality' => 100, //'cachePath' => '/assets/easyimage/', //'cacheTime' => 2592000, //'retinaSupport' => false, ),
and the following to
import section:
'import' => array( //... 'ext.easyimage.EasyImage' ),
$image = new EasyImage('/path/to/image.jpg'); $image->resize(100, 100); $image->save('/full/path/to/thumb.jpg');
$filerequired - Image file path
$driver- Driver:
GD,
Imagick
You can create a thumbnail directly in the
View:
// Create and autocache Yii::app()->easyImage->thumbOf('/path/to/image.jpg', array('rotate' => 90)); // or Yii::app()->easyImage->thumbOf('image.jpg', array('rotate' => 90), array('class' => 'image')); // or Yii::app()->easyImage->thumbOf('image.png', array( 'resize' => array('width' => 100, 'height' => 100), 'rotate' => array('degrees' => 90), 'sharpen' => 50, 'background' => '#ffffff', 'type' => 'jpg', 'quality' => 60, ));
Note. This method return CHtml::image()
$filerequired - Image file path
$params- Image manipulation methods. See Methods
$htmlOptions- options for CHtml::image()
Yii::app()->easyImage->thumbSrcOf('image.jpg', array('crop' => array('width' => 100, 'height' => 100)));
Note. This method return path to image cached.
$filerequired - Image file path
$params- Image manipulation methods. See Methods
Total 17 comments
Hi,
I have used this extension in my project and it gives exception Not an Image or Invalid Image though image exists. the extension throws the exception on linux environment and on windows environment it works normal for the same image.
Try this
@Artur, "E: Unable to locate package php-gd-bundled" when I try apt-get. Is this package available from a different repo? It doesn't appear to be in standard repo's.
I think you should install package "php-gd-bundled".
If you are running you app under Ubuntu or Debian, you may have seen this message. I'm not exactly sure which Ubuntu php5 package release corrects this but it is no longer valid. The current php553 install includes a GD version that has imagerotate so you'll need to comment out these lines 230-232 in Image_GD.php
// if (!Image_GD::$_bundled) { // throw new CException('This method requires imagerotate, which is only available in the bundled version of GD'); // }
I'm now able to rotate images correctly. If you are running on php5.3 or earlier, I think the issue is real and imagerotate is only available where included in the PHP bundle. I ran across this as I develop on WAMP and deploy to LAMP on Ubuntu.
Dear all,
Can we use this extension on CGridView? Any idea ?
Regards!
Dear,
very nice extension I used to use Image extension but moving to this....I wanted to ask if it supports default image if the image was not found: example: when trying to resize user profile image if he user doesn't have an image the a default user.png will be returned....
Cheers
playdog, your code is correct. Result:
Maybe you are using the cache for the page?
How to set it title ?
Was indeed very easy to use. I use it to scan my image folder,and then create thumbnails of each image that does not have a thumbnail then display the thumbnail as a link to the full size image. Easy to combine with with any javascript gallery.
Hi
i wanna save some space on my server then i use your extension. but i have some reasons about your methods. first thing is your thumbOf or your thumbOfSrc doesn't return the right Url. Next thing is i dont understand how to build a retina img without double my images(this step i really doesnt want ).
My Way: My User upload big images like 3000px.... then i cache the size what i need with your extension. My Structure is backend and frontend in other folders. the i save my images in common and build symlink in my Frontend and Backend to my upload Folder then i use your extension to get the sizes what i need but only in Frontend to save Space.
Your change request is good, but you can also fix your problem with this workflow.
Thank you very much Artur for include this change in a future version!
Can I ask just one more change please? :)
I'm using Yii with Yiiboilerplate. The extensions path alias is different from an standard Yii application.
The EasyImage class imports this:
But with Yiiboilerplate, there are several extensions directories for the different applications (for frontend, backend, console and common).
I need change the above lines with:
Could the extension alias be configurable too please?
Thank you! Leandro
Leandro, thanks for your comment! I'll do it at nearest time.
Hi, excellent extension.
However, I got a "file name can't be empty" error if I use:
This error is due the EasyImage constructor uses this:
However, I am using EasyImage from a console command (images are generated asynch) and I need read the images from a different directory and save the thumbs on a different directory.
If I remove "dirname(Yii::app()->basePath)" from EasyImage above line, works like a charm.
Can you add more flexibility regarding paths please?
Thank you, Leandro
+1 for composer support ;)
Not tested, but will be coming back to this extension ;-).
If not done:
Please login to leave your comment.
|
http://www.yiiframework.com/extension/easyimage/
|
CC-MAIN-2018-13
|
refinedweb
| 919
| 58.18
|
PHP and MySQL Programming/PHP Syntax
Contents
[edit]
<?php [code] ?>[edit]
- Enclose php code
- Can be configured in the php.ini to be <? ?>, <script language="php"> </script> etc.
- Embedded in normal HTML code
- Within php tags, statements are separated by a ; (generally also followed by a new line).
Example:
<?php print “Hello World\n”; $date = date(“Y-m-d H:i:s”); print “The date and time at the moment is $date”; ?>
<?=[edit]
- Used if you just want to print out the value of a variable
Example:
<?php $name = "Bobby"; ?> <?=$name?>
Which will output Bobby.
Example:
<?=date(“Y-m-d H:i:s”)?>
Which will output something like 2005-11-09 19:40:05.
Commenting[edit]
#[edit]
- Example:
echo “Hello”; # Everything from the hash is commented out
- Example:
# This entire line is commented out
//[edit]
- Works just as in Java and JavaScript
- Same function as #
/* (text) */[edit]
- Example:
/*All of this is commented out. Even this line!*/
Variables[edit]
➢ Variables in PHP are denoted by the $ prefix.
e.g. : $a = “Hello World”; # this assigns the string “Hello World” to $a.
e.g. : $b = “$a, I'm Ralfe”; # this assigns “Hello World, I'm Ralfe” to $b.
e.g. : $b = $a.”, I'm Ralfe”; # exactly the same as the previous example.
➢ PHP supports dynamic variables.
e.g. : $c = “response”;
e.g. : $$c = “Hello Ralfe”; # this assigns “Hello Ralfe” to $response.
➢ PHP variables do not have to be declared ahead of time, nor do they require a type definition. PHP handles all data type conversions.
e.g. : $a = 4;
e.g. : $b = 12;
e.g. : print “The value of a is $a.”; # Uses a as a String.
e.g. : $c = $a + $b; # $a is now used as an Integer again.
➢ PHP supports boolean variables, which can be assigned either a one or a zero, or a true or false.
e.g. : $a = true;
e.g. : $b = 1;
e.g. : # $a and $b are the same thing!
e.g. : $c = false;
e.g. : $d = 0;
e.g. : # $c and $d are the same thing!
Operators[edit]
➢ Arithmetic Operators
$a = 4;
$b = 2;
// Addition: $a + $b = 6
// Subtraction: $a - $b = 2
// Multiplication: $a * $b = 8
// Division: $a / $b = 2
// Modulus: $a % $b = 0
// Increment: $a++
// Decrement: $a--
➢ Assignment Operators
$a = 4;
$b = $a;
// $b = 4;
➢ Comparison Operators
$a == $b // test if two values are equal
$a != $b // test if two values are not equal
$a < $b // test if the first value is less than the second
$a > $b // test if the first value is greater than the second
$a <= $b // test if the first value is less than or equal to the second
$a >= $b // test if the first value is greater than or equal to the second
Concatenation[edit]
$a = “Fill the halls “;
$b = “with poisoned ivy...“;
$c = $a . $b; # the '.' operator concatenates two variables.
// $c = “Fill the halls with poisoned ivy...”
Arrays[edit]
PHP supports both numerically indexed arrays as well as associative arrays.
$a = array(1, 2, 3, 4);
// $a[0] = 1;
// $a[1] = 2;
// $a[2] = 3;
// $a[3] = 4;
$b = array(“name” => ”Fred”, “age” => 30);
// $b['name'] = “Fred”;
// $b['age'] = 30;
Decision and Loop Statements[edit]
IF THEN ELSE statement
$a = 1; $b = 10; if ($a > $b) { echo "a is greater than b"; } else if ($a == $b) { echo "a is equal to b"; } else { echo "a is not greater than b"; } // OUTPUT: // a is not greater than b
SWITCH statement
$a = 100; switch($a) { case(10): echo "The value is 10"; break; case(100): echo "The value is 100"; break; case(1000): echo "The value is 1000"; break; default: echo "Are you sure you entered in a valid number?"; } // OUTPUT: // The value is 100
FOR statement
for ($i = 0; $i < 10; $i++) { # initialize $i ; while condition ; increment statement echo $i; } // OUTPUT: // 0123456789
FOREACH statement
$a = array(1, 2, 3, 4, 5); foreach ($a as $val){ echo $val; } // OUTPUT: // 12345
WHILE statement
while ($row = mysql_fetch_row($result)){ print $row[0]; }
DO WHILE statement
$i = 0; # Note that it might seem that $i will do{ # never be printed to the screen, but print $i; # a DO WHILE loop always executes at } while ($i >0); # least once!
Functions[edit]
function square_number($number) { return ($number * $number); } $answer = square_number(10); echo "The answer is {$answer}"; // OUTPUT: // The answer is 100
Classes[edit]
class dog { var $name; function dog($name){ $this->name = $name; } function bark(){ echo "Woof! Woof!"; } function who_am_i() { echo "My name is {$this->name), and I am a dog"; } } $the_dog = new dog("John"); $the_dog->who_am_i(); // OUTPUT: // My name is John, and I am a dog
|
https://en.wikibooks.org/wiki/PHP_and_MySQL_Programming/PHP_Syntax
|
CC-MAIN-2016-44
|
refinedweb
| 761
| 71.65
|
>
Dear community,
I am willing to run an external EXE file with command arguments. The Scripting API didn't provide me with information regarding System.IO or running external files. The best info received was a link to MS Framework related classes, but I am actually looking for a straightforward example.
I have searched UnityAnswers for some time about this, and the closest example I have found on UnityAnswers is this:
String path = @"f:\temp\data.txt";
Process foo = new Process();
foo.StartInfo.FileName = "Notepad.exe";
foo.StartInfo.Arguments = path;
foo.Start();
I do not use C# for my project but use Javascript instead. Process isn't recognized there.
Please, can you supply me with an example of how to run an external program like "../VideoPlayer/myVideoPlayer.exe -fullscreen" for instance?
Answer by Mike 3
·
May 05, 2010 at 10:52 AM
Process is in the System.Diagnostics namespace - you'll need to have import System.Diagnostics at the top of your script to be able to use it like you're doing
Alternatively (though less preferable), you could use System.Diagnostics.Process instead
Thanks a great lot. I feel quite ashamed by how simple my problem was ; thanks again for your help in revealing where was my mistake.
Here is the full code:
(At start of script)
import System.Diagnostics;
(where you want it to happen :)
var stringPath = "../"; var myProcess = new Process(); myProcess.StartInfo.FileName = "Notepad.exe"; myProcess.StartInfo.Arguments = stringPath; myProcess.Start();
Will update if other problems are met.
Hi Christopher,
There is nothing to be ashamed of. Rest assured that what you posted will be and has been helpful to others. I am one of those receipents.
Would you believe it - this is still helping people. Myself included. Thanks!
This is even helping to help, the community thank you!
Answer by havik23
·
Dec 10, 2013 at 06:25 PM
For what it's worth here's a code example of executing a .bat file (i.e an external command) outside of unity with a cscript:
using UnityEngine;
using System.Collections;
using System.Diagnostics;
using System;
public class TestBatch : MonoBehaviour {
// Use this for initialization
void Start () {
try {
Process myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = "C:\\Windows\\system32\\cmd.exe";
string path = "C:\\Users\\Brian\\Desktop\\testFile.bat";
myProcess.StartInfo.Arguments = "/c" + path;
myProcess.EnableRaisingEvents = true;
myProcess.Start();
myProcess.WaitForExit();
int ExitCode = myProcess.ExitCode;
//print(ExitCode);
} catch (Exception e){
print(e);
}
}
Thanks for posting this. It helped me a lot. But when I try to build an application in Windows Store it gives me this error "Assets\Solve.cs(9,9): error CS0246: The type or namespace name 'Process' could not be found (are you missing a using directive or an assembly reference?)". I have attached the script belowlink text. Please help.
This worked perfectly for us! Thanks!
Yeah for some reason we were never able to launch an application directly from C# but hitting a batch file worked fine. However (and again for some reason) the batch file still didn't find the executable until we added it to the PATH system variable in environment variables for the built version. From the editor it worked without this but as soon as we made a build we needed to add the folder we were referencing to the PATH even with the full executable path in the batch file.
Answer by sed
·
Feb 18, 2015 at 11:11 PM
Actually, running a bat file is much simpler than @havik23 puts it (given you have the the_script.bat just next to your Assets folder in the file hierarchy)
using UnityEngine;
using System.Collections;
using System.Diagnostics;
public class RunBat : MonoBehaviour {
// Use this for initialization
void Start () {
Process foo = new Process();
foo.StartInfo.FileName = "the_script.bat";
foo.StartInfo.Arguments = "put your arguments here";
foo.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
foo.Start();
}
// Update is called once per frame
void Update () {
}
}
Answer by Gono
·
Sep 23, 2018 at 01:58 AM
I'm 8 years late, but here is a c# script I use daily that is incredibly simple. For the internet :)
using System.Diagnostics;
using System;
private static void RunFile()
{
Process.Start(Environment.CurrentDirectory + @"data.txt");
}
The file will be opened just like double clicking it, and therefore uses the defaults you have set in windows. For example, I use it to run an autohotkey script in my builds folder. Process.Start(Environment.CurrentDirectory + @"\Builds\LaunchClients.ahk"); just runs my script no questions asked. You need System.Diagnostics to use Process.Start() You need System to use Environment.CurrentDirectory. It just returns your project's base directory, and can be replaced with manually typing a directory instead. You should use @ before the string if doing so. Then just add on the filename you want. I use @ before the string to interpret it literally, so no special characters can mess with it. It's not needed for data.txt but if you put a filepath such as "\Builds\LaunchClients.ahk" the slashes may mess with you.
Process.Start(Environment.CurrentDirectory + @"\Builds\LaunchClients.ahk");
System.Diagnostics
Process.Start()
System
Environment.CurrentDirectory
Answer by vfxjex
·
Feb 20, 2014 at 08:35 AM
here is a simple way in Java
function Start () {
System.Diagnostics.Process.Start("f:/temp/data.txt");
}
Erm, you mean JavaScript ;-)
Didn't work!
Actually, this should probably be the following:
function Start()
{
System.Diagnostics.Process.Start("Notepad F:/temp/data.txt");
}
This method seems to work in editor but not in a PC-build. There it throws "Win32Exception: The system cannot find the file someone help me fix my Javascript for Flickering Light?
5
Answers
Application.OpenURL problems with local folder
0
Answers
Rotation accuracy in build
1
Answer
My Build won't run properly on Win 8.1
0
Answers
mecanim run animation script trouble
0
Answers
|
https://answers.unity.com/questions/16675/running-an-external-exe-file-from-unity.html
|
CC-MAIN-2019-22
|
refinedweb
| 977
| 60.11
|
This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project.
>>>>> "Sanjoy" == Sanjoy Das <sanjoy@playingwithpointers.com> writes: Sanjoy> This work was stalled for some time while the copyright assignment was Sanjoy> being worked on; which will be finalized any time now. Super. Sanjoy> In the meantime, I've attached a rebased set of patches for final Sanjoy> reviews. Thanks, and sorry about the delay. It really is best to ping weekly; the squeaky wheel etc. Sanjoy> +#ifdef HAVE_DLFCN_H Sanjoy> +#include <dlfcn.h> Sanjoy> +#elif __MINGW32__ Sanjoy> +#include <windows.h> Sanjoy> +#else Sanjoy> +/* Unsupported configuration. See Eg. gdb_dlopen for details. */ Sanjoy> +#error API to load shared library missing (Eg. libdl) Sanjoy> +#endif I think this should be a runtime error, not a build-time error, because it seems better to me to make a gdb with reduced functionality than to prevent the build for just this feature. Tom
|
https://sourceware.org/legacy-ml/gdb-patches/2011-11/msg00043.html
|
CC-MAIN-2020-50
|
refinedweb
| 154
| 68.57
|
So do you get any actual useful information out of codewars - you know, more than "it doesn't work"?
Also, I'm guessing "abc#d##c" isn't the actual (or only) string being tested.
You need to take...
So do you get any actual useful information out of codewars - you know, more than "it doesn't work"?
Also, I'm guessing "abc#d##c" isn't the actual (or only) string being tested.
You need to take...
Do you want the actual string "ac", or just something that prints as "ac" because it's got backspace characters in it.
Such as "abc\bd\b\bc"
Use two loops.
while ( fgets(buff,SIZE,dosya) ) {
if ( buff[0] == 'E' ) break;
sscanf(buff," %f %f %f %f %f %f ",&musteri.id[i],&musteri.x1[i],&musteri.x2[i],
...
Well the multiply defined things are because your wrath-utils.h should really be called wrath-utils.c, because it contains actual code.
#including definitions only works if you include it once in...
Fix looks good.
Try it and see what happens.
> //#include "wrath-utils.h"
Was probably not necessary to do this.
You definitely need to find out where safe_malloc is prototyped, and include the appropriate header.
Your machine has 64-bit addresses.
Without a prototype, C thinks safe_malloc returns int -...
Like I said in your previous thread.
Fix your warnings.
$ gcc -Wall bar.c
bar.c: In function ‘main’:
bar.c:17:11: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has...
Cross-posted
how get the JPG image size?
how read the GIF and JPG image size? - C++ Forum
Also here -> How to configure VS Code for building an - C++ Forum
So
int main ( ) {
int myInt;
scanf("%d",&myInt);
}
would become
Your test should be
if (*i > *j)
You want to compare what the pointers point to, not the pointers themselves.
> create a static function called ascending2()
You forgot to make it static, not...
Maybe you should upload an example of this "database.cfc" files so we can see what it is you're trying to parse.
Because it seems now far from clear that we're talking about any kind of regular text...
> while ((harf=fgetc(d)) != 'E')
Well this eats the first character of the 1st line, just ruining your attempt to scanf the rest of the line.
Normally I would suggest
char buff[BUFSIZ];...
+1 for laserlight for spotting the pointer issue
@ArakelTheDragon, compile with many warnings enabled and make sure you FIX all of them before running the code.
$ gcc -c -Wall -Wextra bar.c...
Consider different revenue alternatives.
Software as a service - Wikipedia
Presumably the OP is trying to emulate 1980's software 'protection' by locking the installation of the software to the hard disk it was installed on.
This is a stupid idea for several reasons.
1....
> Process returned -1073741819 (0xC0000005) execution time : 6.915 s
Yes, your badly constructed double while loop failed to spot the end of file correctly, so it spent the next 5 to 10 seconds...
strstr() finds one string inside another.
Well for one thing, it's sure to depend on your OS of the moment.
For another thing, the amount of memory you could theoretically allocate at any given moment is likely to be a fluid number that...
When you fill your posts with complaints and heresay, what did you expect.
Posting evidence of what you actually did is better if you want people to give you actionable things to try. "I tried...
crontab(5): tables for driving cron - Linux man page
You can see plenty of examples which show more complicated files that what you're claiming.
Post your actual crontab file (the output of...
Are you even reading the manual page?
If it's a single pid, then the wait() system calls are useless for you.
Again, explain why you're not using pthread_create et al to do this for you. It's...
Please explain why you desperately need CLONE_PARENT in your flags?
All this does is give two things the same pid, such that it becomes impossible to use any of the wait() system calls for one...
Well this works as I would expect.
But then again, it sets all the flags to 0.
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
OK, couple of things in testing.
1. 1024 bytes is nowhere near enough for a stack. Try it with 1MB
2. It seems wait() isn't all that it should be - maybe it's one of the many clone flags you...
|
https://cboard.cprogramming.com/search.php?s=798342dae941e64872072e2ac023144b&searchid=3606688
|
CC-MAIN-2020-16
|
refinedweb
| 766
| 76.93
|
fitter 0.2.0
A tool to fit data to many distributions and best one(s)
fitter package provides a simple class to figure out from whih distribution your data comes from. It uses scipy package to try 80 ditribution and allows you to plot the results to check what is the most probable distribution.
Installation
pip install fitter
Usage
Nothing complicated since there is just one class provided. First, we will need to create some data samples. Let us create a sequence of 100000 samples from a gamma distribution:
from scipy import stats stats.gamma.rvs(2, loc=1.5, scale=2, size=100000)
Now, the question without any knowledge about the distribution of its parameter, what is a probable distribution that fit the data? scipy has 80 distribution with a method called fit that will help us here. The class Fitter will scan all the distribution, call the fit function for you, ignoring those that fail or run forever and finally give you a summary of the best distribution in the sense of sum of the square errors. The best is to give an example:
from fitter import Fitter f = Fitter(data) f.fit() # make take some time since by default, all distribution are tried f.summary()
See the online documentation for details.
- Downloads (All Versions):
- 5 downloads in the last day
- 66 downloads in the last week
- 269 downloads in the last month
- Author: Thomas Cokelaer
- Documentation: fitter package documentation
- Download URL:
- Keywords: fit,distribution,fitting,scipy
- License: GPL
- Platform: Linux,Unix,MacOsX,Windows
- Requires sphinx, numpy, matplotlib, scipy, pandas
-: fitter-0.2.0.xml
|
https://pypi.python.org/pypi/fitter/0.2.0
|
CC-MAIN-2015-48
|
refinedweb
| 268
| 50.77
|
%Library.SysLog
class %Library.SysLogProvide a %Library.SysLog class to allow logging of events while programs are running in a consistent fashion. The advantage of using this is that we can use standard utilities to manage and display this log. Also all log entries automatically get the current namespace, date/time, routine name and process Id logged.
To make logging easier there are three macros defined in %occDiagnostics.inc. This file is included automatically when compiling any class and so you only need to include it manually if you are compiling a MAC file. The macros are:
- $$$SysLog(level,category,message,data) - If the logging level is greater or equal to 'level' this calls Log^%SYS.ISCLOG with the same parameters except 'routine' is set to $ZNAME. If 'data' is an array then pass it by reference
- $$$SysLogError(category,message) - If the logging level is greater than zero it will call LogError^%SYS.ISCLOG with the same parameters except 'routine' is set to $ZNAME.
- $$$SysLogUser - If the logging level is greater than 1 it calls LogUserInfo^%SYS.ISCLOG with 'routine' set to $ZNAME and the other parameters coming from $ZU(67)
One of the advantages of these macros is that they check the logging level before calling the Log() method and so if logging is not turned on at this level then the log macro takes almost no time to execute.
Method Inventory
- CategoryGet()
- CategorySet()
- ClearLog()
- ErrorDetailGet()
- ErrorDetailSet()
- JobGet()
- JobSet()
- Log()
- LogError()
- LogLevelGet()
- LogLevelSet()
- LogUserInfo()
- MaxLogEntriesGet()
- MaxLogEntriesSet()
- RemoveOldEntries()
Methods
Return the comma separated list of categories that we log.
Comma separated list of categories that we log or null to log all categories.
classmethod ClearLog() [ Language = objectscript ]
Reset the entire log, removing all previous entries. It does preserve setup information.
Return the level to log any LogError() events with. See LogError() for a description of the levels.
Set the level to log any LogError() events with. See LogError() for a description of the levels.
Return the comma separated list of jobs that we log.
Comma separated list of job numbers that we log or null to log all jobs.
classmethod Log(level As %Integer = 2, category As %String = "", message As %String, ByRef data As %String, routine As %String) as %Integer [ Language = objectscript ]
Log an event to the system log if the system logging level is greater or equal to the level passed in. You must specify a level to log this event at, the choice being:
The category is a text field that allows you to subdivide the log entries into various types
you normally pick a name for each application such as 'HTTP' for the in build web server in InterSystems IRIS or 'IMT' for
the InterSystems Message Transport application. The message is any text message that you wish to be recorded,
data is any extra data you wish to log. routine is optional and is the routine name you called from.
Note that data can be passed by reference and if done it will merge all this information into
a subscript of the log global so you can store large quantities of information if needed.
The return value of this function is the node number where this data is logged or 0 if no log entry was written
typically because the system log level was not set to log an event of the level passed in.
- 0 - No logging
- 1 - Exceptional events logged, e.g. error messages
- 2 - Detailed event log information, e.g. 'method ABC invoked with parameters X,Y,Z and returned 1234'
- 3 - Raw information logging, e.g. the byte contents of the TCP/IP request sent from the client
So if you wish to log a problem with a Http request because the Type is wrong while reading it into the local variable 'request' you could call:
Besides the information you pass to the Log method it will automatically log the current date and time along with the process Id the calling routine name and the current namespace.
Do ##class(%Library.SysLog).Log(1,"HTTP","Invalid Http request type. Type="_type,request)
classmethod LogError(category As %String = "ERROR", message As %String, routine As %String) as %Integer [ Language = objectscript ]
Call this to log an unexpected ObjectScript error. Pass in the category to log this error under, the message you want reported and the routine that you are logging the error from (this is optional). The level of detail the error is logged at is determined by the system wide setting, see ErrorDetailGet() and ErrorDetailSet() to set/get this value. The choices are:
- 0 - Just log the message and the value of $ZE and $ZU(56,5)
- 1 - Log the message, the value of $ZE and $ZU(56,5) and the call stack
- 2 - Log the local symbol table $ZE, $ZU(56,5) and the call stack
Set the logging level to one of the following
- 0 - No logging
- 1 - Exceptional events logged, e.g. error messages
- 2 - Detailed event log information, e.g. 'method ABC invoked with parameters X,Y,Z and returned 1234'
- 3 - Raw information logging, e.g. the bytes comming from the Http request
classmethod LogUserInfo(category As %String, username As %String, machinename As %String, exename As %String, IPaddress As %String, routine As %String) as %Integer [ Language = objectscript ]
Log the user information at log level 2 (operational) to category 'UserInfo'. If any of username or machinename or exename or IPaddress are blank or missing then they default to the values setup in the partition in $ZU(67,n,$J). You normally call without any parameters at the start of your application to log the person using this job, but you can override the value from $ZU(67) is you need to. If category is blank it defaults to "UserInfo". routine is the optional routine you are logging this from, if not specified it defaults to the value found from $Stack($Stack-1,"PLACE").
classmethod MaxLogEntriesGet() as %Library.Integer [ Language = objectscript ]
Return the current setting for the maximum number of entries before old ones are killed off.
classmethod MaxLogEntriesSet(entries As %Library.Integer) [ Language = objectscript ]
Set the maximum number of entries that this log will hold. If this is not set it defaults to 5,000 entries before it starts removing old entries.
classmethod RemoveOldEntries() [ Language = objectscript ]
If there are more than MaxLogEntriesGet() in the log then remove any old entries that we no longer need. This is called automatically by Log() and LogUserInfo() every 10 entries and so you do not normally need to call this manually.
|
https://docs.intersystems.com/healthconnectlatest/csp/documatic/%25CSP.Documatic.cls?&LIBRARY=ENSLIB&CLASSNAME=%25Library.SysLog
|
CC-MAIN-2022-05
|
refinedweb
| 1,085
| 51.38
|
Question:
Miss.Jane, an experienced English professor, gives practice tests to her students to improve their written skills. Everyday students write an article and they submit it to Jane. Jane is particular that the students use only special characters like , ; : . ? ! in the article.
[Note : Using the above mentioned special characters will help to split the words in a sentence.
All other special characters when used will be considered as a part of the word itself. ]
She counts the total number of words used and the count of each word in the article. Based on this analysis she gives her feedback to the students.
Difficulty arises when the number of students increase. So she wanted to automate the process in the following format. Help her to write a java program to display the words and the number of times it has been used in the article and to display the words using lower case and in alphabetical order.
Sample Input 1
hello Hello HEllo hi hi: hi! Welcome, welcome
Sample Output 1
Number of words 8
Words with the count
hello: 3
hi: 3
welcome: 2Sample Input 2 :
Use Arrays.sort method
Sample Output 2
Number of words 4
Words with the count
arrays: 1
method: 1sort: 1
use: 1
Code:
CountOfWords.java
import java.util.*; @SuppressWarnings("unchecked")//Do not delete this line public class CountOfWords { public static void main (String[] args) { Scanner sc = new Scanner(System.in); String s=sc.nextLine(); s=s.toLowerCase(); String longString = "\"long\""; StringBuilder sb = new StringBuilder(s); for (int i=0;i<sb.length();i++) { if(!(Character.isLetter(sb.charAt(i)))) { if(sb.charAt(i)!=' ' && sb.equals(longString)) { if(sb.charAt(i)!='\'') { sb.deleteCharAt(i); System.out.println(sb); } } } } String str[] =s.split("[\\s,;:.?!]+"); Set<String> words = new HashSet<String>(Arrays.asList(str)); List<String> wordList = new ArrayList<String>(words); Collections.sort(wordList); int count =0; System.out.println("Number of words "+str.length); System.out.println("Words with the count"); int longCount=0; for(String word: wordList) { for(String temp: str) { if(word.equals(temp)) { ++count; } } if(!(word.equals(longString))) { System.out.println(word+":"+count); } else longCount=count; count=0; boolean flag=false; for(String str2 : str) { if(str2.equals(longString)) flag=true; } if(flag==true) System.out.println(longString+":"+longCount); } } }
Recommended:
- Feedback Manipulation
- Retrieve Student Info
- Member Manipulation
- PhoneBook Manipulation
- Count of Each Words
2 thoughts on “Java Program of Count of Each Words”
Thanks for this article, it is very helpful to me! Way simpler than anything else out there.
|
https://quizforexam.com/java-count-of-each-words/
|
CC-MAIN-2021-21
|
refinedweb
| 418
| 51.24
|
SQL Server Architecture Overview
By: Ben Snaidero
Overview
You'll hear this term instance a lot when referring to the SQL Server suite of products. Whether it's the database engine, Analysis Services, Reporting Services or Integration Services when someone refers to an instance of the product this basically means a copy of the executable that is running as a Windows service. For the database engine this is sqlservr.exe, for Analysis Services it's the msmdsrv.exe, for Integration Services it's the MsDtsSrvr.exe and for Reporting Services it's the ReportingServicesService.exe. As far as the architecture goes that is where the similarities between the different products ends. The below sections will give an overview of the rest of the architecture for each of the main products.
Database Engine
The engine of the instance can be broken down into two parts. The Relational Engine and the Storage Engine.
The Relational Engine handles the execution of queries as they are received from client applications. This engine has the following components: Query Parser, Optimizer/Planner, and Executor.
The Storage Engine handles the actual accessing of the data as requested by the query executor. Within this engine there is a transaction manager and buffer manager which interact with the data and log files to select/insert/update/delete data as required.
Databases
Each SQL Server instance contains 4 or more databases which are, at a high level, simply a logical collection of objects. These objects can include tables, indexes, views, users, etc. The initial databases that exist are the system databases: master, model, msdb and tempdb.
- The master database contains all the server configuration settings,
- the model database serves as a template that is used when user databases are created,
- the msdb database contains information related to database backups, replication, SSIS packages and all the configuration information for any SQL Server jobs that exist on the server
- and finally the tempdb database stores any temporary objects that are required by the system.
Database Files
Each of these databases is made up of at least 2 files. The first is the primary datafile which stores the objects that make up the database. The second is the transaction log file which holds all the information related to any changes made to the database. There can be one or more of each of these types of files although having multiple transaction logs won't really help performance as this file is written to sequentially. Data files on the other hand can benefit from having multiple files. For example, by separating table and index data into different data files you can speed up performance as these files can then be accessed in parallel when executing a query. Both of these files are stored on server's filesystem and can be placed where required by specifying the file path when the database is created.
Database Objects
As mentioned above, each database is a collection of different objects. Below is a brief description of the most common objects that you will find in a SQL Server database.
- User/Login - Sometimes used interchangeably in SQL Server they are in fact two different things. A login is used for authentication to the database instance whereas a user is used for database/object access. Each login will have an associated database user (most often with the same name).
- Role - An object that contains a set of permissions for objects within the database. Can be granted to users to ease administration by not having to grant individual permissions to each user.
- Schema - Schema can have many different meanings in a database context but here it can be described as something that holds a collection of objects, kind of like a container or namespace. Other objects like tables, indexes, function, etc. can be grouped logically and assigned to a schema on creation.
- Table - Object that holds the relational data.
- Constraint - These are rules for the data columns in a table. Types of constraints are primary key, foreign key, default, etc.
- Index - This is a structure that can be used to speed up accessing data in a table. Specified columns make up the index and, when specified in a query, can help to speed up performance as the indexed column will contain a pointer to where the rest of the data is located that makes up that row.
- Statistics - Statistics are a set of data that describes the data distribution and cardinality of the columns in a table. These statistics are used by the planner in order to determine the best/fastest method of accessing the table in order to execute a query.
- View - A view is basically a stored query. Sometimes a query can be so complex it is created a view so that other connections can just write "SELECT * FROM view". Note that the actually result set from the query is not stored/cached (this is done for materialized views), only the query text, so each call to the view results in the entire query being executed.
- Stored Procedure/Function - Both of these objects, as you would assume, are objects that store a collection of SQL statements and other than this one similarity they do not have much in common. Some of the key differences are: Functions can only run SELECT and a stored procedure can also run DELETE/INSERT/UPDATE, stored procedures can have both input and output parameters whereas functions can only have input, functions can be used in one or many parts of a SELECT query and stored procedures cannot be used, stored procedures can optionally return a value whereas function must return a value, etc.
Analysis Services
Similar to the database instance an Analysis Services database is really just a logical collection of objects. Each SQL Server Analysis Services instance can have multiple user databases similar to a database instance but with Analysis Services there are no system databases. There is a master.vmp file in the data directory that contains a version map of all the GUIDs for each object in the server. If this file is missing or corrupt the Analysis Services service will not start. The file structure of an analysis service instance is also much more complex than a database instance. For each database that exists there is an XML file which displays the properties of the database as well as a folder which contains the data.
Dimension Objects
Within the database folder there are again XML files which describe the cube and dimension objects properties as well as folders for each of these object types.
Inside each dimension object folder there are the data files for the dimension.
Cube Objects
In the cube object folder we again have an XML file and a folder for each measure defined in the cube.
Analysis Services Objects
The objects contained within an Analysis Services database are very different from what we see in a relational database and below is a short description of the most common objects that would be present in an Analysis Services database.
- Cube - This is a multi-dimensional database that is designed specifically to handle data warehouse and online analytical processing workloads.
- Dimension - Dimensions are structures that categorize or describe facts and measures and are usually organized into a hierarchy. Examples of dimensions are time, places, products, etc. Using time as an example the hierarchy could be days -> weeks -> months -> quarters -> years.
- Measure - A measure is the actual data element. Since measures are numeric they can be summed, averaged, etc. across some, all or none of the defined dimensions.
- Mining structures - A mining structure defines the data upon which any mining models are built upon. One mining structure can support multiple mining models.
- Role - Similar to the database instance roles in Analysis Services define the objects that a user can access.
Reporting Services
With regards to the architecture of Reporting Services, for this tutorial we won't go into any detail in the creation of a report other than to say the .rdl files that are used to define a report can be created using Report Builder or the SSDT application. Once created this .rdl file can then be deployed to a SQL Server Reporting Services instance. The instance itself is a Windows service that is backed by two databases. By default, these databases are named ReportServer and ReportServerTempDB as shown below.
The ReportServer database stores metadata (basically data defined in .rdl) for each reports configuration. This includes the report data sources as well as the definition of the report itself. It also stores metadata related to the scheduling of each report, if one has been defined after the report has been deployed. From a data perspective, snapshot and historical report data it also stored here until its retention time is reached.
The ReportServerTempDB is only used during runtime and stores temporary data, session information, and cached report data.
Integration Services
Similar to Reporting Services, SQL Server Integration Services packages are created by using SSDT. Once created the .dtsx file containing the package definition can then be deployed to any SQL Server Integration Services instance. The Integration Services instance is also just a windows service except in this case there is no special database associated with the service. In the case of SQL Server Integration Services, packages can either be deployed and stored on the filesystem or in the instance. If deployed to the instance they are stored within the msdb database in the tables shown below.
There is also no functionality for scheduling package execution built in to SQL Server Integration Services. If you require that a package be executed on a schedule you can either use the SQL Server Agent or the Windows Task scheduler to handle this requirement.
Additional Information
Last Update: 8/23/2019
|
https://www.mssqltips.com/sqlservertutorial/9220/sql-server-architecture-overview/
|
CC-MAIN-2021-17
|
refinedweb
| 1,628
| 53.21
|
view raw
When i execute with sudo python3 program.py and press de switch 1 throws the next exception:
Taking picture...
Picture takeng...
Traceback (most recent call last):
File "main.py", line 21, in <module>
if GPIO.input(switch1):
RuntimeError: You must setup() the GPIO channel first
import RPi.GPIO as GPIO
import time
import picamera
# initial config for gpio ports
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
# input switches
switch1 = 22
switch2 = 23
switch3 = 24
# setup
GPIO.setup(switch1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# main loop
while True:
if GPIO.input(switch1):
print ("Taking picture...")
with picamera.PiCamera() as camera:
camera.resolution = (1280, 720)
camera.start_preview()
time.sleep(0.5)
camera.capture("test.jpg")
print ("Picture takeng...")
elif GPIO.input(switch2):
print ("Taking video...")
elif GPIO.input(switch3):
print ("Poweroff...")
break
GPIO.cleanup()
The error is telling you that you have not set the pins to work as input and, when you try to access them as so, it fails. I had a similar problem and as far as I see it it should work (you are setting the pins after all).
Try changing
GPIO.setmode(GPIO.BCM) to
GPIO.setmode(GPIO.BOARD). You will also have to change the pin numbers to the physical ones (yours would be 15, 16 and 18).
I still don't know why, but it did the trick on my code.
|
https://codedump.io/share/E3Tvr4soWHkF/1/runtimeerror-you-must-setup-the-gpio-channel-first
|
CC-MAIN-2017-22
|
refinedweb
| 244
| 61.53
|
There are several reasons that the goto is held in such low esteem among software developers. Edsger W. Dijkstra's paper A Case Against the GO TO Statement is a relatively early treatise on the evils of GOTO abuse. In that article, Dijkstra states, "[I became] convinced that the go to statement should be abolished from all 'higher level' programming languages." Dijkstra's Go To Statement Considered Harmful letter not only lambasted the goto statement, but also started a popular computer science trend of using the phrase "considered harmful" (though those two words were apparently used outside of programming before that).
Many programmers since Dijkstra have been bitten by some of the maintainability problems associated with use of goto statements in certain languages. Other programmers have heard these stories or have had the "Thou shalt not use goto" pounded into them so much that they don't need to experience its drawbacks firsthand to believe that they should not use GOTO.
Although the goto statement appears to have a generally bad reputation, it is not without its supporters. Frank Rubin wrote a response to Dijkstra's Go To Statement Considered Harmful (March 1968) called GOTO Considered Harmful' Considered Harmful (March 1987). In that letter, Rubin wrote about Dijkstra's letter having an effect on programmers so dramatic that "the notion that the GOT0 is harmful is accepted almost universally, without question or doubt." Of this observation, Rubin wrote, "This has caused incalculable harm to the field of programming, which has lost an efficacious tool. It is like butchers banning knives because workers sometimes cut themselves." Note that Dijkstra responded to Rubin's letter with On a Somewhat Disappointing Correspondence. The Cunningham & Cunningham Wiki page Go To says this about the goto statement: "The apprentice uses it without thinking. The journeyman avoids it without thinking. The master uses it thoughtfully."
There are numerous other resources that cover the pros and cons of using the goto statement. I don't intend to rehash that debate here other than the brief presentation of the early history of the controversy already covered. I have heard some Java developers stating that Java does not have a goto statement and that is what I want to discuss in the remainder of this blog post.
Java does reserve "goto" as a reserved keyword. However, it is an unused keyword. What this means is that although the keyword does not actually do anything productive, it is also a word that cannot be used in code for names of variables or other constructs. For example, the following code will not compile:
package dustin.examples;
/**
* Class demonstrating Java's goto-like functionality.
*/
public class JavaGotoFunctionality
{
/**
* Main executable function.
*
* @param arguments Command-line arguments: none expected.
*/
public static void main(final String[] arguments)
{
final String goto = "Go to bed!";
}
}
If I try to compile that code, I see an error like that shown in the next screen snapshot.
The error message "<identifier> expected" with a pointer at the space before "goto" gives an experienced Java developer enough of a clue to quickly realize that there is something wrong about using "goto." However, it may not be as obvious to someone new to Java.
I generally do not use the goto construct, but I also recognize that there are situations in which its use makes for code that is more readable and uses less crazy work-arounds than not using it. In Java, this has also been realized and support is provided for some of the most common situations in which a goto statement would be most useful and would likely actually be preferable to alternatives. The most obvious examples of this are the labeled
breakand labeled
continuestatements. These are discussed and demonstrated in the Java Tutorials section Branching Statements.
The ability to label a particular statement and then have the
breakor
continueapply to that statement rather than its most immediate statement (as an unlabeled
breakor
continuedoes) is especially useful in cases where nested loops would otherwise require more code and more complex code to accomplish the same thing. I have found that I can often redesign my data structures and code to avoid such situations, but this is not always practical.
Another good resource related to use of goto-like functionality in Java is the 13 June 2000 JDC Tech Tip Goto Statements and Java Programming. As this tip points out, the labels can actually be used to any block and are not limited to
breakand
continue. However, it is my experience that necessity of this approach outside of
breakand
continueis far less common.
One important observation about labels is that code execution does not literally return to that label when the
break somelabelis executed. Instead, execution flow goes to the statement immediately following the labeled statement. For example, if I had an outer
forloop called "dustin:", then a break to that would actually go to the first executable statement following the end of that labeled
forloop. In other words, it acts more like a "goto the statement following the labeled statement" command.
I don't provide any examples of using these labeled
breakor labeled
continuestatements here because there are plenty of good examples easily located online. Specifically, the two resources that I have already mentioned (Java Tutorials Branching Statements and Goto Statements and Java Programming Tech Tip) include simple illustrative examples.
The more I work in the software development industry, the more convinced I become that there are few absolutes in software development and that extremist positions will almost always be wrong at one point or another. I generally shy away from use of goto or goto-like code, but there are times when it is the best code for the job. Although Java does not have direct goto support, it provides goto-like support that meets most of my relatively infrequent needs for such support.
3 comments:
I believe break and continue, with or without labels, are considered "goto" for the purposes of Dijkstra's paper, which was written at an abstract level and not aimed at any particular keyword of any particular language. They are not "conditional clauses", "alternative clauses", or "repetition clauses" and were definitely frowned on in the heyday of structured programming.
Although they sometimes make code easier to write, it's rare that they make it easier to read which is generally a more important goal. They also prevent most automated "extract method" refactorings as well which is an extra annoyance when you are trying to unwind spaghetti code.
Hi,
I am interested in advertising on your site. I think its awesome!
Please get back to me when you have a chance.
crose@enticelabs.com
Thanks
Scott,
Thanks for the comment. It is certainly true that many people today consider break and continue to be "goto" statements because of the abruptness of their nature. As far as making code easier to read, that must be opinion because I have seen many cases where the work-arounds to avoid these constructs are hard to get one's head around because of the various flags and other "state" things that must be maintained. In fact, this is the main point of my post: software development has very few, if any, absolutes.
Thanks again for taking the time to comment.
|
http://marxsoftware.blogspot.com/2009/09/javas-goto.html
|
CC-MAIN-2016-07
|
refinedweb
| 1,212
| 50.97
|
Working with Files using Replit
In this lesson, you'll gain experience with using and manipulating files using Replit. In the previous lesson you saw how to add new files to a project, but there's a lot more you can do.
Files can be used for many different things. In programming, you'll primarily use them to store data or code. Instead of manually creating files and entering data, you can also use your programs to create files and automatically write data to these.
Replit also offers functionality to mass import or export files from or to the IDE; this is useful in cases when your program writes data to multiple files and you want to export all of these for use in another program.
Working with files using Python
Create a new Python repl and call it
working-with-files.
As before, you'll get a default repl project with a
main.py file. We need a data file to practise reading data programmatically.
- Create a new file using the
add filebutton.
- Call the file
mydata.txt. Previously we created a Python file (
.py) but in this case we are creating a plain text file (
.txt).
- Type a line of text into the file.
You should now have something similar to what you see below.
Go back to the
main.py file and add the following code.
f = open("mydata.txt")
contents = f.read()
f.close()
print(contents)
This opens the file programmatically, reads the data in the file into a variable called
contents, closes the file, and prints the file contents to our output pane.
Press the
Run button. If everything went well, you should see output as shown in the image below.
Creating files using Python
Instead of manually creating files, you can also use Python to do this. Add the following code to your
main.py file.
f = open("createdfile.txt", "w")
f.write("This is some data that our Python script created.\n")
f.close()
Note the
w argument that we pass into the
open function now. This means that we want to open the file in "write" mode. Be careful: if the file already exists, Python will delete it and create a new one. There are many different 'modes' to work with files in different ways which you can read about in the Python documentation.
Run the code again and you should see a new file pop up in the files pane. If you click on the file, you'll find the data that the Python script wrote to it, as shown below.
Building a weather logging system using Python and Replit
Now that you can read from files and write to them, let's build a mini-project that records historical weather temperatures. Our program will
- Get the current temperature for a specified set of cities.
- Write this data to file with today's date.
- Print a summary of this data to the console.
Creating a WeatherStack Account and getting an API key
We'll get weather data from the WeatherStack API. You'll need to sign up at weatherstack.com and follow the instructions to get your own access key. Choose the "free tier" option which is limited to 1000 calls per month.
After sign-up, you should see a page similar to the following containing the API access key.
You should keep this key secret to stop other people using up all of your monthly calls.
Creating our weather reporting project
You can continue to use the
working-with-files project that you created earlier if you want to, but for the demonstration we'll create a new Python repl called
weather report.
In the
main.py file add the following code, but replace the string for
API_KEY with your own one.
import requests
# change the following line to use your own API key
API_KEY = "baaf201731c0cbc4af2c519cb578f907"
WS_URL = ""
city = "London"
parameters = {'access_key': API_KEY, 'query': city}
response = requests.get(WS_URL, parameters)
js = response.json()
print(js)
print()
This code asks WeatherStack for the current temperature in London, gets the JSON version of this and prints it out. You should see something similar to what is shown below.
WeatherStack returns a lot of data, but we are mainly interested in
- The location: To see if we found the correct London and not one of the 29 other places called London.
- The date: We'll record this when we save this data to a file.
- The current temperature: This is specified by default in Celsius, but can be customised if you prefer Fahrenheit.
Add the following code below the existing code to extract these values into a format that's easier to read.
temperature = js['current']['temperature']
date = js['location']['localtime']
city = js['location']['name']
country = js['location']['country']
print(f"The temperature in {city}, {country} on {date} is {temperature} degrees Celsius")
If you run the code again, you'll see a more human-friendly output, as shown below.
This is great for getting the current weather, but now we want to extend it a bit to record weather historically.
We'll create a file called
cities.txt containing the list of cities we want to get weather data for. Our script will request the weather for each city, and save a new line with the weather and timestamp.
Add the
cities.txt file, as in the image below (of course, you can change which cities you would like to get weather info for).
Now remove the code we currently have in
main.py and replace it with the following.
import requests
API_KEY = "baaf201731c0cbc4af2c519cb578f907"
WS_URL = ""
cities = []
with open("cities.txt") as f:
for line in f:
cities.append(line.strip())
print(cities)
for city in cities:
parameters = {'access_key': API_KEY, 'query': city}
response = requests.get(WS_URL, parameters)
js = response.json()
temperature = js['current']['temperature']
date = js['location']['localtime']
with open(f"{city}.txt", "w") as f:
f.write(f"{date},{temperature}\n")
This is similar to the code we had before, but now we
- Read the city names from our
cities.txtfile and put each city into a Python list.
- Loop through the cities and get the weather data for each one.
- Create a new file with the same name as each city and write the date and temperature (separated by a comma) to each file.
In our previous examples we explicitly closed files using
f.close(). In this example, we instead open our files in a
with block. This is a common idiom in Python and is usually how you will open files. You can read more about this in the files section of the Python docs.
If you run this code, you'll see it creates one file for each city.
If you open up one of the files, you'll see it contains the date and temperature that we fetched from WeatherStack.
If you run the script multiple times, each file will still only contain one line of data: that from the most recent run. This is because when we open a file with in "write" mode (
"w"), it overwrites it with the new data. Because we want to create historical weather logs, we need to change the second last line to use "append" mode instead (
"a").
Change
with open(f"{city}.txt", "w") as f:
to
with open(f"{city}.txt", "a") as f:
and run the script again. If you open one of the city files again, you'll see it has a new line instead of the old data being overwritten. Newer data is appended to the end of the file. WeatherStack only updates its data every 5 minutes or so, so you might see exact duplicate lines if you run the script multiple times in quick succession.
Exporting our weather data files
If you run this script every day for a few months, you'll have a nice data set that could be useful in other contexts too. If you want to download all of the data from Replit, you can use the
Download as zip functionality to export all of the files in a repl (including the code and data files).
Once you've downloaded the
.zip file you can extract it in your local file system and find all of the data files which can now be opened with other programs as required.
From the same menu, you can also choose
upload file or
upload folder to import files into your repl. For example, if you cleaned the files using external software and then wanted your repl to start appending new data to the cleaned versions, you could re-import them.
Replit will warn you about overwriting your existing files if you haven't changed the names.
Make it your own
If you followed along, you'll already have your own version of the repl to extend. If not, start from ours. Fork it from the embed below.
Where next?
That's it for our weather reporting project. You learned how to work with files in Python and Replit, including different modes (read, write, or append) in which files can be opened.
You also worked with an external library,
requests, for fetching data over the internet. This module is not actually part of Python, and in the next article you'll learn more about how to manage external modules or dependencies.
|
https://docs.replit.com/tutorials/managing-files-using-repl-it
|
CC-MAIN-2022-27
|
refinedweb
| 1,555
| 73.58
|
I've just started working with Dapper and I don't seem to find something very simple like mapping an entity to a table in my database:
I have a stored procedure:
CREATE PROCEDURE [dbo].GetUserById (@UserId int) AS begin SELECT UserId,LastName,FirstName,EmailAddress FROM users WHERE UserID = @UserId end go
Then an entity:
public class User { public int Id { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public string Email { get; set; } }
And a dapper query in my code:
int userid=1; User User = connection.Query<User>("#GetUserById", new {userid=userid}, commandType: CommandType.StoredProcedure).FirstOrDefault();
My question is: How can I tell my entity User that Id is Userid on my database?
In EF I would do something like this:
MapSingleType(c => new { UserId = c.Id, Firstname = c.Firstname, Lastname = c.Lastname, EmailAddress = c.Email }).ToTable("users");
How can the above be achieved in dapper?
Dapper deliberately doesn't have a mapping layer; it is the absolute minimum that can work, and frankly covers the majority of real scenarios in the process. However, if I understand correctly that you don't want to alias in the TSQL, and don't want any pass-thru properties - then use the non-generic
Query API:
User user = connection.Query("...", ...).Select(obj => new User { Id = (int) obj.UserId, FirstName = (string) obj.FirstName, LastName = (string) obj.LastName, Email = (string) obj.EmailAddress }).FirstOrDefault();
or perhaps more simply in the case of a single record:
var obj = connection.Query("...", ...).FirstOrDefault(); User user = new User { Id = (int) obj.UserId, FirstName = (string) obj.FirstName, LastName = (string) obj.LastName, Email = (string) obj.EmailAddress };
The trick here is that the non-generic
Query(...) API uses
dynamic, offering up members per column name.
It can't, your user class must be defined to match the result coming back from the query.
Once you've got the result back you must map it manually to another class (or use AutoMapper)
|
https://dapper-tutorial.net/knowledge-base/9518119/dapper--------
|
CC-MAIN-2019-35
|
refinedweb
| 323
| 59.4
|
XML::Compile::SOAP11::Encoding - SOAP encoding
### This module may work for you... but may also ### not work. Progress has been made, but the ### implementation is not complete and not well tested. # Add this to load the logic use XML::Compile::SOAP11::Encoding simplify => 1; # The internals are used by the ::SOAP11 module, and # probably should not be called by yourself.
This module loads extra functionality into the XML::Compile::SOAP11 namespace: all kinds of methods which are used to SOAP-encode data..
-Option--Default doc <created internally with utf8> elements found in the $xmlnodes (list of XML::LibXML::Node objects). Use Data::Dumper to figure-out what the produced output is: it is a guess, so may not be perfect (do not use RPC but document style soap for good results).
The decoded data is returned. When "simplify" is set, then the returned data is compact but may be sloppy. Otherwise, a HASH is returned containing as much info as could be extracted from the tree.
This module is part of XML-Compile-SOAP distribution version 3.19,
|
http://search.cpan.org/dist/XML-Compile-SOAP/lib/XML/Compile/SOAP11/Encoding.pod
|
CC-MAIN-2016-40
|
refinedweb
| 178
| 56.66
|
Merging PDFs with Python
Want to share your content on python-bloggers? click here.
I am currently looking for a new job, which means I need to create many resumes and cover letters. When creating a resume, it is good practice to create a PDF file. PDFs cannot be edited, which can make them difficult to work with, but they retain their formatting. It is impossible to tell which version of Microsoft Word a hiring manager is using. So you have to risk a possible formatting error or create a compatible resumes without the latest features.
One issue with using PDFs is that employers will sometimes ask for a cover letter and resume to be submitted as a single PDF. This wouldn’t be an issue if they were both stored in the same document, but if you are like me, you have separate documents creating separate PDFs. You can always use free online PDF mergers, but they can have limitations, and it may not be desirable to give away your personal data. So I decided to create a small Python script that will merge my PDFs together.
The script will require the
PyPDF2 package for dealing with PDFs and the
os package. The
os package is just used to automatically merge all PDFs in the root folder.
import PyPDF2, os
The first step is to create a list of the PDFs in the current folder. It also ensures that the merged PDF is not in the list.
pdfiles = [] for filename in os.listdir('.'): if filename.endswith('.pdf'): if filename != 'merged.pdf': pdfiles.append(filename) pdfiles.sort(key = str.lower)
The file list is also sorted alphabetically to ensure the results are predictable and easy to control. The merged PDF will contain the PDFs in the same order.
The next step is to create a
PdfFileMerger object, which will be the destination for all the data in the PDFs. The first step is to open the first PDF file in the PDF file list. The
PdfFileMerger object will only accept a file object, so we need to create a
PdfFileReader object from the opened PDF. This
PdfFileReader object will then be appended to the
PdfFileMerger object. We proceed then to the next PDF. After all files are added, the write method is used on the merged object to create a merged PDF.
pdfMerge = PyPDF2.PdfFileMerger() for filename in pdfiles: pdfFile = open(filename, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFile) pdfMerge.append(pdfReader) pdfFile.close() pdfMerge.write('merged.pdf')
And that’s everything, a simple Python script that creates a merged PDF from all PDFs in the root folder. It is important to remember that a PDF file needs to be opened, and then a file object can be created. Using the regular PDF file will not work.
Photo by krakenimages on Unsplash
Want to share your content on python-bloggers? click here.
|
https://python-bloggers.com/2022/04/merging-pdfs-with-python/
|
CC-MAIN-2022-40
|
refinedweb
| 480
| 63.9
|
ZooKeeper Features | Why ZooKeeper Is So Popular
Keeping you updated with latest technology trends, Join DataFlair on Telegram
1. Objective – ZooKeeper Features
Today, in this ZooKeeper tutorial, we will see ZooKeeper Features. One distributed application offers a lot of applications, but these applications also come with difficulties as well. Though, these difficulties are very hard to address. So, to overcome all these complexities, Apache ZooKeeper provides a wide range of good features of Zookeeper to the user. Hence in this Zookeeper article, here we will learn best Zookeeper Features to understand What makes it stand out from the crowd so well.
So, let’s start exploring ZooKeeper Features
Let’s explore best ZooKeeper Books
2. Apache Zookeeper Features
So, here is the list of best Features of ZooKeeper:
i. Naming service
To every node, identifying ZooKeeper attaches a unique identification which is quite similar to the DNA. So, that helps to identify it.
ii. Updating the node’s status
Also, it has the flexibility of updating every node. Hence, that feature permits it to store updated information about each node across the cluster.
Have a look at Zookeeper Architecture
iii. Managing the cluster
Moreover, in Zookeeper, the status of each node is maintained in real-time. That leaves lesser chances for errors as well as ambiguity, that’s how it manages the cluster.
iv. Automatic failure recovery
While modifying, ZooKeeper locks the data, so, if a failure occurs in the database, that helps the cluster to recover it automatically.
v. Simplicity
By using a shared hierarchical namespace, it coordinates.
vi. Reliability
When one or more nodes fail, the system keeps performing.
vii. Ordered
By stamping each update, it keeps track with a number denoting its order.
viii. Speed
In the cases where ‘Reads’ are more common, it runs with the ratio of 10:1.
Do you know the top ZooKeeper Applications
ix. Scalability
Performance of Zookeeper can be enhanced by deploying more machines.
x. How is the order beneficial?
To implement higher-level abstractions order is required.
xi. ZooKeeper is fast
Zookeeper works very Fast in “read-dominant” workloads.
xii. Ordered Messages
By stamping each update with a number denoting its order, it keeps track.
xiii. Serialization
Serialization means a surety about the consistency of running application. Though, this approach can be used in MapReduce for coordination of queue in order to execute running threads.
Have a look at ZooKeeper Pros and Cons
xiv. Reliability
As soon as it applies the update until a client overwrites the update, it will persist from that time forward.
xv. Atomicity
Either data transfer succeeds or fails completely.
xvi. Sequential Consistency
Sequential Consistency means, in the same order that they were sent, they apply the updates from a client, in that order only.
xvii. Single System Image
Despite the server from which it connects to, a client will see the same view of the service.
xviii. Timeliness
In some definite time amount, system’s client’s view is up-to-date.
So, this was all in Apache ZooKeeper Features. Hope you like our explanation.
Let’s revise ZooKeeper
Hence, in this ZooKeeper tutorial, we have seen all the best features of Zookeeper that make it stand out from the crowd. Next, we will see ZooKeeper Architecture. Still, if any doubt regarding Apache ZooKeeper features, ask in the comment tab.
See also –
ZooKeeper Leader Election
For reference
|
https://data-flair.training/blogs/zookeeper-features/
|
CC-MAIN-2020-34
|
refinedweb
| 562
| 57.57
|
The best answers to the question “How can I print literal curly-brace characters in a string and also use .format on it?” in the category Dev.
QUESTION:
x = " \{ Hello \} {0} " print(x.format(42))
gives me :
Key Error: Hello\\
I want to print the output:
{Hello} 42
ANSWER:
Python 3.6+ (2017)
In the recent versions of Python one would use f-strings (see also PEP498).
With f-strings one should use double
{{ or
}}
n = 42 print(f" {{Hello}} {n} ")
produces the desired
{Hello} 42
If you need to resolve an expression in the brackets instead of using literal text you’ll need three sets of brackets:
hello = "HELLO" print(f"{{{hello.lower()}}}")
produces
{hello}
ANSWER:
}}.
ANSWER:
The OP wrote this comment:
I was trying to format a small JSON for some purposes, like this:
'{"all": false, "selected": "{}"}'.format(data)to get something like
{"all": false, "selected": "1,2"}
It’s pretty common that the “escaping braces” issue comes up when dealing with JSON.
I suggest doing this:
import json data = "1,2" mydict = {"all": "false", "selected": data} json.dumps(mydict)
It’s cleaner than the alternative, which is:
'{{"all": false, "selected": "{}"}}'.format(data)
Using the
json library is definitely preferable when the JSON string gets more complicated than the example.
ANSWER:
You escape it by doubling the braces.
Eg:
x = "{{ Hello }} {0}" print(x.format(42))
|
https://rotadev.com/how-can-i-print-literal-curly-brace-characters-in-a-string-and-also-use-format-on-it-dev/
|
CC-MAIN-2022-40
|
refinedweb
| 228
| 66.13
|
On 20/04/07, VALLEE Mathieu RD-TECH-GRE
<mathieu.vallee@orange-ftgroup.com> wrote:
> I agree with Giovanni that this could be useful to many people. and therefore worth investigating.
Some time ago, I was also interested in using Jade from OSGi bundles. I don't think my solution
can be integrated as is in Jade, but I describe shortly in case you are interested.
>
> Here is what I did :
> 1. I defined 2 interfaces :
> public interface AgentFactory {
> public Agent createAgent();
> }
> public interface GenericAgentFactory {
> public void createAgent(String name, String className);
> }
>
> 2. for each of the agents classes I wanted to use, I created a bundle which:
> - contains the code of the agent
> - registers an "AgentFactory" service, with a property "agent-type={the agent class name}"
> - when the "createAgent()" method is called, the service returns a new instance of the
agent.
I'm doing something similar in my demo of Guice (IoC) on OSGi.
IMHO using services to delegate construction to bundles outside of
the core bundle is the way to go (much like the 'whiteboard' pattern).
>
> 3. I created a Jade-Core bundle, which :
> - creates a new Jade container (using Runtime.instance().createAgentContainer()) when
it starts
> - registers a "GenericAgentFactory" service.
> - when the "createAgent(String name, String className)" is called, the service does the
following:
> 1. lookup the "AgentFactory" service with property "agent-type=classname"
> 2. call the createAgent() method on this "AgentFactory" factory.
> 3. load the agent in the container (using acceptNewAgent(String name, Agent agent)
in ContainerController)
>
> 4. When I want to create an agent from a normal (i.e. non Jade) OSGi bundle, I do the
following
> - discover the "GenericAgentFactory" service
> - call the "createAgent(String name, String className)" method
>
> The main issue is that if you want agents to create other agents, you have to use the
"GenericAgentFactory" service inside OSGi (you can not directly ask the AMS to create an agent
because it will not find the class). Another issue in my implementation is that I did not
packaged Jade itself as a bundle, but I added it directly to the OSGi platform classpath.
This enables every "Jade" bundle to access Jade classes without explicitly importing all the
required packages. This is not good OSGi practice, but this was quicker for me since there
are quite a lot of packages in Jade and I did not want to bother with defining all the packages
I needed. Maybe a properly defined Jade bundle and using DynamicImport-package would be a
better solution.
Another option is to use a custom classloader to bridge the class hiearchies.
For example: in the core bundle, you create a classloader whose parent is
the bundle classloader, but also has an extra member for the client bundle
classloader (discovered by calling getClassLoader on the instance or class
provided by the client).
Then override the findClass method to delegate any framework classes
to the parent loader, and other classes to the client loader - for example:
public class MyFrameworkClassLoader extends ClassLoader {
private ClassLoader clientLoader;
public MyFrameworkClassLoader(Class clientClazz) {
super(MyFrameworkClassLoader.class.getClassLoader());
clientLoader = clientClazz.getClassLoader();
}
protected Class findClass(String name) throws ClassNotFoundException {
if (null == clientLoader || name.startsWith("my.framework.package.")) {
return super.findClass(name);
} else {
return clientLoader.loadClass(name);
}
}
}
You can use this loader for any code that needs visibility to both framework
and client bundles - most frameworks let you provide classloaders for just
this purpose (for example CGLIB, which is used by Guice).
Hope this helps :)
>
> The main advantages are:
> - My agents can use OSGi services (which was what I was interested in)
> - I can start agents at anytime and from other bundles, not only when the agent bundle
itself starts
> - when developping, I can update an agent, as follows:
> 1. modify the code of the agent
> 2. recompile and update the corresponding bundle on the OSGI platform
> 3. reload the agent in Jade, without restarting anything else.
>
> I didn't investigate too much how I could integrate better with Jade, but at the time
I also noticed that Jade has some kind of dynamic import system, which enables loading jar
files at runtime. I don't remember exactly how this was done, but maybe it could interesting
to enrich this fonctionnality with an OSGi support.
>
> Cheers,
>
> Mathieu
>
> > -----Message d'origine-----
> > De : jade-develop-bounces@avalon.tilab.com
> > [mailto:jade-develop-bounces@avalon.tilab.com] De la part de
> > Caire Giovanni
> > Envoyé : mercredi 18 avril 2007 09:48
> > À : Stefano Lenzi; felix-dev@incubator.apache.org;
> > jade-develop@avalon.TILAB.COM
> > Objet : RE: [jade-develop] Felix/OSGi and JADE Second Part
> >
> > Hi,
> >
> > If I understoot the problem correctly, the solution could be
> > to declare the DynamicImport-package manifest header in the
> > bundle that contains the JADE-Core and specify * as its value.
> > This should allow the JADE-Core bundle to load classes from
> > all exported packages.
> > Let me know if this works. In case it does :-), would you be
> > interested in making your work available to the community. I
> > think it could be useful for many people.
> >
> > Bye
> >
> > Giovanni
> >
> >
> >
> > -----Original Message-----
> > From: jade-develop-bounces@avalon.tilab.com
> > [mailto:jade-develop-bounces@avalon.tilab.com] On Behalf Of
> > Stefano Lenzi
> > Sent: martedì 17 aprile 2007 18.55
> > To: felix-dev@incubator.apache.org; jade-develop@avalon.tilab.com
> > Subject: [jade-develop] Felix/OSGi and JADE Second Part
> >
> > Hi All,
> > I had a chance to clarify my idea and to do more tests.
> > Here is what I got and I hope that you can help me to find a solution.
> >
> > GOAL: The Goal is to run JADE over OSGi so that agents
> > can be installed as bundle and executed when the bundle starts.
> >
> > APPROCH: I have created a JADE-Core bundle that
> > contains all the library used by JADE(e.g.: core, toosl and
> > MTPs). Then I have created a JADE-Example bundle that
> > contains all the example that came with JADE and it also
> > contains a BundleActivator that during the start method
> > executes the setup of the JADE Platform and launches all the
> > agent required by the example.
> >
> > THE PROBLEM: During the start up of the JADE Platform I
> > get the Class Not Found error message that states:
> >
> > "GRAVE: Cannot create agent Buyer-Alpha: Class
> > examples.bookTrading.BookBuyerAgent for agent (
> > agent-identifier :name Buyer-Alpha@asuka:1099/JADE ) not found [nested
> > java.lang.ClassNotFoundException: *** Class
> > 'examples.bookTrading.BookBuyerAgent' was not found because
> > bundle 12 does not import 'examples.bookTrading' even though
> > bundle 13 does export it. Additionally, the class is also
> > available from the system class loader. There are two fixes:
> > 1) Add an import for 'examples.bookTrading'
> > to bundle 12; imports are necessary for each class directly
> > touched by bundle code or indirectly touched, such as super
> > classes if their methods are used. 2) Add package
> > 'examples.bookTrading' to the
> > 'org.osgi.framework.bootdelegation' property; a library or VM
> > bug can cause classes to be loaded by the wrong class loader.
> > The first approach is preferable for preserving modularity. ***]"
> >
> > DEPLOY AND RUNTIME INFORMATION: As you already know I
> > have 2 bundles:
> > JADE-Core and JADE-Examples. The former contains the Boot
> > class that is the class in charge of the startup of the JADE
> > platform, the latter contains some of the Agent that I want
> > to run on the JADE Platform.
> > JADE-Examples imports all the packages exported by JADE-Core,
> > thus the Boot class. But during the JADE Platform startup
> > (made by Boot and other
> > classes) the method Class.loadForName() is invoked and it
> > returns the the above error.
> >
> > TIP or IDEA?
> >
> > Stefano "Kismet" Lenzi
> >
> > P.S.: Sorry for the long post... If you want I can give you
> > more details...
> > P.P.S.: It's my first Class Loading headache :S
> > P.P.P.S.: As you can see I have cross posted the message to
> > Felix and JADE _______________________________________________
> > jade-develop mailing list
> > jade-develop@avalon.tilab.com
> >
> > UNSUBSCRIBE INSTRUCTIONS AT
> >
> > _______________________________________________
> > jade-develop mailing list
> > jade-develop@avalon.tilab.com
> >
> > UNSUBSCRIBE INSTRUCTIONS AT
> >
> >
>
--
Cheers, Stuart
|
http://mail-archives.apache.org/mod_mbox/felix-dev/200704.mbox/%3C81f0d9c0704200745k7ea3ec7ak5cc2c3e3f23a2973@mail.gmail.com%3E
|
CC-MAIN-2018-30
|
refinedweb
| 1,327
| 55.54
|
On 12 Feb 2016 02:10, Andreas Grünbacher wrote: >. i don't see a problem with these three lines being in the public header. we're using the ACL_xxx namespace, and the behavior is the same -- we use only "extern" on the prototypes. the header already has to use "extern". > Since libacl already limits which symbols are visible, I don't really > see the benefit of this change anyway though. while true we still have the libtool linker script to limit exported symbols, using explicit visibility enables better code generation by the compiler. if it knows a symbol is not exported, it doesn't need to go through the PLT because symbol interposition isn't available. it's like declaring symbols static, but across multiple compilation units. when used w/LTO, the compiler can even consider inlining the content. -mike
signature.asc
Description: Digital signature
|
https://lists.gnu.org/archive/html/acl-devel/2016-02/msg00006.html
|
CC-MAIN-2022-27
|
refinedweb
| 145
| 57.67
|
Coding Conventions
The golden rule is to follow whatever conventions are already being used in the module you're editing. If you.
General Rules for all Languages
Spacing
- Tabs are 8 spaces. The reason being that when you cat a text file to a unix console they come out as 8 spaces. Keep your editor set to tabs-as-8-spaces or you'll end up committing misaligned code. No further discussion will be entered into on this point.
- We prefer literal tabs at the start of lines instead of hard spaces.
- Each top-level definition should have a comment explaining what it is for. One liners are fine.
- Running comments in the bodies of functions are encouraged. Write down what you were expecting the code to do when you wrote it, so it reads like a story. Aim for 1 comment line every 5-10 code lines, depending on how complex the code is.
- If a function does several things in a regular way, then it should look like')
-.
- Name conversion functions like globOfTops :: [Top] -> Glob instead of topsToGlob :: [Top] -> Glob. The type may be the opposite way around compared to the name, but it makes the source code easier to read. Consider (globOfTops someTops) vs (topsToGlob someTops).
- If part of a variable name reflects its type, then put that part out the front. For example, source code variables of type Shared.Var should be named something like vThing, with a v out the front. Sets or lists of variables should be named vsThing with vs out the front. Avoid using names like thingVar and thingVars..
Haskell / Disciple Specifics
Module signatures
Like the this, with the commas on the left:
module Thing ( someFunction , someOtherFunction , moreStuff ) where ...
Try to put the do on the same line as the =
Use this:
fun x = do y <- thing return (x + y)
Instead of this:
fun x = do y <- thing return (x + y)
The second version creates extra visual noise. As function names have different lengths, the column position of the top-level do will tend to be different between functions. x y = do restOfThing1 restOfThing2
Note that the continuation is named after the initial one, with a "_good" suffix that identifies the preconditions that the initial one sets up.
|
http://trac.haskell.org/ddc/wiki/Development/CodeConventions?version=23
|
CC-MAIN-2016-44
|
refinedweb
| 376
| 72.87
|
Build a Scheduler Slackbot in 30 Minutes!
Build a Scheduler Slackbot in 30 Minutes!
Let's learn how to create a scheduler bot that adds events to your personal calendar with a simple Slack slash command using the Nylas Calendar API.
Join the DZone community and get the full member experience.Join For Free
The days of leaving Slack to create an event on your calendar are over!
In this tutorial, you are going to learn how to create a scheduler bot that adds events to your personal calendar with a simple Slack slash command using the Nylas Calendar API.
What You'll Need Beforehand
There are a few systems that you'll need to have in place before embarking on this DIY Slack bot journey!
- Git and Github account
- Heroku account
- Slack workspace
- A text editor of your choosing — PyCharm, Atom, Vim, Sublime, etc.
Overview
Here are the high-level steps involved in building the scheduling bot:
Part 0: Basic app setup: Fork the starter code, run the setup script and run the app locally
Part 1: Hook your repo up to Heroku & deploy it: Create a Heroku app, hook it up to your Github repo, deploy it
Part 2: Set up Heroku config variables: Auth an account with Nylas to get the access token, use this to get the ID of the calendar, add these plus the calendar timezone as config variables in Heroku.
Part 3: Connect your app to your Slack workspace: Create a Slack App and configure a slash command to communicate with your app, add a route in your app that listens for the slash command
Part 4: Add text parsing functionality: Parse the text sent from Slack into meaningful components for an event
Part 5: Build scheduling functionality: Send the parsed arguments to the /events endpoint of the Nylas API to create an event on your calendar.
Ready? Let's Dive in!
Part 0: Basic App Setup
Step 0: Fork the Slackbot Starter Code
The code for this project lives in a repository on the Nylas Github account at.
You are going to fork and then clone this repository instead of just cloning it so that you have your own repository that you can connect to Heroku. Follow these steps from Github to fork the repository. Follow the steps up until "Find another repository to fork."
After, you will have a local copy of a directory called
slackbot. This directory has five files:
- Procfile — tells Heroku how to run the app
- app.py — the main app file with initial Flask app setup, you will do all of your development in this file
- requirements.txt — the list of dependencies you need to install
- runtime.txt — tells Heroku that your app is written in Python3
- setup.sh — a script to setup your development environment
For the rest of the tutorial, you will be executing all of your commands in the
/slackbot directory.
In addition to the master branch, which you will be on by default, this repo also contains five other branches corresponding to each part of the tutorial. You can stay on the master branch as you build your Slack bot, but if you get stuck at any step, then you can see the difference between your code and the example application code by using
git diff <part-#>. So if you get stuck during Part 4,
git diff part-4 will show the difference between your code and the example code after part 4.
Step 1: Run the Script
The setup script sets up your development environment and installs necessary dependencies. Run:
source setup.sh
After this script completes, it will print "Set up complete!" in your terminal.
This script will have activated a virtual environment which you will use to keep the development of your project isolated. If your terminal prompt is now prepended with
(.venv) your virtual environment has successfully been activated!
If you are interested in learning more about virtual environments and python3, check out:
Step 2: Run the App Locally
export FLASK_ENV=development
python3 app.py
You should see:
If you visit the URL on the 4th line that the app is running on, you will see
Howdy Hacker!
Woohoo! You made it through the app set up. Pat yourself on the back and crack open a La Croix.
Part 1: Hook Your Repo up to Heroku
Step 0: Create a New Heroku App
You could use DigitalOcean or DIY if you'd prefer, but these instructions will be for Heroku.
Log in to Heroku — — and create a new application by clicking
new in the top right corner and completing the new app form
You can enter your own app name or leave it blank and let Heroku generate one for you! Make note of this URL as you will need it in Part 3 when you connect your application to Slack.
Step 1: Hook up Your Github Repo to Heroku
Heroku has an integration with Github, which enables automatic deploys. This means that whenever you push code to a branch on Github, Heroku will deploy this code. How handy is that!
On the deploy page that you get redirected to after creating an application, in the Deployment method section, click
Connect to GitHub and then in the Connect to GitHub section, click the
Connect to GitHub button.
Next, you will be taken to a page where you can select which repository to connect. If you have successfully created a repository under your GitHub account, then it should come up when you start to type the repository name into the input.
Once you have connected up the repository, click
Enable Automatic Deploys for the master branch. This will simplify the deploy process so that any time you push to master, Heroku will deploy the latest changes.
It's important to note that if you start working on a branch other than master, then you will not have automatic deploys. You can manually deploy code from another branch if you push your code to the other branch select that branch from the manual deploy section and click
Deploy Branch.
Keep Heroku open because you will need it in Part 4, Step 3.
Step 2: Push Code to Master to Trigger a Deploy
Quit your locally running app with
CTRL+C.
The route should now look like:
@app.route('/') def homepage(): return "Howdy hacker!!"
In your terminal, run:
git add .
git commit -m 'Part 1: Hook up repo to Heroku'
git push origin master
After this deploy is complete — it may take a few seconds — visit the URL of your app. You should be greeted with the message
Howdy Hacker!!. Your website is live and ready to welcome any hacker who visits the URL, all thanks to the automatic deploy you configured.
Part 2: Set up Heroku Config Variables
Okay, so to make this work you need 2 major things. First, you need an access token that indicates that you have authorized your account to be accessed through the Nylas API. This is an important step because the API cannot add an event to any old calendar unless it has been authenticated and the owner has given permission. Second, you need the ID of the calendar you want to add events to. Most accounts have a few calendars - some autogenerated and some created by the user. Without this, the API would not know which calendar to send the request for.
Next, you'll set these as config variables in Heroku so that you'll avoid adding and committing them to code in your app.
In Step 0, you will get an access token and in Step 1, you will use this access token to find the ID for the calendar that you wish to add events to. Then, in Step 3 you will add these as config variables to your Heroku app.
Step 0: Get an Access Token
Head over to to register for a free Nylas account or to to sign in to an existing account. Once you've signed into the Nylas dashboard, click Accounts in the left sidebar.
On the Accounts page, click
Auth Account in either the top right or if you have no previously authed accounts, in the center of the page.
In the input window that pops up, type the email address associated with the calendar that you want to add events to and follow the authentication steps.
When you complete authentication, you will be redirected back to the Accounts page of the dashboard. At the top of the page will be a blue notification that looks like:
From the blue notification, copy the value of the access token to a temporary place — you will need this token in the following two steps. In this example, the access token is
xyz123xyz123xyz123xyz123xyz123.
If you dismiss the notification or reload the page, the access token will disappear. For security reasons, there is no way to retrieve that specific token, so if you lose your access token and need to get a new one, click
Auth Account and follow the authorization steps. You can re-auth a previously authenticated account no problem! This will create a new access token for the account.
You will use this token first in the Nylas docs to get the ID of the calendar and second when you add it to Heroku config variables.
You can keep the dashboard page open and as long as you don't navigate away or reload it, the blue notification with the access token will stay at the top of the page.
Step 1: Get the Calendar ID
You can't create an event without telling it what calendar it needs to be added to so you need to get the ID of the calendar you want to add events to.
Head over to. This is the calendar section of the Nylas docs and specifically the
GET /calendars endpoint. You could hit the Nylas API by making a request to in your terminal, but the docs are interactive and make it possible to do in two steps within the site.
Paste your access token into the
Authorization input field at the bottom of the inputs for this endpoint section.
If you then scroll back up to the code in the dark box above, the
authorization: will have been automatically filled out.
Next, click
Try It in the top right corner. This will run the
cURL request on the left and hit the Nylas API with your access token and display the response on the right. This will be a list of your calendars.
From the JSON list of calendars, select which calendar you want to add events to. Some of the calendars you may have never seen before. That is because some providers have default calendars that they automatically generate. One common example is "Holidays." Often, these automatic calendars will have
"read_only": True. This means that you don't have permissions to create events on those calendars. It is important to select a calendar that has
"read_only": False. Copy the
id from your selected calendar.
In the example screenshot above, the
id of the top calendar is
"67qmz3fuk9wfljwj1w8ngshkc". You will have a different value after you run Try It because the ID will be a unique identifier to your calendar.
Step 2: Add Config Variables to Heroku
Go to Heroku and navigate to the settings page for your app. Click
Reveal Config Vars. This will pop open a pair of inputs where the key, or how you want to refer to the variable in your code, is on the left and the value is on the right.
Add your calendar ID as a config variable with a key of
CALENDAR_ID and a value of the ID that you copied in Step 1. Make sure to remove the double quotes from the ID.
Next, you are going to add the access token from Step 0 as a config variable with a key of
ACCESS_TOKEN and the value from Step 0.
Finally, you need to add a config variable with your calendar time zone so that your calendar can properly schedule events. If you don't pass the timezone, then your calendar will assume UTC (Universal Time Coordinated) also known as GMT (Greenwich Mean Time). If your calendar is in any other timezone, then the evens will show upshifted by the timezone UTC offset. Setting the timezone config variable will avoid this!
Since I am writing this in California and it is currently daylight savings, the value will be
PDT. You can also set the value to the UTC offset, which for me would be
-0700. You can find your timezone information here. If you want to use the UTC offset then it needs to be in the proper format. A timezone of UTC+10 would be
+1000 and a timezone of UTC-3 would be
-0300.
Here is how it looked for me:
Or with UTC offset:
Sweet, now that everything in Heroku is configured, we can dive into the exciting next steps.
Part 3: Connect Your App to Slack
Step 1: Create a Slack App
Go to. This is the landing page for building a new Slack app.
If the pop up above does not appear, click
Create New App.
Fill in the
App Name with "Scheduler" or whatever you would like to name this app. The name you select here is not too important.
Next, select the development workspace in which you want to use this app. If you are not signed into your Slack account, when you click the
Development Slack Workspace drop down the only option that will appear is
Sign in to another workspace. Select this and follow these instructions. This will get you to sign into your workspace on the desktop. Once this is successful, head back to and fill out the pop up again. This time, there should be workspace options in the dropdown. Select which workspace you want to add this scheduler app to and hit
Create App.
Step 2: Configure Slack App
You will be taken to an app dashboard. Here, there are lots of options for what type of application and functionality you want to build. You will be making a slash command so select the
Slash Commands option.
Then, select
Create New Command. This will take you to a slash command configuration form.
Command
You can name the command however you want to invoke it when you use it. I choose
/scheduleme because I think it looks cute when invoked in full:
/scheduleme "Dinner with James" "Tomorrow at 7pm" "Tomorrow at 9pm"
but you can select whatever slash command tickles your fancies.
Request URL
For the
Request URL input, copy the URL that your Heroku app was deployed to on step 1 and paste it in the input. Then at the end of the URL, add a
/scheduleme so the URL will look something like:.
This is setting up where Slack should send the request from the slash command. In other words, when you invoke a slash command, Slack needs to know where to send the data. This is specifying a URL and a specific route on that url,
/scheduleme. You will define this route in your python file in Part 5!
Short Description
Add a short description to help you remember what this command does. This will pop up in Slack when you are typing commands that match.
For mine, I put
Adds an event to my calendar!
Usage Hint
This is a hint for how to properly invoke the slash command. As you can see in the screenshot above, this will also pop up when you start typing the command.
For mine, I put
"title" "start date & time" "end date & time".
The scheduler will be expecting three arguments, each in double quotes. The first argument should be the title of the event, the second should be the start date and time and the third should be the end date and time. You will see how these get parsed in when you build out the text parsing functionality in Part 4.
Click
Save in the bottom right corner and you will be redirected back to your app homepage.
Step 3: Install the App in Your Workspace
On the sidebar, click
Install App
Follow the steps to install the app in your workspace. Without this step, your workspace won't know about your app and its slash command.
Step 4: Add the /scheduleme Route to Your Application
In the previous step, you connected your Slack slash command up to the URL of your Heroku app +
/scheduleme. But what is
/scheduleme referring to? Nothing at the moment!
Let's fix that. In your file
app.py, let's add another route. You can add a route with the URL
scheduleme to match what you appended to the end of your Heroku app URL in the
Create New Command form on Slack. You will be doing data processing in this route with the information from the slash command. To indicate that data is sent with the request, you need to add
methods=['POST'] as the second
@app.route parameter. The function name on line 14 doesn't matter in this case, but for the sake of consistency, you can call it
scheduleme as well.
from flask import Flask app = Flask(__name__) PORT = 4390 @app.route('/') def homepage(): return "Howdy hacker!!" @app.route('/scheduleme', methods=['POST']) def scheduleme(): return 'I would like to schedule that, but I haven\'t quite figured out how...' if __name__ == '__main__': app.run(debug=True, port=PORT)
This function doesn't do much — it just returns some text. But let's deploy it to make sure you properly connected your app up to Slack.
Add, commit, and push this code to master to make it live!
Then, go to your Slack workspace and type in
/scheduleme and hit enter. Your bot should respond with:
You have officially made a Slack bot! Now, let's add some functionality!
Debugging
If your bot responded properly, skip this section and continue onto Part 4!
If you get a
404 here, there are a few strategies to identify what's going wrong.
To see if the issue is with your application code, user a cURL request to hit that endpoint.
curl -X POST -F 'text="Post tutorial celebration dance" "Now" "Today at 11pm"' https://<your-app-url>/scheduleme
Replace
<your-app-url> with your Heroku app URL. This command is bypassing Slack, and hitting your application code directly. If the bot does not respond properly, then the problem must be with your application. If your bot does respond properly, then the issue is likely from the connection with your Slack slash command.
Application Problems
- Does your code match the code above?
- Has this new code been deployed — either automatically if you have that setup or otherwise manually via the Heroku UI or Heroku command line interface?
- Run the app locally and curl it from the command line
curl -X POST -F 'text="Post tutorial celebration dance" "Now" "Today at 11pm"'
heroku logs --tail -a <your-app-name>;
Connection Problems
- In Slack, when you type in
/schedulemedoes the command help pop up? If not, your app likely has not be installed to your workspace. Make sure Step 3 was completed properly.
- On the edit command page that you filled out in Step 2, does your request URL end in
/scheduleme?
Part 4: Add Text Parsing Functionality
When you use the slash command, you are going to send some text with it. In this step, you're going to parse that text and make sure you have the correct number of arguments.
Step 0: Add New Dependencies
For parsing the request sent by Slack, you are going to use two new dependencies. First, you are going to import
request from Flask. You will use this to access the information in the request. Next, you are going to unpack the text of the request using a regular expression. For this, you need to add
import re to your import section.
The top of the file will now look like:
from flask import Flask, request import re
Step 1: Get the Text From the Request
Using the
request library, you will need to get the text sent with the slash command. You can do this by adding
raw_text = request.form.get('text') at the top of your
scheduleme route.
Step 2: Unwrap the Text
The text that is sent from the slash command is the string following the command name. For example, if you type
/scheduleme "Workout" "Tomorrow at 7:30am" "Tomorrow at 8:30am" into Slack, the text that you will get in the previous step will
"Workout" "Tomorrow at 7:30am" "Tomorrow at 8:30am". It is important to note that this text is wrapped in single quotes with each of the three components wrapped in double quotes. You can use a regular expression to unwrap the text from single quotes and put all the components into an array.
text_array = re.findall(r'"(.*?)"', raw_text)
Step 3: Error Handling
You should make sure that you have the proper number of arguments and warn if not.
if len(text_array) != 3: return 'The format is /scheduleme "[title]" "[start date & time]" "[end date & time]"'
Step 4: Pull Out Event Components
Finally, let's pull out the different components from the array and give them better names.
title, start, end = text_array
Then to make sure this is all working swimmingly, you can pass them all to a return statement like:
return 'Sweet I parsed the title: {}, start: {} and end: {}'.format(title, start, end)
At the end of this section, your app.py file will look return f'Sweet I parsed the title: {title}, start: {start} and end: {end}' if __name__ == '__main__': app.run(debug=True, port=PORT)
Add, commit and push this code! To test it, type in a full
/scheduleme command to Slack like:
and you should see:
Part 5: Build Scheduling Functionality
This is your last part — hooray you are almost finished! In this last step, you're going to send the request to the Nylas API that will create an event on your calendar.
Step 0: Access the Config Variables in Your Code
To access config variables in your code, you will need to add another dependency,
os. Add the line
import os to the bottom of your import statements.
Next, let's use
os to pull the values of your config variables from Heroku into your code. Replace the return statement with:'
Step 1: Build Request Components
You are going to use the
requests library to send the request to the Nylas API. Add
import requests to your import statements. You are also going to use
dateparser which takes a variety of inputs, for example, "Today at 3 pm," "12/31/2018 at 11:30 pm," "Friday at 9 am," and turns them into DateTime objects. Using this library gives you more flexibility for what you can type in as the start and end components of the slash command. Add
import dateparser to your import statements.
The request is comprised of a few components — a URL, headers and JSON. First, you will create a dictionary of the
timezone_settings. You will pass this into
dateparser.parse() to indicate that you want the date to be parsed into a timezone aware datetime object.
timezone_settings = {'TIMEZONE': timezone, 'RETURN_AS_TIMEZONE_AWARE': True}
Now you have all the information to create the meat of the request, the
json argument. For this, you will create a dictionary with
calendar_id,
title and
when keys. The when dictionary has two keys
start_time and
end_time.
{ 'calendar_id': calendar_id, 'title': title, 'when': { 'start_time': int(dateparser.parse(start, settings=timezone_settings).timestamp()), 'end_time': int(dateparser.parse(end, settings=timezone_settings).timestamp()) } }
There’s a lot going on in the values of
start_time and
end_time! The first step,
dateparser.parse(start, settings=timezone_settings), is parsing the string text into a timezone aware datetime. Then,
.timestamp() is turning it into a unix timestamp. This timestamp is a float, so the final step is turning it into an integer with
int().
The final building block for the request is the headers where you will pass in the access token to prove that you have authorized your account.
headers = {'authorization': access_token}
Finally, bring all these pieces together and wrap it in a a try except block to capture any exceptions.
try: response = requests.post('', headers=headers, json=json) if response.status_code == 200: return f'Wohoo! {title} was scheduled from {start} to {end}' else: return f'Error! Our response has a status of {response.status_code} and text {response.text}' except Exception as e: return f'An exception {e} occurred creating the event!'
Use the requests library to make a post request to the URL
'' passing in the headers and the JSON as keyword arguments.
Your app.py file will end up' timezone_settings = {'TIMEZONE': timezone, 'RETURN_AS_TIMEZONE_AWARE': True json = { 'calendar_id': calendar_id, 'title': title, 'when': { 'start_time': int(dateparser.parse(start, settings=timezone_settings).timestamp()), 'end_time': int(dateparser.parse(end, settings=timezone_settings).timestamp()) } } headers = {'authorization': access_token} try: if response.status_code == 200: return f'Wohoo! {title} was scheduled from {start} to {end}' else: return f'Error! Our response has a status of {response.status_code} and text {response.text}' except Exception as e: return f'An exception {e} occurred creating the event!' if __name__ == '__main__': app.run(debug=True, port=PORT)
Add, commit, and push this. Yay, your Slackbot is complete! Head over to Slack and enter
/scheduleme "Post tutorial celebration dance" "Now" "Today at 11pm". Then, head over to your calendar and you will see a well-deserved celebration dance for scheduled, appropriately, for the rest of the day.
If you run into any issues along the way, check out the debugging section for help!
Published at DZone with permission of Annie Cook , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/build-a-scheduler-slackbot-in-30-minutes?fromrel=true
|
CC-MAIN-2020-34
|
refinedweb
| 4,329
| 71.65
|
Technical Support
On-Line Manuals
RL-ARM User's Guide (MDK v4)
#include <usbhw.h>
U32 USB_WriteEP(
U32 EPNum, /* Endpoint number and direction */
U8 *pData, /* Pointer to data buffer */
U32 cnt); /* Number of bytes to write */
The USB_WriteEP function writes data into the endpoint
buffer. When the host computer requests new data, the
USB_EndPointNumber function can call USB_WriteEP
to send the data. The argument EPNum contains the endpoint
number (0-15) in the first 4 bits, and the direction in bit 7.
Usually, the direction bit is one (1) denoting an IN endpoint.
It is not required to modify this function.
The USB_WriteEP function is part of the USB Device
Controller Driver layer of the RL-USB Software Stack.
The USB_WriteEP function returns the number of bytes
written to the endpoint buffer.
USB_EndPointNumber, USB_ReadEP
#include <usbhw.h>
void USB_EndPoint1 (void) __task {
for (;;) {
os_evt_wait_or (USB_EVT_IN, 0xFFFF); /* Wait for USB_EVT_IN event */
GetInReport ();
USB_WriteEP (0x81, &InReport, sizeof (In.
|
http://www.keil.com/support/man/docs/rlarm/rlarm_usb_writeep.htm
|
CC-MAIN-2020-05
|
refinedweb
| 155
| 56.45
|
Pandas describe() is used to view some basic statistical details like percentile, mean, std etc. of a data frame or a series of numeric values. When this method is applied to a series of string, it returns a different output which is shown in the examples below.
Syntax: DataFrame.describe(percentiles=None, include=None, exclude=None)
Parameters:
- percentile: list like data type of numbers between 0-1 to return the respective percentile
- include: List of data types to be included while describing dataframe. Default is None
- exclude: List of data types to be Excluded while describing dataframe. Default is None
- Return type: Statistical summary of data frame.
The describe() function computes a summary of statistics pertaining to the DataFrame columns.
Example:- The following is a simple exams that illustrates The describe() function computes a summary of statistics pertaining to the DataFrame columns.
import pandas as pd data = [[10, 18, 11], [13, 15, 8], [9, 20, 3]] df = pd.DataFrame(data) print(df.describe())
The following is the out put of the above program
0 1 2 count 3.000000 3.000000 3.000000 mean 10.666667 17.666667 7.333333 std 2.081666 2.516611 4.041452 min 9.000000 15.000000 3.000000 25% 9.500000 16.500000 5.500000 50% 10.000000 18.000000 8.000000 75% 11.500000 19.000000 9.500000 max 13.000000 20.000000 11.000000
Note: only a member of this blog may post a comment.
|
http://www.tutorialtpoint.net/2021/12/python-pandas-dataframedescribe-method.html
|
CC-MAIN-2022-05
|
refinedweb
| 243
| 68.16
|
0
Hey guys,
I have a class with a friend function and a member function with the same name. Calling the friend function from the member function gives me an error: it looks for <classname>::<function> while the friend function is of course simply <function>.
In this case, MinGW GCC says:
\Code\RationalNumber\rational.cpp | In member function `long long unsigned int rational::gcd() const': \Code\RationalNumber\rational.cpp | error: no matching function for call to `rational::gcd(const long long unsigned int&, const long long unsigned int&) const' \Code\RationalNumber\rational.cpp | note: candidates are: long long unsigned int rational::gcd() const
How do I circumvent this naming collision without altering the function names? Can I tell the rational::gcd() to look for the other gcd without namespaces? Or with some sort of "not in any" namespace?
Here's the relevant code:
rational.hpp
class rational { friend unsigned long long gcd(unsigned long long x, unsigned long long y); public: unsigned long long gcd() const; };
rational.cpp
unsigned long long gcd(unsigned long long x, unsigned long long y) { if (x == y) return x; //Euclidean method unsigned long long diff; while (x != 0 && y != 0) { if (x > y) { diff = x - y; x = diff; } else { diff = y - x; y = diff; } } return (x == 0) ? y : x; } unsigned long long rational::gcd() const { return gcd(nominator, denominator); }
Thanks in Advance,
Nick
|
https://www.daniweb.com/programming/software-development/threads/188346/friend-function-member-function-name-collision
|
CC-MAIN-2017-17
|
refinedweb
| 229
| 55.34
|
Hey there, getting the error as above mentioned when try to desrialize a json object .
//GetProduct();
var ress = await GetUserDetailsAsync();
if (!string.IsNullOrEmpty(ress)) { var req = JsonConvert.DeserializeObject<Employee>(ress); await DisplayAlert("Success", "HelloOoOooOO", "ok"); }
using a customize api which have a json response like this,
{
"Result": [
{
"COURSE_ID": 105,
"CREATE_DATE": "0001-01-01T00:00:00",
"CREATE_USER": 0,
"LAST_UPDATE_DATE": "0001-01-01T00:00:00",
"LAST_UPDATE_USER": 0,
"TEN_ID": 0,
"NAME": "Oracle 12c Database",
"DESCRIPTION": "10g, 11g, 12c, 18c ",
"PREFERRED_VENDOR": "",
"INSTRUCTOR": "",
"URL": "",
"EXPIRY_DATE": "0001-01-01T00:00:00",
"RETRAINING_INTERVEL": "",
"DURATION": "5",
"PRICE": 0,
"ACTIVE_FLAG": "Y",
"TERMINATION_DATE": "0001-01-01T00:00:00",
"Task": null
}
],
"Message": "SUCCESS",
"CODE": "SUCCESS"
}
Answers
@FaiZii I have tried with your given data and It is working fine for me, May be you are not parsing the json into right type of object.
I am attaching the console application where I used your json to convert it to an object.
@AmitManchanda can you please elaborate, or what can i share with you "code" so that you can help me,
Thanks
async Task GetUserDetailsAsync()
{
var client = new HttpClient();
This is my code of the api.... where i have the link of the post api to get the data...
and my Class is
public class Employee
{
public List Result { get; set; }
public object Message { get; set; }
public string CODE { get; set; }
@FaiZii Please have a look on my code, I already implemented it for you there. I used your json
@AmitManchanda Have a look at my second comment also, i have seen your code you have just read the text in json but i am reading it from the server and getting this error
@FaiZii Just convert you Price From inr to decimal, As you price is coming in decimal from the API(Saw your API response)
Ok , i will try that in a bit, will reply back if it works
|
https://forums.xamarin.com/discussion/comment/356149/
|
CC-MAIN-2019-39
|
refinedweb
| 309
| 56.12
|
Welcome to Cisco Support Community. We would love to have your feedback.
For an introduction to the new site, click here. And see here for current known issues.
Warning: parameter timer has not been registered under timer namespace
WORD Value for the parameter
application
service XXXX
param YYYY zzz
i am seeing the the message after the outputs shown.
This warning is related to the CLI changes and they do not affect the operation of the script.
but the router does not accept the param value....so the script wont work until i am able to define thhis value.....each time i try to put that value, i see the message that we are talking about...
|
https://supportforums.cisco.com/t5/other-collaboration-voice-and/how-to-solve-this-message-tcls-warning/td-p/1109526
|
CC-MAIN-2017-43
|
refinedweb
| 116
| 75.5
|
.
def my_function(file_name_or_object):
# parameter is string
if isinstance(file_name_or_object, (str, unicode)):
return open(file_name_or_object)
# parameter is an file like object that has at least a read method
elif hasattr(file_name_or_object, “read”):
return file_name_or_object
Comment by me — May 9, 2008 @ 9:37 pm
What about this? It would depend of course in how “filelike” the object has to be. I don’t know whether it is considered the most idiomatic, but it’s used for example in xml.etree.Elementree for the parse function.
if not hasattr(file_name_or_object, ‘read’):
filename_or_object = open(file_name_or_object)
return filename_or_object
Comment by Steven — May 9, 2008 @ 9:51 pm
@me: why do you use ‘hasattr’ with ‘elif’? Why not simply use ‘isinstance(file_name_or_object,file)’? Is it faster? I’m asking because many classes can have ‘read’ method, not necessarily being ‘file-like’.
Comment by vArDo — May 9, 2008 @ 10:02 pm
I agree that in this circumstance a type check ( isinstance(file_name_or_object, basestring) ) is perfectly acceptable. ConfigObj does this. (Particularly as there is no ’string protocol’ and so any filename will have to be passed in as a real string or at least a subclass.)
Michael
Comment by Michael Foord — May 9, 2008 @ 10:02 pm
Isn’t the try/except to be preferred over isinstance/hasattr? Or will it lead to bad logic?
The OP’s case will assume its a file object if it is not open-able; as opposed to assuming it is a file object if it is an instance of basestring.
I suspect that in this case it amounts to the same thing if open itself only works if given an instance of basestring, but style-wise I thought it was preferable to limit the use of isinstance/hasattr?
Hell, I’m nit-picking. either would work!
- Paddy.
Comment by Paddy3118 — May 9, 2008 @ 11:55 pm
If the code is only going to read the data in the file a line at a time then I would say it is far better to specify that the function takes an iterable sequence of strings, so that the client code is responsible for creating the file object and passing it in. This way the client could equally give the function a urlib object, or a StringIO object, or a list of strings, or a generator, or anything else that the user can come up with.
This not only makes the function more flexible and useful, it also makes it much easier to test. I have lots of tests where the production version of the code takes a file object, but the unit tests pass in something like this:
testdata = ”’
lines
of test
data
”’.splitlines()
result = myFunction(testdata)
assert result == expected
This makes the test self-contained, instead of being split across lots of supplementary files.
Having a function that takes either a string or a filename is a code smell IMHO - if you must allow either then have two separate functions, the first takes a file (or string iterable), and the second takes a filename, opens the file and calls the first function.
e.g.
def doStuff(fileObj):
# do stuff with the file
def openFileAndDoStuff(filename):
doStuff(open(filename))
Comment by Dave Kirby — May 10, 2008 @ 12:09 am
You could use named arguments
def my_function(file_name=None, file_object=None):
….if file_object == None:
……..file_object = open(file_name’, ‘r’)
….# Do stuff with file_object
my_function(file_name=’test.txt’)
my_function(file_object=open(’test.txt’,'r’)
Comment by Snazz — May 10, 2008 @ 12:43 am
Another version:
def getfile(obj):
….if all(hasattr(obj, attr) for attr in ['read', 'seek', 'write']):
……..return obj
….elif isinstance(obj, basestring) and os.path.isfile(obj):
……..return file(obj)
….else:
……..raise ValueError(”Not a file-like object or valid path.”)
Comment by Steve Kryskalla — May 10, 2008 @ 3:12 am
I think you could also turn this type of function into a decorator that will automatically coerce an argument of the wrapped function.
Comment by Steve Kryskalla — May 10, 2008 @ 3:16 am
|
http://halfcooked.com/blog/2008/05/09/opening-a-file-in-python/
|
crawl-002
|
refinedweb
| 661
| 61.46
|
.
We, at HPE, were facing the same challenges when trying to build a massive React-based UI application. Redux offered a good starting convention for organizing the flow of data through a one-way, globally accessible pipeline BUT it didn't go quite far enough in describing how the application should be structured.
We'll begin with basics.
Redux + React
This article assumes the reader already knows how to use React and Redux.
React has already proven itself in both speed and its ability for headless rendering, and its wide use has ensured no end to UI engineers who can work with a codebase. Since React simplifies UI rendering by enforcing a unidirectional, top-down data-flow it makes for good pairing partners with Redux.
Redux (paired necessarily with React-Redux) is a great benefit for medium-to-large applications because it offers a convention for how data is fetched, consumed, passed from one component to another, and ultimately displayed in the UI. Allowing Redux to handle the state of the application in a singular/global context takes the guesswork out of knowing what inner-dependencies exist within a large application. With Redux handling the updates to the global application state React can focus wholly on presentation and the handling of user events through props alone.
React's own
setState can certainly be used within components but should be limited as much as possible to simple, interim state that isn't critical nor likely to be used by any other piece of the application. In these cases the usage should be heavily documented as well.
The reason why Redux is used instead of local, ad-hoc changes within the presentation layer or some other centralized store where accessors can mutate state (like MobX, e.g.) is because these systems can inevitably leave data flow inconsistent across the application design translating to longer ramp-up time and more difficulty debugging. In fact, to enforce this and protect references to the state we have wrapped everything in Immutable.
For more context of why this might cause issues consider an application with >100 containers and components that each rely on a set of robust API interdependencies.
Likewise, the use of a
dispatch prop in React components is highly discouraged. Instead, action creators are used exclusively to post updates to the state so that components can remain totally agnostic to state schema design:
// bad const Todos = ({todos, dispatch}) => { return ( <TodoList todos={todos} onClick={dispatch(...)} /> ) } export default connect( state => ({todos}) ) // good const Todos = ({todos, todoListClick}) => { return ( <TodoList todos={todos} onClick={todoListClick} /> ) } export default connect( state => ({todos: state.todos}), { // Instead of using dispatch we just inject action // creators into components that handle how dispatches are // constructed and fired. todoListClick: createAction(TODO_LIST_CLICK) } )
The immediate benefit of constructing an application this way is the certainty that every component and its data flow is architected the exact same way. An engineer who is familiar with this pattern can then jump into another area of the application she doesn't yet have experience with to make changes with little learning curve. Furthermore, she can easily scaffold a new component module without the guesswork of what pieces to create or the How?.
A secondary but immensely important benefit is the ease of unit testing components and state management. I cannot stress enough how important it is to write unit tests for high coverage. It catches so many bugs before they make it into
master. Without going into the virtues of testing suffice it to say it becomes important to make testing as easy and fluid as possible for team members, and this is easiest when presentation and state management concerns are kept as separated as possible.
Modules as a Separation of Concerns
Continuing in this same philosophy, we have embraced an architecture very similar to Redux Ducks and Reactizer. The idea is to keep the application as decentralized as possible by allowing each Module to be responsible for its own feature requirements while at the same time keeping its data in the global store.
New feature modules can be added at any time to extend the application and older features can be upgraded without extensive changes across the app.
Each Module contains the following units:
- Module:
- Module File (
index.js) contains most of the module's Redux code.
- Selectors are simple getter functions used to select data from the state.
- Routes contains the Module's React-Router configuration that is consumed at the top App level. (See
System.importusage.)
- Container: The smart, top rendering class that injects all props from the module file including state and action creators. Any intermediate logic such as filtering, event handler logic, or mounting logic is done in its methods.
- Components: Dumber individual classes or stateless functions that render specific pieces of the UI based on props from the container.
- Elements: Super dumb, stateless functions that are used to keep presentation DRY. These do not call anything on props.
- Tests: Jest unit testing belongs to each Module as well.
An example file structure might look like:
Todos ├── Components │ ├── TodoList.jsx │ └── TodoList.test.jsx ├── Elements │ ├── TodoIcon.jsx │ └── TodoIcon.test.jsx ├── TodoContainer.jsx ├── TodoContainer.test.jsx └── module ├── index.js ├── routes.js ├── selectors.js └── todos.module.test.js
We then structure the contents inside the Module's files with the same format for every Module of the application, enforcing uniformity. A typical
module/index.js file might look like this:' // Action Creators are in the same order as action types export const todos = { showTodos: createAction(SHOW_TODOS), newTodos: createAction(NEW_TODOS), addTodo: createAction(ADD_TODO) } // Initial state is always defined export const initialState = fromJS({ todoResults: { count: 0, start: 0, page: 0, items: [] }, isFetching: false, isVisible: false, filterBy: null }) // Async flow control goes here... // More on this below. //) defualt: return state } }
As you might guess, when every module conforms to this pattern it gives us the benefit of knowing exactly where all of the elements of our large and complex application live without sacrificing the agility of using open-sourced libraries instead of a monolithic framework.
If you have experience with Redux you might by now be wondering how asynchronous actions are handled, like adding a new todo that involves POSTing to an API server and receiving a response. Redux has no opinion about how these action sequences are preformed but of all the available addons out there we have found great value in Redux-Saga.
Redux-Saga for Async Flow Control
Any modern application is going to have asynchronous actions. As such, we don't want these actions to block our application as we wait for them to resolve. In fact, we want these actions to spin off "side effects" that can run in sub-processes that can then later report outcomes back to our store. This is where Redux-Saga comes into play.
Redux-Saga is a coroutine runner (a feature sorely missing from native Javascript) that wraps generator functions called sagas. These functions can yield out declarative effects, promises, other sagas, or other types that are automatically handled. Those computed values are then injected back into the saga for us effectively turning asynchronous code into linear blocks.
Saga effects are really just object descriptors defined by Redux-Saga that are generated by factories and are interpreted by the coroutine runner to produce effects. To show a simple example:
// in module/index.js import {fork, take, put} from 'redux-saga/effects' function* todosSaga () { yield [ fork(addTodoSaga) ] } function* addTodoSaga () { while (true) { const {payload} = yield take(ADD_TODO) const {body} = yield api.todos.add(payload) yield put(todos.addTodoSuccess(body)) } }
In this very simple example the
todosSaga generator would be mounted on module load with Redux-Saga's runner. The yielded array of effects would then run each one concurrently. In this case, we are "forking" the
addTodoSaga which would then run concurrently alongside any other forked sagas.
Since generator functions can be paused on blocking yield statements the infinite
while loop just acts as a "keep alive". The yielded
take effect instructs Redux-Saga to wait until an action with type
ADD_TODO is dispatched at which point the action object is injected back into the saga and captured. Our example api would then call a method that returns a pending Promise (e.g., from fetch), which our runner understands and waits to resolve before injecting the resolved value back into the saga. Finally, the
put effect instructs the runner to dispatch or "put" an action back onto the state, which in this case is created by an action creator.
Again, this example is very simplistic and doesn't handle error handling (such as if fetch rejected) but it illustrates the potential power that coroutine runners can afford engineers by simplifying otherwise complex asynchronous flows into sync-flowing processes. As an added bonus, since Redux-Saga uses declarative effects unit testing becomes that much easier since apis no longer need to be mocked. To see more examples be sure to check out the Redux-Saga docs.
So, putting it all together our previous example
module/index.js file might look something like:
import {fork, take, put} from 'redux-saga/effects'' export const ADD_TODO_SUCCESS = 'todos/ADD_TODO_SUCCESS' export const ADD_TODO_FAILURE = 'todos/ADD_TODO_FAILURE' // Action Creators are in the same order as action types export const todos = { showTodos: createAction(SHOW_TODOS), newTodos: createAction(NEW_TODOS), addTodo: createAction(ADD_TODO), addTodoSuccess: createAction(ADD_TODO_SUCCESS), addTodoFailure: createAction(ADD_TODO_FAILURE) } // Sagas function* todosSaga () { yield [ fork(addTodoSaga) ] } function* addTodoSaga () { while (true) { const {payload} = yield take(ADD_TODO) const {body, error} = yield api.todos.add(payload) if (body) { yield put(todos.addTodoSuccess(body)) } else { yield put(todos.addTodoFailure(error)) } } } // Initial state is always defined export const initialState = fromJS({ todoResults: { count: 0, start: 0, page: 0, items: [] }, isFetching: false, isVisible: false, filterBy: null, error: null }) //) case ADD_TODO_SUCCESS: return state.updateIn(['todoResults', 'items'], items => items.push(payload.items) ) .setIn(['todoResults', 'count'], payload.count) .set('isFetching', false) case ADD_TODO_FAILURE: return state .set('error', payload) .set('isFetching', false) defualt: return state } }
Each Module, on load, forks the main module saga and combines the reducer to Redux's store. The rest of the Module takes care of itself.
Of course, the amazing benefit of using Redux's middlewares still applies here so any shared store logic that should extend to more than a single Module should naturally go into the App's middlewares. (In particular, look for time-traveling, state persistence, authentication services, route pushing, and more.)
Areas for Improvement
While this setup has proven easy to grasp and extend upon within our large application it does have some areas for improvement.
Specifically, we are currently passing every prop needed down from the Container level. These props are either defined in the Container or injected via the
connect HoC. While this makes organization simple it also means every change or addition of a prop equates to changes to every JSX component in the tree. This gets tiring.
There's also little agreement about what constitutes "common" or "global" components that can be shared across the application. Where should these go.
One must be studious with imports in this kind of setup. If an action (or action creator) is required in another Module and the entire
module/index.js is imported for this purpose one might find they have inadvertently imported most of that entire Module.
Lastly, this sort of set up does tend to yield to a lot of duplicated bootstrapping code for each Module. While I'm sure this could be alleviated with a little ingenuity and forethought doing so might also suffer from the same kind of abstractions that we've been striving to avoid.
Conclusion
I hope you have been inspired to use Redux in a slightly different and specific way knowing that the benefits of organization really does evaluate to gained momentum. Have fun, push the boundaries, and as always, learn something new.
Happy Coding!
Stephan Meijer
Nov 21, 2016
If you were using redux-define you could reduce the boilerplate of defining action types.
Especially when using status suffixes like
ERRORor
SUCCESS, it can make a big difference.
Turning your example
Into
Stephan Meijer
Nov 21, 2016
Anand Reddy Rikka
Dec 19, 2016
A Continuous Learner and passionate coder
Very nice post @michaelgilley I'm implementing a similar approach you proposed for my PoC.
Caleb whiting
Jan 6, 2017
Thanks a lot! I've been struggling to maintain a disorganized app for a long time, but I think the concepts you have presented here will do the trick!
Michael Gilley
Jan 6, 2017
Frontend Engineer at Zapier
Jaroslaw Zabiello
Nov 21, 2016
This all can be done much simpler and more declarative than Redux Saga. You have to look at Cerebral's signals and it's excellent function tree, it can be used not only in Cerebral, but also in Redux or Mobx.
Michael Gilley
Nov 21, 2016
Frontend Engineer at Zapier
Vedran Blazenka
Nov 22, 2016
I build web apps with JavaScript, React, ES2015+, Node and other JS libraries!
Question regarding this statement:
Do you have some kind of solution for this?
I find myself using one container that is connected to Redux store and passing everything to my children. Result of that is a lot of returning in mapStateToProps and mapDispatchToProps.
One logical solution for me is to separate one big container to maybe 2-3 smaller containers for easier tracking of what is imported and connected.
Is there anything else you can advise?
Thanks! :)
Michael Gilley
Nov 22, 2016
Frontend Engineer at Zapier
Caner Dağlı
Nov 21, 2016
Engineer // Developer
Thanks for the great post Michael. What if two different modules have common components? How would you organize that?
Michael Gilley
Nov 21, 2016
Frontend Engineer at Zapier
Prashanth Acharya M
Nov 23, 2016
For importing module across features i like Jack hsu () implementation.
Michael Gilley
Nov 24, 2016
Frontend Engineer at Zapier
Tony Brown
Oct 3, 2017
American Space Ninja
Great write up. I worked for HPE as a contractor and we had the task of building a marketplace for HPE employees (data scientists). It was a huge application to say the least, we had data lakes, several databases. We used Docker swarms and had micro-services and followed "best practices". Redux was a great way to maintain application state, and helped get the MVP up and running in a few months, which IMO was amazing!
Tony Brown
Oct 5, 2017
American Space Ninja
pramod
Feb 20, 2017
#Frond end developer, #ui, #javascript
Great post hugely helpful application-skeleton while developing large applications.
Hannah McCain
Oct 2, 2017
thanks for this post! can you point me in the direction of any literature that goes into more depth on the idea of only posting from components — no dispatch? i'd love to learn more.
Michael Gilley
Oct 4, 2017
Frontend Engineer at Zapier
|
https://hashnode.com/post/tips-for-a-better-redux-architecture-lessons-for-enterprise-scale-civrlqhuy0keqc6539boivk2f?utm_campaign=Fullstack%2BReact&utm_medium=web&utm_source=Fullstack_React_48
|
CC-MAIN-2020-10
|
refinedweb
| 2,457
| 52.39
|
You can have Spread automatically merge cells between columns or between rows if the cells have the same value based on the policy that you set. The component can automatically combine cells that have the same contents. You might want to do this, for example, when bound to a database, as shown in the figure below where the cells in the Year column merge where the year value is the same, as with 1995 and 2003.
Unlike spanning cells, merging is an automatic feature. You tell the component which columns and rows allow cells to be combined automatically, and any cells within that set that have the same contents are combined for you.
For more information on spanning cells, refer to Creating a Span of Cells.
The policy you set determines how the component handles merging, as follows:
You can have the cells in the specified row or column combine the cells automatically, or only combine them if the cells to their left (in columns) or above them (in rows) are merged. Typically, if you set the merge policy on several adjacent rows or columns, then you would use Always on the first row or column and Restricted on the remaining rows or columns.
Merged cells take on the properties of the top-left merged cell. For example, if the top-left merged cell has a blue background color, the cells that merge with it display the same background color.
Merged cells do not lose their data; it is simply hidden by the merge. If you remove the merge, the data appears in each cell that was in the merge. You can edit a cell that is merged with another cell. When you double-click the cell to turn edit mode on, the contents of the cell appear in the cell for you to edit them. When you leave edit mode, if the contents of the cell are no longer identical to the cell or cells with which it was previously merged, the cells are no longer displayed as merged.
Cells that are different cell types but have the same contents can merge. For example, a date cell might contain the contents "01/31/02" and the adjacent edit cell might contain the same contents; if the column containing the cells is set to merge, the cells will merge. If the contents change or the merge is removed, the cells maintain their cell types as well as their data.
To set cells to be merged if they have the same value, use the following members:
For more information on these members, refer to the SheetView class (or the Row or Column class) or the DefaultSheetAxisModel of the FarPoint.Win.Spread.Model namespace.
Use the SetColumMerge or SetRowMerge method for the Sheets or ActiveSheet shortcut object.
This example code sets the row and column merge policies for all rows and all columns.
Set the SetColumMerge or SetRowMerge method for a SheetView object.
This example code merges columns and rows.
|
https://www.grapecity.com/spreadnet/docs/online-win/spwin-cellmerge.html
|
CC-MAIN-2021-49
|
refinedweb
| 498
| 66.78
|
Want more? Here are some additional resources on this topic:
The following code example demonstrates how to create a text file and write text to it using the StreamWriter class, which is defined in the System.IO namespace. The StreamWriter constructor takes the name of the file to be created. If the file exists, it is overwritten (unless you pass True as the second StringWriter constructor argument).
The file is then filed using the Write and WriteLine functions.
// text_write.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;
int main()
{
String^ fileName = "textfile.txt";
StreamWriter^ sw = gcnew StreamWriter(fileName);
sw->WriteLine("A text file is born!");
sw->Write("You can use WriteLine");
sw->WriteLine("...or just Write");
sw->WriteLine("and do {0} output too.", "formatted");
sw->WriteLine("You can also send non-text objects:");
sw->WriteLine(DateTime::Now);
sw->Close();
Console::WriteLine("a new file ('{0}') has been written", fileName);
return 0;
}
|
http://msdn.microsoft.com/en-us/library/19czdak8(VS.80).aspx
|
crawl-002
|
refinedweb
| 154
| 56.55
|
(For more resources related to this topic, see here.)
Manifest file
Many application details are specified in the manifest file. Thus, we will modify it to set the correct application name, description, as well as choose suitable tile images. we can adjust these settings on the Application UI page in the Manifest Designer.
Basic configuration
As presented in the following screenshot, set the Display Name field to Space Aim 3D, and adjust the Description field as well. What is more, we should choose the suitable App Icon, which is an image with size 100 x 100 pixels. It represents our application, thus we should provide the game with a proper icon that the user can easily recognize.
In the exemplary game, the icon shows the planet and a few asteroids, which are the main elements in the game. What is more, the image contains the game title. It is important, because we clear the content of the Tile Title setting. Thus the user will not see additional small text with a name of the application, after pinning the tile to the Start screen.
Tiles
Apart from some basic settings, we can also choose tile images. They will be shown on the default tile when the player taps the game to the Start screen.
we can also create secondary tiles, which could navigate to particular locations inside the application. However, such a solution is not shown in this article.
The Windows Phone 8 platform supports three kinds of tile templates: flip, iconic, and cycle. They differ by a way of presenting content. Of course, we can select a suitable one also in the Manifest Designer by choosing an option from the Tile Template list.
The flip tile template is the default option, which allows we to present two sides of the tile and flip between them. Thus, we can present the game logo on the front side and some more information on the other side. The tile flips automatically. we can specify settings regarding the background images, titles shown on the front and back sides, the content presented on the other side, as well as the number displayed on the tile.
The iconic tile template shows the content in a bit different way. Here, a small icon is used to present the application, together with an optional number, for example, regarding received messages in our project. Of course, we can set some properties, including the tile title, the image, as well as the background color.
The cycle tile template is the last available type, which makes it possible to present up to nine images that are changed automatically. Thus, it can be a suitable way to present a tile for the application which works with many images. In case of the cycle tile template, we can also adjust a few settings, such as the title or the shown images.
Tiles can be available in three sizes: small (159 x 159 pixels), medium (336 x 336), and large (691 x 336). The small and medium ones are mandatory, while the large one is optional.
With the usage of the Manifest Designer, it is very easy to prepare the basic version of the default tile for the application, just by selecting a suitable template type and choosing images which should be shown on the tile, depending on its size. we can also enable or disable the support for a large tile.
After adjusting the tiles, we may receive a result as shown in the following screenshot:
As we can see, the tile is presented in three various sizes: small, medium, and large. What is important, we do not just rescale the image, but provide three separate images in particular sizes, which look good regardless of the tile size. Here, we can also find the Space Aim 3D shortcut in the application list. However, we can expect that it appears in the Games group instead. Fortunately, we do not need to worry about it, because after downloading the game from the store, its shortcut will be shown in the proper place.
As we could remember, the flip data template, which we chose, can present two sides of the tile, but now we do not see this effect. Thus, in the following part of this section we will learn how to configure the default tile to support flipping and how to set the background image and the content at the back. To do so, we should open the WMAppManifest.xml file, but not in the Manifest Designer. we need to choose the View Code option from the context menu of this file.
What is interesting, the XML code contains information that we had set in a graphical way. Thus, it can be an additional way of adjusting some settings and adding more complex features, which are not supported directly by the Manifest Designer. The TemplateFlip node, specified in the WMAppManifest.xml file, is as follows:
<TemplateFlip> <SmallImageURI (...)> (...) </SmallImageURI> <Count>0</Count> <BackgroundImageURI (...)> (...) </BackgroundImageURI> <Title></Title> <BackContent>Let's avoid asteroids and reach the target planet!</BackContent> <BackBackgroundImageURI></BackBackgroundImageURI> <BackTitle>Space Aim 3D</BackTitle> <LargeBackgroundImageURI (...)> (...) </LargeBackgroundImageURI> <LargeBackContent>Let's avoid asteroids, reach the target planet, and see players in the vicinity!</LargeBackContent> <LargeBackBackgroundImageURI(...)></LargeBackBackgroundImageURI> <DeviceLockImageURI></DeviceLockImageURI> <HasLarge>True</HasLarge> </TemplateFlip>
Here, we specify the BackContent, BackTitle, and LargeBackContent elements to adjust a way of presenting the back side of the tile. The first setting is a string which will be displayed on the other side of the medium-sized tile. The second setting is the title shown on the back side (regardless of the tile size), while the other is a string shown on the large tile.
When we deploy the application to the emulator or the phone, and tap it to the start screen, we should see that the tile flips automatically, and it should present some additional content on the back side. What is more, it differs depending on the tile size, as shown in the following screenshots:
The Windows Phone 8 platform also supports live tiles, which present the content received from the Internet and are updated automatically. Such a kind of tiles can use either the push notifications or the local notifications.
Remaining settings
we have completed the basic configuration of the application, as well as learned how to set up the default tile. However, a few other modifications are necessary on the Packaging tab. Here, we specify the author and publisher data, as well as a version of the application. Other tabs (Capabilities and Requirements) remain unchanged, because we made the required modifications earlier.
Rating by the users
While designing the web screen, we created the button which should allow the user to rate the game. we can easily implement this functionality with the MarketplaceReviewTask class, which is another launcher used in the exemplary game. we need to modify the Rate method of the webViewModel class, as shown in the following code snippet:
private void Rate() { MarketplaceReviewTask task = new MarketplaceReviewTask(); task.Show(); }
Here, we create a new instance of the MarketplaceReviewTask class (from the Microsoft.Phone.Tasks namespace) and call the Show method. When this part of code is executed, the review page is opened, where the user can rate and review the current application.
Release version
The development environment for programming the Windows Phone 8 applications is equipped with many advanced features regarding their debugging. Such functionalities may require a bit different form of the code, which can be executed slower, but provide the developers with additional possibilities during development. For this reason, it is important to prepare the release version (retail) of the game before publishing.
we can easily generate the release version of the .xap file (with the data of wer application) using the IDE. To do it, we should change two options located next to the green triangle, and a selection of the emulator or device, as shown in the following screenshot. Here, we should indicate that we want to use the Release mode, as well as the ARM platform. Then, we should select Build and Rebuild Solution options to generate the suitable version of the .xap file. Now, we can proceed to the process of testing our game and preparing for submission to the store!
Store Test Kit
Some testing operations are simplified by the Store Test Kit, which allows to perform a set of automatic and manual tests. They can be used to verify many requirements that should be met to accept the application in the store.
we can open the tool by choosing the Open Store Test Kit option from the context menu of the SpaceAim3D project (not solution), or by choosing the Open Store Test Kit entry from the Project menu. The tool contains three pages: Application Details, Automated Tests, and Manual Tests. we will learn how to use all of them in this section.
Application details
In the first page we should specify some details regarding the application, including the store tile image with size 300 x 300 pixels. Apart from it, we need to choose a set of screenshots for each supported screen resolution. It is important to add at least one screenshot and not more than eight. Each of them should be provided in proper resolution, that is, 480 x 800 (WVGA), 768 x 1280 (WXGA), and 720 x 1280 (720P).
The Application Details page is shown in the following screenshot:
In case of applications running in the landscape mode (as in case of wer game), we should provide images that are not rotated, that is, as captured in the emulator.
we can make screenshots either in the emulator (using the Screenshot tab in the Additional Tools window) or on the phone. In the latter case, we should press the Start and power buttons. When a screenshot is taken correctly, a shutter sound is played and the image is saved in a suitable album.
The Application Package field is a read-only textbox, where a path to the .xap file is shown. It is worth mentioning that it indicates the Release version for ARM, thus it is exactly the same version as we generated earlier.
Automated tests
The second page is named Automated Tests. By clicking on the Run Tests button, we run a basic verification of wer project regarding the submission requirements, for example, whether the .xap file size is correct, as well as we provide the suitable icons and screenshots. If all tests are passed, we will receive a result as shown in the following screenshot. Otherwise, some additional notes are shown. In such a situation, we need to fix errors and run the tests once again.
It is important to note that passing all automated tests does not mean that the application does not contain any errors which could prevent the project from being accepted in the store.
Manual tests
Additional verification can be performed manually, by using the Manual Tests tab in the Store Test Kit. Here, we have a list of test cases and their descriptions. we should follow them and manually indicate whether the test is passed or failed as shown in the following screenshot:
Simulation Dashboard
The exemplary game may be used in various conditions, often significantly different than our testing environment. For instance, the player can have a limited access to the Internet or switched off the location services. For this reason, we should try to test our project in many situations. Such a process can be simplified by the Simulation Dashboard tool. we can open it by choosing the Simulation Dashboard option from the Tools menu. Its window is shown in the following screenshot:
This tool makes it possible to simulate some specific network conditions, by choosing a proper network speed and signal strength. we can choose 2G, 3G, 4G, Wi-Fi, and No Network options as the speed, as well as Good, Average, and Poor as the Signal Strength. Thus, we can check how our application behaves if we need to download some data from the Internet using the slower network connection, or even whether the game responds correctly in case of no network access.
Apart from the network simulation, the Simulation Dashboard allows we to lock and unlock the screen just by choosing a suitable option from the Lock Screen group.
The last supported testing feature is named Reminders. Just after pressing the Trigger Reminder button, the reminder is shown in the emulator. Thus, we can easily check how wer application reacts in such a situation.
Windows Phone Application Analysis
Apart from testing the project in real-world conditions, it is important to check its performance and try to eliminate problems in this area. Fortunately, the Windows Phone Application Analysis tool is integrated with the IDE, and we can use it to measure the performance of various parts of our game. The tool can be started by selecting the Start Windows Phone Application Analysis option from the Debug menu.
After launching, we should have the Execution option selected, thus we can click on the Start Session (App will start) element. It automatically starts our game in the emulator, if it is selected as the target. Then, a process of collecting data is started, and we can use the application in various ways to check the performance of its several areas. For instance, we can start by spending some time on the Menu screen, then we launch the game and play ten levels, return to the menu, and open additional screens (such as Ranks, Map, or World). When we want to finish collecting performance data, we should click on the End Session (App will exit) option. Then, the process of collecting data stops and the report is created, which can take some time.
The .sap file is generated for each analysis session. It is saved in the directory of the managed project, and can be later opened and analyzed using the IDE.
The Windows Phone Application Analysis tool presents a lot of important data related to the game performance, including both the managed and the native parts. The graph, presented in the main part of the window, shows the CPU usage at a particular time, as shown in the following screenshot. we can easily analyze which part of our application causes performance issues, and we may try to improve them.
As we can see in the preceding screenshot, the performance results for the Space Aim 3D game are expectable and reasonable. In case of the Menu screen, the CPU usage is very low. It grows significantly for the Game page, but here we need to perform a lot of operations, for example, related to rendering many objects in the 3D game world. What is interesting, the CPU usage grows slightly while consecutive levels, but also on the tenth level, the game works smoothly both in the emulator and on the phone. As soon as we exit to the main menu, the CPU usage decreases almost immediately. The remaining part is related to opening the following game screens: Ranks, Map, World, and others.
The possibilities of the Windows Phone Application Analysis are not limited only to drawing the graph of the CPU usage. we can also see the Hot Path information, which lets us know what part of code uses the most processing power. In our case, it is the region that renders 3D objects on the screen, using Direct3D. What is more, we can click on a name of the particular function to open another view, which shows more details. By using the tool, we can even analyze the performance of particular lines of code, as shown in the following screenshot:
Available features make it significantly easier to find a bottleneck causing performance problems. By running the Windows Phone Application Analysis tool multiple times, while making modifications in the code, we can see how wer changes reflect in the performance.
Frame rate counters
In this article we learned how to use a few tools for testing the application, but we have already used one that also has some features related to testing. It is the emulator, which can show a few numbers next to the edge. They are named frame rate counters and are shown in the following screenshot:
The debugger type for UI task should be set to Managed Only to see the frame rate counters. we can adjust this setting in the managed project properties.
The first two values represent the number of frames per second for updating the screen (the first one) and running of the UI thread (the other). Apart from them, we can monitor some additional results, including the texture memory usage.
Certification requirements
Each application submitted to the store should meet many requirements, specified at the website. They are related to various aspects and are divided into some groups, including:
- App policies –
- Content policies –
- App submission requirements –
- Technical certification requirements –
we should carefully read these policies before submitting the application to the store and adjust the project to comply with all applicable ones. The exemplary game is related to many requirements, including the following:
- your app must provide in-app settings that allow the user to enable and disable wer app's access to and use of location from the Location Service API (point 2.7.3)
- Game apps must be categorized as Games (point 3.11)
- The app must be compiled using retail configuration instead of debug. The app must not contain debugging symbols or output (point 4.2.3)
- For each app, we must provide at least one or up to a maximum of eight screenshots for each supported screen resolution (point 4.6)
- The app must render the first screen within 5 seconds after launch (point 5.2.1)
- For games, when the Back button is pressed during gameplay, the game can choose to present a pause context menu or dialog or navigate the user to the prior menu screen. Pressing the Back button again while in a paused context menu or dialog closes the menu or dialog (point 5.2.4.4)
Of course, many requirements are common for various types of applications, such as a necessity of a quick launch. However, some of them are dedicated to particular kinds of projects, including applications that run under a locked screen, share photos, as well as play background audio. we should check which requirements are related to our application, and ensure that all of them are met before publishing.
Publishing in the store
When we complete testing wer game, we can start the submission process. It contains many stages and part of them is presented in the following diagram (based on):
The process starts with the Not completed status. Then, it changes to, for example, Signing passed and Certification passed. At the end, the submission process is in the Published state. Of course, some problems can occur while analyzing the application before publishing in the Windows Phone Store. Then, the process can be moved to some other states (for example, Signing failed or Certification failed).
we can get the current state of the submission process using Dashboard.
Application information
To start the submission process, open the website, navigate to Dashboard, and click on the Submit app and App info options. Then, we can specify the application alias (defining how the application is named in the Dev Center, for example, Space Aim 3D), category (for example, games), subcategory (for example, action + adventure), as well as choose a suitable pricing, market distribution, and distribution channels.
The Windows Phone 8 applications and games can be distributed in two ways: beta and in the public store, as presented in the following diagram:
In the beta testing, the application can be downloaded and installed only by a limited set of beta testers, defined by the author of the submission. What is more, the application is not visible in the store while browsing through it. Regarding the public release, anyone can access our game, of course according to some additional restrictions set in application details.
Using the beta testing mechanism is a very good way to improve the quality of the final version of our application or game. Additional beta testers could find errors, propose changes, and give we great feedback that could be beneficial for the further work on the project. It is important that the beta version will automatically expire after 90 days since its first submission. What is more, the beta testers need Microsoft accounts.
we can also decide whether our game should be automatically available in the store as soon as it is certified or we will add it manually later. The trial version of wer project can be prepared as well. Thus, the users can try it for free, but with a limited functionality or for a limited period of time. While submitting the game, we can also select game ratings certificates, which may be required in some countries. Of course, various settings mentioned earlier can be either active or inactive depending on previous selections. At the end, click on the Save button.
Map credentials
The last required modifications in the code, which we need to take before submitting the .xap file, are related to configuration of the map services. They should use correct credentials, which we can obtain from the Windows Phone Dev Center. To do so, click on the Map services and Get token options. Then, let's save the generated values, namely Map service ApplicationID and Map service AuthenticationToken. At the end, click on the Close button.
The Map services option is unavailable for beta applications.
View model
The process of setting the proper application ID and authentication token will be performed by the MapViewModel class. Here, we should add two private constant fields representing these settings (MAP_APPLICATION_ID and MAP_AUTHENTICATION_TOKEN) and assign them the values obtained earlier from the Windows Phone Dev Center.
Then, we should prepare the SetMapCredentials method, which updates the maps settings. Here, we set new values of the ApplicationId and AuthenticationToken properties, as shown in the following code:
public void SetMapCredentials() { MapsSettings.ApplicationContext.ApplicationId = MAP_APPLICATION_ID; MapsSettings.ApplicationContext.AuthenticationToken = MAP_AUTHENTICATION_TOKEN; }
View
we need to set the credentials when the Map control is loaded. Thus, we handle the Loaded event (in the MapPage.xaml file), as shown in the following code snippet:
<Controls:Map (...) (...) </Controls:Map>
Then, we call the SetMapCredentials method (on the MapViewModel instance) inside MapPlayers_Loaded.
we should not forget to rebuild the project (for ARM platform in the Release mode) to create the new version of the .xap file for submission.
XAP submission
Now we can proceed towards submitting the .xap file, by choosing the Upload and describe our XAP(s) option. When the page is loaded, click on the Add new hyperlink, and select the .xap file. Then, the uploading process is started. we need to wait until it is completed, which can take some time, depending on the file size. It is worth mentioning that the maximum size of the .xap file is 1 GB.
The .xap file (for example, SpaceAim3D_Release_ARM.xap) should be available in the Bin\ARM\Release folder inside the directory of the managed project.
After uploading, we need to complete the form with the data regarding the project. Here, we specify, for example, the version number, description, as well as URL of website with the privacy policy. What is more, the details read from the .xap file are presented. we should also upload some images, including the application icon and screenshots. Of course, we can use the same as previously chosen while preparing the game details in the Store Test Kit. It is important that the application details can be provided in many languages. The correct language version will be chosen automatically based on the currently set language on the user's phone.
To complete this step of submitting the project, click on the Save button. It navigates we to the page where we can review the provided information and either go back to edit it or submit it. When we select the second option, we have just finished submitting our first game to the store! Now, we should wait for the e-mail message with further information.
If we submit the beta application, we will receive information about its availability soon, together with an address to the website where we can download the game. Then, we can open it on the mobile device, install, and try it! Of course, other beta testers can test our project in the same way.
Regarding the public release, a process of certification can take significantly more time, but we will receive information when it is completed or some errors occur.
Updating submission
While the game is being used, we may like to fix some bugs as well as introduce new features. However, we may not want to create a new separate application in the Windows Phone Store, but just replace the current one. Thus, the users can easily update it.
A process of updating the submission also uses the Windows Phone Dev Center. Here, we need to click on the Apps option on the left, which opens the page with the data of our applications. After choosing a suitable one for editing, we can click on the Update app hyperlink. Here, we choose the Upload and describe wer XAP(s) option and click on the Replace link located next to the information about the previously uploaded .xap file. When the new version is sent, we can update the version number and some additional details, as well. At the end, we just click on the Save button, confirm modifications, and submit the form.
Summary
In this article, we learned how to configure Windows Phone 8 applications and games, as well as how to test them and submit to the store. Thus, they can be available to people from many countries all over the world. The first part of the article was related to the configuration using the manifest file. We learned what basic information can be provided, as well as how to prepare tiles. Next, we allowed the users to rate our project after clicking on the button in the Web screen. Then, we created the release version of the .xap file.
In the following section, we got to know how to test the application or game using tools integrated with the IDE. we used the Store Test Kit, Simulation Dashboard, Windows Phone Application Analysis, as well as frame rate counters. They are equipped with a set of features making testing easier and can be used to improve the software quality. It is worth mentioning that these modules allow we to test not only the basic configuration of the project, but also its performance and behavior in the real-world conditions.
In the last part of the article we learned how to publish our project in the Windows Phone Store. we got to know how the submission process is organized, as well as how to restrict access to our submission only to beta testers. Thus, our game can be tested by a limited set of users. After the testing period, we can resubmit the application and make it available in the public store.
Resources for Article :
Further resources on this subject:
- Managing and Displaying Information [Article]
- Introduction to Game Development Using Unity 3D [Article]
- Interface Designing for Games in iOS [Article]
|
https://www.packtpub.com/books/content/game-publishing
|
CC-MAIN-2015-18
|
refinedweb
| 4,549
| 61.36
|
Participants
Julie Meloni
Joe Gilbert
John Scofield
Jessie Keck
Chris Fitzpatrick
Rick Johnson
Dan Brubaker-Horst
Bess Sadler
Agenda: Progressive Enhancement & Unobtrusive Javascript
Graceful Degradation vs. Progressive Enhancement
Progressive Enhancement:
Fully functional & fully tested without any javascript, then add JS behaviors
Graceful Degradation:
Starting from full JS functionality and making it degrade gracefully
We want to use the Progressive Enhancement approach.
Current State of the Hydra Javascript
There is a lot of javascript. Too much javascript
- takes too long to load into the page
- difficult to debug
- hard to maintain/extend/refine
Many javascript features do not degrade gracefully. Even less (none?) are progressively enhanced.
Basic observation: There are 4 different approaches at play in the code (confusing, hard to debug)
- Some inline javascript
- Event-driven javascript – ok in spots, but not ok as overall arch
- Rails-ish, page-specific javascript controller (ie. edit.js, show.js)
- Plugins – ie hydraMetadata
Other observations:
- Submission form currently requires ajax. Would require multiple submit buttons if ajax disabled.
- Fluid Framework is problematic
New Approach in Blacklight: (Jessie will follow up with more info)
What should be done?
- All features progressively enhanced
- Less (lines of) Javascript
- No inline javascript
- Put code in consistent places
- No javascript includes in view templates. They should go in Rails controllers
- Javascript should not change css
Accessibility
- Ensure Valid Markup!
- Section 508
- ... Julie will provide more reference info
Q: Where should you put the code that specifies which js to load for a particular page?
A: Hold off on that question. Wait and see what conventions come out of Libra.
Should we have a cucumber step definition for "And the html should be valid"?
This would rely on a network connection. Should keep that in a separate cucumber namespace.
Possibly define a single features/valid_html.feature that runs through all of the pages and runs the validity check...
Getting rid of Fluid Framework
This is revisiting an old topic. Yes we should get rid of all Fluid dependencies. They have already been removed from Libra. They should be removed from Hydrangea (and any other Hydra heads) in anticipation of the next Libra merge.
How will it be done?
Using Libra as a straw man for identifying conventions
Libra goes into production this week. UVa has cleaned up many parts of the javascript
- reduced the overall amount of javascript loaded
- removed dependency on Fluid framework
- squashed bugs
- cleaned up html
- addressed some accessibility issues
They will be documenting what they changed, how and why. We can use this code as a straw man for identifying conventions around javascript behavior.
In the meantime, Hydrus / Hypatia development proceed with NO javascript
Hydrus & Hypatia developers will
- remove the javascript includes from Hydrus & Hypatia
- leave the javascript files unouched -- allows us to retain any potentially important javascript customizations
- implement & test all features with javascript disabled
This provides the foundation for using progressive enhancement approach in all features of all hydra heads. Once we decide on javascript conventions, we will enhance these features according to those conventions.
Meanwhile, work on a solution for Automated Testing of JS
John Scofield will proceed with setting up a solution for automated testing (HYDRA-276), trying out the solution described at
|
https://wiki.duraspace.org/display/hydra/Committers+Call+2011-04-04+-+Progressive+Enhancement
|
CC-MAIN-2018-05
|
refinedweb
| 532
| 54.42
|
Many programmers always argue that the problems in Competitive Programming always end up with TLE(Time Limit Exceed). The Main problem of this error is that it will not allow you to know that your solution would reach to correct solution or not!
Why TLE comes?
- Online Judge Restrictions: TLE comes because the Online judge have some restriction that it will not allow to process the instruction after certain Time limit given by Problem setter usually (1 sec).
- Server Configuration: The exact time taken by the code depends on the speed of server,architecture of server,OS and certainly on the complexity of the algorithm. So different servers like practice, codechef, SPOJ etc may have different execution speed. By estimating the maximum value of N (N is total number of instructions of your whole code), you can roughy estimate the TLE would occur or not in 1 sec.
MAX value of N Time complexity 10^8 O(N) Border case 10^7 O(N) Might be accepted 10^6 O(N) Perfect 10^5 O(N * logN) 10^3 O(N ^ 2) 10^2 O(N ^ 3) 10^9 O(logN) or Sqrt(N)
So after analyzing this chart you can roughly estimate your Time complexity and make your code within the upper bound limit.
- Method of reading input and writing output is too slow: Sometimes methods used by a programmer for input output may cause TLE..
- In Python, you could try speeding up your solutions by adding the following two lines to the start of your file:
import psyco psyco.full()
- Bounds of loops may be reduced : Read the bounds in the input carefully before writing your program, and try to figure out which inputs will cause your program to run the slowest. For example if a problem tells you that N <= 100000 or N<=1000000, and your program has nested loops each which go up to N, your program will never be fast enough.
- Optimize your Algorithm: If nothing works after all this, then you should try changing the algorithm or the approach you are using to solve your problem. Generally , the internal test cases are designed in such a way that you will be able to clear all of them only if you choose the best possible algorithm.
- Look for Suggestions given: Although this should be the last step but you must look at the comments given below any problem in which other programmers might have given a hint on how the problem can be soved in a better and more efficient way. T.
|
https://www.geeksforgeeks.org/overcome-time-limit-exceedtle/
|
CC-MAIN-2018-09
|
refinedweb
| 427
| 60.89
|
04 March 2010 22:56 [Source: ICIS news]
By Ivan Lerner
NEW YORK (ICIS news)--The global chemical industry can expect margins to expand beginning in 2010 and earnings to recover - and with them, mergers and acquisitions (M&A) to return, a US chemical financier said on Thursday.
Tim Wilding, managing director for ?xml:namespace>
Wilding was speaking at a luncheon in
For 2009, M&A activity was down “but not out”, said Wilding.
There was a significant pick up in activity in the 2009 fourth quarter, with a 61% increase over the third quarter and an 89% increase over the 2008 fourth quarter. Wilding projects that pick-up continuing into 2010, with the pace of deal activity accelerating into 2011.
“Despite all the… gloom and doom, corporate
But what may occur in the near-term “is probably the last [major] wave of industry consolidation” to be seen for a while.
Chemical stocks have consistently outperformed broader indices over the last year, noted the financier. This is partially the result of industry “overreaction to the downturn”, said Wilding.
Several companies exceeded analysts’ expectations in the recent quarter. Some
Performance has been driven by both genuine growth and a restocking of inventory, Wilding said.
From a peak of $2,600bn (€1,590bn) in chemical industry M&A deals in 2007, global M&A activity declined to its 2004 levels of roughly $1,500bn in 2009, he said.
Wilding said it would be “tough to get back to 2007 levels”.
Compared with the rest of the world, the M&A activity of US-based companies has also decreased on a proportional basis, he said.
In 2004, 36.5% of M&A deals involved American companies, but that declined to 19% in 2009.
Additionally, there are fewer deals being done with specialty chemical companies. In 2003, about 70% of the global M&A activity involved specialties. By 2009, however, that was down to 24.6%, Wilding.
|
http://www.icis.com/Articles/2010/03/04/9340161/chem+industry+ma+should+expand+in+2010+2011++us+exec.html
|
CC-MAIN-2013-20
|
refinedweb
| 323
| 54.32
|
When you interact with the outside world, the iostream library is the way to go in C++. As always you have to keep a few rules in mind. Let me show, which rules.
The C++ core guidelines gives a good overview to iostreams:
Suprisingly for me and in contrast to the fact, that iostreams are quite important and are used by the most C++ developers there are only five rules which a deal with them and this rules have not much content. Here are they:
printf
ios_base::sync_with_stdio(false)
endl
To make a story out of the rules, I have to add additional information. This is not necessary for the first rule:
First, here is the bad example from the guidelines. Using character-level input for more than one character:
char c;
char buf[128];
int i = 0;
while (cin.get(c) && !isspace(c) && i < 128)
buf[i++] = c;
if (i == 128) {
// ... handle too long string ....
}
To be honest, this is a terrible solution for a simple job. My remark does not hold for the right way to do it:
string s;
s.reserve(128);
cin >> s;
Presumably, the better way is also the faster way.
The next rule states a no-brainer.
The question is now: How can we deal with bad data? Each stream has a state associated.
Flags represent the state of the stream. The methods for dealing with these flags need the header <iostream>.
Examples causing the different states of a stream
std::ios::eofbit
std::ios::failbit
std::ios::badbit
stream.fail() returns whether std::ios::failbit or std::ios::badbit is set.
stream.clear()
stream.clear(sta)
stream.rdstate()
stream.setstate(fla)
Operations on a stream have only an effect if the stream is in the goodbit state. If the stream is in the badbit state, it can not be reset to the goodbit state.
// streamState.cpp
#include <ios>
#include <iostream>
int main(){
std::cout << std::boolalpha << std::endl;
std::cout << "In failbit-state: " << std::cin.fail() << std::endl;
std::cout << std::endl;
int myInt;
while (std::cin >> myInt){
std::cout << "Output: " << myInt << std::endl;
std::cout << "In failbit-state: " << std::cin.fail() << std::endl;
std::cout << std::endl;
}
std::cout << "In failbit-state: " << std::cin.fail() << std::endl;
std::cin.clear();
std::cout << "In failbit-state: " << std::cin.fail() << std::endl;
std::cout << std::endl;
}
The input of the string wrongInput causes the stream std::cin to be in std::ios::failbit state. Consequently, wrongInput and std::cin.fail() cannot be displayed. First, you have to set the stream std::cin in the goodbit state.
You can show your output with printf or with iostreams. My tip is obvious.
The following two program displays two times the equivalent formatted data. First, by using printf and a format strings; second, by using iostreams and format manipulators.
// printfIostreams.cpp
#include <cstdio>
#include <iomanip>
#include <iostream>
int main(){
printf("\n");
printf("Characters: %c %c \n", 'a', 65);
printf("Decimals: %d %ld\n", 2011, 650000L);
printf("Preceding with blanks: %10d \n", 2011);
printf("Preceding with zeros: %010d \n", 2011);
printf("Doubles: %4.2f %E \n", 3.1416, 3.1416);
printf("%s \n", "From C to C++");
std::cout << std::endl;
std::cout << "Characters: " << 'a' << " " << static_cast<char>(65) << std::endl;
std::cout << "Decimals: " << 2011 << " " << 650000L << std::endl;
std::cout << "Preceding with blanks: " << std::setw(10) << 2011 << std::endl;
std::cout << "Preceding with zeros: " << std::setfill('0') << std::setw(10) << 20011 << std::endl;
std::cout << "Doubles: " << std::setprecision(3) << 3.1416 << " "
<< std::setprecision(6) << std::scientific << 3.1416 << std::endl;
std::cout << "From C to C++" << std::endl;
std::cout << std::endl;
}
As promised, the same output:
Okay, but why should you prefer iostreams to printf? There is a subtle but critical difference between printf and iostreams. The format string with printf specifies the type, and the format of the displayed value, the format manipulator with iostreams specifies only the format. To say it the other way around: The compiler deduces the correct type automatically in case of an isotream.
Let me make my point clear. When you had a bad day or are new to C++ and specify the wrong type in a format string, you get undefined behaviour.
// printfIostreamsUndefinedBehaviour.cpp
#include <cstdio>
#include <iostream>
int main(){
printf("\n");
printf("2011: %d\n",2011);
printf("3.1416: %d\n",3.1416);
printf("\"2011\": %d\n","2011");
// printf("%s\n",2011); // segmentation fault
std::cout << std::endl;
std::cout << "2011: " << 2011 << std::endl;
std::cout << "3.146: " << 3.1416 << std::endl;
std::cout << "\"2011\": " << "2011" << std::endl;
std::cout << std::endl;
}
This is how undefined behaviour looks like on my local PC.
Of course, the compiler usually writes in case of a wrong format string a warning, but you have no guarantee. Additionally, I know what often happens when the deadline is passed. You ignore the warnings and maybe, will look at it later. Instead of dealing with errors, don't make errors in the first place.
The difference between printf and iostreams reminds to the most important design guideline from Scott Meyers: "Make interfaces easy to use correctly and hard to use incorrectly."
I used in the iostream example format specifiers. To make your life as a software developer easier, you should keep a few of the format manipulators in mind. Let me show in my next post, which ones. 2382
All 4316715
Currently are 173 guests and no members online
Kubik-Rubik Joomla! Extensions
Read more...
Read more...
|
https://www.modernescpp.com/index.php/c-core-guidelines-iostream
|
CC-MAIN-2020-34
|
refinedweb
| 911
| 66.23
|
Problem
You need to store items in a sequence, but your requirements don't match up well with a vector. Specifically, you need to be able to efficiently add and remove items in the middle of the sequence, not just at the end.
Solution
Use a list, declared in , to hold your data. lists offer better performance and more flexibility when modifying the sequence at someplace other than the beginning or the end. Example 6-5 shows you how to use a list, and shows off some of its unique operations.
Example 6-5. Using a list
#include #include #include #include using namespace std; // A simple functor for printing template struct printer { void operator( )(const T& s) { cout << s << ' '; } }; bool inline even(int n) { return(n % 2 == 0); } printer strPrinter; printer intPrinter; int main( ) { list lstOne; list lstTwo; lstOne.push_back("Red"); lstOne.push_back("Green"); lstOne.push_back("Blue"); lstTwo.push_front("Orange"); lstTwo.push_front("Yellow"); lstTwo.push_front("Fuschia"); for_each(lstOne.begin( ), // Print each element in the list lstOne.end( ), // with a custom functor, print strPrinter); lstOne.sort( ); // list has a member for sorting lstTwo.sort( ); lstOne.merge(lstTwo); // Merge the two lists and print for_each(lstOne.begin( ), // the results (the lists must be lstOne.end( ), // sorted before merging) strPrinter); list intLst; intLst.push_back(0); intLst.push_back(1); intLst.push_back(2); intLst.push_back(3); intLst.push_back(4); // Remove all values greater than 2 intLst.remove_if(bind2nd(greater( ), 2)); for_each(intLst.begin( ), intLst.end( ), intPrinter); // Or, remove all even values intLst.remove_if(even); }
Discussion
A list is a sequence provides constant complexity for inserting or deleting elements at any position, but it requires linear complexity to find elements. lists are usually implemented as a doubly linked list, which means that each element is stored in a node that has a pointer to its previous and next elements in the sequence. It meets all the requirements of a standard sequence container, plus provides a few unique member functions.
Declaring a list is straightforward, just give it the type of the elements you're going to store in it, and, optionally, specify a memory allocation class:
list > // The memory allocator // to use
The Value template parameter is the type of the elements that will be stored in the list. It must be a type that supports copy construction and assignment. Allocator is the memory allocation class to use; the standard allocator is the default (and will be sufficient for most of your needs).
Following is a typical list declaration (from Example 6-5):
list lstOne;
After you've declared your list, put some things in it with push_front or push_back, like this:
lstOne.push_back("Red"); // Add these to the end of the list lstOne.push_back("Green"); lstOne.push_back("Blue"); lstTwo.push_front("Orange"); // Add these to the beginning lstTwo.push_front("Yellow"); lstTwo.push_front("Fuschia");
Pushing elements on a list takes constant time, but not amortized constant time as with a vector. A list implementation does not need to occasionally resize its buffer, so you won't have the intermittent performance penalty you would with a vector. The list will just have to update a handful of pointers, and not much else.
Use pop_front or pop_back (no arguments) to remove elements from the beginning or end of the list. Despite their name, the "pop" member functions don't return the popped element, as you might expect à la typical stack semantics; to get a reference to the element at the beginning or end of a sequence, use back or front.
Typically, a list looks like what is displayed in Figure 6-2. Each node has (at least) three parts: the object it contains, a pointer to the previous node, and a pointer to the next node. For the rest of this recipe, I will refer to the next and previous pointers as next_ and prev_.
Figure 6-2. A doubly linked list
Once you see how a list is implemented, it's probably obvious why some of the operations have different complexity than a vector. Adding an element anywhere in the list requires only that the preceding and following items have their next_ and prev_ pointers adjusted. One nice thing about lists is that only iterators pointing to the affected object(s) are invalidated when you insert or erase elements. Iterators to other elements are unaffected.
The insertion and deletion methods are insert and erase. insert takes an iterator as its first argument, and either an object of type T, a number and then an object of type T, or an ending iterator as its second argument. The iterator points to the item that is to have the insert performed immediately preceding it. Each of the insert overloads is used like this:
list strLst; list::iterator p; // ... string s = "Scion"; p = find(strLst.begin( ), strLst.end( ), // std::find from "Toyota"); strLst.insert(p, s); // Insert s right before p strLst.insert(p, 16, s); // Insert 16 copies of s right before p strLst.insert(p, myOtherStrLst.begin( ), // Insert everything in myOtherStrLst.end( )); // myOtherStrLst before p
Erasing elements is similar:
p = find(strLst.begin( ), strLst.end( ), // std::find from "Toyota"); strLst1.erase(p); // Erase this element strLst2.erase(p, strLst.end( )); // Erase p to the end strLst3.clear( ); // Erase all elements
In addition to the standard container member functions, list provides a few interesting ones. The first is splice .
splice does what it sounds like: it splices two lists together. Here's how I could have spliced lstTwo into lstOne in Example 6-5:
list::iterator p = // Find somewhere to insert the other std::find(lstOne.begin( ), // list lstOne.end( ), "Green"); lstOne.splice(p, lstTwo); // Insert lstTwo right before "Green"
p is an iterator that refers to an element in lstOne. lstTwo is inserted into lstOne immediately preceding p. As with an insertion, all that really needs to be done here is to change the next_ and prev_ pointers on the affected nodes, so this operation takes constant time. lstTwo is empty after you splice it into lstOne, which is why it is not a const parameter. You can also insert a single element from lstTwo into lstOne, or a range of items from lstTwo. In both cases, the items that are spliced in are removed from the originating list.
If your lists are sorted (list has its own sort member function; std::sort won't work with a list), and you want to merge them together and preserve their sorted order, use merge instead of splice. merge will combine the two lists into one, and if two elements are equivalent, the one from lstOne comes first in the final list. As with splice, the argument list is empty afterward.
list also has some cool aggregate operations for removing things. Imagine that you want to erase all occurrences of an element. All you have to do is call remove with an argument that, when compared to each item in the list, will give (*p == item) != false, where p is a list iterator. Call remove like this:
strLst.remove("Harry");
This will remove all elements from strLst where el == "Harry". If you want to remove elements that satisfy some other predicate, such as being larger than some value, use remove_if instead:
bool inline even(int n) { return(n % 2 == 0); } list intLst; // Fill up intLst... intLst.remove_if(even); // Removes all elements where even(*p) // is != false
If your predicates are more complicated, consider using some of the functors in . For example, if you want to remove elements that are greater than some value, you can use greater (from ) and bind2nd combined with remove_if:
intLst.remove_if(std::bind2nd(std::greater( ), 2));
This will remove all values greater than 2 from intLst. The syntax is a little esoteric, but what's happening is straightforward. bind2nd takes two arguments, a function object (call it f) and a value (v), and returns a function object that takes a single argument (arg) and invokes f(arg, v). bind2nd is a slick way to do just this sort of thing without having to write a bunch of little functions.
A list is a good alternative to vector when you need a standard sequence container. list's different internal representation permits it to provide different complexities for many of the standard sequence operations and a few interesting operations of its own.
See Also
Recipe 6.1
Building C++ Applications
Code Organization
Numbers
Strings and Text
Dates and Times
Managing Data with Containers
Algorithms
Classes
Exceptions and Safety
Streams and Files
Science and Mathematics
Multithreading
Internationalization
XML
Miscellaneous
Index
|
https://flylib.com/books/en/2.131.1/storing_objects_in_a_list.html
|
CC-MAIN-2021-21
|
refinedweb
| 1,421
| 55.34
|
.)
QueryExp
Query]
"Cascading or Federation means that it is straightforward to import MBeans from a remote MBean Server as if they were local.."
but this means that cascading also virtualize connection and synchronization with remote mbeanServer? i.e. what happens if connection with remote mbServer goes down, or an Mbean mirrored has been unregistered from its remote mbeanServer?
thanks
Posted by: lukebike on February 14, 2008 at 12:42 AM
These are excellent questions, and we have given considerable thought to them. The blog entry I referenced described an implementation where the imported MBeans were represented by "mirror MBeans" locally, which means you do have to decide how synchronization works. But the design in the JMX API makes use of the new namespace support so that for example a reference to foo//bar:type=Baz can be forwarded directly to the remote server that is federated as "foo", where it is seen as a reference to bar:type=Baz. That means that if an MBean is unregistered from the remote server then it is immediately inaccessible in the local server too, and if the connection to the remote server breaks then accesses to its MBeans will get exceptions. You can also add a listener to the namespace in order to be informed when the connection breaks. See the class javax.management.namespaces.JMXServiceURLNamespace in the API documentation.
Posted by: emcmanus on February 14, 2008 at 01:07 AM
maybe it's a stupid question, but where can I download jmx2.0 jar??
thanks
Posted by: lukebike on February 14, 2008 at 07:11 AM
Not a stupid question at all. The jar currently isn't available publicly but we're working on it. Stay tuned!
Posted by: emcmanus on February 14, 2008 at 07:22 AM
ok!
Posted by: lukebike on February 14, 2008 at 07:40 AM
|
http://weblogs.java.net/blog/emcmanus/archive/2007/12/jmx_api_20_earl_1.html
|
crawl-002
|
refinedweb
| 308
| 51.89
|
I downgraded to aurora before a month because CM11 was very slow(at least the last versions). I was waiting for CM12 to give another try.
I'm thinking of doing a first CM12 release. Almost everything works, I'm just now improving the memory allocation in Wi-Fi driver and updating accelerometer & magnetometer drivers. The only major issue is 720p recording, which produces green recording on stock camera & Google camera. Other camera apps procued correct 720p recording though.
Since Lollipop uses ART, I also enabled dex preoptimization. Without that first boot would take more than 20 minutes, and gapps would increase it even further. However enabling the preoptimization increases /system size to over 500MB, so BlePart-2 is becoming too small. I have to make another partition table for it, and it takes some time as updating partition table is very complicated. There is also a LVM partition table method, which would be a lot safer, however I am still investigating if it's worth it on our phone.
Requirements
28.10.2014 Adjusted proximity sensor threshold to match stock. Fixed bogus data sometimes coming from light/proximity sensor. Minor adjustments to display backlight adjustment. Added rmt_oeminfo binary to solve some issues with modem. Reverted to dzo's CPU table. Adjustments to power_profile.xml (changes Settings->Battery usage info). Increased Synaptics resume delay from 50ms to 100ms (should improve TS resume from sleep). General changes in kernel code. Wi-Fi: Changed deep sleep settings. Wi-Fi: Added back GPIOs. Wi-Fi: Removed GPIO27 configuration. 07.09.2014 Added error checks for pmem_wrapper. Added support for flush_pmem_file/fd in pmem_wrapper. Enabled newer APANIC_MMC driver. Fixed a security bug in net. Fixed NG (noise gate) enable in TPA2028D1. Increased SF heap size by 2MB. Reverted to 2.6.32 speaker & handset microphone config. Reverted to 2.6.32 speaker & speaker amplifier config (should greatly improve music quality & loud speaker in calls). Reconfigured Atmel TS with 2.6.32 parameters (greatly improving experience, reducing touch freeze to nearly zero). Made proximity sensor report initial value after enabling (fixing proximity wake if enabled). Improved magnetic sensor calibration code. Disabled RIL debug socket (not working anyway). Process RIL response codes properly (unsolicited). Added support for getDataCallProfile in RIL. Minor cleanups in camera HAL. Disabled continuous auto-focus in preview mode (apps that support continuous-video can still use). Store all ifaces properly in RIL (fixes MMS). Supply active/status in RIL. Rearranged media_codecs.xml Enabled Qualcomm HW MP3 decoder. Added entries for tcp delayed ack. Fixed keyboards error with home key declaration. Supply gateway with data call parameters in RIL. Removed TARGET_ARCH_LOWMEM (testing). Remove unused console entry when booting up (ttyDCC0 is not available on u8800 by default). Wi-Fi: Remove all unused GPIOs. Wi-Fi: Make sure wlan2 regulator is at 2.5v. Wi-Fi: Disable pmapp vreg voting (may fail, which causes high power usage). 03.08.2014 Disabled gapless mode (fixes some issues when LPA is enabled). Removed ffmpeg h263/h264/mpeg4 entries (covered by HW & Google). Updates to power HAL (from LX). Increase light sensor multiplier to 5.0f Use auto-brightness mapping from m7. Sample proximity sensor data for both close/far. Disabled MDP retire fence. Remove more dead code from camera HAL. Use custom virtual key mapping in recovery. Fix BT power entries (in reversed order). Added informative BT power class. Enabled BT In-Band Sleep. Increased BT serial baud-rate to 3MB. Removed unneeded libmm-omxcore from build. Disabled display HAL patch for PMEM support. Enabled ION support in camera HAL. Moved camera HAL out of Android namespace. Enabled PMEM->ION wrapper (pmem now uses ION memory). Added support for continuous auto focus (experimental). Wi-Fi: Enable FW to handle probe requests. Wi-Fi: Remove XO core voting. Synced with kk_2.7-stable Minor updates to ION cma heap. Updated BFQ scheduler to v7r5. Minor updates to various kernel drivers. Disabled voltage battery driver (not used right now). Delay Synaptics resume 50ms (experimental). Disabled fluence in qdsp5v2. Converted qdsp5v2 devices to ION. Enabled Huawei battery driver (sends consumer events to modem). Increase light/proximity sensor delay .5 ms. Get battery voltage from modem. Do not allow RPC to reconnect on reboot call. 27.06.2014 Make sure accelerometer/magnetometer/touch screen power regulators are turned on/off when needed. Minor changes with APS-12D driver. Extend the list of CPU frequencies (experimental). Reboot/shutdown is now faster in kernel side (IRQ is disabled properly). Recovery: ADB sideload now works for zips up to 220MB. Disabled FMEM for PMEM_ADSP heap. Enabled CMA for PMEM_ADSP heap (increases available total memory when camera is not used). Minor adjustments in kernel board code. Disabled unsupported BT features (BLE, SMP). Removed junk on init.qcom.rc. Code optimizations in camera driver. Wi-Fi: Sync with volans. Wi-Fi: Add back XO buffer controls. Wi-Fi: Make sure device mode is correct without P2P enabled (after volans sync). Wi-Fi: Use board provided MAC address on Huawei U8800 (after volans sync). Wi-Fi: Start/Stop SME sessions without completion variables (after volans sync). Wi-Fi: Add back RF settling time config (after volans sync). Wi-Fi: Set low SD clock frequency. 17.06.2014 Enabled BFQ IO scheduler (v7r4). Enabled deadline IO scheduler. Removed unused modules. Added cifs module. Changed interrupt line to low (should help with TS issues). Wi-Fi: Disabled early suspend deep sleep. Wi-Fi: Sync with volans (includes changes to qcom_cfg.ini). Added support to auto-update recovery (must be enabled manually in development options). Decreased BT startup time by nearly one second. Increased BT buffer size to 1024. Supress wakelocks when RIL gets unsupported message. Patched multiple Linux kernel security bugs. Patched some kernel panics. Enabled MM to use CMA heap (more memory when video encoder/decoder is not in use). Enabled PMEM ADSP heap to use FMEM (more memory when camera is not in use). Updated to kk-2.7-stable. Added deferred timers to KSM. Increased audio buffer size. Added availability to use phone as USB keyboard/mouse () Disabled EXT2 (EXT4 handles it). Disabled VCAP (not used). Disabled video adapters & tuners (not used). Disabled unused ethernet drivers (not used). Set LSM mmap minimum address to 4096. Enabled faster USB scheduler. Use default memory allocator (SLUB). Disabled KGSL shadow writes (should solve some GPU errors). Enabled various networking options. Added new Synaptics driver. Increased MM heap size (some apps failed to use video decoder). Changed DCDC bus config (used for charger). Enabled RCU boost. Enabled APANIC driver (on hard crash, logs dumped to /data/dontpanic/) Removed CMUpdater (as it is not useful on this ROM). 16.05.2014 Fixed SIM lock status (can now be enabled/disabled & changed properly). Added more CPU frequencies (1.5-1.8 GHz). Changed microphone configuration in handset & speaker mode (48KHz for all types, according to stock). Added newer Adreno libraries (AU_LINUX_ANDROID_KK_2.7_RB1.04.04.00.007.018). Patched a new exploit found in Linux kernel (). Temporary: partially reverted Theme Engine (fixes SystemUI lockups & high memory usage). 11.05.2014 Updated to kk-2.7-stable. Added BT/WLAN MAC address configuration to IDEOSX5Settings. Wi-Fi: Restart wlan module from start. Wi-Fi: Remove GPIO20 configuration (SD card detect on U8800). Wi-Fi: Read MAC address from kernel (on U8800). Wi-Fi: Sync with volans (fixes Wi-Fi hotspot). Restart audio, media codecs configuration. Restart audio policy configuration. Allow BT/WLAN mac address to be read from kernel (/sys/hwprops/) Reduced Torch low brightness (128 vs 64). If it's too dim you can always enable high brightness. Enable SD eject option. Fixed an issue where "Please replug headset" was shown after reboot (no need to replug in that case). Disable LPA (to manually enable, /system/build.prop : lpa.decode=true) Enabled ffmpeg codecs. 27.04.2014 Added S/N reading from kernel side. Synced wifi changes from prima (mostly code style related). Wi-Fi should now start always (bug introduced in the last release). Updated to kk-2.7-stable. Reverted to stock audio configuration. Added new TPA2028D1 driver. Improved Synaptics TS (should not freeze anymore). Increased USB power budget to allow more devices to connect. 06.04.2014 Added S/N reading. Adjust zRAM settings for better performance Adjust KSM settings for better performance Added /sdcard -> /storage/sdcard0 for some apps. hwmac -> hwprops Fixed wifi memory deallocation problem on exit. Added multiple changes to wifi from prima driver. Removed more dead code from the kernel. Fixed portrait videos rotation below 720p. Fixed camera EXIF data for maker & model. Fixed third party camera software (Focal). Added possibility to mask mass storage as cdrom (DriveDroid can benefit from this). Solved problem with display when sending "stop" & "start" commands. Using zRAM from 3.14 kernel. Updated to kk-2.7-stable. Reverted to default audio configuration (wip). 24.02.2014 AAC playback fixed. Fixed LEDs pulsing in wrong order. Notification->Attention->Battery (LED priority list). Reverted to older Synaptics driver (should fix lockups). Rebased kernel to kk_2.7_rb1.27. Fixed some volume/audio problems (need to be confirmed, speaker mode in call is still bugged). Fixed microphone not muting while in call. Fixed problems with FM radio volume (going loud when switching). Fixed sound recorder. Adjusted proximity sensor thresholds. Fixed battery capacity (using Huawei method for now). Enabled zRAM (thanks to @forumber2). 09.02.2014 Rebased kernel on kk_2.7_rb1.22 (minor fixes, better graphics performance). Fixed Synaptics TS freeze (finger not tracked) (not confirmed). Fixed display freezing on some targets. Added pulsing notification leds with customizable speed (hardware blinking). Fixed RIL without SIM. Fixed sometimes phone going very laggy (caused by RIL). Added FM radio support. Decreased speaker db range (should improve quality). Added v2 of DeviceSettings (now called IDEOS X5 Settings) Added support for customizable BT power. Added support for customizable charging current. Adjusted proximity sensor (50mA current lets more IR light through). Removed bloat from camera HAL (WiP). Rebased kernel on latest branch for KK (improves graphics & minor fixes). Added more codecs to support more audio/video formats. Fixed some VIDC memory leaks (causing video recording/playback problems). Removed unused adreno library & replaced with a new one. 19.01.2014 (These changes have been made upon the latest cm-10.1 version) Updated codebase to cm-11.0. Fixed camera flash. Fixed video recording. Fixed video HW playback. Applied some fixes to audio HAL. Fixed a problem where the charger was shown connected even though it wasn't. Applied smaller fixes to display driver. Released some unused memory. Using MDP retire fence (may fix some display problems). Removed some unused kernel drivers. Updated android kernel counterpart drivers (binder, lowmemorykiller) Updated freezer driver. Enabled SELinux. Added CMHW vibrator scaling (in Settings->more). Stripped vibrator tuning from DeviceSettings. Added modifiable button brightness. Added modifiable notification leds. Greatly reduced init.rc scripts. Enabled KSM. Added QCOM optimizations for faster CPU operations. Added support to multimount UMS (internal & external). Added support for /data encryption. Added torch with two brightness setting. Fixed some camera problems. Added Finnish translations to DeviceSettings (zazza97) Enabled QCOM Audio/Video enhancements. Enabled low_ram flag. Updated synaptics driver. Smaller fixes for APS-12D driver. Disabled highmem in kernel (should reduce the footprint a lil). Fixed Wi-Fi not starting problems. Reduced the time where display does not enter/exit sleep properly. Updated CPU power management driver. Updated FUSE driver (for SD cards). Removed some unused memory allocations. Build RIL daemon and libril from source. Removed some bloat in camera HAL.
|
http://forum.xda-developers.com/showthread.php?p=59429015
|
CC-MAIN-2015-14
|
refinedweb
| 1,919
| 63.96
|
React.js - Is there a way to grab props.match.params value before the render() method? - reactjs
I have a Post class which will dynamically display content from each post from the database depending on the params. My issue is that I want to use state, but the only time the match.params id value is available is during the render method - at which point I can't use set state because of infinite loops. As a work around I'm using local variables and only setting them in render if match.params is not null. But I ideally want to use state.
Is there a way to grab that param before the render method so i can use set state?
UPDATED TO SHOW CODE:
This bit is here is where I check to see the param and match it with the post from db:
render() {
if(this.state.props.match) {
post = this.props.data.posts.find(post => post.id == this.props.match.params.id );
}
}
Because match.params is only available at this stage, I can't do it when the component first loads as it would be null.
In that post object I have a comments object, and again I would like to assign but can't. So what I'm having to do is assign it to state when I make a POST request (thus a method and not render):
postComment = (e, postId, postComments) => {
e.preventDefault();
let data = {
comment: this.state.comment,
post_id: postId
}
if(this.state.comment != "") {
axios.post('', data)
.then(response => {
// handle success
console.log(response);
postComments.unshift(response.data);
this.setState({
});
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
This means that to display the comments, I then have to compare state with the comments object in post. If state is bigger than the other, i.e. a new value has been entered, map that one, else map the other otherwise existing comments won't get displayed:
{
this.state.comments > post.comments ?
this.state.comments.map(comment =>
<p key={comment.id}>{comment.comment}</p>
)
:
post.comments.map(comment =>
<p key={comment.id}>{comment.comment}</p>
)
}
It just feels a bit messy and working with one array in state would be cleaner.
this.state.props.match:
{path: "/blog/:id(\d+)", url: "/blog/2", isExact: true, params: {…}}
isExact: true
params: {id: "2"}
path: "/blog/:id(\d+)"
url: "/blog/2"}
So when clicking on post 2 (blog/2), the above will print, when clicking on 3, id would be 3 and so on
ok, so i had something similar to your problem. In general if your state depends on props, you can try to use getDerivedStateFromProps.
static getDerivedStateFromProps(props, state) {
post = props.data.posts.find(post => post.id == props.match.params.id );
if (post !== state.post) {
//add your magic here
return {
//return a new state....this is like calling setState
};
}
return null; // do nothing
}
Related
React state contains correct data initially but is overwritten by previous value
i have a state variable which is initially set to null. After getting data from server i update its state. In doing so.. it loads correct data for items with different ids. however on opening the item that was previously opened... sets the state with correct value. however it then overwrites the state value with previous opened item. I am not sure what going wrong. Below is the code, class Items extends React.PureComponent { constructor(props) { super(props); this.state = { item_details: null, }; componentDidMount() { this.load_item_details(); } componentDidUpdate(PrevProps) { this.load_item_details(); } load_item_details = () => { const file_name = 'item_details.json'; client.get_item_details_file(this.props.item_id, file_name, 'json') .then((request) => { this.setState({item_details: request.response}); })}; } Could someone help me solve this. thanks. Edit: This is how the output looks the first time i run the application clicking some item for the first time. Now when i click another item with id 8 it outputs correct data (from output state with array 25) however it is replaced with previous item details (from output state with array 806).
You have item_id inside method 1 and item_id inside method 8 in the second log. Looks like you send two simultaneous requests with different ids. Since data for item_id=1 is much larger than data for item_id=8 it arrives later and overwrites everything. Try to call load_item_details only when needed and use some flag to block simultaneous requests. ... this.state = { item_details: null, isLoading: false, }; ... componentDidUpdate(PrevProps) { if (PrevProps.item_id !== this.props.item_id) this.load_item_details(); } ... load_item_details = () => { if (this.state.isLoading) return; const file_name = 'item_details.json'; this.setState({isLoading: true}); client.get_item_details_file(this.props.item_id, file_name, 'json') .then((request) => { this.setState({item_details: request.response, isLoading: false}); })}; } Note that this code will not react to any changes to item_id while load_item_details is fetching data. And it will break on error inside client.get_item_details_file.
You probably have a typo on your code: load_item_details = () => { const file_name = 'item_details.json'; client.get_item_details_file(this.props.item_id, file_name, 'json') .then((request) => { this.setState({item_detail: request.response}); })}; } It should be this.setState({item_details: request.response})
State Updates After Second Load of componentWillReceiveProps and will not map
I am passing properties from a parent to the child and want to map the resulting array. When I try to console log the result, the properties only reach after the second time the function is called. The first time it returns "[]". Even when the state "users" array is recieved, mapping it does nothing. state={ users: null } componentWillReceiveProps(){ var userInLobby = this.props.users && this.props.users.map(userdata=>{ if(userdata.status === "online"){ var user = firebase.firestore().collection("users").doc(userdata.id).get().then(user=>{ return { username: user.data().username, }; }) return user }else{ return null; } }) var userInLobbyDisplay = [] userInLobby && Promise.all(userInLobby).then(values => values.map(user=>{ return userInLobbyDisplay.push(user) })) this.setState({ users: userInLobbyDisplay }) } render(){ console.log(this.state.users) return( <div className="lobby"> { this.state.users && this.state.users.map(user=>{ return user.username }) } </div> ) How can I map the users array from the state to the DOM when receiving props for the first time?
You are using a soon to be deprecated API, you should follow the documentation guidelines and switch to the newer APIs, specifically the new getDerivedStateFromProps You can read more here. static getDerivedStateFromProps(props, state) { // Your code here }
Cannot access state from ComponentDidMount() [duplicate]
This question already has an answer here: setState doesn't update the state immediately 8 answers In componentDidMount() I'm calling setQueryParams to set the query parameters into state which works fine. componentDidMount() { this.setQueryParams(); console.log(this.state.query); $.getJSON(`/search?${this.state.query}`, (response) => { this.addDiveCenters(response.centers) this.buildFilters(response.filters, false) }); console.log(this.state.query); } However, after the setQueryParams() call, console.log(this.state.query) is returning '' (the default state). After the page loads I can run $r.state.query and everything is perfect,but for some reason I cannot access the state! I need the initial state to make an AJAX call. Right now, every single page loads to /search because this.state.query is blank. setQueryParams = (param = null, value = null) => {() }); console.log(this.state.query); // doesn't display anything! }
It will take some time because this.setState behaves asynchronous this.setState has callback method which notify that state has been updated this.setState({ query: params.toString() },() => { // Do something here. }); Read this Solution :- componentDidMount() { this.setQueryParams(null, null, () => { console.log(this.state.query); $.getJSON(`/search?${this.state.query}`, (response) => { this.addDiveCenters(response.centers) this.buildFilters(response.filters, false) }); console.log(this.state.query); }); } Pass callback method in setQueryParams setQueryParams = (param = null, value = null,callback) => {() },callback); console.log(this.state.query); // doesn't display anything! }
State Updates May Be Asynchronous
The setState is an Async function, so it gets time to set your value as state and when you log the state value, the new value hasn't been set yet.
From the react docs: Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately. This is why you are not getting the response you expect immediately. However, somewhat confusingly, there are times when set state is immediate. However, you should never expect it to be. Since the state change is asynchronous, react provides a way to, ahem, react to the state after it has been changed, by means of a callback. So you can write code like this: this.setState({ query: params },(updatedState) => { console.log("updated state:", updatedState) });
React-redux project - chained dependent async calls not working with redux-promise middleware?
I'm new to using redux, and I'm trying to set up redux-promise as middleware. I have this case I can't seem to get to work (things work for me when I'm just trying to do one async call without chaining) Say I have two API calls: 1) getItem(someId) -> {attr1: something, attr2: something, tagIds: [...]} 2) getTags() -> [{someTagObject1}, {someTagObject2}] I need to call the first one, and get an item, then get all the tags, and then return an object that contains both the item and the tags relating to that item. Right now, my action creator is like this: export function fetchTagsForItem(id = null, params = new Map()) { return { type: FETCH_ITEM_INFO, payload: getItem(...) // some axios call .then(item => getTags() // gets all tags .then(tags => toItemDetails(tags.data, item.data))) } } I have a console.log in toItemDetails, and I can see that when the calls are completed, we eventually get into toItemDetails and result in the right information. However, it looks like we're getting to the reducer before the calls are completed, and I'm just getting an undefined payload from the reducer (and it doesn't try again). The reducer is just trying to return action.payload for this case. I know the chained calls aren't great, but I'd at least like to see it working. Is this something that can be done with just redux-promise? If not, any examples of how to get this functioning would be greatly appreciated!
I filled in your missing code with placeholder functions and it worked for me - my payload ended up containing a promise which resolved to the return value of toItemDetails. So maybe it's something in the code you haven't included here. function getItem(id) { return Promise.resolve({ attr1: 'hello', data: 'data inside item', tagIds: [1, 3, 5] }); } function getTags(tagIds) { return Promise.resolve({ data: 'abc' }); } function toItemDetails(tagData, itemData) { return { itemDetails: { tagData, itemData } }; } function fetchTagsForItem(id = null) { let itemFromAxios; return { type: 'FETCH_ITEM_INFO', payload: getItem(id) .then(item => { itemFromAxios = item; return getTags(item.tagIds); }) .then(tags => toItemDetails(tags.data, itemFromAxios.data)) }; } const action = fetchTagsForItem(1); action.payload.then(result => { console.log(`result: ${JSON.stringify(result)}`); }); Output: result: {"itemDetails":{"tagData":"abc","itemData":"data inside item"}} In order to access item in the second step, you'll need to store it in a variable that is declared in the function scope of fetchTagsForItem, because the two .thens are essentially siblings: both can access the enclosing scope, but the second call to .then won't have access to vars declared in the first one. Separation of concerns The code that creates the action you send to Redux is also making multiple Axios calls and massaging the returned data. This makes it more complicated to read and understand, and will make it harder to do things like handle errors in your Axios calls. I suggest splitting things up. One option: Put any code that calls Axios in its own function Set payload to the return value of that function. Move that function, and all other funcs that call Axios, into a separate file (or set of files). That file becomes your API client. This would look something like: // apiclient.js const BASE_URL = ''; const makeUrl = (relativeUrl) => BASE_URL + relativeUrl; function getItemById(id) { return axios.get(makeUrl(GET_ITEM_URL) + id); } function fetchTagsForItemWithId(id) { ... } // Other client calls and helper funcs here export default { fetchTagsForItemWithId }; Your actions file: // items-actions.js import ApiClient from './api-client'; function fetchItemTags(id) { const itemInfoPromise = ApiClient.fetchTagsForItemWithId(id); return { type: 'FETCH_ITEM_INFO', payload: itemInfoPromise }; }
ReactJS - mapped array not updating after ajax
I've got a simple component that renders a table. The rows are mapped like this: render () { return ( {this.state.data.map(function(row, i){ return <Row row={row} key={i}/> }.bind(this))} ) } The state is initialized in the constructor: this.state = { data: props.hasOwnProperty('data') ? props.data : [], route: props.hasOwnProperty('route') ? props.route : null } The data can be initialized in the DOM, or after, the route is passed to the container and bound correctly. In this case, I 'm doing it after in the componentDidMount method: componentDidMount () { axios.get(this.state.route) .then(function(resp){ this.setStateParametersFromAjax(resp); }.bind(this)) .catch(function(err){ console.log(err); }) } The setStateParametersFromAjax(resp) method is defined here: this.setState({ data: resp.data.data, }); This all works flawlessly on DOM load. However, there are buttons that will perform subsequent requests later on. These requests perform the same axios call. The problem is, that even though the state is updated (verified by adding a callback as the 2nd argument to the setState method and logging this.state), the DOM does not update. What do I need to do to make it so that the DOM updates with this new data as well? Edit I had simplified the code a bit, there is a method called fetch() that accepts an argument of params that defines the ajax call: fetch (params) { if(typeof params != "object") { params = {}; } axios.get(this.state.route, { params }).then(function(resp) { this.setStateParametersFromAjax(resp); }.bind(this)) .catch(function(err){ console.log(err); }) } The componentDidMount() method calls this on load: componentDidmMount () { this.fetch(); } When a button is clicked later, this calls a function that calls the fetch method with parameters: <li className="page-item" onClick={this.getNextPage.bind(this)}> Where the function is defined: getNextPage (event) { event.preventDefault(); this.fetch({ arg: val }); }
You should use a unique key value other than index. Even the state is updated, react may not update DOM if the key not changed.
|
https://html.developreference.com/article/10000233/React.js+-+Is+there+a+way+to+grab+props.match.params+value+before+the+render()+method%3F
|
CC-MAIN-2022-05
|
refinedweb
| 2,344
| 51.14
|
NAME
RSA_padding_add_PKCS1_type_1, RSA_padding_check_PKCS1_type_1, RSA_padding_add_PKCS1_type_2, RSA_padding_check_PKCS1_type_2, RSA_padding_add_PKCS1_OAEP, RSA_padding_check_PKCS1_OAEP, RSA_padding_add_PKCS1_OAEP_mgf1, RSA_padding_check_PKCS1_OAEP_mgf1, RSA_padding_add_none, RSA_padding_check_none - asymmetric encryption padding
SYNOPSIS
#include <openssl/rsa.h>
The following functions have been deprecated since OpenSSL 3.0, and can be hidden entirely by defining OPENSSL_API_COMPAT with a suitable version value, see openssl_user_macros(7):
int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen, const unsigned char *f, int fl); int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen, const unsigned char *f, int fl, int rsa_len); int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen, const unsigned char *f, int fl); int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen, const unsigned char *f, int fl, int rsa_len); int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen, const unsigned char *f, int fl, const unsigned char *p, int pl); int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen, const unsigned char *f, int fl, int rsa_len, const unsigned char *p, int pl); int RSA_padding_add_PKCS1_OAEP_mgf1(unsigned char *to, int tlen, const unsigned char *f, int fl, const unsigned char *p, int pl, const EVP_MD *md, const EVP_MD *mgf1md); int RSA_padding_check_PKCS1_OAEP_mgf1(unsigned char *to, int tlen, const unsigned char *f, int fl, int rsa_len, const unsigned char *p, int pl, const EVP_MD *md, const EVP_MD *mgf1md); int RSA_padding_add_none(unsigned char *to, int tlen, const unsigned char *f, int fl); int RSA_padding_check_none(unsigned char *to, int tlen, const unsigned char *f, int fl, int rsa_len);
DESCRIPTION
All of the functions described on this page are deprecated. Applications should instead use the EVP PKEY APIs.
The RSA_padding_xxx_xxx() functions are called from the RSA encrypt, decrypt, sign and verify functions. Normally they should not be called from application programs.
However, they can also be called directly to implement padding for other asymmetric ciphers. RSA_padding_add_PKCS1_OAEP() and RSA_padding_check_PKCS1_OAEP() may be used in an application combined with RSA_NO_PADDING in order to implement OAEP with an encoding parameter.
RSA_padding_add_xxx() encodes fl bytes from f so as to fit into tlen bytes and stores the result at to. An error occurs if fl does not meet the size requirements of the encoding method.
The following encoding methods are implemented:
- PKCS1_type_1
PKCS #1 v2.0 EMSA-PKCS1-v1_5 (PKCS #1 v1.5 block type 1); used for signatures
- PKCS1_type_2
PKCS #1 v2.0 EME-PKCS1-v1_5 (PKCS #1 v1.5 block type 2)
- PKCS1_OAEP
PKCS #1 v2.0 EME-OAEP
- none
simply copy the data
The random number generator must be seeded prior to calling RSA_padding_add_xxx(). If the automatic seeding or reseeding of the OpenSSL CSPRNG fails due to external circumstances (see RAND(7)), the operation will fail.
RSA_padding_check_xxx() verifies that the fl bytes at f contain a valid encoding for a rsa_len byte RSA key in the respective encoding method and stores the recovered data of at most tlen bytes (for RSA_NO_PADDING: of size tlen) at to.
For RSA_padding_xxx_OAEP(), p points to the encoding parameter of length pl. p may be NULL if pl is 0.
For RSA_padding_xxx_OAEP_mgf1(), md points to the md hash, if md is NULL that means md=sha1, and mgf1md points to the mgf1 hash, if mgf1md is NULL that means mgf1md=md.
RETURN VALUES
The RSA_padding_add_xxx() functions return 1 on success, 0 on error. The RSA_padding_check_xxx() functions return the length of the recovered data, -1 on error. Error codes can be obtained by calling ERR_get_error(3).
WARNINGS
The result of RSA_padding_check_PKCS1_type_2() is a very sensitive information which can potentially be used to mount a Bleichenbacher padding oracle attack. This is an inherent weakness in the PKCS #1 v1.5 padding design. Prefer PKCS1_OAEP padding. If that is not possible, the result of RSA_padding_check_PKCS1_type_2() should be checked in constant time if it matches the expected length of the plaintext and additionally some application specific consistency checks on the plaintext need to be performed in constant time. If the plaintext is rejected it must be kept secret which of the checks caused the application to reject the message. Do not remove the zero-padding from the decrypted raw RSA data which was computed by RSA_private_decrypt() with RSA_NO_PADDING, as this would create a small timing side channel which could be used to mount a Bleichenbacher attack against any padding mode including PKCS1_OAEP.
SEE ALSO
RSA_public_encrypt(3), RSA_private_decrypt(3), RSA_sign(3), RSA_verify(3), RAND.
|
https://www.openssl.org/docs/man3.0/man3/RSA_padding_check_PKCS1_OAEP.html
|
CC-MAIN-2022-40
|
refinedweb
| 694
| 50.57
|
StreamWriter Constructor (Stream)
Initializes a new instance of the StreamWriter class for the specified stream by using UTF-8 encoding and the default whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as StreamWriter. The BaseStream property is initialized using the stream parameter. The position of the stream is not reset.
The StreamWriter object calls Dispose() on the provided Stream object when StreamWriter.Dispose is called.
For a list of common I/O tasks, see Common I/O Tasks.
The following code example demonstrates this constructor.
using System; using System.IO; namespace ConsoleApplication { class Program { static void Main(string[] args) { string fileName = "test.txt"; string textToAdd = "Example text in file"; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.CreateNew); using (StreamWriter writer = new StreamWriter(fs)) { writer.Write(textToAdd); } } finally { if (fs != null) fs.Dispose(); } } } }
Available since 4.5
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
|
https://msdn.microsoft.com/en-us/library/wtbhzte9.aspx
|
CC-MAIN-2015-48
|
refinedweb
| 182
| 53.78
|
I need to list out data sources for some portal items using ArcGIS api for python, then get information for those data sources that only arcpy can provide.
Can arcpy be used in an ArcGIS api for python script?
I could make an arcpy script and use ArcGIS Rest API within it, but I'd like to leverage the new ArcGIS API for python if possible.
Thank you,
Randy McGregor
Solved! Go to Solution.
Thank you! I'm a bit embarrassed that it is that straightforward. I did have the impression that you couldn't directly access arcpy in this manner, but I was mistaken about that, apparently.
import arcpy
start a Jupyter Notebook or JupyterLab notebook run the import arcpy. You have access to arcpy and the tools in arctoolbox as well
Thank you! I'm a bit embarrassed that it is that straightforward. I did have the impression that you couldn't directly access arcpy in this manner, but I was mistaken about that, apparently.
Yes they can be used together. However, you need to use python 3 so you need to install pro.
Thanks. I do have pro installed.
Its as simple as import arcpy, arcgis (if you arent using notebooks)
So, if you're just making a "regular" python script with IDLE, import both arcpy and arcgis, then you have the both arcpy and arcgis api for python libraries?
Yes. That is exactly what I do!
I would suggest not, unless you need both arcpy and arcgis. Loading unnecessary modules into an IDE or script should be avoided for both performance and maintainability reasons. That said, arcgis loads arcpy for its own internal uses if arcpy is available, which is partially why loading arcgis takes so long relative to other packages.
>>> import sys >>> sys.modules.keys() & {'arcpy', 'arcgis'} set() >>> import arcgis >>> sys.modules.keys() & {'arcpy', 'arcgis'} {'arcgis', 'arcpy'} >>>
I haven't had any real problems with it.
|
https://community.esri.com/t5/arcgis-api-for-python-questions/can-arcpy-and-arcgis-api-for-python-code-be-used/td-p/778234
|
CC-MAIN-2022-27
|
refinedweb
| 321
| 65.62
|
It is religion which tells us how to spend life in every aspects of life. It has proved each and every thing that the modern science has proved now in 21st century but it has proved that aspects 1400 years before.
=================================
attorney directory
If Islam is the religion of peace why is this?
I once believed that, unfortunately, it now shoves planes through Buildings killing many many innocent people. I have no belief that that was the work of Allah, but rather a Human being.......Islam has become controlled just as Western religion has, it holds back people, whereas it should move them forward.
Islam is most definitely a religion of peace. No true Muslim condones terrorism, violence and murder of innocent men, women and children. A true Muslim does not put down other religions either.
I read some of the comments made about Islam and I was really shocked. I was shocked that all these people who are artistic and eloquent with their writing could be so harsh and ignorant.
I say ignorant because you must truly read an Islamic teaching to understand Islam not watch FoxNews or CNN.
Do not let the people who do perpetrate disgraceful acts give you your opinion of Islam. Talk to a Muslim, read a book, look up Islamic sites. Learn about the religion before you spew hatred.
Those who throw hatred toward an entire religion for what some have done are just as bad because you are spreading the dislike. And nothing good comes from spreading hatred.
Well - thanks for the input. Religion = good. People who do not suck up to religion = bad. very eloquent. You join just to tell us how awesome Islam is? Or was there a point here?
I sure as hell do not watch CNN or Fox. I make my decisions based on what people say and do. Not what your TV tells me to thanks.
Well I'm sorry that you feel the way that you do. I did not join HubPages to promote Islam. But I let my light shine by just being the best Muslimah I can be. I have opinions, thoughts, and truths about many subjects. You will see this in my writing.
I am who I am and you are who you are. Insha Allah(God willing) we learn from each other. I look forward to reading your hubs and I invite you to read mine. Much luck to you in your endeavors.
Well - seeing as you have no hubs yet....... But feel free to read mine. And I am quite happy making my own decisions thank you. But - you go ahead and repeat what you have been told to.
I totally agree that Islam is the religion of Peace and i was reading the 1st page post of this forum and some claimed it to be proved that Islam is the religion of Peace
I have some Own Points to discuss here
1. Every Religion teaches us good things and if any of the follower doesn't obey the religion then who is to be called wrong, the religion or the followers?
2. I'm a Muslim and my religion prohibits me to rape a girl yet i do then who is wrong, me or my religion?
Of course it's my fault because Islam doesn't teach us these things !!!
Here i would say, That Beard is known as Symbol of Muslims, Christ also kept beard and all the other Prophets did so and It to be obeyed by all the Christan, they must keep beard because they are following Christ, but they don't; here if i say the Christianity is not good religion, it would hurt the feelings of Christan and i don't want this to do,
Look Dear, USA is victim country where so much rapes happen (you may get the statistics) who lives in USA, Muslims? who do those rapes? MUSLIMS? Their crime rate is high, who do this?
obviously those who live there - and Their religion stops them to do all these, yet they do, it's their fault not of the religion.
Allah sent Prophets time to time on earth and Muhammad is the Last Prophet of Allah with a Book Qur'an, which not only tell you what to do and what no to do but also tell you how to do ...
when to do, what to think, how to live, what you should wear, who you can talk to, when you can talk to them, etc etc.
June 16 2009."
(The Asian News)
Sorry, what was that comment you made?
Lady I am with you on this..... Pakistan has too many fundamentalists... I did rate them as the most dangerous.... you gotta read this … post234449
This report of ICC was not showed in any of the local or international newspapers or news channels and if so please give me the reference. Also Pakistan is not the caliphate-islamic state. It's rulers are Honorary Freemasons.
Secondly, what will you say about Freemasonry and Zionism who is killing and butchering 1000s of innocents world wide, for instance, Paletine, Lebenon, Kashmir, Iraq, Afghanistan, Pakistan, Vietnam (in the past), Japan (past), Kosovo, chechnya, Bosnia ... and the list goes on and on ... what will you say about Atheist White Americans killing Black ones, the last century faced horrific tragedies against BLACKS of USA.
dear friend, lets talk about the solution please. you are muslim i respect for that but why are we here marketing our religion. this is why religion got poluted, because the way each of you spread. are every one of you racing with each other in the name of religion. WHY?
The Lady_E started it, i did'nt
Lol - you've been marketing your religion through so many threads here. So - at least be honest about that
dont defend, it will make you weaker, the more you defend the more you weaker will be, let it go, both of you not bad person indeed. how about starts to work on it, how? make others love islam and for that islam must show their love first,
i love you, it does not mean i can allow you put yourself into HELL. I will atleast present you the right way. Then it's your choice to follow or not, no obligation at all.
Have you gone to heaven ? How can you guide others?
Sure he has gone to heaven....in his dreams to enjoy the heavenly virgins...LOL
Of course - he hasn't, but he would like to think that he has!! That thinking of course comes from the arrogance of feeling superior in some way to other human beings - solely based on the relgion that he comes from!!!
Lol - so you want to save us all! I don't see any reason for converting. If I believe in God, I believe in God. I don't see any reason why I should subscribe to what one person's interpretation of God was or is.
I don't see the Quran as anything special or unique. It hasn't imbibed in its followers nonviolence or tolerance of other faiths. It has promoted dictatorial tendencies and regressive methods in parts of the world that have chosen to implement Shariah Law in its "purest form."
it's not implemented in it's purest form. Regarding tolerance, sorry, we can not tolerate so many rapes per day in USA or any other part of the world and we can not forgive them. ONLY DEATH PENALTY for rapists. God forbid, We can not watch you be raped again and again
The purest form = chopping off limbs/heads, stoning women for adultery, etc. Can you deny that? What's your preference - you would like to see implementation of such laws across the Muslim world?
As for "rapes in the USA" - that's a different topic. Maybe you can open another thread to discuss that. As far as I can see, this thread is named "Islam" - so stick to the topic.
who stonned women for adultry ???
Perhaps you need to Google some. What's the punishment for adultery in Islam?
1 - When an unmarried man and woman caught in adultery - they get 100 lashes each
Evidence 1: 4 sane persons scrutinized them having sexual intercourse.
Evidence 2: Acknowledgment of both guilty.
Evidence 3: DNA Tests.
2 - When a married man and woman caught in adultery - they get death penalty
Evidence 1: 4 sane persons scrutinized them having sexual intercourse
Evidence 2: Acknowledgment of both guilty.
Evidence 3: DNA Tests
3 - When a rapist rapes a woman - the rapist gets the death penalty not the woman.
Evidence 1: Acknowledgment of the victim only.
Evidence 2: Physical evidence of bodily scar/bruise/mark/damage, torn clothing etc of the victim.
Evidence 3: DNA Tests
Ouch!! I don't know what to say!!! Btw, are you saying that stoning of married adulterous women does not happen or is not prescribed by the Quran?
@Shil In case you haven't noticed... he keeps copy pasting the same thing.... He feels Allah has drilled a direct pipe into his brain.... Oops.... Usman's mind is closed for anything and everything that doesn't revolve around Freemasons or Zionists...LOL
how can you love me? when even your love for your family is not TRUE and how can you make me believe that you love me when there is no realisation of YOUR TRUE SELF, till you realise the word LOVE never exist within us. PLEASE understand it, i am not get you down. appreciate you
OK Usman. This was all over the news and the source I used above was Asian news. As for your second paragraph, lets not drift from the thread topic which was simply
"Islam is the Religion of Peace".
So, if you say that comment was not shown in any local newspaper, how about this one. I even heard it on the news:
Oct 2008
Female British Aid worker killed ‘because of Religion’
A female British aid worker has been killed by gunmen in Kabul because she was 'spreading Christianity,' it has been confirmed.
Two unidentified hitmen on motorbikes attacked Gayle Williams as she walked alone at 8am, the Foreign and Commonwealth Office said.
An FCO spokeswoman said: "We can confirm that a British national was shot dead in Kabul today. Next of kin have been informed."
Metro.co.uk News
May I add that this woman was helping the Country.
Dear Lady
who were the motorbikers ??? does any one know ???
If you figure them as Muslims, why can't they be Freemasons as the soldiers of Zionists are also there in Afghanistan.
Moreover, Afghanistan has got no Caliphate - Islamic State or Caliph rather an American Govt. Thoese Americans whose half population is born out of wedlock (illegitimate). For reference please take the following.
Mmmh. OK Usman. I think I’ll leave it here for now. Thanks for your responses. The world would just be a better and happier place if innocent lives are not cut short in the name of Religion.
A Salaam alei-kun.
@LadyE Don't even try reasoning with this guy.... he sees the whole universe infested with Freemasons and Zionists....LOL
Yes Islam is the Best religion in the world. There has always been the concept of black sheep. So there aRE SOME BLACK SHEEP in the Islamic countries but not all muslims are wrong and they dont want to blow them up. those people whichdo this are being misguided about Islam.
Islam Is the Best Religion.
It is religion which tells us how to spend life in every aspects of life.
It has proved each and every thing that the modern science has proved now in 21st century but it has proved that aspects 1400 years before.
It has given the rights of women but other religion they dont give as such rights for them which islam gives them ,specially in the 19th centuy they have not given the right of vote in the 17th century they have not the authority to touch the Holy book
Do you have any idea how stupid you sound saying islam is a religion of peace and then picking a fight with all the other religionists?
The sooner we get your religion back in the bronze ages where it belongs, the better.
there is no fight with others; why do u think if someone say christianity or islam.. religion of peace would bring fight; any religion should bring peace inside yourself and others; and this is so clear.
and also for your knowledge muslems believe in all books ( Torah, bible , Quran) came from one God within different stages; and because islam it's the last stage in God messages; and that's the reason many believers from jews and christian enter islam happy because they understood the messages.
if you believe in God, and you were jews believe in moses and torah; then, if you deny jesus and bible; God-the father- will never accept youbecause you deny God message.
and also if you are christian you belive in jesus and bible; then, you hear about Muhammad and the last book from God-Quran- and you deny it; God will not accept you.
islam just name equal the meaning of christianity; only because islam the last stage of God messages and islam present all of them.
but For God wisdom you believe or not- it's your choice no body will choose for you; and no body to blame except you-..
in the end ; i ask God to guide us to His right way all of you my brothers...
And I say the Torah Quoran and the bible all worship an abhorant, by-polar and hysterical sociopathic entity who scares the bloody daylights out of god-botherers who were indoctrinated at an early age, then bought up listening to this crap.
Kudos!
let us see, what happens.
Mark does have a point, your religion does have more extremist than any other religion. I would say if any religion is peaceful it is Buddhism or such.
I just wrote a hub on the terrorism that comes forth from Islam. Your holy book does state a jihad or holy war against all infidels..and that would be me since i don't agree with your religion.
I am not saying all muslims are violent...just your extremists and those who support extremists.
Dear Jew!
Qur'an does not state any holy war against infidels, it's your misconception which you got from international media. Jihad means to strive and struggle, it does not mean HOLY WAR. On the other hand, In some books of the Old Testament (for example, Joshua) commandments are given to commit horrible violence against non-Jewish peoples. Mass murder is commanded, with no regard for women, children or the elderly. This merciless savagery is totally against God's justice. Take for instance, the black history of CRUSADERS. Also the hisotory of SALAH UDIN AYUBI who when entered Jerusalam pardoned each and every non muslsim whether Jews or Christians and let them with the fair choice of stay in peace or leave in peace.
That also is a misconception God only required the complete annihilation of the race after they tried to destroy Israel. For example, they did not kill a pregnant woman once but had mercy on her. Later in life her child grew to hate israel and seek its destruction. If not for Esther asking the king of persia to spare the lives of the jews, they would have been killed. It was for this reason God had commanded it.
Yes, I do remember the black history of the crusade...but it is not commanded once in our bible to do that...it was wrong but history cannot be changed...only the future can be changed.
Extremist factions of Islam declare that Qu'ran state they must die in the name of allah to go to heaven killing an infidel...I don't know if the Qu'ran states this or not, but i do know this is what the extreme factions are saying. I having nothing against peaceful Islam. I had many friends in Israel who were Muslim. But I do not agree at all with such groups as Hamas, Hezbollah, Fatah, etc.
You see when Muslim governments are not doing their job to resist Israeli unjust invasion then these kind of groups develped to fill up the gape. Have a look at the maps of Israel in 1948 and now in 2009, it will become crystal clear how the Jews illegally captured Palestine despite the fact these Jews were welcomed by Muslims as guests in 1947 after being kicked out by Hitler. So, now what these guests did to the innocents of Palestine and their territory, the judgment is completely yours now.
may be because muslim countries are oppressed very much either by western leaders or by their friends (local leaders)
there is no problem with making Jihad aginst those who fight Muslims to change thier ideals or take their wealth
don't you think ?
altough , most wetern people are nice but there are also many have been fooled by the leaders to engage in what called good wars.
very obvious ?
Very obvious. And one of the tools they use is religion.
so , is there anything in Quran encourges Muslims to kill people just because they are infidels according to Islam ?
(by the way I am an infidel too according to other religions , it is not a bad word)
To be honest - I do not know the book that well. There are certainly muslimists who think it does.
And I am an infidel according to all religions except FSMism.
or may be they don't understand what in it
so do you pray in the kitchen for the great FSM or enjoying his sons is enough to be grateful
No - It Is Written That We Must Toast Him With Red Wine.
No question. Oddly enough He Commands all the same things I agree with. Strange how Perfect His Noodlyness is. And of course, He Came after all the other minor religions to Unite Mankind in Friendship and Pasta.
Ramen
Where is the famous christian acceptance and brotherhood?
You are kidding right? Did you just join HubPages to propagate this. If so, stay on and try and prove all that you are saying with FACTS. Also, try and explain what is going on in the SWAT area of Pakistan, where the Taliban have gone on a school-buring spree. IMHO, I don't see Islam evolving - only regressing with time. It seems the followers just want to follow the Book that was written 1400 years before. Apparently, Islam can't be adapted to modern times. So, we have Shariah Law being asked for by the Taliban and being grated by the Pakistani Govt in Pakistan. Kinda gives you an idea of where Islam is headed.
name one law in Shariah prevents modern life evolution
you would say; some muslims
show me where it says in Islam to do so.
I don't know if its an error or anything. Frankly, I wouldn't care less, and I'm not making fun of anyone either. I just like the phrase...spend life in every aspects of life.
It means it can be spent on killing, butchering, rapeing, sex, loot, raid, plunder, gamble, drink, decieve ..................
If islam is the religion of peace, why do all the islam church members love to blow themselves and other people up? Huh? It is definitely NOT the religion of "peace". Christianity is!
--John
\
"all the islam church members"??
Well hey! It's my good buddy oh boy everybody. Did you go back an eat your words yet? Do I hear an apology?
John, You have a complete misconception of Islam and I am Christian you need to study World Religions and study the Ka'ran as that is not true. Christianity is a branch of religion and Jesus was originally a Jew , who became Christianities Lord and Saviour. True Christians would not blasphemy other religions when you are holding your head high as a Christian you have to ask yourself WWJD? Can you lead others to Christ by acting the way you do? Christianity is not the religion of Peace either as look at what you are doing you are yelling, shame on you.
And I dont mean to yell. Im not actually yelling. Im typing like im yelling but im not yelling. I dont even mean to yell. Well, type like i am yelling.
John- I can't even get a retraction from you? Whats your deal? Too immature? Or are you really that dumb?
\
Hmm, I dont know. I guess we just like to post on the same forum topics. Something wrong? Immature? How???
John, Be nice WWJD??? you do owe her an apology, that would be the right thing to do.
you are welcome ... but try to be nice
please fix yourself
Of course, if i am doing something wrong, then obviously it's not the fault of the religion. Consider, someone gets a latest BMW and he/she can not drive and sits on the driving seat and just bangs up the car. Now, who will be blamed. The car or the driver. If you want to test Islam then judge it by the best person who is Prophet Muhammad (pbuh).
C'mon let's get real and admit that he's right...
again;...
The ones who blow themselves up are name sake muslims, acting as mercenaries, constantly fed by Zionists. Look around it's happening all over the world, Sudan, Pakistan, SriLanka, Palestine. They use to buy these kind of people from both sides, government and non - government (rebells / taliban etc) and make them fight, spread terror and demoralize Islam or any other system which itches their beloved systems of capitalism, zionism, freemasonary etc.
dear Islam is the religion of peace. what you are saying is not the way of Islam but different reasons are behind that, those may be psychological, economical or racial etc.I'm a hindu by religion but I have a belief and faith On Islam because Islam gives Complete and better solution to our life as well as hereafter.
Better for who? I feel confident in saying not many muslims follow the idea of blowing anything up. It is those who insist that others follow their doctrine who are to blame on all sides of the argument including self proclaimed christians and others as well who are indoctrinated with hatred and fear.
Islam is a great religion. But so is Christianity, Hinduism, Buddhism, Jewism et al. What is your point anyway?
You have a point.
Sadly, the majority of the Western wall has a bad view of Islam because of only a small number of them.
I know some people who are Islamic, none of them want to blow themselves up. It's the extremists we need to worry about, and of course we do. Due to the media, we fear the man on the train with the rucksack, if he is of a certain ethnic persuasion.
Personally, I believe that one of the largest and most successful terrorist groups in the world, is the media. The definition of a terrorist
"a radical who employs terror as a political weapon; usually organizes with other terrorists in small cells"
Hmm, kind of sums up the media. If they stopped making everything sound so "Hollywood" and stopped making it seem like it's much worse than it actually is, then it might quieten down the extremists.
Sadly, the only thing that's likely to stop all of this, is a couple of 20 megaton Nukes served up about 5am.
I'll give you that one.
"Western wall has a bad view of Islam because of only a small number of them"?
The Truth is the extremist are not true Muslim but are brain washed Muslim who think they are acting in the name of Ala. The 99.9999999999% of Muslim are good law abiding citizens and not a threat to society.
You know, I have a question. I am a Christian and when come across Christians in my personal life who try to oppress other people I will say something about it. So do Muslims who are against violence know other Muslims who are for violence? And if so, what do they do about it? I always wondered about that? Because I know 2 Muslim people who are great ambassadors for their culture and I feel really bad for them because of the rep their religion has. If I needed it they would give me the shirt off their back. So I always wondered about this.
I am really coming to the conclusion that it was neither them, or Christians or any other religion that put enmity between us, but more like a snake who puts words in to confuse and set people against each other.
I know some Muslims too and I went to a Mosque and just asked them myself. She women there said, (and she was very kind and lovey person) something to the effect of, now they aren't really of God are they?
It actually blew my mind. I was thinking doyee, how did I miss that one. The most obvious answer. I also asked her why Muslims are fighting Christians. She said, no what they do is what they do but for us in Islam, it means peace and we love Jesus.
Then she asked me if believe Jesus is God. I said no, she said do you believe Jesus is the son of God. I said sure, that is what they call him. And she said, no God does not have a son but Jesus is a prophet.
I said ok, doesn't bother me none, then I asked why they are fighting over that. She said they are not. But some people want to make you think that they are.
I also asked her, if we are all God's Children then how come Jesus cannot be the son of God. And she said, when you put it that way, then yes he is but this isn't something that people understand.
- and of course there was a lot more to understand about it but it's for me to say-
Agreed. I'll be back in a few hours. We could chat. ciao
please sandra!
dont make confussions. Son or sons of God refers to the phenomenon which directs towards the affection and love between the relationship of a father and son. Son or Sons of God does not refer to be begotted son or sons of God. Ask any christian pope, he will also give you this theme for the father and son/sons mentioned in Bibles. Hope you are getting the points in my replies.
Any given religion has extreme people, Christians had David Koresh the muslims have the radical imams that propagate bombs to get their point across. You cannot condemn all muslims based on the actions of a few. Their Koran does advocate killing unbelievers in a couple of verses that the radicals base their whole philosophy on. They get adherents because they are much more active in their communities than others. The loudest voice gets heard not necesarily the right voice. Non radical muslims just live their lives like anyone else Muslim does not mean suicide bomber. Radical muslim can mean suicide bomber but we must know there is a difference. We don't have to approve of thier religion but we have to not condemn all muslims based on the actions of the radicals. The Christian bible says judge not and you will not be judged, it also says the measuer you use will be used against you. Christ will hold us accountable for everything we say and do that does not line up with His will. Yes, this includes hating other religions. We are not called to hate them.
Sorry, your info is very unrealistic.
For more detailed authentic references, please click on the following
Hey I like this comment very much..... I like your name and avatar, I am going to be your fan,.... do you like Cat Stevens..
Every religion was great and were for the people of their respective times. Islam is the last and final religion rather a complete way of life for the whole of human kind.
Christianity, Judaism, Hinduism, almost all the religions teach to follow only ONE God - ALLAH but their followers DONT. All these religions prophecised the comming of Prophet Muhammad (peace be upon him) as the last and final messenger from Allah and instructed to follow him but their followers DONT. So it's the duty of a Muslim to inform them, next, it's their choice. Nobody can force you.
i dont think that islam is a religion of peace. THOSE MUSLIM people must prove to all that they are true muslim by there deeds..
The criteria for judging Islam is not Muslims. It's Qur'an and the last and final messenger Prophet Muhammad (peace be upon him)
I haven't seen many but here's an Islamic web site that denounces terrorism. … alism.html
Not many know that tens of thousands, both Muslims and Christians witnessed sightings of the Blessed Virgin Mary in Cairo, Egypt in the 1960s.
I very much like the similarities between Islam and Christianity. Muslims recognize the virgin birth of Jesus by Mary, they give reverence to Jesus and Mary, they believe the antichrist (they call it the dajjal) has to come before Jesus returns to do away with the antichrist and a lot of other similarities. What I don't get about Islam is the fact that they do believe that Jesus will return and do away with the antichrist to make everything perfect, but they believe Jesus is just a prophet and not God. No other prophet has done anything similar. That is quite the job for just a prophet, isn't it?
Mike
Someone explained it to me this way... because God (Allah) is above All. or like Jesus said, "A pupil is not above his teacher, but everyone that is perfectly instructed will be like his teacher.
So while they revere Mohammad as the last ( I believe) prophet, it is not fair or right to place one above the other because God is Above all and no one, even in perfection is better than the other.
Though I may have it wrong so maybe someone from the Islamic faith can come and explain it better for us. Eng M. maybe? Where you at Eng.M?
I like what you said here Sandra and is very much part of my faith where none of the prophets is better than the other. In fact none of the prophets ever denigrated another. They come at a different time and place, but always from the same source, with the same inherent principles like the Golden Rule which is present in every religion, but with different social teachings that reflect the needs of the day as part of an ongoing progressive revelation. We might call it Monday, Tuesday, Wed etc but its the light from the same Sun.
So correct-The Prophets are One .
The stages of life are man then God -man or prophet and then God-when man no longer exists.
Yes, light from the same sun but light consists of rays and different type of rays (in terms of their intensity and reach) for different times and differnt people. The last ray is ISLAM which is for the last group of people until the end of universe. Islam confirms and respects all the previous Prophets and their respective revelations. All of those prophets and revelations prophecised about the coming of the last and final Messenger Prophet Muhammad (pbuh) and instructed to follow him. Even hinduism has got this information. So, please go back to your scriptures and read them in context. I will try to give the direct references if someone wants.
My dear!
Allah is the greatest. All are equal in the eyes of God. I am glad you are getting the stuff.
And what does Allah say about homosexuals?
totally forbidden, NOT ALLOWED
The act is forbidden or the person who is homosexual is forbidden?
How can a person be forbidden?
No it doesn't. If you mean homosexual persons are unwelcome then why not say so?
And presumably this is what you mean when you say "love."?
What does the word "love" mean? Same as unwelcome and forbidden?
I see you have now dropped your other persona in favor of this one. Why?
Dear Make!
Your question is absolutly valid and relevent. You are just one click away to find out your answer. If you have time then click on
But Sandra there is lots of proof in the Bible that Jesus is God though. Not just from His apostles but from Jesus Himself. In John 10:30 Jesus says "I and the Father are one."
It would be nice to see us come together.
Yeah I wouldn't mind getting Eng M. to answer my question. I'll post it again.
What I don't get about Islam is the fact that they do believe that Jesus will return and do away with the antichrist (dajjal) to make everything perfect, but they believe Jesus is just a prophet and not God. No other prophet has done anything similar. That is quite the job for just a prophet, isn't it?
Mike
But in this passage Jesus is not saying he is God, but rather that he is of God's equal in heaven, by his grace and that he, Christ's rite of passage comes about his duty to forgiveness.
Mike not remembering where this quote is isn't there also a reference to Jesus saying that He also comes from God. We often take one thing in isolation but its the complete revelation of the prophets, the indicators of their station and the transformations they brought to the world that are the 'fruits' we should examine. Mohammed for example infused huge developments in mathematics and was responsible for many advancements. Prophets have been characterised by their innate knowledge and their ability to transform hearts which is why there are huge numbers of followers of the major religions (not the denominations per se). If people don't recognise the prophet, or follow His teachings -I'm talking in general- its not the fault of the prophet but our own inability to examine without judgement and with clear eyes, yeh?
That is very insightful LBD.
These Zionists (not ordianry christians, jews or hindus) have vanished the whole history from their text books which deals with the contributions of Muslims in the field of science specially when europe was indulged in its DARK AGES. Please refer to the following infamous web site
DISCOVER THE 1000 YEARS OF MISSING HISTORY
I certainly understand Jesus said this but these are my thoughts on my acceptance of Christ as god but not God. Either way I really want us to come together as well.
Jesus is Mohammad----- Mohammad is Jesus= Buddha, Zaratushtra,Krishna, Mahavira, Guru Nanak.
\
I respectfully disagree. I don't know what I believe to be the truth, but this doesn't seem reasonable. Too broad perhaps.
Its is the truth all humans should understand-its high time these foolish wars in the name of One god stops.
No Sir
Jesus (pbuh) = Jesus (pbuh)
Muhammad (pbuh) = Muhammad (pbuh)
The prophets came one after another as successors.
Every thing is not God
Every thing is God's, He is the creator, the ultimate one.
He created humans, the ultimate machine (creation) from God and Prophets are specially appointed personel for delivering the message of God to others and give them guidance
John 10:30, I and the Father are one.
For context,.
So, God and Jesus(pbuh) were one in profession, not one in person.
No RKHenry Jesus is clearly saying He is God in John 10:30. John 1:1, Matthew 11:27, Luke 10:22 are just some verses that speak of the Divinity of Jesus and the whole chapter of John 14 talks about the Trinity. Matthew 28:19 says "Going therefore, teach ye all nations; baptizing them in the name of the Father, and of the Son, and of the Holy Ghost."
You got me. I'm not familiar with those verses. I am just familiar with what my parents always said. I don't think they were bible readers either. Who knows where they got the crazy idea that Christ was the son of God and not God himself.
Confused. But hey thanks.
I think what is best for us to be together and worlds apart is to start looking for all the things that are good. To start focusing on the good instead of looking to snuff out what is bad because by looking for what is good, we are snuffing out what is bad.
I think we can already see what is bad and that it has been there so long and in some ways we have become acclimated to looking for those things to, I guess, protect ourselves from it and all along we have been against each other who are for the same.
It doesn't make sense. Like what Jesus said about pulling the straw from your brothers eyes when you have a rafter in your own eye.
I came to the conclusion that the "rafter" in my own eye is that for every straw drawn from another is yet another in my own. I don't have just one straw in my eye but I have many that I can see in my brothers. So when I see it in my brothers I need only to remove it from myself.
And I believe it is a continual process. I believe I will always be a seeker and I will find many things and I will understand many things but when it comes to the last straw the only one who can remove this from my eye is God.
Because, what you cannot see in me, I also cannot see in myself. I hope this makes some sense.
So why did Jesus when he was on the cross say" why have you forsaken me? "
Everything is God-this entire cosmos is God-Jesus understood himself and so he made the statement that he is the son of God or he is God.
The little finger is part of the body,the same way is man part of the cosmos or gods body.
Like Hindus have On Namo Shiva- I bow to god
Shiv ho hum- I am God.
Please correct your understanding related to Hindism books. Refer to the following for One God who has got no image, no partner (world, universe etc)
Do understand Hindu philosophy has both concepts.The Muslim concept that even the prophet cannot be compared to god and the Christian concept where the prophet is equated with god.Both are correct
Om namo shiva -I bow to god and Shiv ho hum- I am god are both true.
All is Allah so you and everything are a part of him.The essence pervades everything.
Please read the verses you mentioned in context, then you will realize what does it actually mean. There is a hell of difference between God (Caps G) and god (small g).
I am a knower of god or Allah.I write on him as he has instructed me to,the very purpose I am here on this planet right now, to spread his message
And what is the difference for you as I don't see any difference.
I guess I addressed what you said in my previous post Lifebydesign (nice name by the way). See Lifebydesign there is just way too much proof in the Bible, both in the Old and New Testaments for a Christian to not recognize Jesus as God.
Maybe Eng M. will try to answer my question.
I've tried many times to get an answer to my question from a Muslim but I don't believe I have got one yet.
happy days to you
makemany , Sandra and all the others
I hope I could answer your question Makemoney about why we think Jesus is just a prophet, yet he is still alive and would come in the end of days to kill the antichrist
First, muslims don't differentiate between any prophet
we have to believe on all of them as equal prophets sent by God
God
Quran
YUSUFALI translation
But, each prophet was better than others in some area and so all humans
ex: some people have special skills and other people have others.
Moses had many miracels and was a very strong man
Jesus was very nice ,soft and a man with special capabilities like bringing some dead to life
Suliman could deal with jins and control them
and Mohammed had the Quran ,the preserved book on earth
In addition to Jesus abilities, God has given him miraculous birth and death to test people in some way
his death comes after thousands of years fom his born which was a miracle in itsself
So, God is capable of doing everything
he has many characteristics described by his 99 names and his characteristics appear in his actions
thanx
Thanks Eng.M
My next question was going to be "but why will it be Jesus that kills the antichrist and not Moses, Isaiah, Jeremias, Daniel or even Mohamed?" But it looks like you have already answered that by saying "each prophet was better than others in some area."
Belief in the divinity of Jesus and in the Trinity, the Father, the Son and the Holy Ghost is a fundamental belief of all Christians.
So it looks like we are at an impasse as to coming together as one for the time being.
But we can continue to try to foster an open dialogue and peace.
Thanks again Eng.M
Mike
Make Money how do you know that it won't be Muhammed? The bible? Do you have any other resource other than that? Curious.
Yeah from the Bible but also from Muslims RKHenry. See, that was the reason for my original question. Muslims also believe that Jesus will return to do away with the antichrist. I think it's pretty cool that both Muslims and Christians believe that.
Also, he is making this role because God knows there will be a big controversy at the end of days about who really Jesus was ?
there is one prayer in Islam says:
thanks God who didn't have a son
you know why ? because I don't know either
may be because that will confuse us and let many enities control us
what you think ?
we don't need to
we need to learn from each other
all the time, with love
No
thank you MakeMoney
Your question is again very valid.
Yes, Jesus (peace be upon him) is alive and was not killed.
The three major misconceptions which we see around in the Christian world, Jesus (pbuh)’s death, his claim to be God and the concept of TRINITY, were merely developed by the Christian elders and due to this very reason Jesus (pbuh) will return to earth before the end of time for proving them to be wrong and killing the Antichrist (Dajjal) for the peace to prevail on earth. Jesus (pbuh) is the only messenger of Allah from the total of 124 thousand messengers in the history of mankind, whose followers, majority of them consider him to be divine, the begotten son of God and was killed by Jews on the cross ruthlessly. All these type of things, attributed to Jesus (pbuh) are unique in the sense because none of the other messengers of Allah faced these types of allegations which the Christians attribute to Jesus Christ (pbuh). His return is also mentioned in Bible without any doubt..
For other detailes please click on
Sandra asked this question and I have answered it for her- make money can look it up.
Makemoney
believe me , I read the holy bibel and I found that Jesus didn't say 'I am God' or 'worship me'
they were all interpretations made after his death by the monks
he could be his son as we are his sons
but he is one of the best sons
(if son means that God has crated us from him)
is it from perfection of God to have a son as we have sons?
does he need to show us his love this way? aren't there other ways ?
God says:
(Say: He is Allah, the One and Only; Allah, the Eternal, Absolute; He begetteth not, nor is He begotten; And there is none like unto Him. ) 112
Quran
YUSUFALI translation
There is no God but the one who gave everything
regards
Yes but they don't believe in the divinity of Jesus Christ. They think He was just a prophet. Muslims show reverence to both Jesus and Mary, which is also cool I think.
How do you feel about the fact that Christ was both? Is that a possibility? If not why?
I like this - both. Why does it have to be 'either/or' it can be 'and' in some instances.
I've always thought divinity was related to being a prophet? Baha'is by the way believe in the divine station of all the prophets - or Manifestations of God as we call them.
I still don't understand why can't Christ be both.
You mean man and Prophet? He can, and from what I remember he alludes to it Himself.
Absolutely.
In fact Moses if I remember correctly was the 'Friend' of God. It is a progressive revelation after all. [As an aside: we go to the next class of school with a different teacher, but that doesn't mean we say the one before was wrong or ignorant, or couldn't teach us about more advanced things. They teach us what is relevant for the social and spiritual needs of the time that they appear and to our capacity to get it. Not that we always do, or want to ]
Where ever I go, I cant escape you, can I RK? LOL
AEvans, your right. I apologize. But Islam is not the religion of peace, everyone knows that. Thats all Ill say! lol
I was actually just thinking that Misha. RKHenry, are you a guy or a girl? lol
I would respectfully disagree with you, RK,
These figures are all symbols of the enlightened human being/God throughout various cultures. It is a universal mythos I believe he is suggesting. Broad enough for me to be able to handle it--if you know what I'm saying.
Yeah, and I'm happy for you. But still its too broad for me. I wish somebody would of thought to ask me why. Maybe then the problem could've been address. I don't know, but food for thought. I did leave an open ended statement. I was looking for answers not rebuttals. Respectfully speaking.
Rosa Parks isn't Ghandi and Ghandi wasn't Rosa Parks, but they still wanted the same thing. That's what I'm saying. They were different men for a reason. To pretend to know that reason is something different.
And Lita was looking for a spiced up intellectual flirt. Adjust accordingly
Now, Misha! Don't be jealous! That's bad.
RK--Ignore Misha, please. He really doesn't know what he's saying half the time,
So, OK, open ended. What do you think? (It really wasn't a rebuttal. Just my thoughts.)
I think that there can be universals with cultural specifics--especially in regard to these 'enlightened being/ Christ figures.' Rosa & Ghandi I see as a bit different...
Lita Girl, you crack me up.
When you say "universals"- do you mean universal meaning? Principles? Ideas? Beliefs?
All of the above. Can be found in almost any realm--a la Joseph Campbell, idea of "Mythos," if you have read him.
I didn't read the beginning of this thread, so... I see now your question about Christ being both God and Prophet. And really see no reason why not. I would view that as transcendence in stages....and perhaps we all are doing that.
I do think mohitmisra makes a lot of sense. Concerning religion, I personally do not like a lot of specifics or organization, either--this is what all that Old World fighting and killing was/is about, in my eyes. Some, like Mark Knowles, would say get rid of God all together. I'd say, people--stop being so stupid and by all means practice a measure of decency and tolerance all around.
They taught exactly the same thing.Here the essence is the same in all of them.
taught the same thing, that does not mean i am you and you are me.
Here in this dimension we split up but we come from the one and will always be one. You are me and I am you. All is me from my view point.One.
"Nothing really belongs to me,
At the same time all is mine as far as I can see "
I read this somewhere...you are God in the form of (mohitmisra, in this case) and I am the same God in the form of Capable Woman.
We are the same God in different forms... I dunno, I find this quite beautiful and it helps me empathize with others.
Happy you can relate with this truth you are indeed a goddess.
But dear, what about the verses from veda which directs Hindus to worship only ONE God and do not add partners, images or idols to Him. Have a look at
Also Hinduism have prophesized about the Qur’an and Muhammad (pbuh) and instructed to follow Muhammad (pbuh) when you find him or become aware of him.
You are only looking at on part of the philosophy as it matches the Muslim philosophy.if you read more you will understand more .
Aham Bhramasmi-- I am Brahma, Om Namo Shiva- I am Shiva exist i Hindu philosphy.
Tat Tvam Asi -"Thou art that," "That thou art," or "You are that,"
An idol is a physical manifestation of the divine and its okay to start with it but one needs to go beyond to the formless.
The Hindus also believe Muhammad is not the last prophet .The last prophet will be born into a bhramin family, will write and unite the religions.
Age of Aquarius will witness a great prophet from the east has been prophecised. - that means NOW.
And apart from yourself, Mohit, who do you think might be the One????
Comming to the Prophet Muhammad (peace be upon him) issue. Please refer to the following which clearly prophecise Prophet Muhammad (pbuh)???
Both these philosophies are correct.Be open minded.
If you contradict the second part then you are saying ,
all is not Allah.
I never said Muhammad is not a great prophet ,he is very, very great.What I am saying is Jesus is equally great and Islam is not greater than Christianity because of the difference in philosophy.They had exactly the same message of oneness and love to humanity from God.
Prophet Muhammad- "salla allahu alayhi wa sallam" meaning “To your be your religion, to me be mine.”
He taught tolerance between religions and never said his was the true and greatest religion which some Muslims do today.Some foolish Christians also say Jesus is the greatest and this ego only leads to stupid wars which needs to stop.
I need to add its a pleasure debating with you.
Dear Mohit, you are a very logical person, i like your style.
Now, i want to say something about this greatness issue which you explained. You see when some muslims compare a prophet with another, they do not do it on the basis of their personalities, physical strengths or miracles as the missionaries do rather the comparison is on the overall achievements of the delivered message, the final goals and their effects. In the same way, certain well known non muslim historians have done the same job and put Prophet Muhammad (peace be upon him) number ONE like The Hundred by Michael H. Hart. Here, if you ponder, famous non muslim professionals praising a being, implies that there is something very special in it. Imagine, non-muslims, doing research and writing books to remove the misconceptions related to Allah, Muhammad (pbuh) and Islam, those misconceptions which are immensly created by Zionits on daily basis as they only fear ISLAM to be the only remaining ideology which can remove their evil machinations to rule the world with one eyed Antichrist-Dajjal and under the new world order against which laymen of the world over specially europians and americans have staged a large number of protests and are staunch opposers to this evil system.
In addition, i agree that Islam, christianity, hinduism and others are great religions but the greatest of them, if someone calls Islam to be the greatest way of life bears a valid reason and the foremost is that God who gave religions to His people is the same in all religions THE ONE GOD. He Himself told his followers in several scriptures that there will be a final great Messenger Prophet Muhammad (pbuh) and a final great word Qur'an for you to come. Who so ever finds it, starts following it. Now, tell me what's the big deal in that.???
At last, i never claimed any superiority or close mindedness You informed me that there is nothing in Hinduism which is related to Muhammad (pbuh), in response, my job was to agree with you BUT the problem is that there are some verses in hindu scriptures which deals with this subject and i simply quoted them, you can check it up. Now, after getting the evidence, you agree with it or not, it's totally up to you, neither i am forcing you nor will i kill you . RELAX
Dear usmanali81 I enjoy debating with scholars
Hinduism believes in a few maha avatars or prophets and amongst them are Jesus and Muhammad who are also know as avatars of Vishnu.Some texts say there will be one more and some there will be two more avatars.
Now, after getting the evidence, you agree with it or not, it's totally up to you, neither i am forcing you nor will i kill you . RELAX neither am I or will I
Like I said before the Buddhists expect the return of Buddha, Christians the return of Christ, some Muslims the Mahdi, Parsee the twins, Hindus the Vishnu avatar.This will be the tenth and final maha avatar.
Here, if you ponder, famous non muslim professionals praising a being, implies that there is something very special in it. Imagine, non-muslims, doing research and writing books to remove .
I am half a Hindu and half Parsee meaning part of my ancestors were from Iran.I praise all the prophets
Praised all religions in my book.
???
My book Ponder Awhile is ranked over The Holy Quran on Franklin but that doesn't make me the greater prophet. Like I said before god sends the prophets when this earth is in a mess and he spreads god knowledge in the language of that time.The Essence is the same right from Zarathustra the first recorded prophet or from the Holy hindu texts like the Vedas which you quoted earlier one.
I am trying to answer you - Respectfully speaking.
Sorry,. So, if there are any avaters in Hinduism whose return (come back) is expected does not include Muhammad (pbuh). Muhammad (pbuh) has alread come to this earth and will never return.
Regarding Mahdi, Muslims do not believe he will return or he will be the Prophet, no, not at all. It's only a prediction about a Muslim man among others named Mahdi who will lead the people of the world as a just Muslim leader / Caliph near the end of time and during this time Jesus (pbuh) will also return (come back).
In my example of the medical books, i tried to explain the Qur'an outdates previous religious scriptures. It's not that Qur'an outdates a medical book or a philosophy book and vice versa
Prophets represent the Light or Allah. Have you been one with the Light or Allah- I have.
You do believe Christians, Hindus and Parsee expect another prophet so for many Muhammad is not the last prophet. One holy hindu texts say there will be an unlimited amount of prophets. Many believe he is eminent.
Sikhs believe Guru Nanak was a prophet and the tribe of Baha'i believes Baha'ullah was a prophet . All three were great masters.
Mohit!
I do not have to believe the Muslims, Christians, Hindus, Sikhs about their believes and practices. What i need to believe is the one which is written in their scriptures and it's totally opposite what they practice and preach, i dont know why but it's STRANGE.
You are talking about unlimited amount of prophets to come in these scriptures, i wonder where is that??? Regarding Guru Nanak and others, i did not say they were wrong or not great.
What i am talking about is related to the LAST Prophet ... LAST (Prophet Muhammad (pbuh))... mentioned and predicted in almost all of the religious scriptures whether it be Bible, Hindu or Sikh scriptures and instructed very well to follow him when you find him. What i am talking about is worshiping ONE God and none other which is mentioned in almost all of these religeous scriptures.
So now tell me, do i need to follow what's written in these scriptures or i have to follow the false notions and practices of their followers???
The scriptures Hindu and Parsee say there will be one more prophet who is expected now .I repeat Hindu philosophy - he will be born onto a Brahman family,will write and unite the religions- Kalki.
The age of Aquarius will start with this prophet from the East. The Buddhists Expect the return of Buddha- The laughing Buddha,Maetriya and the Dalai Lama is supposedly gaurding the universe and he will take over.
The Parsees expect the twins as the present day avatars.
Christians the return of Christ.
Recently many believed Sai Baba and Meher Baba to be avatars or prophets. Both were supreme masters.
Then like I said before you had the great Guru Nanak. Many Mulsims converted to Sikhs because they felt the ideology of Islam has been corrupted over a period of time.They felt Islam considered themselves as the best which is not true and that all religions are equal and god is one.Something Guru Nanak and Muhammad taught. Muhammad himself said to your religion be true and me to mine. Live and let live - Mahavira,
So according to you Muhammad was the last prophet and so the greatest.?
You are not following the scriptures.
Hinduism is not confined to Brahmins only. The new "prophet" may also be born in a harijan or dalit family. The main draw-back in Hinduism is the ego problem among the religious-sects.
Hinduism shrinks because of the Brahmin atrocities. Unless and until there is equality and liberalism, no one will stick to Hindu religious thoughts.
As for Budha, he should have come by now and he should have visited the Srilankan Tamil camps where lakhs of people are herded like cattle in a small area, ready to be sent for the kill. More than a lakh Tamils have been killed, in the last 5 months, their habitations reduced to ashes and there is now there is no sign of any habitation. What is the meaning of religion and Budha laughing after allowing such a holocaust.
All were done on the pretext of Budhist supremacy in Srilanka.
Who are you to decide what the Buddha should be doing?
It is prophecised that he will be born into a Brahman family. Brahman- knower of Brahma- an awakened or enlightened one .Anyone can become a Brahman.Most of the masterpieces from India have been written by Brahmans who have showed mankind the way to god.A harijan or dalit can become a Brahman.
Death is happening in all parts of the world and not just in Sri Lanka, its your ego towards the Tamils and Sri Lankans which makes you make such statement.
The laughing Buddha symbolizes someone who understand the cosmic joke- all is he- he is the one dying.
How a dalit can become brahman???
A Brahman is a knower of Brahma-Allah, an enlightened one.Anyone irrespective of their caste can become a Brahman.
But Hinduism does not consider him / her as a brahman. Hindu scriptures catagorically divide people in 4 castes on the basis of their net worth of family, education, finance, economics, politics etc. Take for example the following.
Bhagavad-Gita, Ch.18, verse 40
The Lord says: “There is no being on earth, or again in heaven among the gods, that is liberated from the three qualities born of Nature.”
Bhagavad-Gita, Ch.18, verse 41
“Of Brahmans, Kshatriyas and Vaishiyas, as also the Shudras, O Arjun, the duties are distributed according to the qualities born of their own nature.”
Bhagavad-Gita, Ch.18, verse 42
“Serenity, self-restraint, austerity, purity, forgiveness and also uprightness, knowledge, realization and belief in God are the duties of the Brahmans, born of their own nature.”
Bhagavad-Gita, Ch.18, verse 43
“Prowess, splendour, firmness, dexterity and also not fleeing from battle, generosity and lordliness are the duties of Kshatriyas, born of their own nature.”
Bhagavad-Gita, Ch.18, verse 44
“Agriculture, cattle-rearing and trade are the duties of the Vaishiyas merchant class), born of their own nature; and action consisting of service is the duty of the Shudras (servant class), born of their own nature.”
Bhagavad-Gita, Ch.18, verse 45
“Each man devoted to his own duty, attains perfection.”
Here one is talking about an a enlightened society where all castes are needed in order to function properly.Perform your duty whatever it is , is the meaning of the above passage.Understand what you are made for, the reason you are here on this planet and do it, this will burn your desires, the reason you have materialized and you can attain Moksha.
This is why Krishna chided Arjuna on the battle field saying, "you are a shatriya, your job is of a warrior and you must do your job, the outcome of the battle has already been decided."
A person born into a sudra or shatriya family may have the qualities of a Brahman in him, takes interest in spiritual subjects.An enlightened one a knower of Brahma is called a Brahmin.You may be born intro a Brahman family but you become one upon gaining enlightenment.
My surname is "Misra "- "the name given to the Brahmins-enlightened ones who settled by the river Ganges." This is from my fathers side who lived in Allahabad the confluence of the Ganga, Jamuna and mystical Sraswati, but I became a Brahmin , a knower of Brahma or Allah at the age of twenty four when I came in contact with god, got enlightened.
Brahmin is the class of educators, law makers,]
Dvija "twice-born"-- reborn is what Christianity calls these saints.
Or what Jesus meant by saying one must be reborn
Here one is absolutly not talking about the enlightened society rather the text is talking about the NATURE of different kinds of people divided into different classes. Yes, Shudras may have the qualities of Brahmans and can think of becoming Brahmans BUT can not actually become Brahmans, Kshatriyas or Vaishiyas..”
There are thousands of verses of Vedas and other books of Sanatan Dharm, which talk, about Caste system and Vedantist agree with it totally as mentioned the statements above.
Now turn towards the Glorious Qur’an: Alhamdulillah, Allah clearly states in the glorious Qur’an in
Surah Hujuraat (49:13) that, “O mankind! We created you from a single pair of a male and a female and made you into nations and tribes that ye may know each other not that ye may despise each other. Verily the most honored among you in the sight of Allah (God) is (he who is) the most righteous of you. And Allah has full knowledge and is well acquainted (with all things).”
Here one is absolutly not talking about the enlightened society rather the text is talking about the NATURE of different kinds of people divided into different classes.
Only an enlightened society can see this. It is similar to what some of the Greek philosophers proposed. In early age let the child play, then with time we can observe as elders who care as to what the child is inclined and tutor him as such.Is he inclined to spirituality, towards a warrior or towards the arts.
The folly happens when the wrong person is in the wrong field.
Yes, Shudras or sudras may have the qualities of Brahmans and can think of becoming Brahmans smile BUT can not actually become Brahmans, Kshatriyas or Vaishiyas.
This is wrong ego which we have in India today and what some believe, someone born into a Brahmin family calls himself a Brahmin.No he comes from a family of Brahmins, Kabir the weaver - a Vaishiyas gained enlightenment, became a Brahmin or knower of god.
Enlightenment is the criteria for being called Brahmin.
"Verily the most honored among you in the sight of Allah (God) is (he who is) the most righteous of you. And Allah has full knowledge and is well acquainted (with all things).”[/b]"
-this person will be called a Brahmin.
The Qur'anic quotation which i mentioned was for showing you that Islam / Qur'an does not support this kind of seperative classes which Hinduism believes in. It's not the matter of Indians rather it's the matter of Hindu scriptures who themselves support and encourage this class system. You did not go through the other two verses from Hindu Scriptures. I am mentioning them here again..”
These is metaphorical usmanali, don't take them literally.
The undercurrent of an enlightened society is that all is one.The Brahmin cannot live without the Kshatriya or vashiya or sudra.Neither can the Kshatriya live without the Brahmin or vaishya or sudra and similarly the rest.There was respect for each , when the respect got lost is when the injustice started..
The meaning of this is that all these different parts make up god. He cant function properly if any one is missing. He needs all to become whole.
But feet can not become mouth so people in the feet are suppressed and degraded all the time. Consult a celebrated history for that.
Moreover, as per science brain has got a higher class than feet
Can you be able without your feet? Are feet not important?
There are many passages in spirituality which you cannot take literally or you miss out on the meaning .
There is a passage in the Quran which says something like" you will have 7 virgins when you go to heaven." If you take this literally you are totally missing the point.The point being heaven is a far greater and happier dimension then we are in.
Some would say what a ridiculous thing to say.What need of virgins when one is with Allah.There is no two in the dimension of god, all is One- Allah, so who can have sex with who?
Then you have the third eye in hinduism, if you actually think there is one more eye needed on your body , again you are missing out on the depth.
You have "when thy eye be single" Jesus. Now if you think only a person with one eye can enter heaven again you are missing out on the depth of these words.
This is not metaphorical at all. Look at the verses again, very plain to understand. Also if you read the verses before and after them in context, it becomes even more clear that human beings are degraded and divided religiously in Hinduism.
Now that you say Brahman cannot live without the Kshatriya; this thing is absolutly not mentioned in any of the Hindu religious scriptures. Infact it's your own philosophy to be kept in DARK. Do you know Shudras (merchant class) are not entitled to the study of the Vedas as you said they can think of it and can become enlightened but are not actually allowed to do it.
Do not take it personal. It's the fact which Hindu scriptures itselves are evident on it. Take one more in the following
Translation and explanations by Swami Vireswarananda Advaita Ashrama, Mayavati, Himalayas
Brahma-Sutras 1-3-36:
Because purificatory ceremonies are mentioned (in the case of the twice born) and their absence are declared (in the case of the Shudras).
[Note: Purificatory ceremonies like Upanayana (Sacred Thread) etc. are declared by the scriptures to be a necessary condition of the study of all kinds of knowledge or Vidya; but these are meant only for the higher castes (Brahmins, Kshatriyas and Vaishiyas). Their absence in the case of the Shudras is repeatedly declared in the scriptures.
"Shudras do not incur sin (by eating prohibited food), nor have they any purificatory rights " etc. (Manusmrti 10-12-6). Consequently they are not entitled to the study of the Vedas.]
When you are not looking at it in an enlightened way, you are corrupting it.Its your outlook.
Purificatory ceremonies like Upanayana (Sacred Thread) etc. are declared by the scriptures to be a necessary condition of the study of all kinds of knowledge or Vidya- I never had the thread ceremony and got enlightened without it.
Like I said before the Greek philosophers also proposed this as an enlightened way of society.
Sir,
You have a remarkable in depth understanding of the Vedic scriptures. Seriously, not many Hindus I have met are as well versed about Hindu texts like you are. Are you a Theology major expert(especially comparative religions)?
Coming to your observations about Hinduism I humbly admit that some of my fore fathers might have practiced discrimination of others based on caste(because even I belong to the priestly community). But thankfully our generation in India is slowly rising above caste based distinctions (but sadly politicians like Mayawati still persist on playing the caste based politics as if two wrongs make a right). It is really a pleasure to meet such a scholar who has such a vast knowledge of other religions. In fact the need of the hour is to come together as one. We seem to have all the religions in the world to divide each other but not enough to love each other.
He doesn't understand the scriptures.
Like Mark mentioned earlier you need to be castrated in order to enter heaven according to the Quran.This is totally absurd if you take it literally, the depth means one needs to be pure.One needs to be stripped of his ego and attachments.
Ridiculing is too easy, try and see the truth, the beauty in a spiritual passage.
A couplet form "Ponder Awhile"
"We are constantly fighting like cats ad dogs,
Reality is covered by some strange fog."
This is metaphorical, please don't go looking for a fog to go through.
Be practical Mohit , may be the class system can do something for Philosophers but for Practitioners this system can do nothing accept INJUSTICE.
Dont Muslims have different people in different jobs,dont you have scholars, artists ,warriors and workers?
Which society in the world doesn't?
Like the passage you mentioned says man cannot function properly without his legs, arms, stomach and mind, all are needed.
Oh no dont think muslims are to back positions..they are very cleaver as so many I mate in my class..
and I found so many muslims are very helpful, thay are very honest with their God -allah..and I dont know why in India people fights for the Hindu Muslim issue...they dont thinks that this issue was made by British to split india in to parts n so pakistan came to born...
many people have respects for Hinduism ....
I request u all Hindus and Muslima who r in Hubpages try to write on this issue and plz end up the wor....
thanks ..for nice subject...
All the prophets and religions are equal Apeksha ,is my point.
u people go on writing big posts so some times many diverts from main subjects...
same thing wan tell to people...
I get very irritated when anyone praises their own prophet or religion and tries to put down other prophets or religions
i did not do it at all, go back and have a look again.
You were saying old medicine and new medicine and like I said the message is the same since the beginning, god doesn't get old.He is beyond time
"You are made of such fine light ,love tissue,
No beginning , no end an ageless issue. "
For your kind information, the most cleaver and genious people of the world are JEWS. QUR'AN praised them , so astonishing. You see the maximum number of phd in the world are produced by Israel.
Saints or god men are have been produced in every nook and corner of this planet.
My dear friend!
Yes, every family, group, society, country has got these distributions BUT Hinduism is the only religion who catagorically documented the forcefull division of people and assigned classes to them on the basis of their family background, social, financial and political status, color, caste etc. The text in Hindu scriptures clearly describes that the people working under different classes can not join another class no matter if a Shudar can do the job of Brahman, they are simply not allowed by Hinduism to do so.
Corrupted minds corrupted the ideal yet the essence or philosophy is correct.This corruption took place with time due to the greed of man ,it was not always there.
My ancestors being Parsees had to flee Iran because Muslims were chopping of their heads if they didn't convert to Islam, Hinduism doesn't force anyone into their belief.The Parsees couldn't live in peace in Iran and so came to India which is know all over the world for its religious tolerance.
Hindus accept both Jesus and Muhammad as great prophets but sadly its not the other way around, the great Hindu prophets are not given the respect they deserve by Christians and Muslims.
For your kind info brother!
Iran has got more than 6,000 jews living peacfully with Muslims, even Israel invited them for permanent residency but they refused and preferred to live with Muslims, why ???
Iran has got a considerable amount of Parsee as well.
For confirmation, you can watch several documentries built by BBC and other channels and get amazed.
Now comming to the religion of your ancestors, it's just to amaze you, do not misundertand me.
The Zorastrians… the Parsis, they call Almighty God as ‘Ahora Mazda’. ‘Ahora’ means ‘the Lord’ … ‘God’, ‘Mazda’ means ‘Wise’. ‘Ahora Mazda’ means ‘the Wise Lord’ or ‘the Wise God’, and He has been given several attributes and names in the ‘Dasatir’. For example, - ‘He is the only One, He has no beginning, no origin, and no end - He has no father, no mother, no wife, no son. He has got no image - He is beyond imagination. There is nothing like Him - No vision can see Him. He is beyond comprehension. He is closer to you than yourself’. There are also other attributes given to Almighty God, in the ‘Awastha’. The other Sacred Scripture of the Parsis. It is mentioned in the ‘Awastha’, in the ‘Kathas’, and the ‘Yasnas’, He is called as the Creator, in Yasna, Ch. No.31, Verse No.7 and 11, and also in other places in Yasna, Ch. No. 44, Verse No.7, Ch. No. 50, Verse No.11, Ch.No. 51, Verse No.7. In several places He is called as the ‘Creator’.
Peace be upon you
Buddy its common truth the Parsees fled from Iran and came to India as they were being persecuted by the Muslims.
So now is the prophet Muhammad greater than the prophet Zarathustra,? they taught exactly the same thing.
Some Parsees also have this foolish ego that since Zarataushtra is the first prophet he is the greatest ,it is as absurd as some Mulsims saying Muhammad being the last prophet is the greatest or some Christians saying because Jesus was crucified he is the greatest prophet.
He is closer to you than yourself- I am a knower of god ,try to understand I have spent the last few years of my life as a poet spreading gods message.
You may not like it but many do call me prophet.
CW, he doesn't have the "remarkable in depth understanding of the Vedic scriptures" as you think. He is one among many Muslims out there, who resort to copy-n-paste to further their propaganda.
Their only goal is to prove that Islam is the perfect religion and all non-Muslims should convert to Islam because of that. He's not a theologian - just a humble copy-n-paster of texts. He wouldn't have read most of what he's copying and pasting himself.
Correctly said, if he did have the understanding he would never try and ridicule it and say Islam is a superior philosophy..
Exactly. Those not familiar with this copy-n-paste mechanism would mistake this guy as having vast knowledge of other religions but what he really is - is a guy with lot of spare time on his hands and lots of cut-n-paste material!! Posting those is being passed off as debate!!
Dont worry, will defeat him in a debate
Ha ha - I know you will. But, problem is he won't oblige. He knows what he is good at --- that is copying and pasting verses from the Internet
Let him try, will explain those verse to him, the real meaning.
But, he doesn't have an open mind - does he? If one comes to a debate (in the real sense), one comes with an open mind. Yes, you take a position, but are also willing to consider other views.
If you come with the sole intention of proving that your way is the right way - you seek to only prove your superiority. Its a self-fulfilling prophecy situation!!!
Will open up his mind.He has limited understanding right now, will teach him.
Dear!
If some one knows the correct formula for making a nuclear bomb and he / she comes and show you, then what's wrong in taking the correct formula. Any way, you love to be on the wrong formula, go ahead, it's your choice. But i am still here, so you can ask for the formula any time
Have a look at this link please you will understand I have the correct knowledge or formula. not you. … r/ebooks/0
where did i say that???
Your own Hindu Scripture is saying that. Your own Hindu Scripture is dividing people in classes. The class issue was started by YOU and VENUGOPAL SIVAGNA. i just mentioned some of the verses from Hindu Scriptures, i from my ownself said nothing.
Like I said if you are not thinking in an enlightened way you will corrupt whats written.
For example if it's written, "Go and rape the the poor girl". How can you get enlightenment from this sentence. Enlightenment which you are talking about can work in Philosophy. So dont mix it up with religious scriptures as these are meant for ordianry people and thus are written in easy languages whose chapters and verses must be read in context. Do you know what a CONTEXT is ??? Also explain the enlightenment which you are talking about.
Enlightenment-in light-one with Allah-Shiva-The Holy Spirit.
So its true to enter heaven one needs to be castrated?
Its true you will have 7 virgins when you go to heaven?
Enlightenment is religious.Making contact with the creator, god, Allah, Brahma, Shiva, Ahura Mazda, The Holy Spirit.
Can you tell me in which text its mentioned go rape the poor girl?
The enlightened ones write religious scriptures.
Why have you not answered my question "don't Muslims have holy men, warriors, artists and manual laborer.? Dont you need all in order to function properly.? Can you function properly without your hands or feet?
Stop making the great prophet Muhammad into a fanatic.
So what I am getting from your present statements is that what Shil/Mohit suggested earlier about you copy/pasting without understanding seems to be possible in your case. Well then there are countless writings written by others who have found discrepancies in Islam and even on Prophet Muhammad (PBUH) and for the sake of a discussion I can also include them but then it won't be me who is talking to you(but some other writer). Btw every religion will have some strengths and weaknesses. If we only selectively read/understand(that too with a preset mindset) then we will only "see" what we want to see. I hope my friend you will understand what I am trying to say. Have a good day.
Dear,
I quote from the religious scriptures not from the books of other folks.
The countless writings against Islam are from other people not from the religious scripture-Qur'an. Let me help you with this if you want to malign Islam. Buy the book by the name of Satanic Verses by Salman Rushdie and push your limits to degrade Islam. The more you degrade Islam the more it prevails. Do you know after 911, ISLAM became the most searched word in GOOGLE. Do you know ISLAM is the fastest growing religion in Europe and America after 911, which SWORD is forcing them to become Muslims???
SWORD- I just told you many of my ancestors fled Iran because they didn't want to convert. The others stayed back and converted as they didn't want their heads chopped off in the name of Allah.
What is your Taliban about?
This is why when the great Guru Nanak came on this planet, many converted from Islam to become Sikhs where there is no distinction between religons.
Taliban is the political game plan of Zionist Jews, Zionist Christians, Zionist Hindus and Zionist Muslims to gain full control of the most important parts of the world, to sweep away the hurdles for the awaited Antichrist by Freemasons, New Conservatives and Zionists.
Talibans are mercenaries just like the Tamil Tigers taking money, food and weapons from their Zionist God Fathers just for promoting chaos, killing of innocents and dome the the whole territories with evil clouds, this same thing was also prophecized by Prophet Muhammd (peace be upon him) as a sign of the arrival of Antichrist-Dajjal. Talibans have got no businesses, no bank balances, no jobs, they are getting their stuff from Zionists and their agents. Even when some Talibans were caught dead by Pakistan Army or Tribal Elders, they were found un circumcised bearing enough evidence for these people to be mercenaries bought from different locations of the world like Russia, India, Arab, Pakistan etc., AMAZING HA, for conformation have a look at some of those videos on YouTube (if they are not banned). Circumcision is compulsory in ISLAM.
I understand the frustration by the Muslims, no one wants an outsider coming to their country and dictating terms.
What we were talking about is tolerance and Parsees fled to India because Muslims in that part had no tolerance and were converting people with the sword, with force.What sort of philosophy is this?
Why are people so against the Freemasons? They were founded on the teachings of the first prophet Zarathustra and do a lot for charity.
Come on dear, get some more info.
According to Freemasons themselves, their roots start from Ancient Egypt. For the history of Freemasons, you have to study the chain of Ancient Egypt--Crusaders--Knights Templars--Kabbalah--Freemasons Freemasons believe on Kabbalah which is a secret mystical book full of black magic and things like these which were also preached and practiced by the Ancient Egyptian Council of Magicians to Pharaoh. And it's the common practice of magicians to hide behind the black deeds and concepts by making use of charity, donations, gifts and things like that on the front end. Please go through and get enlightened what God did with one of the greatest deniers.
Some of the most respectable men in India are Freemasons, you do understand magic can be black when misused and white when used correctly or for good.The first known inscripition for Jesus was on a bowl where he was called magician.I joined the Freemasons but was too busy to go to their meetings.The Kabbalah is a mystical book , meant to reach god,this universe is magic.
A couplet for "Ponder Awhile"
"Either you can see the magic,
Or your life is indeed tragic."
"If you can see the magic in just one flower, your life will change drastically" Buddha
I am enlightened.
hhmmm, so you are a Freemason, a Hindu, a Parsi at the same time ... Kindly put your legs in one boat other wise your legs will tear apart.
All is Allah , all is Shiva. Who will tear my legs apart? Only a sadist, fanatic. Like the ones who attacked Jesus and Muhamamad.
I belong to all.
No one will tear your legs apart. This will be done automatically. Have some practical on two real boats in a river.
So what can I do if my dad is a Hindu and mother is a Parsee ? Disown both or one of them or embrace both. ?
God is the same for all of humanity, all religions.Are his legs torn apart?
Give me the evidence to back up your claims. How and in which way is the Taliban the "political game plan of Zionist Jews, Zionist Christians, Zionist Hindus and Zionist Muslims"?
Prior to 9/11 most Muslims were praising the Taliban for being the "ideal Muslims" by following the Koran perfectly. Now, they've become creations of other people? You've got quite the imagination to come up with this.
Not me, these are your own religions, proving that ISLAM is the perfect religion, i am just compiling up the information and presenting it to you. Now if you dont like it, through it away.
Even Atheists are comming towards Islam. Do you know something about Pragmatism; a new form of Atheism in which people agreed upon One God concept but further they say "ok fine, yes, there is One God but He has nothing to do with our lives". May be in future they say "ok fine, let's bring God in our lives as we can not clear up our own created mess, oh God please Guide us"
This is not the meaning of these words, and you are speaking with a forked tongue. I understand your religion encourages you to lie in order to push your irrational beliefs on everyone else, but please.......
A new atheism that believes in one god.
I can recommend the Oxford English dictionary if you are having difficulty understanding these words. It will help a lot.
Dictionary gives word by word meaning not the explaination. There is a whole world behind Capitalism, dictionary can not take it all too small. So for you, consult some Pragmatist scholar.
LOL
What do you think atheism and pragmatism mean then? LOL
Making up your own BS definitions is not helping your cause. In fact - thank you very much for reminding me why I am not interested in following your religion. I do not like liars and cheats. It is against my moral code. You clearly have none. Thank you once again.
how old are you ???
Please answer the questions. I do not like to see people lying, stealing other's word and spreading deliberate misinformation.
Thank you once again for reminding me why I do not like religionists.
Do you even know what "atheist" and "pragmatist," mean?
Yes, of course, it means that
USA alone has got the maximum number of prisons and prisoners in the world.
In USA alone, maximum number of rapes take place per day (almost 2000 rapes per day).
USA alone, has got the maximum number of registered cases of Depression, Hypertension, Obesity, Breast Cancer, Aids ....... (a long list of diseases) despite the fact that they are leading a top notch facilitated life.
In 2009, from USA alone, the credit crunch started and ate the whole world, imagine their auditors did not knew about what's happening in their own sleeves .
USA alone, is under the debt of 7.0 Trillion Dollars bought most of it from Rothchilds (they are Jews not Muslims ).
USA alone, has deposited the maximum number of soldiers in different territories of the world, just for killing and butchering innocents in order to fulfull their SADIST desires.
Danmark and Greenland alone, has got the maximum number of suicide cases despite the fact, these are the safest places and considered as heavens on earth.
EUROPE and USA alone, have got the maximum number of old age houses, where the open minded Atheists and Zionists dump their innocent and loving parents single-handedly.
UK alone, awarded the honor of SIR to Salman Rushdi for his book Satanic Verses in which he merely used slang language and abused Christianity, Islam and the Prophets.
Do you want some more explaination for any of the ISMs ???
Yes please. This is extremely funny. Do it some more. You are beautifully demonstrating MUSLIMISM for all to see.
amazingly you keep going out of the topic of discussion
stop being childish please , you know the figures he provided could be right
it has nothing to do with Islam
why do you insist to attack people
having fun doing that or just killing some time
None of which address the question I asked.
that's right
but I mean that you don't have to disagree with the other part of discussion all the time to make your point Mark
I know that he might wanted to tell you results of the two but not what they mean
regardless of their meanings
he and I also don't think your proposal is better for humanity
What other part of the discussion? That is meaningless garbage thrown out to confuse the fact that this muslimist does not know the meaning of the words "atheist" or "pragmatist." What does the amount of depression in the US have to do with the meaning of these words?
Yes, it addresses very clearly but may be not for funny people like you
No it doesn't mr muslimist. You may think raping women and stoning adulterers to death is the answer to American depression but I do not see what that has to do with atheism. Perhaps you could explain.
Country Woman has explained why you are very, very wrong. Perhaps you could reply to her also?
Muslimist is the term invented by you in this forum. You can call me a Muslim. You people asked a list of questions one after another. Now you tell me if a rapist comes and rapes your mother, daughter, sister, wife or spouse, which punishment will you prefer for him???
You are demonstrating the term muslimist right now. In fact, I would say you invented it yourself - not me. Please answer the question instead of going off on another tangent. What does depressed people in Denmark or America have to do with atheism?
read my answer in detail which i gave to CW
I have read your rantings. Oddly enough, I do not see the rape, child abuse and depression statistics for any muslim countries on your list. Neither do I see what this has to do with atheism.
I am not depressed, not do I rape women or abuse children - and I am offended that you suggest the fact that I do not believe your fairy tail will make me do these things.
You do not understand what atheism means - it means I do not believe in a god - any god - yours or any of the other thousands that people claim to believe in. That is all.
It does not mean I am a rapist, child molester or depressed or ill.
You are muslimist with a one-sided, bigoted, irrational viewpoint.
As far as I recall - your prophet had a nine year old wife and rape is legal in Muslim countries is it not?
1- it was normal at that time ( people have different judgments at different eras )
2- she is one of the most tradition(the prophet says)teller , around 5000 right one , she used to teach men and women their religion
(young people are more willing to remember)
3- to strengthen relation with the prophet , his best companion Abu Bakor asked to do so
4-other wives the prophet had were mostly old , divorced or widows ( he could have better if it's only about women)
and no mr.Marksist , it is illegal
All right - let's deal with this one for now. The legal age for women to be married was 9 years old - or at least to consummate a marriage. This is what your book says.
I often hear the argument that the word of god as written in your book is never-changing and is the same today as it was when it was written. In Iran the legal age for marriage is still nine for girls.
So are you now saying that the word of god can now be changed to suit modern day ethics?
no I didn't say that
Quran or sunnah don't mention anything about this aspect
there are many things are left according to different eras
the word doesn't need to change
it is written to suit all times ..
it is flexible ..
Dear Mark!
I respect you as an elderly man. Kindly put off your glasses to see the whole picture of Atheism. I am not saying that all atheists are bad. You are a good atheist but over all if you analyse this ideology leads to destruction as for an atheist there is No God, No Heaven, No Hell, No Life after death, so there is no compliance and audit for him / her that is why they make use of this materialistic world in any way which suites them.
Now,: third-world non-Muslim and Muslim countries. See the following examples:
A 9-year old Thai girl gave birth:
The news item can be obtained from New Straits Times, 10/3/2001.
Activists condemn Gypsy girl's arranged wedding in Romania?
Child brides as young as 8 (eight) were common among the Byzantine emperors and nobility!.
Threrefore, Prophet Muhammad's marriage with Aisha was 100% legal and acceptable by all laws and Divine Religions!
This is rubbish. Muslims are just as likely as anyone else to make use of this materialistic world. In fact, where slavery is still in operation - it is in muslim countries.
How dare you tell me what my standards are. I have seen you lie and steal other people's words and now you are telling me what atheists do and do not do? This is the problem with having an irrational belief such as yours - you start behaving like this - and wars ensue.
I do not need to believe in your invisible super being to lead a moral life. I am quite capable of making my own judgments as to what is acceptable behavior and what is not.
Interesting argument in favor of having sex with children you put forward. Odd that you were castigating the West for child abuse and promiscuity, yet in your culture it is still acceptable for a man to have several wives and have sex with 10 year olds.
As for the respect - you have not shown me any respect - so please do not lie about that as well. You sir, are a muslimist through and through.
I DARED as it's an attitude of LIONS to rip off the evils like Hyena.
I don't understand. You favor sex with children and lie and steal other's work. You also claim to respect me and show disrespect.
Are these things not evil? Is this what your religion is all about? I am confused.
LOL - what was that again? That's the most ridiculous statement I've come across anywhere!!!
Are you justifying child marriage? Also, in Saudi Arabia, you have cases of old men marrying young girls. CNN reported one such instance just a while back. Hmm, so what does one make of that?
When an Arab marries a young lady, it comes on CNN headlines and when a white son of a bitch rapist rapes a breast feeding baby or juveniles it comes as a small news on CNN, WHY???
Take for example the following from Washington post which came as a small news.
MOUNTWOOD DR., 9500 block, Dec. 9. A man allegedly had sexual contact with a female juvenile. A 33-year-old Manassas man was arrested.
Also, no one is talking about legality here - what about the morality of it? Did he feel comfortable marrying a child? You talk as if all men around that time were marrying children - was that the case?
may be she was happy to be married to the best man ever on earth
he died on her lap
and yes , it was the case
people mustn't marry young girls now especially as there are no reasons for that
as Muslims , we are sure that the prophet didn't oppress anyone by anyway
we believe this marriage as it was for reasons , it was also performed to have this contraversory issue in our days
Yes, she was comfortable and very happy.
How do you know -- were you a witness? Did you interview her?
If i did'nt then why are you promoting misinterpretations as i am dead shure you also did'nt interviewed her, why are you misrepresenting her???
What misinterpretation are you talking about --- its a fact. He did marry that girl -- so what is the misinterpretation? Did non-muslims manufacture her?
how much you get from Zionists???
It seems you are compiling up my replies and posts and preparing a book or a hub to right, very BAAD, you are stealing my stuff.
The misrepresentation from her side by you that she is not happy with that man
Oh yes - would she have thought of him as daddy. I am sure she would have been happy to have a father figure --- that would have made it alright, would it? Its a question of age and the morality of it and the correctness of it. A little girl wouldn't know - but a grown up adult should've known better!!!
Their is a trend by the old men of westerners to have juvenile mistresses aside from their so called wife / spouse / girl friend. So what's wrong if an old Muslim man marries a juvenile and gives her complete rights and respect as that of a wife.
If you can't see anything wrong in this you are one sick puppy!
Your past was just a creepy sperm and your future is dry clay. Whay are you so arrogant???
Fear ALLAH
He's blind. How can he see imperfection in his prophet. He's drowning in his own propaganda!!
Mr Usman- The "westerners" if they have any inappropriate relationships then they can be charged with bigamy/adultery hence punishable by a court of law. But in this case no matter even if given "rights" and "respect" the core issue of the subject being a minor makes even her consent(for consummation of marriage) inadmissible in any court of law and goes completely against all principles of natural justice. Hope you can understand my rationale and not take this as a personal attack on any individual. I am talking more from a principle point of view.
principles of natural justice, what a joke.
Mark- It is not funny at all for me. He is having a terrible misconception and if he is a young guy then please try to inform guys like him that there is more to it than what meets the eye.
Usman- First I thought you are an elderly person but after reading couple of posts I feel you may be a young guy who is just not getting the so called "facts" from the right sources. I have studied in US and also presently working in US. It is fair to say that there are good people and not so good people in every religion or even with no religion. And also my earlier point is there would be people always trying to prove others as bad to show themselves as good. A case in point is a guy called Zakir Naik who distorts and misrepresents facts to suit his particular point of view. Personally I have many wonderful Muslim friends and I have a pretty good opinion about Islam my friend. Have a good day.
Be my guest CW. I have a feeling you will be talking to deaf ears though. He is on a number of other discussion forums pushing his religion in much the same fashion.
Looking forward to the ensuing conversation actually.
not pushing just presenting, by the way right now you are in the forum of ISLAM presenting yourself as a funny guy
Mark- Maybe you are right about the "deaf" ears.
PS: I just read his response and wouldn't like to further engage in pointless conversations on this thread. Have a good day.
You give up too easy.
Just remember - these are open, public forums that anyone can see. I am not really talking to him.
Well there should be some give and take in fruitful discussions otherwise we would be going in circles. I am open to listen and discuss but when somebody doesn't want to listen then there is no point. I actually wanted to write a hub. Do you think there is anything to be gained in pouring water on desert sand when rather I could be watering a thirsty plant. I prefer to direct my energies where it might be of some use either to me(enjoying/learning) or others. But I admire you for your resolve. Have a good day and a wonderful weekend ahead. Btw I preferred my last post in this thread to be the last one but now I don't know(but I still hope I don't have to come back here)
Well, as I said - I am not really talking to these people. I am well aware that they have the information they need piped directly into their heads by their god, so I don't really expect them to listen.
But - other people can see and read these forums and make their own mind up.
Usman- 1) This point is correct. But it is also due to two factors one is that US has the third largest population in the world and also many a times many of the prisoners in 1st/2nd in population i.e., China/India have quasi judicial lockups more so in .)" (copied from the source).
Also many of the jails are full of drug dealers and other illegal activities for which the US still has a Judicial remedy unlike some countries where there "quick" justice meted out to such folks.
Source:- … -prisoners
2) About rapes there is no clear evidence but South Africa seems to have the highest incidence of rapes in the world. And also out of personal experience I felt much much safer both in the university campus and also around my present work place/home in US. Personally I have never heard of any incidences of rape in my brief stay in US so far(except in news sometimes).
Source: … 452C553558
3) Diseases and depressions: Many nations don't even acknowledge mental conditions as disorders to even seek treatment hence it is highly commendable that US and other western countries not only identify but also seek to redress the disorders.
4) US does have treasury bonds which are held by China/Japan(but no way any private family owns substantial stake in the US to control its decision making). And also Rothchild's total wealth i.e., there own wealth is no where near to "7.0 Trillion Dollars". Although reading further about family wealth folks like Rothchild's I found lot of conspiracy theories abound around them:-
Source: (For individual wealth) … _land.html
5) US does have its presence everywhere when the central agency like UN isn't adequate and I do agree it sometimes needlessly goes into war. But there purpose can be termed more profit motive rather than "sadism" which might seem with abu ghraib/guatanamo incidents. Sadly Bush spoiled the US image a lot and Obama is trying to redeem the US image. And also US is one of the first countries to mobilize relief/aid when and where it is needed hence they might be profit seekers but not "sadists".
6) Countries like Greenland which are in the arctic circle have half the year in total darkness and that might have a lot to do with the detrimental psychological effects although I have not researched this piece further.
7) Europe/US societies differ but at least everyone has an equal shot towards retirement pensions from government agencies like Social security where as in many Asian countries if the kids don't look after the parents then they have no other go. And more ever US does have a very strong Christian influence (especially in Midwest and deep south) hence not all are atheists and also all atheists aren't people with no human emotions of empathy or love as it seems to be from that statement.
8) "SIR" is a title award given by the British Monarchy as much as Bharat Ratna by India or Nishan-e-Imtiaz/Nishan-e-Pakistan by Pakistan hence it is up to the respective countries internal decision making body to take that call.
PS: Hope I did ok in my attempt, Mark
Dear CountryWomen
(1) USA and China have got separate ideologies, no matter based on the Darwin’s Theory of Evolution, yet their development and structures are different that is why China claims to be a Socialist state where as USA a Capitalist. Now if you analyze the history, the cry of Atheism originated from USA and has got the maximum number of Atheists. USA’s ordinary as well as elite classes were very much influenced by Atheism over the past hundred years, no matter Freemasons and Zionists supported Atheism as it takes people away from religion very easily. Take for example the support for the song of Lennon-Imagine there is no religion, recently, even Obama promoted the same very song in a gathering.
That’s the reason I mentioned the causes and effects of following the doctrine of Atheism by USA and Europe especially as an answer to Marks immature question.
(2) Sexual assault Statistics
• 1 in 3 girls and 1 in 4 boys will be sexually assaulted before age 18. (Office of Criminal Justice Planning)
• 80% of all rapes that occur are committed by a date or acquaintance. (Office of Criminal Justice Planning)
• 1.3 women in the United States are forcibly raped each minute. (Rape in America: A Report to the Nation)
• 68% of rapes occur between the hours of 6pm and 6am. (U.S. Dept of Justice)
• Only 2% of rapists are convicted and imprisoned. (U.S. Senate Judiciary Committee)
(3) You did not read my point carefully, read it again in the following especially the bold letters, also remember, USA claims to be the Super Power of the World.
USA alone, has got the maximum number of registered cases of Depression, Hypertension, Obesity, Breast Cancer, Aids ....... (a long list of diseases) despite the fact that they are leading a top notch facilitated life.
(4) Please do not give me wikipedia reference because it’s easily changeable, any body, you and me as well, can change the information on wikipedia. Just create a user account (free) and see how you can play with wikipedia
You call them conspiracy theories but for your kind information these have now become facts as thousands of evidences and chain of actions and reactions are recorded in this regard as well as in support of 911-that the job was not done by Afghanistan or Obama sorry Osama
(5) Thanks for agreeing but killing and butchering is not allowed whether it be for profit or for filling up the UN gape.
(6) Research it again.
(7) The true Christians are believed to be the nuns and popes in churches, the Christians you see around are merely name sake Christians just as there are name sake Muslims. Majority of the world whether be Muslims or Non Muslims are greatly influenced and submerged by materialistic gains which supports Atheism and this in turn supports Freemasons and Zionists.
(8) But spoiling an award on a book whose supporting material is slang, abusive and violent, how ridiculous. A proud English nation giving award for a pathetic book. Hhmmm …. Oh I see … May be it’s the effect of repeated marriages with cousins for generations that is why the Queen did it unintentionally as she blinks her eyes unintentionally.
Lol - you are a funny guy. You quote all those statistics as if that's supposed to mean anything. Well - news for you - it means nothing. In democratic countries, you have free access to information, you can gather data from people and people are open to sharing information. How many Islamic countries around the world can match that.
You make it seem as if sexual assualts don't happen in Islamic countries. Lol - read up some. In Pakistan, incest is common place. Now of course they don't show up in offical numbers - why? Obviously, because talking about the subject is taboo in countries like that. Also, the repercussions for the girl/woman involved is huge - could even mean death. So, why would a sexual abuse victim speak up in Islamic countries and how would that show up in statistics.
Statistics mean zilch. Fact is a lot worse happens in closed Muslim societies that go unreported because of fear, as I've stated above. Just who are you kidding with those lame numbers. Stop pretending you live in an ideal society. Your house is just as dirty (if not more). Stop deluding yourself.
Just another thing, I know sodomy of young kids is commonplace in Afghanistan. You ain't proving anything quoting statistics!!!
These Muslim countries which you see around are name sake Muslim countries divided in 1920s after the destruction of Khilafa. Caliphate(Khilafa) is the true Islamic State System. Read The Last Mughal by a non muslim historian to clear your misconceptions. For an overview of the book
You forgot, Mark is a funny guy not me
Zakir Naik distorts and misrepresents ... hhmmm ... like for example ???
My friend only folks who want to believe in people like him actually like him. Oh by the way here is one link among many links which state some of his assertions to be incorrect. If you want more links then let me know.
PS: I do admire that man for his memory in trying to remember the quotes/verse numbers but alas it is his agenda that keeps others from taking him seriously(unless for those who want to believe him).
i told you not to mention the wikepedia references as their text can be changed by anyone. Therefore it's not authentic. The sentence in the very first paragraph in your wikipedia reference "human males are polygamous by nature and that a man is less likely to cheat if he has more than one wife." proves wikipedia to be RUBBISH promoting falsehood against Islam as they get heavy payments from their Zionit God fathers. This sentence was never ever told by Zakir Naik. Take a look at the videos for clarification. The media takes verses as well as speeches of scholars out of context. So if you want to have the clear picture watch the whole videos not the edited portions of that as the wikipedia is presenting just to degrade Islam.
I guess you will only believe in what you want to believe. You feel the whole world is a "Zionist" conspiracy and Islam is 100% right and all others are 100% wrong. No matter myself or anybody else provides any amount of proof it will be discredited since they don't align to your views. It is ok for Dr.Zakir Naik and others to degrade other religions but not ok if there is any criticism of Islam in anyway by others. Grow up my friend. Anyway here is another link just search online and you will find may links like this.
PS: Thanks for inspiring me to write this hub: … rn-Nations
I hate to say "I told you so," but....
Out of experience comes good judgement. Please give me some more time to learn(maybe a few decades)..LOL
Edit: Dingdong even if religious I now feel reason only works with "reasonable" people.
LOL
Well, I have given up with people like him. Now - I just make fun of them and subscribe to the view that I am 100% certain there is no such thing as whatever it is they are 100% certain is right. Drives them insane... as you have seen.
Well his initial post where he compared different religions (including verses) seemed like a scholar but later his inability to understand other view points started making me doubt whether even the original posts were based on his own reading/understanding.
Anyway I guess by the time I get wise like you I would have people cracking these jokes at me.
That would be me actually lol
I did point out earlier that he had been cutting and pasting arguments that he had taken from elsewhere - these were not his own thoughts or words. But I guess that is OK if you are doing it in allah's name.....
Well I got into the thread from the middle and maybe I should have gone back couple of pages where you had already mentioned. I know you have a lot more experience and must have dealt with many folks to figure out by now. Btw it was meant to be me(how long it will take for me to become wise since I am 26 now) and not meant for you or anyone.
you can laugh as much you want because you are funning guy at all
Isn't it one thing all religious people do alike?
No one is degrading other religions, rather we are just showing the both sides of the picture. If i am standing on a cliff and getting amazed by the beautiful landscape and suddenly an innocent child comes near the edge while running unknowingly what a cliff is, what the edge is, what the pain is and what the death is??? You tell me is'nt it my duty to hold the child right there, is'nt it my duty to correct the child. If i let the child fall off the cliff, does not his parents blame me for not stopping him.
So, the clear pictures are presented to you and now if you want to jump off the cliff and die then go ahead, your choice.
The clear picture is that all the prophets are messengers of god, all are equal and no person should try and convert someone into his religion as both bow to the same one god.
Their message has been the same and you have quoted these before.
Even if I change the name from the Vedas to the Zen Avistha to the Quran - the message is identical.
Ekam evaditiyam
“He is One only without a second” -The Holy Quran
Na casya kasuj janita na cadhipah
“Of Him there are neither parents nor Lord” - The Holy Vedas
Na tasya pratima asti
“There is no image of Him - The Holy Avistha
Have changed the names, can you find a difference or are these truths identical.
God does not age with time as we humans do, his message is the same from the beginning of time as he is timeless.The prophets or messenger come to reiterate the same truth .
Prophet Muhammad- "salla allahu alayhi wa sallam" meaning “To your be your religion, to me be mine.”
Message is by the same ONE God-Allah and Message itself bears some similarities at certain points but not at all points. Take for example the message of following the final prophet which is there in all other religious scriptures and not in Qur'an as Qur'an itself was revealed on the last Prophet.
The message of all prophets is that there is this super entity which is all powerful, exists in everything and has all knowledge.
Being one with this entity is our true nature and it is a state of absolute bliss which we all can experience and is our true home , from where we and everything has come and will go back to.
Agreed, but the message does not stop here. It goes on and commands you to follow Prophet Muhammad (peace be upon him).
I am called prophet by many and my book is even ranked over editions of the Holy Quran.No one commands me except god. For me all the prophets are very great and equal and they have exactly the same message.
This is going back to the finger pointing to the moon or the message and the messenger .
Stop focusing on the finger or you miss out on the glory of the moon, similarly stop focusing more on the messenger than the message.You miss the point.
Please show me the difference in the philosophy of different religions or even saints? must be many gods according to you.
The biggest difference is related to the implementation. ISLAM gives you the right path as well as a way to implement that right path. No other religion on earth gives you these amazing details, take for instance. THEFT which is forbidden in Christianity, Islam and Hinduism (that's the right path). Now further only goes Islam and teaches you the way how to stop theft indivisually and globally. The step wise explaination is as follows.
(1) Islam guides and instructs not to become thief and do not steal.
(2) Islam guides and instructs about ZAKAT (charity) which is a minimum amount, 2.5% of the prescribed quantity of Gold or cash equivalent accumulated for one year. This amount must be given to poors and needy (a list of these kind of people are also mentioned) per lunar year by each and every rich person of community. The collection and distribution of Zakat can be done on government level if there exists CALIPHATE and CALIPH.
(3) After getting ZAKAT, if someone steals then comes the punishment of chopping off hands (the punishment is so sever that if a thief hears about it, at once starts thinking thousand times before robbery)
Imagine, if you implement these steps today, the poverty will be eradicated from the whole world. Even if only the 10 richest of the world, whose budget is more the the 3rd world countries all over, start giving ZAKAT there will be no poor on the face of this earth.
Why aren't muslim countries doing well then - in fact, why are they doing so terribly? You'd think life would be a paradise in your brotherhood countries, since you seem to make it sound as if following Islam is a cure-all. What's the state of education, status of women, poverty in islamic countries?
these Islamic countries are name sake Islamic countries, built after the destruction of Caliphate in 1922 by the hands of Christian Zionists. Now each of these countries were then given agents as Prime Ministers and Presidents which are called HONORARY MASONS in the language of Freemasony. Look at Africa in the world map. The irony is that they have divided the Muslim territory of Caliphate merely by using a ruler and pencil, drawing straight lines. So, these countries do not possess the complete Islamic law as a whole and the foremost evidence in this regard is that these countries are divided. In contrast, Caliphate (Islamic state), has got no division and all the territories are run under one governing body; Caliph, which we do not find today.
These are very minor philosophies.I am talking about God here.Do different religions worship different gods?
Do good is the message of all religions- wake up.
No religions tells you to steal or injure someone.All religions are equally good is what you need to understand.They are teachings of great masters who represent the Light or God.
Dear!
I am not trying to convert you at all, rather i am presenting you the things. I agree all the prophets (peace be upon them all) are equal and except the last prophet all the other prophets emphasized upon following the last Prophet Muhammad (peace be upon him) as he comes. So, when your Hindu Scriptures is saying that and you do not follow this commandment of your scripture it's your fault, not mine. I think it's very clear to you now and needs no further clarification
I am enlightened and take direct guidance and orders from God, don't need any prophet or any religion.
The prophets are guides who guide you on the path to walk, one must become like them.
Now Allah told me to write and show humanity the oneness in all religion and his prophets as ugly wars are happening in his name which really irritates him.
Allow me to stop you from falling over the cliff. Open your eyes, let go your ridiculous notions of muslimism and avoid the inevitable conflict with the other religionisms.
You can stop yourself from falling. It is not too late.
It seems there is some magic in your glasses which is not letting you see the clear pictures and kept you in delusion for years but i think there is a little spark in your heart which will ultimatley revert you back to ISLAM you will be welcomed.
It can be argued that you are the one living in delusion and self-propaganda. How many humans are there in the world and how many of them happen to be muslims? It seems the "truth" wasn't so true.
Wouldn't all this time (1400 years) have been enough to have made non-muslims see and accept the "truth." The fact that, they continue to follow their own religions -- proves the point that there is no such thing as "the truth" that you speak of.
I don't agree that just because all have not accepted "the truth" then it goes to reason that it (truth) does not exist. If that were the case ALL would accept it. Or,conversely, ALL would reject it.
The reality is, that the "truth IS out there", and it's up to each individual to find it. Unfortunately, today, truth has become relative for most people. Absolute truth is just that, absolute.In other words it stands alone. Being believed, accepted, rejected, denied or ignored does not change a thing. It just IS.
Of course, I am not speaking of, (or for), Islam.
Whether the "truth" exists or not --- no one belonging to any one religion can state with certainty that his/her way is the "only true way."
That attitude has cost many lives in the past, would continue to cost lives in the future. All for what? God? Why is it that goodness isn't limited to one group of people if they are the only ones to whom "truth" has been revealed?
To me religion is my own personal matter -- and I don't like someone preaching to me and sitting in judgment on my religion. Its none of their business. They've been given no divine right to do that.
Who is preaching to you? You mean outside of HP?
As I often say, these are mere words on a screen. You read them with your own prejudices. What one writes as a light hearted comment, another will take deep offence to. Others opinions/beliefs are just as valid as your own, and vice-versa. Take what you want, and give what you want.Don't blame others for that.
I wasn't talking to you - if your response was based on my post.
Are you a Muslim???
not even for Atheism ?
religious response at many times come as a result of the certain language Atheists use.
it is like religious people are trying to stop the revolutionary movement of absolute materialism thinking
regardless of who is right and what are the intentions of both sides , if a side uses the certainty language he must expect a similar response (which applies for both)
LOL
Absolute materialism thinking? Yeah right. The only reason you say you have the truth is because some atheist said there was no god first. Oh - wait a minute - that is not possible.
Guess you must have started by saying you had the truth.
Why do you guys always resort to semantics? Atheists are no more or less materialistic than anyone else. So - best to try a new argument.
Mark- That often seems to be the issue. I have seen the moment I say I am not sure if there is a God and I don't even say this with a certainty and lo behold I get lectures in ethics/morality. Somehow not being "religious"(according to them) makes me less of a human or lacking in the ability to spiritually progress. Isn't it possible that a human being can internalize what is universally good or bad and what is relatively good or bad with/without religion?
Even in this thread there are certain people who start with the assumption that there way of thinking/beliefs is the only way and then somehow there idea of only one life makes it imperative on all of us to choose there "only" way right here right now. I mean they feel that this is the only important religion or way to be followed as of now or for eternity. And then there are others who feel they have been listening to "God" and somehow have a different take but then there own idea of "self importance" seems equally inadequate. Anyway each to his/her own. As long as somebody doesn't tell me that "you will go to hell" I am fine with there beliefs. Have a good day everyone
I said absolute referring to atheism as part of it
people in some aspect are two groups :
those who have some religious or spiritual thinking
and those who completely deny them
I know materialism could include a lot of religious people
I might be material in some ways
so don't get everything wrong , would you ?
The attitude which you are talking about cost many lives in the past, present and future as well BUT not from Muslims' side. It was, is and will be from the side of Freemasons, Zionists, Fascists. The World War III will be initiated by Zionists (with Christian allies) against Muslims just as they did in WWI and WWII and Muslims will face sever caualties and losses.
RIGHT man, you are DAMN right!
It seems that you will also become a Muslim in the near future because as prophecised both in Christianity and Islam; after the ARMAGEDDON-WORLD WAR III, the world will become totally aware of the hidden agendas and propagandas of Freemasons and Zionists against ISLAM and innocent human beings and there will not be a single human who will be a Non-Muslims, everyone will happily accept ISLAM as the ULTIMATE ART OF LIVING ON EARTH.
So, get ready, if you survive in WWIII, you will find yourself as a Muslim after that.
Regarding the CIA references given by CIA for gender population is totally wrong and tottally oposite to authentic sources. Sources like
U.S. Department of Justice
Federal Bureau of Investigation
U.S. Senate Judiciary Committee
and some others EXCLUDING CIA because CIA has got the worst reputation for their false reports. Take for example, the report of nuclear weapons in Afghanistan and Iraq, after invasion no nuclear weapons found and the CIA reports were just used to invade for killing and buthcering innocents. Also at the end when Bush admitted his faults in his last speach (during an interview), the CIA did not publish any report for Bush to be the number one terrorist as they did with Osama. Where is CIA now??? why Bush is not trialed for fullfilling his sadist desires in Iraq. Bush admitted and was sorry that there were no weapons of mass destrucition in Iraq. That's how CIA misreportS and is used for Zionists agendas agains innocents. There are hundreds of other examples on false and bogus CIA reports.
they are two different Physicological attitude toward people , life , religionists and religions as well as what is happening generally in life
and congrats for the 100 by the way
That's a question that should be asked of you - how old are you seriously?? Most of the muslims I've encountered spouting this BS are 16 - 18 year old kids. You must be one of them - lol!!
please dont call me sir, i am not a scholar. I am just an ordinary Muslim.
When we see religions are dividing us, it's not the religions rather some mischief mongors who do it for personal gains. I repeatidly tell people to read your scriptures in context and then you will realize what's true and what's false. For comming together ther must be a central point around which all religions can sit together. There must be some points (not all) to which all religions must agree.
Now if you analyse, there are many things which are common in all the religions like "dont be adultrous, dont rape, dont loot, dont decieve, dont gamble, dont drink, dont have pork, dont have clothes of opposite sex, maintain modesty in clothes as well as hearts etc etc BUT the most basic commonality in all the religions is worship only ONE God and Prophet Muhammad is the last and final Messenger of God. This bottom line is as important as 2+2=4. If you do not agree with 2+2=4 then you can not become a good mathematician or engineer. Similarly the ONE God and the final Messenger concept is there in all the religious scriptures whether it be Christianity, Hinduism, Sikhism or Islam. Please have a look at my prevous posts for valid references from Bibles and vedas. Also. Now at least, come to this very basic commonality that all the religions have. All the religions agree that there is none worthy of worship accept ONE God and Prophet Muhammad (pbuh) will be the last and final Messenger, so whoever finds him, follow him. If there own religions are directing them towards ISLAM, QUR'AN, ALLAH, MUHAMMAD (PBUH) then what's the matter, why they deny this very basic and clear cut directions of their scriptures??? Even though Bibles, Hindu and other religious scriptures have been altered so many times in history yet the players were unable to remove these facts from these altered scriptures, is it not amazing, is it not a miracle of Qur'an, still preserved for the last 1400 years in it's orginal language, letter by letter. Qur'an is not the property of any Muslim rather it's a way of life for the whole of mankind as the previous scriptures were for the people of that time that is why the prophecy of following the last Messenger Muhammad (pbuh) is mentioned in all the previous scriptures.
After this intimation, you agree or not, that's totally upto you and them. No body can force you.
again what you are saying are related to the ideologies of the followers which are not there in their scriptures
Prophet Muhammad (pbuh) did not say your religion be true and me to mine rather he said to the whole of mankind "OBEY ALLAH (One God) AND OBEY HIS MESSENGER (Muhammad pbuh)"
Read different philosophies in order to understand whats in their scriptures.
Prophet Muhammad- "salla allahu alayhi wa sallam"
What do you think this means.Muhammad was not a fanatic, none of the prophets are fanatics.They understand the oneness of all.
Someone who thinks "HIS PROPHET-HIS RELIGIONS IS THE BEST."
= FANATIC.
Drop the my in order to see the truth.
"Behold but one in all things, It is the second that leads you astray" Kabir.
So you are entermingling the subject of Philosophy and Religious Scriptures. For your kind information, none of the religious scriptures state to learn / read this scripture according to this particular philosophy. Scriptures are self explainatory. Take for example the following famous verse from Bible.
".
Regarding me, i am nothing, i am just a lay man, my past was just a drop of sperm and my future is in the clay, you know very well i am not a fanatic as i am showing you the verses from these scriptures (forget about Qur'an and Islam) which themselves testify that there is no god but God (ONE) and Prophet Muhammad (pbuh) is the final Messenger of God. So where is fanatisim??? In me or in these scriptures. These scriptures themselves ordering you to follow Prophet Muhammad (pbuh) and take what he gives you. I quoted several verses from Bible as well as Hindu Scriptures mentioning clearing what i am explaining you.
So if some Christian, Hindu, Sikh, Atheist or Zionist does not agree with this basic notion of ONE God and the LAST Messenger (Muhammad (pbuh)) then it means they also do not agree with their own scriptures and just practice and preach the falsehood. In my whole replies especially to you and Sandra i did not quoted any Qur'anic verse or Hadith rather i quoted your own scriptures and showed how these Popes and Pandits hide these kind of verses from their scriptures and only preach what they like for some penny gains.
The biggest problem in this context is that the ordianary muslims, christians, hindus, sikhs do not read their scriptures at all, most of them have'nt read even a single translated verse ever in their whole lives. So now, if i or some one else comes and delivers the true context based interpretations, this becomes inacceptable for some of them and label us as fanatics
If you believe in Popes, Pandits or Mullas OR that you believe in what the scriptures tell you to do, the choice is totally yours.
".
Thay are one ,what you call the right expantion-
then i come to the right explaination of the the above mentioned verse that Jesus (pbuh) was saying that he and Allah are one in profession, the profession of delivering the true message.
Is very wrong, you do not understand Jesus or Allah .
I do no 'stringing.' lol. I simply am not that mean. (And if it seems like it--keep in mind it is always only done with slight humor attached with those I think can handle it.)
But doubt I have 'answers' anyway, so OK!
I dont belive on religions so I cant write anyting..Islam ,Hindu....
You have to have a reason for not believing but if you do not believe on religions then i must present ISLAM to you as the ultimate way of life as ISLAM at first, claims to be the ultimate way of life which encompasses Islam as a religion as well.
Usmanali81 - you have clearly come here to 'prove' that your religion is the only true one and that all others are either wrong or superseded by yours.
Just so we know the benefits of your religion, please provide a brief description of what awaits a christian, a hindu and an atheist or agnostic after death.
Please contrast this with what awaits a muslim after death. Please tell us in your own words, without reference to scripture. Thank you for your time.
For Both, Muslims and Non-Muslims alike, there is another life which is eternal and that's the thing which awaits us. Death is actually a transition to another life. There, to live eternally, are two places, Hell and Heaven. So, after getting the message and signs from Allah, we are bound to follow him and his given way of life - ISLAM which was also the way of life for all the preceding prophets and their companions.
And how do you know this is true, except by reference to the Quran?
hi Paraglider ,
I hope Usman would execuse me
because as I muslim
you simply submit to the creator
you start by pondering creatures , believe in a power
you read the books and have faith
faith is something you believe but without seeing God
this faith becomes as a reality as much as you ponder the world , study it and think about it
best reagrds
In other words you can't do it without begging the question. You can't simply submit to the creator if you don't think there's a creator. In other words, you can't start without having already started. Therein lies the irrationality.
Dear Paraglider,
Qur'an speaks about future in several places, off which almost 80% have become proved now, by established science, for instance, consider the following scientific facts in accordance with Qur'anic Verses.
Regarding the origin of the universe: happening by “chance” is nill.
“Do not the Unbelievers see that the heavens and the earth were joined together (as one unit of Creation), before We clove them asunder?” Qur’an Ch 21:V30
Regarding the impermanence of the sun’s existence:.
“And the Sun runs its course for a period determined for it; that is the decree of (Him) the exalted in Might, the All-Knowing.” Qur’an Ch 36:V38
Regarding the nature of the universe:
Edwin Hubble, provided observational evidence that all galaxies are moving away from one another, which implies that the universe is expanding. The expansion of the universe is now an established scientific fact.
“With power and skill did We construct the Firmament: For it is We Who create the vastness of Space.”
Qur’an Ch51:V47
Now, if a logical person ponders then he / she will come to the conclusion that "If Qur'an is 80% in complete accordance with established science then the remaining 20% which are not yet proved by science, for example, Heaven, Hell, Life after Death, will also be proved as correct and perfect in future where science becomes more advance.
Dude - it is really bad form to cut and paste arguments taken from other websites word for word. … 71844.html
Yes, of course but it's good to copy from a website which has no copy rights, for example,
I was more talking about you trying to pass these off as your own arguments rather than the copyright aspect.
I know your religion does not encourage you to think for yourself, but still......
Very bad form. And rude.
Mark - there are a group of guys like him on another forum I know of. They have lots of such cut-n-paste items saved on their PC. They spend all their time trying to prove Islam as the greatest religion ever, the one and only truth, etc. Its best to ignore folks like him.
I know - I started a thread about this recently after finding a christian website that suggested people cut and paste from their site to use as arguments against people who choose not to believe their stuff:
Which goes to one of my core arguments against most religions in that they discourage people from thinking for themselves.
Not really sure what one would hope to achieve by doing this.
Mark! what a funny guy you are
For your kind info religions have books which are to be followed.
Only in ISMs you can do and think anything you want, whether kill, butcher, rape, sex, loot, raid, plunder, gamble, decieve drink, ............ the list does not seem to end
LOL - Yours is just another ISM - which allows lying apparently.
For your kind information - I do not lie. I do not take other people's words and pretend they are my own.
You mean you have had an original thought? Here I thought there was nothing new under the sun! How wrong I was.
Seriously though, none of us can claim uniqueness when it comes to language. Everything we know we learned from others.In that sense, we don't own our thoughts/words as its originators.
Speak for yourself dj. I am not a religionist so I am allowed independent thoughts once in a while.
That is not the point I was making though.
Yes, agreed. Even in creation, no body is able to create a unique thing that we have never seen before, for instance, scientists create robots which resembles humans, insects or animals already created by ALLAH.
hhmmm, i did not pretend the references are my own. I openly admit it and giving an authentic reference is a good practice. You seem to be an atheist. Now if i say something against atheism, even with valid proof, it will not matter at all because i am a lay man and if i give you some valid references of some well known personalities with their vast vision, experiance and supporting evidences then it matters a slight. Now, if have something nice to say on it then come to
You cut and pasted something and gave no reference. Only after I pointed this out did you admit they were not your words.
I have nothing nice to say about your ridiculous statements on the other thread.I am not even sure what you are saying here either.
"valid proof"? What is that exactly?
consult dictionary for it
I don't have access to the dictionary you appear to be using. Your ignorance of science and language is quite astounding.
First of all, i do not cut rather copy and paste. This action is done only for the valid references. It's very legall and you can also do it.
Adding a link to make a point of reference is not what you are doing. Legality has nothing to do with it. This is a moral issue. You are cutting and pasting other people's words and attempting to pass them of as your own. This is lying. Isn't that a punishable offense against Allah?
I've seen all that pseudo-scientific stuff before, in a printed book claiming to prove that Islam predicted modern science. Unfortunately, vague phrases that can be interpreted retrospctively to have been prophecies carry no weight as argument.
What you are saying is that the Quran can be said to be in accordance with rigorous scientific discoveries, therefore where it diverges completely even from the field of scientific study, it should be taken to be absolutely true.
Sorry, but your argument doesn't stand up.
If there is a choice between two things to eat A and B. And you have to choose only one of them to survive.
A is 80% pure
B is 20% pure
Which one will you prefer ???
Pure what? Pure drivel, maybe.
Look - if have a box of clock parts and I shake them all together, will they turn into a clock? No of course they won't. But that, and all other baby metaphors, do not constitute sensible argument. Apart from quoting scripture and other people's leavings, you've not said anything yet to support your case.
Imagine, without typical metaphores, how boring the lecture of a teacher will be, how boring will be the speach of Obama, how difficult to make a child understand, how difficult to explain the theory of reletivity Therefore, relevant metaphores are a MUST to use for a good writing and speach
How pompous and arrogant of you to claim that. No wonder tolerance of other religions doesn't come naturally to people like you.
i am very tolerant, i did'nt kill you yet
Rajabilil and others on here who are supposed to understand Islam, please check this out:
and tell me what you think.
Thanks
Also click on
Please refer to the books written by NON MUSLIM celebrated Historians. I stressed on Non Muslims because most of the readers do not agree with the Muslim Hisorians.
In the near future i will be writing a hub (INSHA ALLAH) mentioning some of the beautiful, informative websites worth visiting because most of the non muslims and muslims alike access some wrong websites which does clearly delivers the true message of Islam and these kind of sites are just injected into the NET for maligning and degrading ISLAM and promoting PRAGMATISM (successor of ATHEISM), CAPITALISM AND ZIONISM.
I appreciate the good side of Islam, Christianity & Judaism. I understand the hypocracy, violence and hatred that have occured, and will continue to occur--there is only so much I can do. I just want to save a life, help others out, and maybe teach someone peace (once I learn that abstract concept myself, in it's most pure state [but even then, what is that?])
Religion is how you translate it, I don't think there is any "religion of peace", since humans are all different, translate religion different, and thus violence may occur (sometimes on global, genocidal levels).
I'm not understating the seriousness of religious violence, I just understand why it occurs, and the psychology behind it. A calm mind acts quicker, swifter and more precisely.
Selam
what do u mean there is no religion of peace...as far as i'm concern there is no religion that does not promote peace...all religion promotes freedom, kindness and good deeds...it's just us as an individual take this thing for granted which explains the violence and hatred amongst each other
I fail to understand why people fight in the name of God and religion. God must be laughing at all of us thinking what kind of jokers HE has created. Religion is nothing but a road map to reach the Almighty and there is nothing wrong in having different road maps. We have all the time in the world to say our map is better than his road map. Time we all grow up.
Too many roads to choose from. Trouble is, they are ALL dead ends. Even if they could reach the "gate", they will find it shut.
Jesus is that gate, and many will not be able to go through. (for obvious reasons).
Jay
sometimes it might be the case
but sometimes people need to discuss with love to have a strong faith
both cases may coexist , I hope we would be from the last type
thanx
Yes, it's time to grow up and do not count 2+2=5.
Dear, If ISLAM claims to be the final word of God and Prophet Muhammad (pbuh) is the final messenger of God whom each and every human being must follow then their is a reason for that and the foremost reason is that the same message is prophecised in alimost all ohter religious scriptures and they instruct their followers to start following ISLAM if you find it.
So now, what's the problem in accepting ISLAM if your own religions are directing you.
But FSM came after islam. Surely this is the true religion to follow? Did you try what I suggested? You will feel much better afterwards.
You probably won't be afraid of gay people any more either.
We dont get affraid. Remember, we dont join army to earn
homosexuality
and more more
of course some diseases are not only becauce of homosexuality
And therein lies the ridiculous contradiction of your irrational beliefs. Islam is another religion of hate and intolerance.
That is why I asked the original question. You said the people were forbidden. Don't see how you can do that.
Do you think homosexuals should be punished?
you may need to read more and write less
do not just repeat what people say
where did I say that
qute me please
no if they didn't do it in public
and for myself , honestly , I don't either love or hate them
i thought that up all by myself thanks. Unlike yourself - I can think for myself instead of parroting stuff from a 1600 year old hate manual.
Try thinking for yourself instead of just repeating the stuff in your book. You might see how irrational you are being.
If you come to my country (Indonesia), you'll see the majority of Indonesians are Muslims, many of the Muslim women wear veils, with variety of clothes; long pants, skirts, or long dresses. We go to school, study in university, get married, and raise our children.
We do what other people all around the world do everyday; go to work and earn some money. None of my family members thinks of blowing him self or hurts others who aren't Muslims, what for? It's busy enough taking care of our own families, why bother doing irrational things such as hurting others?
About homosexuality, actually that is not the only thing forbidden in Islam. Muslims are also not allowed to drink alcohol, pork meat, or engaged in sexual relationship unless they are married.
Whether one likes it or not, when one embraces Islam, he must follow the rules. That way, he can show God (Allah) that he has become the good follower.
BUT, God (Allah) says in Quran that there's no force for anyone to embrace Islam. Being a Muslim or not is a man's choice, even those who have embraced Islam the first time must never force others to do the same, let alone hurt them.
About some Muslims who prefer do the 'harsh' ways, I think the problem is not as easy as calling them 'terrorists'. Even us Indonesians had to fight over our freedom for 350 years before the first president proclaimed Indonesia's Independence in 1945. Long before the year, we fought Portuguese, Netherlands, UK, and Japan's colonial governments and troops who came to Indonesia and tried to rule us. I think the same thing may be happening to the Muslims in Iraq, Pakistan, or Afghanistan right now. Maybe it's because we're seeing the battle now, that we address them as terrorists. Perhaps, hundreds of years later, our grandsons don't even recognize any battle that has ever happened there because the countries have become a safe, prosperous, free places to live.
All in all, I think it's very rude to accuse and generalize that all Muslims are 'terrorists' and Islam is 'another religion of hate and intolerance'. Muslims are just like any other people in the world who want peaceful life to live (so are the Christians, Buddhists, Hindus). The rules in Islam are set only for the followers, when you're a Muslim you should obey them but you don't have to if you're not. NONETHELESS, being a Muslim is choice, not a force.
Forgive my lack in English.
I think you should read a few of the other posts and threads - see how many of them are clearly showing hatred and intolerance towards gay people.
They do not seem to have a problem with people eating bacon sandwiches, but the gay thing is obviously intolerant.
And your English is fine.
Just like your attitude towards religion in general, 'twin.'
Like I said - if you have nothing to say why bother? I mean - I am up for a good argument, but your inane one liners are unlikely to do much for me.
Try saying something - go ahead - I will argue with you. Or does your religion rely solely on antagonizing people? Do you even have any opinions that are not negative one liners?
When the Creator wants you to have women then why you run after GAYISM ?????????????????????????????????????
Maybe your creator is a homophobe like you?
so much people say islam is old and intolerate,here I found not that evidence but people who never know islam itself
Posting in an epic trainwreck thread, as per usual.
See you guys next week!
Aren't you glad you suggested a religion forum?
I am, there are gems in this forum, mostly threads that don't have ten pages of back and forth arguments!
It never ceases to kill me how muslim extremists are so eager to blow themselves up. I mean, here's the rest of the world taking medical checkups, eating low carb diets, exercising, doing therapy, yoga and all what not just to keep alive, and these guys just go along, strapping their chests with loads of C4, and blowing themselves into smithereens. It gets me all the time.
Those who blow themselves up killing innocents can not be justified at all in Islam.
But now consider the case of those whose, innocent mothers, daughters, sisters and wives were raped, tortured and killed ruthlessly in front of them after tying them up, whose respectfull fathers were beaten to death in front of their eyes, properties and belongings looted, houses captured and destroyed, tell me what will be their state of mind??? Do you expect them to roast a lamb and distribute candies to Israeli and American soldiers????????????????????????????????????????
I belong to a Muslim family, never once has my parents disapproved my being friends with people belonging to other religions or castes. I may not be the perfect Muslim, but I do pray & read the Quran & I have yet to come across any statements that encourages killing, hurting or even verbally abusing any individual be it Muslims, Jews, Hindus, Christians etc. The Quran states that humans hold the most prestigious position among all living beings.
The extremist groups who are spoiling the name of Islam are not Muslims in any sense of the word! They are just against humanity and they will duly suffer the consequences in life or at the day of judgment. It saddens me when people compare & fight over religions and nationalities. No religion promotes such profanities, it is the people who hav wrong perceptions & we are all accountable for what is happening in the world today.
If we hope for world peace, we all need to join hands & come together for fighting against extremism and all the causes that are promoting differences among all.
I challenge that we can not fight extremism by ignoring the fact and influence of Zionism the world over. Do you know what Zionism is??? The extremists which people talk about do not have any businesses, jobs or bank accounts then who is providing them MONEY, FOOD and WEAPONS??? Think about it.
Now we are getting to what your religion is really all about.
Just another ISM.
I did not ever say to become ignorant of these issues, i was merely stating my opinion regarding the religious debate. People everywhere hold wrong perceptions about our religion, If we start calling them names as well, wat would be the difference among us all? Our religion teaches us the msg of peace & patience. The same qualities among many were practiced by Mohammad PBUH. He did not seek revenge from his enemies even after He gained victory over Makkah.
I am well aware of these extremists & the propaganda surrounding the whole Islamic teaching concept. either way we Muslims are being targeted in the name of war against terror, wat about those poor innocent people who have been deprived of their homes, properties, even their basic needs. People have lost their relatives, family members etc. Its not that easy to start fighting or conducting a war against anyone, everyone overlooks the after effects of such issues.
you are most welcome and by the way i or other muslims did not created the names like ZIONISM, ZIONISTS, FREEMASONS, NEW CONSERVATIVES etc. These names were given by themselves. If you have any beautiful names for them, do not hasitate to suggest them . smile
And here comes the megalomaniac again, mohit get back on your pills!
Truth doesn't change because you cannot handle it.
No truth here to handle.
Give it time, you will understand.
Typically condescending.
You started your crap again.
Just pointing out your propensity to let your ego run the race.
Speaking the truth.If you had written a book got ranked over Holy Bibles, Holy Qurans,top 10 poetry, top philosophy-Religious, top 10 spiritualism and mentioned it - it would be called truth.Only a foolish megalomaniac , zealot would come and abuse you in case you were really that person.
Here we go with the megalomania again.
You are the meglomaniac, the idiot, the zealot, the fool, the swine.
He he! You are as weak as piss mohit. You lose your cool pretty easy ay?
ASSHOLE go tell this to your pop.
Beautiful.
Glad you liked a dose of your own medicine- hope it feels really nice.
Nothing going on here.You speak, you say who you are!
i just want to laugh here (not on any particular) ... please let me ...
Mohit and Earnest!
Can't you two bear with each other. Earnest really have some big problem with Mohit. I don't know what's that???
You don't? Try reading this.
mohitmisra wrote:
earnestshub wrote:
mohitmisra wrote:
Speaking the truth.If you had written a book got ranked over Holy Bibles, Holy Qurans,top 10 poetry, top philosophy-Religious, top 10 spiritualism and mentioned it - it would be called truth.
Here we go with the megalomania again.
You are the meglomaniac, the idiot, the zealot, the fool, the swine.
The list grows...
usmanali81 and me are having a nice debate, kindly stay out of it as you don't understand what we are talking about.
Just letting you see yourself!
Have I lied about my book rankings that you call me names? If I had not written a book and got ranked and then you called me names I would accept it but why should I take your abuse when I am speaking the truth? I have never come to your business forum and abused you.
This is a religious forum, i don't believe that has anything to do with business, unless you are trolling here for sales of your book.
And I am a very highly ranked religious poet/philosopher is simple truth.Means I am very qualified to be here and express my views and I do not lie.
Your ranking is negligible except on two sites, your poetry is infantile, and how much you know about nothing astounds me.
anyway you wanna take the discussion to some place and he wants to take it to another
don't you get it
he is saying , I dont need to know what they mean because they don't worth that
and we are called Muslims ya Marksist
My thought is that Islam is as good as any other religion. It is only a group of people who are earning bad name to this religion. Recently there was some "Racial Discrimination" against Indians in the US and Australia. We cannot say all Americans or Australians are IDEOTS or Terrorists because of these incidents. South Africa and even the US have witnessed the war of supremacy between the BLACK and the WHITE. It is only a group of people.
Dear Mark!
You are really a funny guy
Leaving right now as i have to do some shooting practice
Wa salam ( Peace be upon you)
You shall not murder!!!
and brain wash kids to die for you..
Thats all Ive got to say about that
only if some one wanted to kill or control you
violence is solved with love but with violence sometimes
"These wars are justified or are they lame?
It is with love and not terror does the One get tame."
Don't click on the picture. It is a spam journalism site. If you don't want any unwanted cookies or bugs- I would stay away!
What a crappy move Guidebaba!!
Many wars have, and still being fought in the name of God.
Who-evers name it is done is still wrong!
Any god
Any man
Wrong
Probably you are right about others reading and making up there minds(if not the intended target). I will see about how I feel and decide whether to participate. I sometimes feel drained when the point I am trying to make doesn't seem to go through. Thanks for the encouragement.
My pleasure - he will be back tomorrow after terrorist training school.
usmanali80 Wrote the following
Dear Mark!
I respect you as an elderly man.
usmanali81 why respect someone only because they are elderly, which Mark is not by the way.
I agree with Mark, you are rude in the extreme! Not all people are controlled by some invisible entity so that they will behave out of fear. Some of us have the capacity to control and deal with our own processes and do not need to be told that we are somehow less than you because we have chosen to think for ourselves.
I have nothing against any religion including Islam. In fact I do not believe in Religion. It is the single most destructive institution that man has ever created.It has divided people and most of the religious leaders are nothing but criminals. we don't need religion to guide us..
we need perfect rules to guide us , don't we ?
people are not perfect
Religion isn't perfect either - in fact, some religions are more dangerous than people themselves. People who blow up other people state they do so because of their religion and its teachings - don't they? Why is it that they interpret their religion differently than some others following the same religion?
it might be because they would act bad with or without religion interpretations
it is their nature , don't you think ?
they may fight for the ideology if religions'v never existed
I agree, some would fight for the sake of fighting.
If it is in their nature and religion doesn't have to do anything with it --- then why claim one religion is better / perfect / the true religion / etc ?
Just accept that they are good and bad people in all religions and the good shall go to Heaven and the bad shall go to Hell (if you believe in God). Why categorize some as "infidels" and condemn them and say they will go to Hell, etc?
That's intolerance - don't you think??
I think
may be because God wanted us to worship him by his way
(simply not having partners with him)
he may wanted to test us to know whether we would think our religion is better because of ego or because we are grateful to him
a true religion is approached by loving God & people without seeking fame or anything else
people should love eachother and show others the way of good
we do this as we are grateful to whom created us and guided us to good
people don't judge who is in hell or heaven as we don't know what in the hearts
people have rights to God
their rights to other people is included in these of God
everything goes back to him
And this apparently includes the right to F*** 10 year old girls.
well , some aspects in life can't be taken , understood alone
don't you think ?
discuss the points I wrote before
tell me where I am wrong instead of repeating specific points for your own purposes
it is about faith
no one of us was alive at the time of the prophet
A TRUTH = TRUTH
AND FALSE = FALSE
So do not mix them, when Islam claims to be the final truth now, then their is a reason for that. The foremost reason is the other religions themselves prophecised Muhammad (peace be upon him) and instructed to follow him. So, now following the outdated religions like Christianity, Judaism, Hinduism etc is itself keeping our selves in DARK.
Now you must come towards the light; ISLAM-The Final Art of Living for Mankind.
So everyone should convert to Islam correct?
They are obviously worshiping some other god and false prophets -correct?
The prophets spoke different truths according to you-correct?
If this is not called fanatical behavior-what is?
This like god telling his left arm to chop his right arm off- madness.
Please do understand all other religions believe there will be one more prophet after Muhammad if not a few prophets after him.
Bingo.
After getting the real true picture, everyone SHOULD accept ISLAM and if they don't, then it's their own choice and no body can force them. Now that's BINGO
Not in this lifetime. Not even in the next though I'm very open and receptive to muslim people. Everyone can worship whatever they want and that's A-Ok with me. Not interested in your religion for myself. Sorry.
It's ok, certainly you can but the next stage of life will be based on punishment and reward. No second chance will be given in the form of new life from scratch.
Not according to your prophet who was a wise man.
Prophet Muhammad- "salla allahu alayhi wa sallam" meaning “To your be your religion, to me be mine.”
Please listen to your prophet and stop making up your own stories and in the process make him out to be some fanatic.
You are ruining the prophets name, he taught tolerance and not fanaticism.
God belongs to all and not only to those who call themselves Muslims.
For your kind info, "salla allahu alayhi wa sallam" means peace be upon him. It's not to your be your religion, to me be mine.
And yes, God belongs to all and the message of ISLAM is for the whole of mankind not only for Muslims
Qur'an, Ch 2-THE COW, V."
Peace is what he wants , what all the prophets want.
Live and let live-Mahavira
So if god belongs to all of humanity including every religion then let people follow the religion they want to .
Some Parsees say Zaratushtra was the first recorded prophet-does that make their religion greater than any other?
Before that you had Hinduism which simply engulfed all philosophies-Hindus-Indus -the people residing by the river Indus.
When you say one cannot compare Jesus with god then you cannot say all is Allah.In your case all is not Allah. Poor god no longer omnipresent.
Bramha, Allah, Jevovah, Vishnu, Ahuramazda, Shiva...
What’s in a name?
A way to identify the same,
Geography, language is mainly to blame.
Your glory is such,
Man asks for too much.
Meditation or one pointed concentration is the key,
But who says there is no fee?
Names does not matter but when a name refers to a God with 10 heads and 50 hands and sun shining behind it, that really irritates as Hinduism itself is against creating images of God so why do these Hindus do it, it's their fault not mine.
The first and the last prophet of the world does not make some one great. The greatness comes where all the religious scriptures of the world mentioned the comming of Prophet Muhammad (peace be upon him) in Arabia and instructed to follow him when you find him. That's GREATNESS, that's where the elders of other religions start personal jealousy and hide behind these verses by misquoting, misinterpreting the scriptures out of context to ordianary people.
WAKE UP ... the world is near to end
So why have mosques, aren't they equated with idols?
The hands and heads are symbolic.
You will have to remove All is Allah from your philosophy which is something you cannot do.If all is Allah then not only the prophets but every humans, animal ,thing is Allah.
You have this philosophy but turn a blind eye to it and discredit other religions.
How many times do I repeat that all other religions expect their prophet, do you really think Muhammad was Jesus who had returned or that Muhammad was a twin which the Parsees expect or that he was born into a Brahmin family, wrote and united the religions according to Hindu philosophy? NO
Look at the one in all in order to understand truth, your religion or prophets is the best is non sense.
Masjid represents the unity and disipline. It's not that we have idols there. Even some people have houses on top of Masjids and live there. Tell me which idol worshiper stands or sleeps on top of his / her idol???
So, Masjid is not an idol
If the whole world were to be dominated by Islamists then, I'd guess the top priority would be to destroy statues of Buddha and other such idols.
I am not advocating Taliban but the fact is if Bhudda was alive today, even he had destroyed these statues
Nonsense it stand for the ideal man every human can become.
Isn't it something physical?
The Buddhas statues become idols but the mosques do not- how convenient.
We enter the Masjid, the followers of Bhuddas could not enter a statue. Any way Bhudda also forbidden statues but their followers built them and worshiped, it's not my fault rather the followers'
Its called respect and its just fine.
So you are saying is all is not Allah who is limited in space and does not encompass everything.Buddha was great prophet like Muhammad , how would you feel if someone had torn or blown him up.?
This my religion is the best attitude has and is only leading to ugly wars and it is not what Allah wants .This is your greed and your ego power trip which makes you say this.
"Unto Allah is your return and he is able to do all things" The Holy Quran.
Everything including every human comes and goes back to Allah and not only those who call themselves Muslims.Allah or Shiva or Jevovah is juts a name symbolizing the same great entity or God.
This is as foolish as fighting over ma or mata or mai or mater or mother saying no only ma is correct all others are wrong.
All stand for mother , its just a different name used by different languages.
Yes, every one will return to Allah but Allah will not forgive those who associated partners with Him, who made images of Him, who did not followed the fullfilled prophecies regarding Prophet Muhammad (peace be upon him) mentioned in Bibles, Hindism, Bhuddism, Sikhism, Parsiism .......... list goes on and on
The last prophet is yet to appear accordoing to the Christians, Hindus and Parsees ,why cant you understand that.?
Sikhism was founded on the teachings of Guru Nanak who was considered as a great prophet by many and does not say Guru Nanak is not a prophet and that Muhammad was the last prophet.Which crappy books are you reading?
They have The Holy Guru Granth Sahib considered as the word of god and is a compilation of different spiritual poets who praised the light and these poets belonged to different religions- Omkara- God is one, so beautiful, no fanaticism.
Images and idols are a mark of respect for that particular saint or prophet who represent the light.They are guides who take you beyond to Allah -the Light.
Mohit,
Refer to the following which clearly prophecise Prophet Muhammad (pbuh) catagorically in Hinduism and Christianity (major religions)
Guru Nanak, Guru Garanth Sahib, Osho and many others are not dwellers of Arabia but Prophet Muhammad (pbuh) is.
So bored with this copy-n-paste. Are you typographically challenged my friend? Come on - use your own mind for a change.
My mind is deadly sure about what is written in your books but the problem is you are not getting it. when you will get rid of saying 2+2=5
Lol - you don't have a mind to speak of. This thread is filled with reams of material you've copied from other forums/sites.
So, where does that leave you? All that you've done on this thread is to display muslims in bad light to all those who've read this thread.
You've come across as being intolerant and dismissive of anything and everything different from Islam.
Hinduism does consider Muhammad as one of the great prophets but believes there will be one more who will be born into a Brahmin family will write and unite the religions something Muhammad doesn't fit into.
a both in the ‘Panchgavya’ and the Ganges water (i.e. purging him of all time)
Did the prophet Muhammad bathe in the river Ganges?
Do you really belie people who follow the teachings of the Great Buddha or the Great Jesus Christ are wrong?
Is Jesus Christ not going to return?
Is the Maetrya or Buddhs not expected now?
The prophet Muhammad has simply repeated these philosophies which were written a long time before he came on this planet and you have quoted from the Vedas and Avestha, truth does not change over time but is timeless like god.
The prophets come and repeat the same truth when humanity has gone astray, when people abuse religions and stop following the correct path to walk.
Guru Granth Sahib is the Sikh Holy book and not a saint or prophet like Guru Nanak or Osho. It includes great Mulsim poets saints like Kabir and Farid.
Now tell me these great mystics were foolish ?.
Dear Mohit,
The Prophet Muhammad (pbuh)’ as described by Qur'an.
Further if you read
Bhavishya Purana: Prati Sarag Parv III: Khand 3: Adhyay 3: Shalokas 10 to 27
“The Malechha have spoiled the well-known land of the Arabs. Arya Dharma is not to be found in the country. Before also there appeared a misguided fiend [enemy] whom I had killed; he has now again appeared being sent by a powerful enemy. To show these enemies the right path and to give them guidance the well-known Mahmada .”
This Prophecy states:
: Surah Al Fi’l: 105: 1 – 5)
(iv) Prophet Muhammad (pbuh) has been given the responsibility to guide the opponents of Divine Truth. Allah testifies the same responsibility in the Qur’an. (Al Qur’an: Surah Al Ma’idah: 5: 67)
(v) The Indian Raja need not go to Arab land since his purification will take place in India after the ‘Musalmaan’ meaning the Muslims will arise in India . This is what is promised by Allah that Islam will not just reach India but will prevail all over the world. (Al Qur’an: Surah Tauba: 9: 32, 33; Surah Fata’h: 48: 28; Surah Saff: 61: 9). Muhammad [pbuh] too commanded in His last sermon to all those present in the sermon to spread on earth wherever possible, in order to convey the Message of Islam in the Light of Qur’an and Authentic hadiths as mentioned in a Hadith recorded in Sahih Bukhari: vol: 4 H: 667
(vi) The coming Prophet Muhammad [pbuh] will attest the Truth of the Aryan faith i.e. Monotheism and will reform the misguided people. This is what the purpose of Muhammad [pbuh] being sent to mankind as Messenger was and as is testified in: (Al Qur’an: Surah Ambiya: 21: 25; Surah An’am: 161 to 165)
(vii) The Prophet’s followers will be circumcised. They will be without a tale on their heads, they will keep beards and they will create a great revolution. A similar message is mentioned in a Hadith recorded in Sahih Bukhari: vol: 7 H: 780, 781
(viii) They will announce the adhan i.e. ‘call for prayer’. Al Qur’an: Sura Ma’idah: 5: 58; Sura Jumu’ah: 62: 9 AND Sahih Bukhari: vol: 1 H: 578
(ix) He will only eat lawful things and animals, but will not eat pork. The Qur’an confirms this in no less than 4 different places: “Forbidden for you for food are dead meat, blood, flesh of swine and that on which had been invoked the name of other than Allah…”. In Surah Al-Baqarah: 2: 173; Sura Al-Ma’idah: 5: 3; Surah Al-An’aam: 6 : 145; Surah Nahl: 16: 115
(x) They will not purify with grass like the Hindus, but by means of sword they will fight the evil-doers. The Qur’an confirms this in Surah Baqarah: 2: 191, 192; Surah Nisa: 4: 74 – 78; Surah Taubah: 9: 111
(xi) They will be called Musalmaan. Similar Message is in Surah Aal-e-Imran: 3: 64; Surah An’aam: 6: 163; Surah Fussilat: 41: 33
(xii) They will be a meat-eating nation. The Qur’an permits humans to eat herbivorous animals in Surah Ma’idah: 5: 1 and in Surah Mu’minoon: 23: 21
===============================================================
Now,.
For Mahdi, Muslims do not believe he will return or he will be the Prophet, no, not at all. It's only a prediction about a Muslim man among others named Mahdi who will lead the people of the world as a just and honest Muslim leader / Caliph near the end of time and during this time Jesus (pbuh) will also return (come back).
Please do a search on avatars and you will understand Kalki is supposed to come now and and not fifteen hundred years ago.
You are saying Jesus will return and at te same time Muhammad is the last prophet. so what will Jesus be when he returns.
Of the ten universally recognized avatars, nine have already manifested whereas the tenth is yet to appear.
It is important to note that the all the Avatars are earthly form of Lord Vishnu , who himself is eternal, unchangeable and immutable. specially popes and priests
Didn't Muhammad repeat what had been said many thousands of years before him.The prophets come to reiterate the same truth.The truth doesn't change, its timeless like god.
Yes, the truth remains the same. What you are talking about is the basic truth: Follow only ONE God-Allah. In addition to that there are several other things, there are several other does and don'ts which were somewhat same as well as different from book to book. For example, the prophecy as an instruction to follow the last and final Messenger Prophet Muhammad (peace be upon him) when he comes is there in almost all the religious scriputes of the world but is not there in Qura'n because Qur'an itself was revealed on Prophet Muhammd (pbuh).
So, the basic message is the same but depending upon different situations, circumstances and mental levels of the people of different times the particular books were revealed and for the people who are near the end of time, the book is QUR'AN, for you as well as for me.
Follow the truth of the messengers which is the same.Have respect for the all the prophets and religions equally.
For example, the prophecy as an instruction to follow the last and final Messenger Prophet Muhammad -how many times do I have to repeat that most geat relgions are waiting for the last prophet who will unite the religions as all are children of god.
You agree he spoke nothing new so live and let live.
Would you try and teach Muhammad about god? My work is being ranked in the same league as the Holy Quran, dont you think you can learn the truth about god from me?
Muslims respect all the prophets more than any other.
Regarding the prophecy, it had been fullfilled more than 1400 years ago, i mentioned the verses of Hindu Scriptures to you in detail. So what are you waiting for, Antichrist???
You are very thick skinned and fanatical.Please read what I have written about different religions expecting their prophet now as I am sick and tired of repeating it.
Why don't you write a book and get ranked over the Holy Quran since you believe you have a better understanding about god than I do.?
Since all the prophets spoke the same truth why in the world should everyone follow Muhammad?
You agree they spoke the same truth so what sense does it make? Is it because he is your prophet and you belong to Islam?
Oh sure -- the most important thing to God is to punish those who've made images of him - ridiculous!!
You cannot respect his prophets, he gets angry and doesn't allow you to come home.
Usmanali has changed the philosophy to all is not Allah who has suddenly become limited in his capacity. Poor god is no longer omnipresent.
I think from your point of view, the punishment must first be given to the naked on the beaches.
Why are you irritated by differences? That's intolerant - if you can't accept another way of life, being lived by another group of people. How does that affect you? Why should you be bothered by any of that? They are not telling you how you should live - so why are you so affected by it?
The answer is your perceived superiority about your religion and about yourselves as a people.
"Wake up" - you say -- are we all asleep according to you Well, speaks volumes for the arrogant attitude of Muslims like you. Intolerance seems to be in-built in Islam, if I were to go by your utterances.
there are a lot of similarities between your religion and mine even i am following the prophecies regarding Qur'an, Islam, Muhammad (peace be upon him) mentioned in your religions.
The differences which you have got with me are the same as you have got with your own religion, i think it's Hinduism. You are not following the fulfilled prophecies but i do and yes that's the difference
Lol - I have got no differences with my own religion. My religion isn't rigid and unflexible. I don't have to take literally even word and phrase written in my books - unlike you. Beheadings and chopping off hands need not be practiced in my religion to conform to the book. And I glad it is that way
hhmmm, your religion is flexible, go ahead, STEAL
Doesn't seem to stop you does it? I have watched you stealing other people's words and pretending they are your own. THIEF!
nice head Mark, you seem to visit the shoe maker frequently ... ha ... m i right
Its the same message by all prophets, religions are brothers and should not fight with each other as to which is the superior one.
i am just defending . The attacks are from your side
You say "no body can force." Unfortunately (from your perspective) muslims don't have the power to enforce Islam on others in this age. If they had the power, such intolerance as shown by you, would ensure that they did use power to convert.
where did i show intolerance in my sentence. Infact, i said "and if they don't, then it's their own choice and no body can force them."
Who are you to sit in judgment of "truth" and "false?" Who gave you and your co-religionists the right to sit in judgment of that? You just prove the fact by your postings - the fact that you are an intolerant lot.
You and others like you are just like the Taliban in mindset -- you have just covered yourselves with a veneer of apparent modernity.
It is funny to see people like you drown in your own propaganda. Please yourself and believe in your grand delusions -- for you have nothing better to do than to try and prove the "greatness" of your own religion.
And people wonder why Islam breeds intolerance? With an attitude like that - should one wonder why the Taliban destroyed the Buddha statues in Afghanistan? Its intolerance and it seems to be a hallmark of much of your co-religionists.
may be Taliban was trying to teach Bhudhas, not to worship statues as Bhudism also denounces images of God.
Regarding judgments, i did not made it, these are the judgments made by your own scriptures, you don't believe it, go ahead, enjoy!
ISLAM is the only perfect way of life remained to be followed. Islam does not promote killing.
"There is no need to change your faith,
And on your old religion lay a wreath."
Like I said before only someone who is ignorant about god will try and convert someone and only an equally ignorant person will convert.
Also you mentioned the Parsees living in Iran , they escaped into caves and mountains when the massacre was taking place and came out of hiding years later when the madness had stopped.
No religion in the world promotes killing , all promote peace and oneness. The prophet has understood the oneness of this entire cosmos and shares this message .
God exists in everything.
There is no such thing as a "perfect way." Such words indicate an arrogant mindset that says --- my way is the only way, the only true way and all other ways are trash, etc, etc. Which is what you have been trying to prove unsuccessfully here.
If Islam does not promote killing:
1. Why are so many of those who carry out terrorist attacks Muslims?
2. Why do they justify their actions in the name of Islam --- obviously some verses are open to interpretation - aren't they?
You may say it does not promote killing -- however, what is the ground reality? Are they not killing and don't they expect to be rewarded by Allah?
There are some things which are perfected by Allah, your Lord and my Lord
Ch 3-The Table, V."
Those who blow themselves up killing innocents can not be justified at all in Islam..
Regarding ground realities. Read this
"we found genetically engineerd dates alomst equals the lenght of a hand and burgers in a foreign packing."
Lol - is that the best you've got to explain the Taliban? So, let me see. What you are saying is that the Taliban was created and air-dropped into Pakistan/Afghanistan? Is it?
Where did these enlightened Taliban gain their education from? Which madrassas were they? Do I hear madrassas in Pakistan?
Oh wait - but I can see another Zionist conspiracy theory being put forward to that as well
Shill1987,
i am really very sorry about your mental condition, any way, there are 100s of more methods to drop them in Pakistan, for example, by road, 100s of roads lead to Pakistan from IRAN, INDIA, CHINA, AFGHANISTAN, RUSSIA and there are 100s of no mans lands in these territories where these mercenaries get their training from Zionits.
Further, there are different tribes and groups in some of these areas. Zionists also use to buy the elders of some trouble making groups, train them, feed them with dumps of food, weapons, money, ideas. These things then automatically distributed to the people under a group lead by it's elder.
Now you will ask how Zionits come in these territories??? They come via HONARARY MASONS most of whom work as PMs and Presidents of the countries involved. Also some of the leading businessmen, diplomats, higher officials are hired as honarary masons who help them achive their goals. Ultimatly, Zionts buy people from both sides and watch them fighting, killing and butchering and that's the prerequisite of the awaited Antichrist-One eyed Dajjal
By the way how you got your training for degrading Islam by making such foolish replies.
Lol - who are you kidding? The Taliban were neither air-dropped from the skies not transported via roads. They studied in madrassas in Pakistan. Face facts, instead of living in denial.
come on, go ahead, right a book on my replies, the book will get best sellers award
I see that you've run out of copy-n-paste stuff. Oh dear - why don't you visit some of your favorite Islamist forums for some inspiration. You are at a complete loss for words aren't you?
i think you are in the wrong place, go to a beach and count the number of naked people there.
This forum's title is ISLAM.
I have written a book and its got ranked over the Holy Quran so what advice do you have for me?
immediatly go to a Psychiatirist
You need a visit for sure. But, I wonder if the psychiatrist would remain sane after a Q&A session with you
Franklin-top spiritual and religion sorted by popularity … r/ebooks/0
4.
$1.50
[Add to Cart]
Ponder Awhile
Model Number: BBAL1419646729DLDA
Author: Misra, Mohit.K., ... more »
11.
$12.95
[Add to Cart]
The Qur'an
Model Number: BBAL9780192831934DLDA
Author: Haleem (Translator), M. A. S. Abdel ... more »
eBooks : Spiritual & Religion : Mobipocket Reader - Download
Truth is arrogant for the common man but simply truth for the awakened one.
You should visit a doctor for trying to teach me about god or Allah or Jevovah or Shiva.
Muslims have told me your book is so easy to understand god but the Quran is too complicated. Couldn't understand god after reading the Quran but got a better understanding after reading your book. This is true for almost all spiritual books, they are just too complicated for the common man and can very easily be misunderstood.
For better understanding of Qur'an you have to read the traditions of Prophet Muhammad (pbuh).
I understand the Quran or Allah better than you do.I have read about the prophet.Dont you think a spiritual writer ranked over the Quran would have a better understanding than most humans or at least you.? Do you think you can write on god and get ranked over the Quran, be one the same page as the Holy Quran and Holy Bible ?
students of Madrassas are still studying there.
In other words - they were not air-dropped or transported via road by Zionists but are the creation of your own madrassas - that brainwash young kids to hate all things Western, to hate music, to hate modernity, etc.
Just to add ---- there are no "perfect rules." That's a myth. And no religion can claim to have laid down "perfect rules" for people to follow!!!
may be you are right
but people can't know the perfect rules when they see it because they are not perfect
Myths are ISMs bassed on Pagan ideologies.
hhmmm...World War I and II were not the product of relgions rather the ideologies were from ISMs and none of the ISMs believe in the ONE God-Allah.
So, look at the history, even today and then make your decision again.
If Islam is the religion of peace
then what religion do the 'taliban' follow? .....yea right!
Doesn't quite answer the question --- don't you think?
You know the time when the Taliban were ruling Afghanistan, I came across so any muslims on online discussion forums (all educated ones) who were praising the Taliban for implementing the "true Islamic way." Now, I ask you this --- were they all wrong?
Now, of course, a lot of them shy away from owning up to the Taliban openly -- because they've gotten so much bad press. But, still they argue that they were essentially good people --- and still are good people. So, there seems to be a confusion amongst muslims as to what to make of the Taliban.
Why this confusion. Why don't they all share unqualified outrage at what they Taliban did and still do?
I don't know
I am just trying to say that some people act due to their religions but in fact they are not told anywhere to kill innocents
I don't really know them to judge them
but it could be just the case of chosing between two bad alternatives
I think the Taliban were very extreme in implementing Islam
you are right
it is so much contraversial
I haven't really met one of the Taliban
but if they are killing innocents people then I am completely against them
and I am more against those who kill more innocents than the Taliban do (The US army)
what do the Taliban still do ?
best regards
All I got to say is obviously "rajabilal" posted this forum to create a strong debate and stir up controversy.
Are you joking... ranked over Quran and Bible in Sales/Popularity? How come I have never heard of you?114 years ago
Jesus was considered false messiah by majority among people who had heard about jesus till romans accepted christianity...then he became accepted saviour,god by majority who heard about him etc...then came muhammad who... Claire Evans17anesix4 years ago
That Jesus is Real?Please, only serious answers. I'd really like to know.
by Kashif Habib2 years ago
Is there something you really dislike most in islamic teachings?Please be brief.
|
http://hubpages.com/religion-philosophy/forum/12053/islam
|
CC-MAIN-2017-26
|
refinedweb
| 32,518
| 71.44
|
react-native-svgreact-native-svg
react-native-svg is built to provide a SVG interface to react native on both iOS and Android.
FeaturesFeatures
- Supports most SVG elements and properties (Rect, Circle, Line, Polyline, Polygon, G ...).
- Easy to convert SVG code into ReactNative code.
InstallationInstallation
AutomaticAutomatic
With Expo, this is pre-installed. Jump ahead to Usage
Install library from
npmnpm install react-native-svg --save
# NOTICE:
- react-native-svg >= 3.2.0 only supports react-native >= 0.29.0
- react-native-svg >= 4.2.0 only supports react-native >= 0.32.0
- react-native-svg >= 4.3.0 only supports react-native >= 0.33.0
- react-native-svg >= 4.4.0 only supports react-native >= 0.38.0 and react >= 15.4.0
- react-native-svg >= 4.5.0 only supports react-native >= 0.40.0 and react >= 15.4.0
- react-native-svg >= 5.1.8 only supports react-native >= 0.44.0 and react == 16.0.0-alpha.6
- react-native-svg >= 5.2.0 only supports react-native >= 0.45.0 and react == 16.0.0-alpha.12
- react-native-svg >= 5.3.0 only supports react-native >= 0.46.0 and react == 16.0.0-alpha.12
- react-native-svg >= 5.4.1 only supports react-native >= 0.47.0 and react == 16.0.0-alpha.12
- react-native-svg >= 5.5.1 only supports react-native >= 0.50.0 and react == 16.0.0
Link native codereact-native link react-native-svg
Or use
rnpminstead:rnpm link react-native-svg
ManualManual
AndroidAndroid
- Add
import com.horcrux.svg.SvgPackage;to the imports at the top of the file
- Add
new SvgPackage()to the list returned by the
getPackages()method. Add a comma to the previous item if there's already something there.
Usage>;}
Common props:Common props:
Supported elements:Supported elements:
SvgSvg
RectRect
The element is used to create a rectangle and variations of a rectangle shape:
Code explanation:
- The width and height props of the element define the height and the width of the rectangle.
- The x prop defines the left position of the rectangle (e.g. x="25" places the rectangle 25 px from the left margin).
- The y prop defines the top position of the rectangle (e.g. y="5" places the rectangle 5 px from the top margin).
CircleCircle
The element is used to create a circle:
Code explanation:
- The cx and cy props define the x and y coordinates of the center of the circle. If cx and cy are omitted, the circle's center is set to (0,0)
- The r prop defines the radius of the circle
EllipseEllipse cx prop defines the x coordinate of the center of the ellipse
- The cy prop defines the y coordinate of the center of the ellipse
- The rx prop defines the horizontal radius
- The ry prop defines the vertical radius
LineLine
The element is an SVG basic shape, used to create a line connecting two points.
Code explanation:
- The x1 prop defines the start of the line on the x-axis.
- The y1 prop defines the start of the line on the y-axis.
- The x2 prop defines the end of the line on the x-axis.
- The y2 prop defines the end of the line on the y-axis.
PolygonPolygon
The element is used to create a graphic that contains at least three sides. Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
Code explanation:
- The points prop defines the x and y coordinates for each corner of the polygon
PolylinePolyline
The element is used to create any shape that consists of only straight lines:
Code explanation:
- The points prop defines the x and y coordinates for each point of the polyline
PathPath
The.
TextText
The element is used to define text.
STROKED TEXT
TSpanTSpan
TextPathTextPath
In addition to text drawn in a straight line, SVG also includes the ability to place text along the shape of a
We go up and down,then up again
GG
UseUse.
SymbolSymbol
The SVG element is used to define reusable symbols. The shapes nested inside a are not displayed unless referenced by a element.
DefsDefs
The element is used to embed definitions that can be reused inside an SVG image. For instance, you can group SVG shapes together and reuse them as a single shape.
ImageImage
The element allows a raster image to be included in an Svg componenet.
HOGWARTS
ClipPathClipPath
The SVG element defines a clipping path. A clipping path is used/referenced using the clipPath property
Q
LinearGradientLinearGradient:
- Horizontal gradients are created when y1 and y2 are equal and x1 and x2 differ
- Vertical gradients are created when x1 and x2 are equal and y1 and y2 differ
- Angular gradients are created when x1 and x2 differ and y1 and y2 differ
Code explanation:
- The id prop of the tag defines a unique name for the gradient
- The x1, x2, y1,y2 props of the tag define the start and end position of the gradient
- The color range for a gradient can be composed of two or more colors. Each color is specified with a tag. The offset prop is used to define where the gradient color begin and end
- The fill prop links the ellipse element to the gradient
NOTICE: LinearGradient also supports percentage as prop:
This result is same as the example before. But it's recommend to use exact number instead; it has performance advantages over using percentages.
RadialGradientRadialGradient
The element is used to define a radial gradient. The element must be nested within a <Defs> tag. The <Defs> tag is short for definitions and contains definition of special elements (such as gradients).
Code explanation:
- The id prop of the tag defines a unique name for the gradient
- The cx, cy and r props define the outermost circle and the fx and fy define the innermost circle
- The color range for a gradient can be composed of two or more colors. Each color is specified with a tag. The offset prop is used to define where the gradient color begin and end
- The fill prop links the ellipse element to the gradient
Touch EventsTouch Events.
Run example:Run example:
git clone react-native-svg-examplenpm i# run Android: react-native run-android# run iOS: react-native run-ios
TODO:TODO:
- Add Native method for elements.
- Pattern element.
- Mask element.
- Marker element.
- Load Image from URL.
- Transform prop support.
Known issues:Known issues:
- Unable to apply focus point of RadialGradient on Android.
|
https://www.npmjs.com/package/react-native-xsy-svg
|
CC-MAIN-2022-21
|
refinedweb
| 1,089
| 57.67
|
This C++ program which converts given Gray Code to Binary Code. Both the codes can be stored in a character string. The Binary Code is formed as follows: The most significant bit is same for both, the bit value of next position of Gray Code and previous Binary Code are XORed and stored in next position of Binary Code until we reach the end of Gray Code string.
Here is the source code of the C++ program which converts the given Gray Code to Binary Code. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Convert Gray Code to Binary Code
*/
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
std::string gray, binary;
std::cout << "Enter the gray code ";
std::cin >> gray;
binary = gray[0];
for (int i = 0; i < gray.length() - 1; i++)
{
/* XOR operation */
if (binary[i] == gray[i+1])
binary = binary + "0";
else
binary = binary + "1";
}
std::cout << "Gray Code : " << gray << std::endl
<< "Binary Code : " << binary << std::endl;
return 0;
}
$ a.out Enter the gray code 1000 Gray Code : 1000 Binary Code : 1111 $ a.out Enter the gray code 0101 Gray Code : 0101 Binary Code : 0110
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
If you wish to look at all C++ Programming examples, go to C++ Programs.
|
https://www.sanfoundry.com/cpp-program-convert-gray-to-binary/
|
CC-MAIN-2018-34
|
refinedweb
| 226
| 68.81
|
/*
* Field.Field;
import java.lang.reflect.Modifier;
import org.simpleframework.xml.util.Cache;
import org.simpleframework.xml.util.ConcurrentCache;
/**
* The <code>FieldContact</code> object is used to act as a contact
* for a field within an object. This allows a value to be set on an
* object field during deserialization and acquired from the same
* field during serialization.
* @author Niall Gallagher
* @see org.simpleframework.xml.core.FieldScanner
*/
class FieldContact implements Contact {
/**
* This cache contains the annotations present on the field.
*/
private final Cache<Annotation> cache;
* This is the list of annotations associated with the field.
private final Annotation[] list;
* This is the label that marks the field within the object.
*/
private final Annotation label;
* This represents the field within the schema class object.
*/
private final Field field;
* This is the name for this contact as taken from the field.
private final String name;
* This is the modifiers for the field that this represents.
private final int modifier;
* Constructor for the <code>FieldContact</code> object. This is
* used as a point of contact for a field within a schema class.
* Values can be read and written directly to the field with this.
*
* @param field this is the field that is the point of contact
* @param label this is the annotation that is used by the field
* @param list this is the list of annotations on the field
public FieldContact(Field field, Annotation label, Annotation[] list) {
this.cache = new ConcurrentCache<Annotation>();
this.modifier = field.getModifiers();
this.name = field.getName();
this.label = label;
this.field = field;
this.list = list;
}
*
public boolean isReadOnly() {
return !isStatic() && isFinal();
}
* static field or method. A static field or method is one that
* contains the "static" keyword. Any static final fields will
* be read only and does not require any matching annotation.
* @return this returns true if the contact is a static one
public boolean isStatic() {
return Modifier.isStatic(modifier);
* This is used to identify annotated methods are fields that
* can not be modified. Such field will require that there is
* a constructor that can have the value injected in to it.
* @return this returns true if the field or method is final
public boolean isFinal() {
return Modifier.isFinal(modifier);
* field.getType();
* Reflector.getDependent(field);
* This provides the dependent classes for the contact. This will
* typically represent a generic types for the actual type. For
* contacts that use a <code>Map</code> type this will be the
* generic type parameter for that map type declaration.
public Class[] getDependents() {
return Reflector.getDependents(field);
* This is the class that declares the contact. The declaring
* class is where the field represented been defined. This will
* typically be a class rather than an interface.
* @return this returns the class the contact is declared within
public Class getDeclaringClass() {
return field.getDeclaringClass();
* This is used to acquire the name of the field. This will return
* the name of the field which can then be used to determine the
* XML attribute or element the contact represents. This ensures
* that the name provided string is internalized for performance.
* @return this returns the name of the field represented
public String getName() {
return name;
*) {
if(type == label.annotationType()) {
return (T) label;
}
return getCache(type);
private <T extends Annotation> T getCache(Class<T> type) {
if(cache.isEmpty()) {
for(Annotation entry : list) {
Class key = entry.annotationType();
cache.cache(key, entry);
}
return (T)cache.fetch(type);
* {
if(!isFinal()) {
field.set field.get(source);
* This is used to describe the contact as it exists within the
* owning class. It is used to provide error messages that can
* be used to debug issues that occur when processing a contact.
* The string provided is the generic field string.
* @return this returns a string representation of the contact
public String toString() {
return String.format("field '%s' %s", getName(), field.toString());
}
|
http://simple.sourceforge.net/download/stream/report/cobertura/org.simpleframework.xml.core.FieldContact.html
|
CC-MAIN-2017-13
|
refinedweb
| 624
| 50.94
|
View Complete Post)
hello,
i want to know if a workflow can run when it detects a sync has been done with a list with project 2010 ?
thanks
I'm running VS 2010 on Win7 64bit. When I create a new prject using the "Windows Phone Game (4.0)" template and try to build the solution, I get the following error message:
Error 1 The "BuildContent" task could not be loaded from the assembly Microsoft.Xna.Framework.Content.Pipeline, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553. Could not load file or assembly 'Microsoft.Xna.Framework.dll' or one of its dependencies. The specified module could not be found. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask. TestBuild
Anyone else having this problem?
Thanks ran into a compile issue stating Error: "Mixed mode assembly is built against version of runtime v1.1.4322 and cannot be loaded in 4.0 runtime without additional configuration information" for a License.licx file from a 3rd party component included inside
my Project I wanted to update to .Net 4.0
The problem was not in the license.licx file or the assembly, but lc.exe included with Visual Studio 2010 C:\<ProgramFilesFolder>\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\lc.exe
This is the exe that processes the license.licx file when compiling the project.
I needed to add support inside a config file in order resolve this error. So I created a new lc.exe.config inside notepad and added this information then copied it to the same directory as the exe and now my license can be checked appropriately and
my projcet can now use the .Net 4.0 Framework.
lc.exe.config
<?xml version ="1.0"?>
<configuration>
<runtime>
&
|
http://www.dotnetspark.com/links/10514-imported-workflow-project-does-not-compile.aspx
|
CC-MAIN-2017-43
|
refinedweb
| 314
| 59.5
|
1597326638
You found this article because you want to send emails using Python script. Now a days, it’s a common task to send email through a system. In this article will learn how to send emails with simple text/HTML contents with/without attachment in Python.
There are so many ways to send mail through python code. One is by using the **smtplib **module. One setting needs to be changed in the gmail account to receive the email from python script.
Better to create a new gmail account and use in development because there’s a chance you might accidentally expose your login details. Also, the inbox gets filled up rapidly with test emails. Below link will redirect on required page of gmail setting as shown below in picture.
Turn Allow less secure app to ON
Required module need to be import at the beginning of the code.
import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart
Configured the email attributes like subject ,receiver email, sender email, password of sender.
sender_email = 'mypython2244@gmail.com' receiver_email = 'mypython2244@gmail.com' password = 'XXXXXX' ## please put your password here. message = MIMEMultipart("alternative") message["Subject"] = "How to send mail from a Python script" message["From"] = sender_email message["To"] = receiver_email
Here two variable create one holding plain text and other holding HTML code these represents two different message body. Here will learn how to configure plain text and html text in email body.Create Account</a> </p> </body> </html> """
Now the final step is to attache these two body with mail content and send to gmail account.
## Turn these into plain/html MIMEText objects part1 = MIMEText(text, "Body_text") part2 = MIMEText(html, "body_html") ## Add HTML/plain-text parts to MIMEMultipart message() )
Sending.
#development #python #send mail #python's #send emails
|
https://morioh.com/p/977b148a4973
|
CC-MAIN-2022-40
|
refinedweb
| 300
| 65.93
|
The following program have no compile time errors, because, in particular the first line indeicates the program directive, there are no space between after or before declaration of # statement. So that the program run corectly.
//Header file
#include
using namespace std;
//Main function
int main()
{
//Variable declaration
int number_of_pods, peas_per_pod, total_peas;
cout << "Press return after entering a number.
";
Prompting the user to enter input values from the keyboard.
//inputting pods
cout << "Enter the number of pods:
";
cin >> number_of_pods;
//inputting peas
cout << "Enter the number of peas in a pod:
";
cin >> peas_per_pod;
Compute the total peas usng the values of number of pods and peas per pod.
//calculating total peas
total_peas = number_of_pods * peas_per_pod;
Display the output.
//Displaying output in format
cout << "If you have ";
cout << number_of_pods;
cout << " peas pods
";
cout << "and ";
cout << peas_per_pod;
cout << " peas in each pod, then
";
cout << "you have ";
cout << total_peas;
cout << " peas in all the pods.
";
return 0;
}//End main
Sample Output:
Press return after entering a number.
Enter the number of pods:
5
Enter the number of peas in a pod:
7
If you have 5 peas pods
and 7 peas in each pod, then
you have 35 peas in all the pods.
Chegg Solution Manuals are written by vetted Chegg Programming experts, and rated by students - so you know you're getting high quality answers. Solutions Manuals are available for thousands of the most popular college and high school textbooks in subjects such as Math, Science (Physics, Chemistry, Biology), Engineering (Mechanical, Electrical, Civil), Business and more. Understanding Problem Solving With C++ 8th Edition homework has never been easier than with Chegg Study.
It's easier to figure out tough problems faster using Chegg Study. Unlike static PDF Problem Solving With C++ Problem Solving With C++ Programming.
|
https://www.chegg.com/homework-help/problem-solving-with-c-8th-edition-solutions-9780132162739
|
CC-MAIN-2018-30
|
refinedweb
| 291
| 59.03
|
------------------------------------------------------------------------------- *** PRELIMINARY *** Building Hercules-390 for AIX 5.3 ------------------------------------ 1. Standard AIX systems do not have autoconf, automake, zlib or bzip2 libraries and headers; these can be downloaded from <> and installed using rpm (rpm is part of AIX 5.3). Autoconf/automake require some pre-requisites, such as gettext, info, m4, libsigsegv and expat; all these could be downloaded and installed from the same place. 2. Enter the configure and make commands to build/install Hercules: ./configure && make && make install (or you can run each command separately if you want). 3. That's it! Enjoy your private mainframe. :) ------------------------------------------------------------------------------- The above is based on efforts done by Alexey Bozrikov [bozy@fgm.com.cy], Harold Grovesteen [h.grovsteen@tx.rr.com] and Fish [fish@softdevlabs.com] on the Hercules-390 Yahoo group list during the month of October 2009. ------------------------------------------------------------------------------- Still remaining TODO: - Get SCSI tape working: resolve <sys/mtio.h> header & 'struct mtget' issue(s). #if defined( HAVE_STRUCT_MTGET_MT_GSTAT ) #else // !defined( HAVE_STRUCT_MTGET_MT_GSTAT ) #endif // defined( HAVE_STRUCT_MTGET_MT_GSTAT ) - Test networking (did you do this yet Alexey?)
|
http://sourceforge.net/p/hercules-390/git/ci/master/tree/
|
CC-MAIN-2015-18
|
refinedweb
| 169
| 60.72
|
We work with text file a lot in scripts and O'Reilly cookbooks are awesome. They are quick references when you need something fast. This book is full of good examples when you need to, say, validate an IPv4 address in a bunch of text, or find a particular BGP neighbor / IP combination.
Here is a quick example of what I drew up from Recipe 3.5 to search for IPs in a list of IPs:
##### Script #####
# Modified from "Regular Expression Cookbook 2nd Edition", Recipe 3.5
import re
pattern = raw_input("Type in Pattern to Search: ")
f = raw_input("Type the file to search: ")
subject = open(f, 'r').readlines()
reobj = re.compile(pattern)
print('... Start ...')
for line in subject:
if reobj.search(line):
print("Matched: " + pattern + " in line " + line.strip())
print('... Done ...')
#####
I use the following script to generate a file that has all the IPs in 192.168.1.0/24 and 10.0.0.0/24 called TestIP.txt:
#####
#!/usr/bin/env python
f = open('TestIP.txt', 'w')
# prints all the IPs in 192.168.1.0/24
for i in range(256):
f.write('192.168.1.'+str(i)+'\n')
# prints all the IPs in 10.0.0.0/24
for i in range(256):
f.write('10.0.0.'+str(i)+'\n')
f.close()
#####
##### TestIP.txt #####
.....
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
<blah>
192.168.1.252
192.168.1.253
192.168.1.254
192.168.1.255
10.0.0.0
10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4
10.0.0.5
<blah>
10.0.0.252
10.0.0.253
10.0.0.254
10.0.0.255
##### Here is one usage ###
>>>
Type in Pattern to Search: 10.0.0.5
Type the file to search: TestIP.txt
... Start ...
Matched: 10.0.0.5 in line 10.0.0.5
Matched: 10.0.0.5 in line 10.0.0.50
Matched: 10.0.0.5 in line 10.0.0.51
Matched: 10.0.0.5 in line 10.0.0.52
Matched: 10.0.0.5 in line 10.0.0.53
Matched: 10.0.0.5 in line 10.0.0.54
Matched: 10.0.0.5 in line 10.0.0.55
Matched: 10.0.0.5 in line 10.0.0.56
Matched: 10.0.0.5 in line 10.0.0.57
Matched: 10.0.0.5 in line 10.0.0.58
Matched: 10.0.0.5 in line 10.0.0.59
... Done ...
>>>
##### You can also use meta characters to narrow down your search ($ means end)
>>>
Type in Pattern to Search: 10.0.0.5$
Type the file to search: TestIP.txt
Matched: 10.0.0.5$ in line 10.0.0.5
###
Done
>>>
### Some examples that allows for IPv4 and IPv6 addrsses
8.16 Checking IPv4 address, disallowing leading 0:
^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}↵ (?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$
8.17 Checking IPv6 address within text8.16 :
(?<![:.\w])(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}(?![:.\w])
Here is the review as it appears on Amazon:
O'Reilly cookbooks are awesome. But just like I don't read the recipes cover-to-cover in regular cookbooks, I don't read all the recipes in the O'Reilly cookbooks either. Also just like regular cookbooks, the day before Thanksgiving is not a good time to open the cookbook for the first time, I at least glance thru all the recipes to know what is there, pick out a few that I can use right away, and dog ear the ones I think I will come back to. So here are the criteria that I review this book with:
1. Easy Navigation: Yep, this book is easy to navigate. If I need to do, say form validation, I know I should start at Chapter 4 "Validation and Formatting".
2. Clear and precise explanation: Yes, I think the explanation are short and precise to the topic of discussion.
3. Pointer for more information: This is hard to do, but the book has a section on "See Also" for correlation between recipes and a general pointer toward 'Master Regular Expression' in the introduction chapter.
4. Easy Reading: Hum.. here is more of a wish list of mine, I wish the book is broken down into different books by language. The book covers these languages, VB.NET, C#, Java, JavaScript, XRegExp, PHP, Perl, Python, and Ruby. I typically skip down to Python and occasionally stop at C# and PHP. The book is over 600 pages and listed at $49.99. I would have been happy to pay 1/5 of the price to get one that just focus on Python, and another 1/5 of the price to get one on PHP.
All in all, it is a good value and a keeper on the bookshelf. But I really think it should be broken down into language-specific cookbook as most reader probably use only one or two languages on a daily basis. With today's print-on-demand, e-book format, I think it would be very minimal work for the author and a whole lot of less skipping for the readers. Just my 2 cents.
Hey Eric.
This books actually looks really cool! Perhaps bit "geekish" to think of regex as being cool, but whatever! :D
Really nice example you have there!
I'm having fun with python, and actually creating a small script for Mac tracking("show mac add | include ab12", and show the cdp neighbor and continue until found). But regex' with PExpect ain't that easy imo >.<
Hi Joe, yeah totally. I think 90% of the time we just figure out the RE for whatever it is we are doing and just move on with life. :) Which makes it a perfect cookbook-type of subject.
For the problem you described, do you grab the output, dump it to a temp file and analyze? That is how I find easier to do than try to do it in memory via PExpect. But maybe you mean something else?
This comment has been removed by the author.
Pretty awesome Joe. I will make sure I use it next time I have the need. Nice of you to put all the comments in the code. :)
Cleaned it up a
|
https://blog.pythonicneteng.com/2012/09/book-review-regular-expression-cookbook.html?showComment=1533319947828
|
CC-MAIN-2022-27
|
refinedweb
| 1,110
| 86.6
|
I have been reading and watching few videos on learning Rails 4. All tutorials has their own code so, in my views, easy to follow. I can't seem to learn anything or remember few things so I have decided to use my own code and see if I could follow instead of using their code.
So far I understand the Controller corresponds with the views:
# In my controller
def index
@x = "I love Ruby"
end
<% = @x %> #=> I love Ruby
def index
@x = "I love Ruby"
end
def languages_i_hate
languages = %w[
Perl
PHP
C#
C++ ]
end
<%= These are the languages I hate to bits: #{languages_i_hate.upcase}!
What you are trying to do here is access a controller method in the view. When you do this the controller method is accessed as if it was a helper method. Normally controller methods aren't available to be used in this way, but you can tell the controller to make them available as helpers.
See
BTW, when you have methods in the controller which aren't actions, ie don't correspond to a route/url, you should put them in a
protected section, by convention at the bottom of the controller. This makes it clear to rails and to the reader that they're not actions.
|
https://codedump.io/share/HtANDwjU9L6l/1/rails-4-what-goes-in-controller-and-model
|
CC-MAIN-2017-43
|
refinedweb
| 213
| 73.61
|
This article was written and submitted by an external developer. The Google App Engine team thanks Andi Albrecht for his time and expertise.
Andi Albrecht
October 2008
NOTE (Nov 2010): The App Engine team recommends readers also consider an alternative the approach in this article which attempts to port various App Engine APIs to Django.) For more information on using Django-nonrel with App Engine, please see our Django-nonrel article which shows you how to convert a native App Engine webapp app to a pure Django app.
Introduction
In this article we explain how to port applications that were originally designed for App Engine with Django to any environment that supports Django. The helper application provides a Django based implementation of the App Engine APIs and its aim is to minimize the effort of porting your App Engine application to run anywhere using Django.
After a short instruction on how to obtain the
gae2django helper application, we demonstrate using the helper so that Rietveld, the code review tool written by Guido van Rossum, runs on any environment that supports Django.
Finally, we talk through how to use the helper with your own App Engine Django application, and give some notes about required changes and potential pitfalls.
To follow the examples in this article, we assume you are using the command line and have a Mercurial client installed on your system.
Obtaining the Helper
The project is hosted on Google project hosting, which uses Mercurial. To obtain the
gae2django helper run
hg clone django-gae2django from the command line to fetch the latest version from the project's repository.
The
django-gae2django directory contains a Django project structure along with the helper. You should use this same directory structure when including the helper with your existing Google App Engine applications.
The Rietveld Example
In addition to the helper, there's an
examples directory with everything prepared to convert Rietveld to pure Django. To learn more about Rietveld visit its project page at or see it in action at.
The core of Rietveld is a Django application called
codereview. Rietveld was built originally for App Engine and uses Django's URL resolving and template rendering functionality.
Since Rietveld makes heavy use of the Google App Engine APIs, it will not run by default on pure Django. And maintaining two separate versions of the application would also require the added problem of keeping the features of both versions in sync. Instead, we'll use gae2django to allow the code originally written for App Engine to run in a pure Django environment.
To get started with the Rietveld example, change into the
examples/rietveld directory and
make all (refer to the
README file in that directory for manual setup instructions).
make all does three things:
- Fetches the entire Rietveld application from its repository
- Applies the patches required to get it running on Django
- Runs
./manage.py syncdbto setup the database used in this example
During the final step, Django will ask if you would like to create a superuser account. Answer "yes" here and give the required information. You can create additional users later by following the steps outlined in User authentication in Django.
After you have installed Rietveld, run
./manage.py runserver localhost:8000 to start the server. Point your browser to to use Rietveld running on pure Django.
In the next sections, we step through all of the changes the helper made to the original
codereview application, but if you want to have a look at the changes first, why not use the code review tool?
To upload the changes made by the helper, run the following command in the
codereview directory:
../static/upload.py -s 127.0.0.1:8000 -m "codereview on Django" Upload server: 127.0.0.1:8000 (change with -s/--server) Login URL: '' Username: USERNAME_AS_PROVIDED_ABOVE Password: Issue created. URL: Uploading views.py Uploading library.py
Use the username and password of the superuser created when setting up Rietveld. The above command uploads the original and modified files to your local instance of Rietveld. Loading the "Recent Issues" page will show the change as the first issue.
Next, we explain how the helper works and how to use it for your own application.
Installing the Helper in Your Own Project
To install the
gae2django helper in your own project, open your
manage.py script and add the following at the top before any Django imports:
import gae2django gae2django.install()
In
settings.py add
gae2django under the
INSTALLED_APPS setting. Add
gae2django.middleware.FixRequestUserMiddleware to
MIDDLEWARE_CLASSES directly after Django's authentication middleware.
The App Engine API replacement is exposed as the
./manage.py shell >>> from google.appengine.api import users >>> users.create_login_url("foo") '/accounts/login/?next=foo'
Now that
gae2django is installed, calls to App Engine's Users API are mapped to Django's authentication system, App Engine models and properties are mapped to Django models and fields, GQL queries are translated to model filters, and calls to the Mail API are handled by Django's mail module.
Changes to Your Application
If you are following along, you've probably noticed the
patches directory and the
rietveld_helper application. These contain modifications to the original application, and are required to run Rietveld using pure Django. Not all differences between App Engine and pure Django's are automatically covered by using the helper.
Depending on your use the App Engine APIs, a few additional changes to your original App Engine application might be required to run on pure Django. The following sections give you some hints about the differences between both frameworks and how these issues are resolved for Rietveld. This should allow you to implement similar changes for your own application.
The User Class
Semantically, the most significant difference between pure Django and App Engine involve the User's API. With Django's
User model, email is a field, but in the App Engine Users API the email is retrieved using a method. Also, Django doesn't have the
nickname method which is available in App Engine. When gae2django translates Rietveld, every call to
user.email() in Rietveld is replaced by
user.email and the
user.nickname() is set from the profile class.
Anonymous Users
Another difference between the App Engine Users API and Django's behavior is how anonymous users are handled. If the current user isn't logged in on App Engine
users.get_current_user() returns
None. Django has an
AnonymousUser instance. With Rietveld we solve this by adding another middleware class in
rietveld_helper. This class removes the user that is added to the
request instance when the user is anonymous. Since the Rietveld only checks
request.user and constructs a
User object from scratch, this is all we need to do.
You may need to implement additional solutions for this issue with your own application, such as replacing conditional statements like
user is None with
user.is_anonymous().
Models and Properties
The Datastore API implementation of the helper is fairly robust. For the Rietveld example no changes to the original models or GQL queries were made.
The
gae2django implementation of
google.appengine.ext.db.Model creates additional model fields (prefixed with
gae_*) to store a key for an instance and, if necessary, to store an ancestry path to resolve parent relationships.
GQL queries are analyzed and translated into Django field lookups. The returned
QuerySets work almost exactly the same as result sets in App Engine.
Application Specific Changes
The changes to
upload.py are specific to the code review application.
upload.py is a command line script to upload changes in a version controlled working tree to the review server and it requires authentication on the server from the command line. The modified version of this script in the
static directory uses Django's login form to retrieve an authentication cookie from the Django server. Have a look at
patches/upload.diff if you are interested in this more advanced topic.
In addition to the middleware class for the Users API,
rietveld_helper provides the
ROOT_URLCONF for Django. The URLs for Rietveld are imported in
rietveld_helper/urls.py and are extended by additional, Django specific, URLs for sign in, sign out, and for serving static files.
Upcoming Development
The
gae2django helper application is still in an early stage of development and not all parts of Google's App Engine APIs are currently covered by this project. At the moment the project focuses on Rietveld as an reference implementation. Upcoming development will include greater coverage of the App Engine APIs, unit tests, and other example applications. If you know an App Engine based application suitable for demonstrating and testing the helper's functionality, read the section about contributing to this project below.
Contributing
Please file bug reports and feature requests on the project site at or if you have code to contribute upload it to and add
albrecht.andi@googlemail.com as reviewer.
Conclusion
The
gae2django helper application can be used to simplify the porting of applications designed for Google App Engine to pure Django projects. It simplifies the reuse of the application code as it provides Django adapters for most of App Engine's methods and classes. It reduces the effort porting an application to Django by freeing the developer to deal only with cases when the frameworks differ and application specific issues.
|
https://cloud.google.com/appengine/articles/pure_django
|
CC-MAIN-2015-48
|
refinedweb
| 1,553
| 55.44
|
Package: ghostscript Version: 9.04~dfsg-3 Severity: normal 0. ghostscript lies about the toolkit used to create the XMP in x:xmptk. It uses an identifier normally associated with Adobe's toolkit even though it does not use that toolkit[0]. The attribute is unspecified by the XMP specification, so it should probably be removed. 1. The value for rdf:about is not a URI. XMP is based on RDF, and RDF requires that rdf:about be a URI. The XMP specification does as well. There's really no reason to generate a UUID per document and rdf:about="" is more meaningful anyway, so again, it should probably be removed. 2. "uuid:" (as used in xapMM:DocumentID) is not a registered URI scheme. There is a perfectly good existing URN specification for that, so "urn:uuid:" should be used instead. (The use of "adobe:ns:meta/" as a namespace is unfortunate, but we're stuck with it now.) There is a PDF demonstrating these bugs in #649909. (I can clone these into separate bugs if you'd prefer.) [0] I was actually surprised to see this at first because I stopped work on XMP upstream because they refused to add a dependency on exempi and I didn't really feel like reinventing the wheel just for them. I then realized that there was no external dependency at all, but instead some text hard-coded into the source. -- System Information: Debian Release: wheezy/sid APT prefers unstable APT policy: (500, 'unstable'), (1, 'experimental') Architecture: amd64 (x86_64) Kernel: Linux 3.1.0-1-amd64 (SMP w/2 CPU cores) Locale: LANG=en_US.UTF-8, LC_CTYPE=en_US.UTF-8 (charmap=UTF-8) Shell: /bin/sh linked to /bin/dash Versions of packages ghostscript depends on: ii cdebconf [debconf-2.0] 0.158 ii debconf [debconf-2.0] 1.5.41 ii debianutils 4.0.4 ii gsfonts 1:8.11+urwcyr1.0.7~pre44-4.2 ii libc6 2.13-21 ii libgs9 9.04~dfsg-3 ghostscript recommends no packages. Versions of packages ghostscript suggests: ii ghostscript-cups 9.04~dfsg-3 ii ghostscript-x 9.04~dfsg-3 ii hpijs 3.11.10-1 -- no debconf
|
https://lists.debian.org/debian-printing/2011/11/msg00049.html
|
CC-MAIN-2021-43
|
refinedweb
| 366
| 61.02
|
I am developing an unfinished linear algebra (matrix) class and wanted to provide the ability to enumerate it horizontally (by row) or vertically (by column). So I tried to implement IEnumerable, this requires implementing a method called GetEnumerator(). Then it can get a little confusing.
IEnumerable
GetEnumerator()
IEnumerator
yield
I tend to find that articles on this subject (and many others) start simple enough and then get more complex / theoretical / detailed than I would like. I would prefer basic, practical advice and guidance with a smattering of theory and explanation, I can learn bit by bit, not all at once. I am not Sheldon. In fact I wasn't completely sure until I'd finished writing the attached demo app, then I understood it (on a practical basis). So, we will look at implementing IEnumerable, by creating IEnumerator classes or by the use of yield - and we will compare the two approaches. I will also mention at least one other way of making a class enumerable (without explicitly implementing IEnumerable). We will also see two ways of allowing a user of a class to choose from n different ways of enumerating that class (as many as you implement), one with yield and one with IEnumerators.
n
IEnumerators
If you are simply looking to understand (as I was) if yield is an alternative to creating IEnumerator classes (rather than something complementary for example) then the answer is: yes; although there are differences which are probably not trivial in many cases, we'll have a short look at this.
If you arrived here trying to work out what yield is / does then here's my take.
When you use an Iterator method with yield it doesn't execute to its natural conclusion, every time it encounters a yield it does the same as a return statement and then stops right where it is, the method doesn't finish, then next time you call the method, it picks up where it left off, i.e. it does not start afresh each time you call it. So during a foreach loop these methods will run from start to finish once only, not once for each value in a collection, array or other grouping of data. It's a method that returns values many times not once - magic (or perhaps not magic, just the compiler saving us time since behind the scenes(^) it apparently creates IEnumerator like code anyway...)
Iterator
return
foreach
Warning 1: If you like your patterns and principles then even in code this short I have no doubt I've broken many. C'est la vie!
Warning 2: If there is a lack of detail in the semantics, then you have my apologies. I am writing from a practical perspective and sometimes to keep it simple, practical and readable I intentionally (or unintentionally) skip over the detail. For this reason the way two different people interpret the missing detail might be different. If you need or want to get that detail absolutely correct then there is masses of such information out there and I'm not going to try and replicate it here, that's not the intention. If there are clear written errors then I'm very happy to correct them.
The genesis of this article was (is) an unfinished linear alegbra (matrix) project. I wanted to provide the ability to traverse the matrix by column (vertically) or by row (horizontally) which meant implementing IEnumerable. OK, so how do we do that then? Well, we start with the classic Google search. A great deal of somewhat frustrating time later I had a good idea I could use the yield keyword or I could create a class that implemented IEnumerator, or maybe I had to do both, could do both, didn't have to do either or had to do something else entirely; who knew?
Ultimately you can use yield or create a class that implements IEnumerator, your choice. There may be things that each is better suited for, I don't know enough yet to say one way or the other. As for my matrix class I can also implement 2 enumerators (or 10 if I really wanted), each doing something different and which can be interchanged at run time.
The 'classic' (or 'old' if you prefer new shiny things) way of implementing IEnumerable is fairly straight forward so I'll start with a verbal description and then add the code .
The IEnumerable interface simply demands you implement a GetEnumerator() method that returns an object that has implemented IEnumerator. Then IEnumerator demands you implement several methods, the two key ones are the MoveNext() method and the Current property.
MoveNext()
Current
So imagine you use a foreach loop on a object that has implemented IEnumerable, such as this:
foreach (double element in EnumerableMatrix)
{
Console.WriteLine(element.ToString());
}
What's actually happening is that the GetEnumerator() method is called on the EnumerableMatrix object. This returns a new object which we know must have implemented IEnumerator. This IEnumerator object can then be looped over using the MoveNext() method and the Current property of IEnumerator. In fact the code above is shorthand for this.
EnumerableMatrix
IEnumerator ObjectToEnumerate = EnumerableMatrix.GetEnumerator()
while (while ObjectToEnumerate.MoveNext() == True)
{
Console.WriteLine(ObjectToEnumerate.Current.ToString());
}
You could do this manually in order to gain more control over the enumeration than provided by foreach. In the Points of Interest section we have a quick look at the IL code and we can see directly that foreach is turned into MoveNext() and Current as shown above.
So, asuming we understand what a foreach loop actually does then it gets even easier to understand the 'old' or classic way of making an object enumerable. We start with the class we want to enumerate.
public class ByEnumerator : IEnumerable<double>
{
Public IEnumerator<Double> GetEnumerator()
{
Return New MyNewEnumerator()
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
It really is that straightforward. IEnumerable simply demands implementation of those two methods and you just point the less specific one at the other.
In my case I was enumerating a two dimensional array of double and wanted to be able to choose between two different IEnumerators. So we need a few changes. We've done the following:
Added a constructor that simply takes an existing 2 dimensional array of double.
public ByEnumerator(double[,] matrix)
{
this._matrix = matrix;
this._matrixEnumerator = MatrixEnumerator.Horizontal;
}
A property to allow the choice between different enumeration methods and an enum to represent the different possible enumerators.
enum
public MatrixEnumerator Enumerator
{
get { return this._matrixEnumerator; }
set { this._matrixEnumerator = value; }
}
public enum MatrixEnumerator
{
Vertical,
Horizontal
}
And finally some conditional code to create the desired IEnumerator instance.
public IEnumerator<double> GetEnumerator()
{
switch (this._matrixEnumerator)
{
case MatrixEnumerator.Vertical:
return new VerticalMatrixEnumerator(this._matrix);
case MatrixEnumerator.Horizontal:
return new HorizontalMatrixEnumerator(this._matrix);
default:
throw new InvalidOperationException();
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
Now all we need to do is implement those two new classes, the Horizontal and Vertical enumerators.
You can see that the IEnumerator we return depends on the class property, Enumerator. Now we just need to create two two IEnumerator classes mentioned in the code above. We'll show the Horizontal one first and you'll see that we simply add code to the four methods mentioned earlier. There are various private fields to keep track of where we are in the array and other than that the important method is MoveNext(). You can also see that we pass a copy of the 2D array from the IEnumerable class to the IEnumerator class (I assume this is why modifiying an object whilst enumerating it tends to cause chaos).
Enumerator
First off the private fields and the constructor.
public class HorizontalMatrixEnumerator : IEnumerator<double>
{
private double[,] _matrix;
private int _colIndex;
private int _rowIndex;
private double _curItem;
private int _lastCol;
private int _lastRow;
public HorizontalMatrixEnumerator(double[,] matrix)
{
this._matrix = matrix;
this._colIndex = -1;
this._rowIndex = 0;
this._curItem = double.NaN;
this._lastCol = matrix.GetUpperBound(1);
this._lastRow = matrix.GetUpperBound(0);
}
_matrix
_colIndex
_rowIndex
0
-1
_curItem
_lastCol
_lastRow
UpperBounds
Now the Current property.
public double Current
{
get
{
if (double.IsNaN(this._curItem))
{
throw new InvalidOperationException();
}
return this._curItem;
}
}
object System.Collections.IEnumerator.Current
{
get { return this.Current(); }
}
As noted, it's just a wrapper for the _curItem field. It throws an exception if it's NaN - it is initialised as such in the constructor - this ensures that we throw an exception if the user of the object (the foreach loop for example) tries to use it before MoveNext() has been called, it's a bit nicer than letting them find out when their code throws a wobbly because it was expecting a useful value and got something it didn't know how to deal with.
NaN
Now the interesting bit, MoveNext().
public bool MoveNext()
{
if (this._colIndex == this._lastCol & this._rowIndex == this._lastRow)
{
return false;
}
if (this._colIndex == this._lastCol)
{
this._colIndex = 0;
this._rowIndex += 1;
}
else
{
this._colIndex += 1;
}
this._curItem = this._matrix[this._rowIndex, this._colIndex];
return true;
}
false
while {true} do ...
true
It's worth noting that the MoveNext() method presented above is essentially a pair of nested for loops which have been made unnecessarily complex, the yield version (that we will show shortly) is easier to code and is also easier to understand. The image below should make that clear.
for
You can see that every time the column index reaches 2 we need to reset it to 0 and add 1 to the row index, or simply add 1 to the column index until is does reach 2.
2
1
Finally the Reset() method just puts the relevant fields back to how they were when the object was created.
Reset()
public void Reset()
{
this._colIndex = -1;
this._rowIndex = 0;
this._curItem = double.NaN;
}
} // Class
The Vertical enumerator changes a few things but mostly the MoveNext() method as shown below.
We just flip around the row and column variables in the if () ... else ... section such that we move down columns rather than across rows. We also initialise _rowIndex to -1 (instead of 0) and _colIndex to 0 (instead of -1).
if () ... else ...
public bool MoveNext()
{
if (this._colIndex == this._lastCol & this._rowIndex == this._lastRow)
{
return false;
}
if (this._rowIndex == this._lastRow)
{
this._rowIndex = 0;
this._colIndex += 1;
}
else
{
this._rowIndex += 1;
}
this._curItem = this._matrix[this._rowIndex, this._colIndex];
return true;
}
Now whilst that's pretty easy, it means creating two extra classes and (relatively) more code than feels necessary for something relatively simple, can we do better? Let's have a crack at yield...
So how do we do the same thing with yield?
Most of the code doesn't change. The first thing is that the GetEnumerator() method doesn't create new objects, it calls a couple of private class methods. Other than that it's identical, you have to be watching carefully just to notice that something has changed.
public IEnumerator<double> GetEnumerator()
{
switch (this._matrixEnumerator)
{
case MatrixEnumerator.Horizontal:
return this.HorizontalEnumerator();
case MatrixEnumerator.Vertical:
return this.VerticalEnumerator();
default:
throw new InvalidOperationException();
}
}
Essentially identical, but rather than return new HorizontalMatrixEnumerator(this._matrix) we see return this.HorizontalEnumerator(), which is a method reference not an object. Then we just need to implement those two new methods.
return new HorizontalMatrixEnumerator(this._matrix)
return this.HorizontalEnumerator()
private IEnumerator<double> VerticalEnumerator()
{
if (this._matrix != null)
{
for (int col = 0; col <= this._matrix.GetUpperBound(1); col++)
{
for (int row = 0; row <= this._matrix.GetUpperBound(0); row++)
{
yield return this._matrix[row, col];
}
}
} else {
throw new InvalidOperationException();
}
}
private IEnumerator<double> HorizontalEnumerator()
{
if (this._matrix != null)
{
for (int row = 0; row <= this._matrix.GetUpperBound(0); row++)
{
for (int col = 0; col <= this._matrix.GetUpperBound(1); col++)
{
yield return this._matrix[row, col];
}
}
} else {
throw new InvalidOperationException();
}
}
It took me a while to figure out exactly how to declare those two methods but eventually you work out that they need to have a return type of IEnumerator. You can see this in the code and other than that it involves no more than looping your way through the array. Not much easier technically, in fact no easier at all but certainly less code and without those extra classes to maintain.
What is very clear though is that it's a lot less code than two IEnumerator classes. It's also a lot easier to see what's going on, it is clearly two nested for loops, which as we said above is what the MoveNext() method is actually doing, only in a more complex way.
By way of explanation this really isn't very much, but if you've read and understood how to do the same thing with IEnumerators then understanding yield is as simple as this:
The only difference between the two is which way you loop through the array, columns first or rows first.
If this explanation doesn't work for you there's of options out there that explain it in different ways and to greater detail, Google(^) is your friend.
OK, I'm not going to try and explain this in great detail (the article is aimed at beginners and there's much I don't yet understand or at least I imagine there is), just enough (I hope) to make sense of what yield actually does and how. You can almost think of the Iterator method as a separate programme, the programme running the foreach loop on your IEnumerable object then sends a message to the other one saying 'give me the next one' - right now this sounds exactly like a MoveNext() followed by a Current - but the clever bit is the other programme stops execution as soon as it has executed yield statement, then waits until you ask it for the next one, at which point it executes the next statement and continues until it reachs the next yield statement, executes it and then waits once more. In the case above each time it reaches the 'next' yield statement it is actually the same one, but in a loop, you could equally have a set of yield statements one after the other (see the MSDN example(^))
Yes, some donkey (when designing .Net and VB / C#) decided that it would be smart to index arrays as (row, column) and DataGridViews as (column, row).
Wild or zany? This is what the CP article template suggests. Really? When coding? Wild and zany. Maybe if I drank too much coffee and did something really crazy that was in no way related to coding but otherwise, no.
We can show clearly the point made earlier, that running foreach on an IEnumerable object is the same as manually creating the IEnumerator and initiating a while (true) do ... loop. This happens to be the code for the foreach performed on the object which uses an IEnumerator rather than yield, although it's very similar indeed for the yield version.
while (true) do ...
IL_016d: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1<float64> IEnumerableCS.ByEnumerator::GetEnumerator()
IL_0172: stloc.s CS$5$0001
.try
{
IL_0174: br.s IL_01a1
// loop start (head: IL_01a1)
IL_0176: ldloc.s CS$5$0001
IL_0178: callvirt instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<float64>::get_Current()
IL_017d: conv.r8
IL_017e: stloc.s Val
IL_0180: nop
IL_0181: ldloc.s output
IL_0183: ldloc.s Val
IL_0185: ldc.i4.2
IL_0186: call float64 [mscorlib]System.Math::Round(float64, int32)
IL_018b: stloc.s CS$0$0002
IL_018d: ldloca.s CS$0$0002
IL_018f: call instance string [mscorlib]System.Double::ToString()
IL_0194: ldstr " ¦ "
IL_0199: call string [mscorlib]System.String::Concat(string, string, string)
IL_019e: stloc.s output
IL_01a0: nop
IL_01a1: ldloc.s CS$5$0001
IL_01a3: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
IL_01a8: stloc.s CS$4$0000
IL_01aa: ldloc.s CS$4$0000
IL_01ac: brtrue.s IL_0176
// end loop
IL_01ae: leave.s IL_01c4
} // end .try
finally
{
IL_01b0: ldloc.s CS$5$0001
IL_01b2: ldnull
IL_01b3: ceq
IL_01b5: stloc.s CS$4$0000
IL_01b7: ldloc.s CS$4$0000
IL_01b9: brtrue.s IL_01c3
IL_01bb: ldloc.s CS$5$0001
IL_01bd: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_01c2: nop
IL_01c3: endfinally
// end handler
You can clearly see that at IL_0174 it jumps (unconditionally) to the short section that includes the call to MoveNext(), starting at IL_01a1. At the end of that section it branches on true (IL_01b9) to the slightly longer section above (assuming MoveNext() returned true), starting at IL_0176 which then calls Current. Completely consistent with a while (true) do ... loop, i.e. if the object to enumerate is empty it never tries to call Current; meanwhile for a non-empty object the first time that MoveNext() returns false is when it tries to move past the last position, at which point the branch on true (IL_01b9) doesn't branch and the code flows onwards out of the loop.
IL_0174
IL_01a1
IL_01b9
IL_0176
I thought I'd remembered reading that when you use yield the compiler responds by creating an IEnumerator, so it's really just shorthand to allow for code that's easier to read, write and maintain, I thought I'd see if this was true - since I have the perfect examnple to test it on - by looking at what IL code is produced by the compiler. (Try ILSpy(^) or the ILDisassembler that comes with Windows 7.1 SDK(^).) Here's what you see, first we'll look at the classes and code that is produced, in particular the ByYield class.
There's our HorizontalEnumerator method highlighted, now what does the IL code say?
HorizontalEnumerator
.method private hidebysig
instance class [mscorlib]System.Collections.Generic.IEnumerator`1<float64> HorizontalEnumerator () cil managed
{
// Method begins at RVA 0x22ec
// Code size 16 (0x10)
.maxstack 2
.locals init (
[0] class IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'
)
IL_0000: ldc.i4.0
IL_0001: newobj instance void IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::.ctor(int32)
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldarg.0
IL_0009: stfld class IEnumerableCS.ByYield IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<>4__this'
IL_000e: ldloc.0
IL_000f: ret
} // end of method ByYield::HorizontalEnumerator
I don't get all of that, but I do see a reference to IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4. We can see that in the image just above - it's the third item in the ByYield description, just under DerivedTypes. Here's what's contained in that class member.
IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4
ByYield
DerivedTypes
There's are old friends, two methods MoveNext() and Reset(), and the Current property; those methods were not written in the ByYield class, the compiler has created them. Cearly the compiler treats yield as shorthand for 'please write me an IEnumerator'.
We can compare, at a very amateur level, whether the compilers version of an IEnumerator is much better than its attempt to optimise the MoveNext() we wrote above. The compilers conversion of the two nested for loops with a yield in the middle is on the left. It's conversion of my MoveNext() method is on the right.
.method private final hidebysig newslot virtual
instance bool MoveNext () cil managed
{
.override method instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
// Method begins at RVA 0x225c
// Code size 248 (0xf8)
.maxstack 4
.locals init (
[0] bool CS$1$0000,
[1] int32 CS$4$0001,
[2] bool CS$4$0002
)
IL_0000: ldarg.0
IL_0001: ldfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<>1__state'
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: switch (IL_0019, IL_0017)
IL_0015: br.s IL_001b
IL_0017: br.s IL_007f
IL_0019: br.s IL_0020
IL_001b: br IL_00f2
IL_0020: ldarg.0
IL_0021: ldc.i4.m1
IL_0022: stfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<>1__state'
IL_0027: nop
IL_0028: ldarg.0
IL_0029: ldfld class IEnumerableCS.ByYield IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<>4__this'
IL_002e: ldfld float64[0..., 0...] IEnumerableCS.ByYield::_matrix
IL_0033: ldnull
IL_0034: ceq
IL_0036: stloc.2
IL_0037: ldloc.2
IL_0038: brtrue IL_00ea
IL_003d: nop
IL_003e: ldarg.0
IL_003f: ldc.i4.0
IL_0040: stfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<row>5__5'
IL_0045: br.s IL_00c4
IL_0047: nop
IL_0048: ldarg.0
IL_0049: ldc.i4.0
IL_004a: stfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<col>5__6'
IL_004f: br.s IL_0095
IL_0051: nop
IL_0052: ldarg.0
IL_0053: ldarg.0
IL_0054: ldfld class IEnumerableCS.ByYield IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<>4__this'
IL_0059: ldfld float64[0..., 0...] IEnumerableCS.ByYield::_matrix
IL_005e: ldarg.0
IL_005f: ldfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<row>5__5'
IL_0064: ldarg.0
IL_0065: ldfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<col>5__6'
IL_006a: call instance float64 float64[0..., 0...]::Get(int32, int32)
IL_006f: stfld float64 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<>2__current'
IL_0074: ldarg.0
IL_0075: ldc.i4.1
IL_0076: stfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<>1__state'
IL_007b: ldc.i4.1
IL_007c: stloc.0
IL_007d: br.s IL_00f6
IL_007f: ldarg.0
IL_0080: ldc.i4.m1
IL_0081: stfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<>1__state'
IL_0086: nop
IL_0087: ldarg.0
IL_0088: dup
IL_0089: ldfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<col>5__6'
IL_008e: ldc.i4.1
IL_008f: add
IL_0090: stfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<col>5__6'
IL_0095: ldarg.0
IL_0096: ldfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<col>5__6'
IL_009b: ldarg.0
IL_009c: ldfld class IEnumerableCS.ByYield IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<>4__this'
IL_00a1: ldfld float64[0..., 0...] IEnumerableCS.ByYield::_matrix
IL_00a6: ldc.i4.1
IL_00a7: callvirt instance int32 [mscorlib]System.Array::GetUpperBound(int32)
IL_00ac: cgt
IL_00ae: ldc.i4.0
IL_00af: ceq
IL_00b1: stloc.2
IL_00b2: ldloc.2
IL_00b3: brtrue.s IL_0051
IL_00b5: nop
IL_00b6: ldarg.0
IL_00b7: dup
IL_00b8: ldfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<row>5__5'
IL_00bd: ldc.i4.1
IL_00be: add
IL_00bf: stfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<row>5__5'
IL_00c4: ldarg.0
IL_00c5: ldfld int32 IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<row>5__5'
IL_00ca: ldarg.0
IL_00cb: ldfld class IEnumerableCS.ByYield IEnumerableCS.ByYield/'<HorizontalEnumerator>d__4'::'<>4__this'
IL_00d0: ldfld float64[0..., 0...] IEnumerableCS.ByYield::_matrix
IL_00d5: ldc.i4.0
IL_00d6: callvirt instance int32 [mscorlib]System.Array::GetUpperBound(int32)
IL_00db: cgt
IL_00dd: ldc.i4.0
IL_00de: ceq
IL_00e0: stloc.2
IL_00e1: ldloc.2
IL_00e2: brtrue IL_0047
IL_00e7: nop
IL_00e8: br.s IL_00f1
IL_00ea: nop
IL_00eb: newobj instance void [mscorlib]System.InvalidOperationException::.ctor()
IL_00f0: throw
IL_00f1: nop
IL_00f2: ldc.i4.0
IL_00f3: stloc.0
IL_00f4: br.s IL_00f6
IL_00f6: ldloc.0
IL_00f7: ret
} // end of method '<HorizontalEnumerator>d__4'::MoveNext
.method public final hidebysig newslot virtual
instance bool MoveNext () cil managed
{
// Method begins at RVA 0x251c
// Code size 139 (0x8b)
.maxstack 4
.locals init (
[0] bool CS$1$0000,
[1] bool CS$4$0001
)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_colIndex
IL_0007: ldarg.0
IL_0008: ldfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_lastCol
IL_000d: ceq
IL_000f: ldarg.0
IL_0010: ldfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_rowIndex
IL_0015: ldarg.0
IL_0016: ldfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_lastRow
IL_001b: ceq
IL_001d: and
IL_001e: ldc.i4.0
IL_001f: ceq
IL_0021: stloc.1
IL_0022: ldloc.1
IL_0023: brtrue.s IL_002a
IL_0025: nop
IL_0026: ldc.i4.0
IL_0027: stloc.0
IL_0028: br.s IL_0089
IL_002a: ldarg.0
IL_002b: ldfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_colIndex
IL_0030: ldarg.0
IL_0031: ldfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_lastCol
IL_0036: ceq
IL_0038: ldc.i4.0
IL_0039: ceq
IL_003b: stloc.1
IL_003c: ldloc.1
IL_003d: brtrue.s IL_0058
IL_003f: nop
IL_0040: ldarg.0
IL_0041: ldc.i4.0
IL_0042: stfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_colIndex
IL_0047: ldarg.0
IL_0048: dup
IL_0049: ldfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_rowIndex
IL_004e: ldc.i4.1
IL_004f: add
IL_0050: stfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_rowIndex
IL_0055: nop
IL_0056: br.s IL_0068
IL_0058: nop
IL_0059: ldarg.0
IL_005a: dup
IL_005b: ldfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_colIndex
IL_0060: ldc.i4.1
IL_0061: add
IL_0062: stfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_colIndex
IL_0067: nop
IL_0068: ldarg.0
IL_0069: ldarg.0
IL_006a: ldfld float64[0..., 0...] IEnumerableCS.HorizontalMatrixEnumerator::_matrix
IL_006f: ldarg.0
IL_0070: ldfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_rowIndex
IL_0075: ldarg.0
IL_0076: ldfld int32 IEnumerableCS.HorizontalMatrixEnumerator::_colIndex
IL_007b: call instance float64 float64[0..., 0...]::Get(int32, int32)
IL_0080: stfld float64 IEnumerableCS.HorizontalMatrixEnumerator::_curItem
IL_0085: ldc.i4.1
IL_0086: stloc.0
IL_0087: br.s IL_0089
IL_0089: ldloc.0
IL_008a: ret
} // end of method HorizontalMatrixEnumerator::MoveNext
I'm not qualified to comment with any professionalism, but whilst the compiler clearly has to do more work with yield in order to turn two nested for loops into an IEnumerator than when it is given dedicated IEnumerator code, there isn't (seemingly) a huge difference between the two. Whether one of them is more efficient I don't know - maybe someone has time to test... I guess it shouldn't be a surprise, the fact that the compiler is capable of doing this at all impresses me, especially if you imagine just how complex some methods with a yield statement might be and it has to be able to handle tham all.
It's probably worth thinking about this is if you have a class that may contain very large amounts of data, which needs to be enumerable and where time is critical, in such cases trying both your own IEnumerator and yield is probably worth the time, to see which results in quicker execution.
Version 5 (21 April 2013): Fixed issue with test for var == double.NaN, should have been double.IsNaN(var); added section on 'foreach == while (MoveNext()) + Current' further typographical errors fixed and re-wrote some sections for clarity
var == double.NaN
double.IsNaN(var)
Version 4 (13 April 2013): [No code changes in demo app] Re-wrote introduction to improve flow, fixed some typographical errors
Version 3 (12 April 2013): [No code changes in demo app] Changed do while to while do
Version 2 (11 April 2013): [No code changes in demo app] Clarifications and extra information subsequent to reader comments and addition of new section, 'How Does the Compiler Implement Yield?'
Version 1 (7 April 2013): Shiny and Newny and.
|
http://www.codeproject.com/Articles/573753/Pick-Your-Enumerator-Me-Understand-Yield-and-IEnum?fid=1830051&df=180&mpp=10&sort=Position&spc=None&tid=4538920
|
CC-MAIN-2014-52
|
refinedweb
| 4,241
| 52.26
|
Tag-plugin draw-function and transparency
On 26/02/2013 at 06:07, xxxxxxxx wrote:
Hey guys.
I'm toying around with a tag-plugin which draws a simple polygon into the viewport. The polygon should be transparent which I set by using BaseDraw.SetTransparency(-235). It works, the polygon is transparent but has one major flaw: every polygon-object behind my polygon is not visible except for it's wireframe-lines (the world-grid is also visible).
def Draw(self, tag, op, bd, bh) : bd.SetMatrix_Matrix(None, c4d.Matrix()) bd.SetTransparency(-235) p = ( c4d.Vector(0,0,0), c4d.Vector(100,0,0), c4d.Vector(50,100,0) ) f = ( c4d.Vector(1,0,0), c4d.Vector(0,0,1), c4d.Vector(0,1,0) ) bd.DrawPolygon(p, f)
Is there some kind of workaround for this? The transparency works fine in my tool-plugins.
Thanks
Phil
On 27/02/2013 at 00:31, xxxxxxxx wrote:
Hi Phil,
With a positive value for the transparency it works. But it's dotted.
I asked the developers if it's possible to get a true transparency from within a TagData plugin.
On 27/02/2013 at 02:39, xxxxxxxx wrote:
Hi Yannick.
Yeah I tried the dotted version, but I don't like the look (too dominant) and in my viewport other objects start flickering when I use positive values.
I assume there won't be a workaround, but I just want to be sure.
Thanks for your help.
On 27/02/2013 at 07:55, xxxxxxxx wrote:
Maybe I don't understand the problem. But it seems to work fine for me.
I tried it using the Py-LiquidPainter plugin example in the python SDK. The two triangle polygons are transparent. And the objects behind it are seen through them as expected.
...plugin code def Draw(self, doc, data, bd, bh, bt, flags) : bd.SetMatrix_Matrix(None, c4d.Matrix()) bd.SetTransparency(-235) ...Rest of the plugin code
-ScottA
On 27/02/2013 at 08:45, xxxxxxxx wrote:
i guess the point is that he is trying to do it from a tag plugin, c4d seems to throttle tag draw
functions.
On 28/02/2013 at 00:13, xxxxxxxx wrote:
Yeah that's exactly the point. Tool-plugins like LiquidPainter work without problems, tags not so much
On 26/03/2013 at 06:57, xxxxxxxx wrote:
The developers told me that true transparencies are only possible with shaders.
The result is more or less undefined when using BaseDraw::SetTransparency().
On 26/03/2013 at 07:34, xxxxxxxx wrote:
Thanks for the clarification Yannick.
|
https://plugincafe.maxon.net/topic/6976/7857_tagplugin-drawfunction-and-transparency
|
CC-MAIN-2020-40
|
refinedweb
| 430
| 66.84
|
In this example, we use two for loops in conjunction with the putchar library function to print all uppercase letters followed by all lowercase letters. The loop variable ch is assumed to be of type char or int. The first for loop prints the uppercase letters as loop variable ch assumes values as ‘A’, 'B’, ... , ‘z’.
Then a put char function prints a newline character to move the cursor to the next line on which the second for loop prints the lowercase letters. Note that the same loop variable is used for both for loops. The output is given below.
#include <stdio.h>
void main()
{
int ch;
clrscr();
printf("Print all uppercase letters followed by all lowercase letters on the next line :\n");
/* print uppercase letters */
for (ch= 'A'; ch<= 'Z'; ch++)
putchar(ch);
putchar ('\n' ) ;
/* print lowercase letters */
for (ch= 'a'; ch<= 'z'; ch++)
putchar(ch);
putchar ('
|
http://ecomputernotes.com/what-is-c/control-structures/print-all-uppercase-letters-followed-by-all-lowercase-letters-on-the-next-line
|
CC-MAIN-2018-17
|
refinedweb
| 148
| 75.95
|
Hey C++ Programmers,
I try to write an script just you can call the array number (Aperatures[0], ..., Aperatures[9]) to print
his numbers... So this is my script, writted in Dev C++....
The Script:
But if i run my script, i get an error thad sey the follows:But if i run my script, i get an error thad sey the follows:Code:#include <iostream> using namespace std; int main() { int Aperatures[10]; int j; Aperatures[0] = 1; Aperatures[1] = 2; Aperatures[2] = 3; Aperatures[3] = 4; Aperatures[4] = 5; Aperatures[5] = 6; Aperatures[6] = 7; Aperatures[7] = 8; Aperatures[8] = 9; Aperatures[9] = 10; while (j < 9) { cout << "Stapel: "; cin >> j; for (int i = 0; i < j; i++) { cout << "Aperature" << Aperatures[i] << endl; } } return 0; }
Error i get:
I get an question for the follows: how can i understand the syntax error i get, as this error:
So, if i understand this, i hope i can fix this problem for the next case....So, if i understand this, i hope i can fix this problem for the next case....
Just can anyone correct my code and learn my to understand the type error i get ?,
Thanks, Jamie.
|
http://forums.devshed.com/programming-42/devc-array-script-error-found-980675.html
|
CC-MAIN-2019-26
|
refinedweb
| 199
| 57.74
|
Abstract: It seems that the AnyModule::AnyModel shadows AnyModel. ----------------------------------------------------------------- If you are in a hurry, please skip to "The Problem". The idea ---------- One important topic in architecting engines is to make them as isolated as possible in terms of namespace and database schema (if supported). In this way we can be confident that our engine can be used by other applications without risk of name clashes. Example ---------- As an example, let's assume that we want to create a 'task_list_engine'. Ideally we would like to have a TaskList namespace and, for the databases that support it, a separate task_list schema. Given that we want to represent the concept of Category in our task list, we will have a TaskList::Category model, a askList::CategoryController and a task_list.categories table in our database (task_list = schema name, categories = table name). The Problem ---------------- Easy to check: 1 - create a test rails application (e.g. tasklist) 2 - setup a db (e.g. tasklist_dev) with a table (e.g. categories) 3 - from RAILS_ROOT $ ./script generate scaffold category 4 - run the application and point to you should see the usual good stuff. 5 - $ ./script generate model task_list/category Now tha application is broken and you get: "uninitialized constant Category" error. It seems that the Task_List::Category shadows Category. Can anybody explain why? Is it a Rails flaw? Mauro
on 2006-01-13 18:14
on 2006-01-14 00:25
. I can't imagine they would say seperating out your models into seperate modules would be a bad idea. -Nick p.s. Using controllers in different modules hasn't been problem. Have done that quite a bit with no surprising results.
on 2006-01-14 02:58
Nick Stuart wrote: >. Definetely. There were a few mails on this topic on the rails-core mailing list, but unfortunately no response from the core team.
on 2006-01-14 03:11
Super-secret idea: rewrite the Rails plugin system (and any other parts of Rails dependency-mechanisms required) so that it handles namespaces in a consistent, predicable, controllable and safe way. Incorporate some form of 'engine-style' features into that system. Make /app an implicit 'engine' at the top of the pile for elegance of implementation. Each part gets loaded into its own namespace. Demonstrate to community. Pray for adoption. Have a beer. I have some ideas how to do this, but nothing is clear yet. First though, if you guys could help me track down this bug...... - james
on 2006-01-14 10:19
Hi James, I guess that what you suggest is the most sensible way to go about it. My original intention (The Idea ;-) ) was to improve the engines plugin so that it could handle the modularization. What I mean: given the ENGINE_NAME the engine generator creates all the models, controllers and views with their own ENGINE_NAME subdirectories - mapped to the ENGINE_NAME:: namespace. For databases like postgres you could go even further: the model ENGINE_NAME::MODEL_NAME < ActiveRecord::Base gets mapped to the table ENGINE_NAME.MODEL_NAMEs I agree to all the following (1a is my add on): 1 - Each part gets loaded into its own namespace. 1a- Clever Database mapping 2 - Demonstrate to community. 3 - Pray for adoption. 4 - Well, I don't drink... Virtual beer for me! I'll have a look to the bug over the weekend. Mauro
|
https://www.ruby-forum.com/topic/51643
|
CC-MAIN-2015-22
|
refinedweb
| 554
| 67.45
|
The style model includes appearance settings, whether determined in the Spread Designer, or set as properties in the Properties List or as inherited by a custom skin for a whole sheet or by a custom style for individual cells. For more information on appearance settings for a sheet, refer to Creating a Skin for Sheets and Applying a Skin to a Sheet. For more information on appearance settings for a cell, refer to Creating and Applying a Custom Style for Cells.
The appearance settings may be set from any of the following classes in the Spread namespace that represent shortcut objects:
They also may be set from any of these classes in the Spread namespace that affect style:
The order of inheritance is described in Object Parentage. Here is a list of the style properties that are included in the style model, which are basically the members of the StyleInfo class, and affect the appearance or style of a cell:
The style model includes the cell types as well. The various cell types determine the appearance of a cell in several ways. For more information about the various cell types, refer to Customizing with Cell Types.
To use the underlying style model, use the methods of the style model for that sheet, specifically the GetDirectInfo method and SetDirectInfo method, and the settings in the StyleInfo object. Refer to the Assembly Reference for more information on the style model in general and to the DefaultSheetStyleModel methods in particular.
“Direct” in the style model means “not composite” or “not inherited.” SetDirectInfo sets the style properties that have been set for the specified cell, column, or row directly and does not return any settings that are set for higher levels (such as the entire model), while GetCompositeInfo gives the style properties "composed" or "merged" into one StyleInfo object that contains all the settings that are used to paint and edit the cell, column, or row, including any inherited settings.
Properties that correspond to StyleInfo properties are stored in the style model through the ISheetStyleModel interface. Style properties can be set for a cell, row (column index set to -1), column (row index set to -1), or the entire model (column and row index set to -1). Properties that are not set in a cell are inherited from the row setting, or the column setting if the row has no setting, or the model default if the column also has no setting. The default is exposed through the DefaultStyle property (SheetView.DefaultStyle, ColumnHeader.DefaultStyle, and RowHeader.DefaultStyle).
If you set or get a style property using Rows.Default or Rows[-1] or Columns.Default or Columns[-1], then you will actually be setting or getting the DefaultStyle property. This is because Column and Row always use a row index of -1 and a column index of -1 when accessing the style model, respectively, and so using a column index or a row index of -1 will be setting or getting the model default.
Setting StyleName replaces the style in the style model with the NamedStyle having the specified name. This has the effect of changing the settings of all of the style-related properties, including ParentStyleName (which wraps StyleInfo.Parent). Any previous setting for style-related properties like BackColor, Font, Border, or ParentStyleName are overwritten when you set StyleName. The component expects that the named style is set up with all the properties as you want them to be set. If this includes the named style having a parent NamedStyle, then you should have that parent set already when you assign it with StyleName, or you should assign it separately using a reference to the NamedStyle object (this has the same effect as setting ParentStyleName after setting StyleName). Keep in mind that after you have set StyleName, all cells where you have used that name are sharing the same NamedStyle object, and any changes that you make to one of those cells will also be changing all of the other cells sharing the same named style.
The style properties for a cell can be composited or merged from the Cell, Row, Column, Sheet, and parent NamedStyle objects. This code snippet illustrates the order of inheritance of a composited style:
This code creates two NamedStyle objects with a parent-child relationship, then sets some properties on the styles and adds them to the NamedStyleCollection in the FpSpread component. Then the background color for the first column is set to blue and the cell type for the first row is set to Number, and the first cells in the first two rows are both set to use the NamedStyle named “test.” The result is that the cells in the first column are blue, except for the cells in the first two rows, which are red because the “test” style inherits the red background color from its parent NamedStyle. The parent style overrides the inherited setting for the column.
The cell type for the first cell is Number, since there is no cell type set in either NamedStyle object. There is a cell type set in the first row which is inherited by all cells in the row. The cell type for the second cell is General since there is no cell type setting for the cell, row, or column. The default cell type for the sheet is General. For more information on inheritance of style settings, refer to Object Parentage.
The FormatInfo strings in a saved XML file are DateTimeFormatInfo or NumberFormatInfo objects that store the format of the data. These are created in the style model when a General cell is edited, if the style model implements IParseFormatSupport. These format objects allow the cells to display the data in the same format that was used to enter it. The General cell type parses the string into a number or DateTime, and generates the IFormatProvider and format string necessary to render the data as it was entered. If you use TextCellType instead of GeneralCellType, then it works the same as the edit cells did in the ActiveX Spread, and no FormatInfo is stored in the style model, but the data entered into the cells is always treated as text.
|
https://www.grapecity.com/spreadnet/docs/v14/online-asp/spweb-model-stylestuff.html
|
CC-MAIN-2022-21
|
refinedweb
| 1,033
| 54.66
|
Response editsnichols: Overall I think the snodbc extension is really good. My only request is it would be nice if it worked with Tcl version 8.31. I know it uses the new Tcl dictionary object. This section would have to be rewritten.
Download edit2008-11-18: davidw has recently modified SnODBC to improve performance, with the addition of some C coded files. See github
- [URL: ]snodbc.kit
sdx update -from snodbc.kit2008-05-21: These binaries are not supported now and will be removed soon. Please use starkit.
Build and Install editjc).
Releases edit2008-05-21 New version is available: 1.2.20080521. Features added:
- OUTPUT and INPUTOUTPUT parameters
- NULL and DEFAULT representation for parameters
- -multisets flag may be set before connecting, thus it's usable now.
- Supports retrieving non-fatal diagnostic messages (SQL_SUCCESS_WITH_INFO) for connection and statement
- Fixed memory leaks in statement objects.
- Numerous other bug fixes.
Description editSnODBC is mostly compatible with TclODBC, but there are some subtle differences. See the documentation for details.The main good difference is that SnODBC supports Unicode character types. Other advantages of SnODBC include:
- Support for ODBC GUI: you may bring up datasource selection dialog to establish a connection, and save the connection string for subsequent connections.
- Additional support for metadata: rowid, primarykeys, procedures and procedurecolumns metadata queries.
- Support for scrollable cursors: navigate back and forth on the result set when the driver supports it.
- Setting NULL representation for a statement in order to distinguish NULLs from the empty string value..
Fixed Bug: Datasources and Drivers editescargo 2005-10-27: I downloaded the Microsoft Windows binary-only version (not the starkit) and found two problems with its installation on my ActiveState 8.4.11 installation (on Windows XP Pro).
- The file permissions on ffidl06.dll were not executable, so I had to change the permissions before it would load.
- The pkgIndex.tcl file uses the odbc namespace, but it does not ensure that it is created.
database datasources systemI got a response:
can't rename "{EngTestDB {SQL Server}}": command doesn't exist.
Example: Check Connection Status editArlie.A/AK:'" }
Bug Report: Prepared Statements and NULL edit.
Bug Report: Lassign editArlie L. Codina 2007-02-24:database connect sqlca IACCS sa arliecError.
Fixed Bug: Prepared Statements and Blank Tcl Data editsn)
|
http://wiki.tcl.tk/14698
|
CC-MAIN-2017-04
|
refinedweb
| 379
| 51.85
|
Example of creating a new form and calling the application in C#
The task
Develop a demo application, which calls secondary form from main form based on scheme showed on Figure 1. Application realizes the interconnection between different forms, which can be the dialog windows.
In the main form Form1 need to place:
- the control of Label type for showing of returning result from the secondary form;
- the control of Button type for calling of the secondary form.
- In the secondary form Form2 need to place:
- the control of Label type for showing of form’s title.
- two controls Button type for confirmation or not confirmation selection (action) in a secondary form.
Fig. 1. The interconnection scheme between forms
Progress
1. Run Microsoft Visual Studio 2010
Save the project in some folder.
After creating of application we have one form. The program code of form is placed to “Form1.cs” file (Fig. 2).
Fig. 2. The main form of application
2. Designing the main form
From the controls palette “Toolbox” we place on the form:
- the control of Button type;
- the control of Label type.
Automatically two objects with the names button1 and label1 are created.
In the control of type “Button“, set the “Text” property to value “Show Form 2“.
Property Text of Label type control set to value “Result = “.
After changes, the main form Form1 of application will look as shown in Figure 3.
Fig. 3. Main form of application after changes
3. Developing the secondary form
For developing secondary form in C# we can use the several methods.
Method 1.
To add secondary form to project by this method we need to call the command (Fig. 4)
Project -> Add Windows Form...
Fig. 4. Command “Add Windows Form…” to add a new form
As result, the window “Add New Item – Windows Forms Application1” will be opened. In this window we select the element “Windows Form” (Fig. 5). Leave the form’s name as “Form2.cs“.
Fig. 5. Window of adding a new form to project
After pressing at “Add” button the new form will be added to the project (Fig. 6).
Fig. 6. The newly-created form Form2 and file “Form2.cs“
Method 2.
Also, we can add the new form to project with the help of corresponding command from the context menu (Fig. 7).
The sequence of actions is as follows:
- in the “Solution Explorer” click of the right mouse button at the title of application “WindowsFormsApplication1“;
- select submenu Add;
- in submenu Add select the command “Windows Form…“.
Fig. 7. Adding the new form from Solution Explorer
As a result, the window, which is displayed at figure 5, will be opened.
5. Developing the secondary form
The next step is the developing of secondary form. Using tools “Toolbox“, you need to create secondary form Form2 as is shown in figure 8. This structure of form corresponds to the condition task. In the same way, we have such controls on the Form2: label1, button1, button2.
Fig. 8. Secondary form Form2
6. Programming of event handling of click at the buttons “OK” and “Cancel” of form Form2
We program the event of click at button “OK“. In the program code of event handling button1_Click() (button “OK“), type the following string:
this.DialogResult = DialogResult.OK;
this means that the result of the return in Form2 have “OK“.
Likewise in the event handler button2_Click we type:
this.DialogResult = DialogResult.Cancel;
This means the choice of a button “Cancel” (button2).
After changes, listing of program code of file “Form2.cs” will as follows:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; } private void button2_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } } }
To go to the program code of form “Form2” (file “Form2.cs“) we need use “Solution Explorer“. For this, in “Solution Explorer“, we need to call the context menu for form “Form2” and select the command “View Code” from this menu (Fig. 9).
Fig. 9. Command “View Code” to go to the program code mode
7. Calling Form2 from the main form
According to problem condition, to call Form2 from Form1, we need to program the event of clicking at the button “Show Form 2“.
The program code of event handling will be as follows:
... private void button1_Click(object sender, EventArgs e) { Form2 f = new Form2(); // creating Form2 object if (f.ShowDialog() == DialogResult.OK) // call the form Form2 { label1.Text = "Result = OK!"; } else { label1.Text = "Result = Cancel!"; } } ...
In the above code listing, first of all, the class instance of Form2 type will be created. The conditional jump “if” calls the dialog box in Form2 with the help of string
f.ShowDialog()
Function ShowDialog () displays a form’s window and keeps it open as long as the user does not make any selection. After user selection of some command, window closes with the returning code. It checks the return code with known constants of class DialogResult. After checking, the message about selected action by user in Form2, is displayed.
Listing of the all code of Form1 is the next:) { Form2 f = new Form2(); if (f.ShowDialog() == DialogResult.OK) { label1.Text = "Result = OK!"; } else { label1.Text = "Result = Cancel!"; } } } }
8. Running the application
After performing actions we can run the application and test it.
- 004 – Delphi. A new form creating and connecting it to the main form of application.
- 008 – C++ Builder. An example of creating and calling a new form from main form of application.
- 002 – An example of creation of dialog window in MS Visual Studio 2010 – C++ (MFC).
|
http://www.bestprog.net/en/2016/01/09/006-example-of-creating-a-new-form-and-calling-the-application-in-c/
|
CC-MAIN-2017-39
|
refinedweb
| 956
| 58.69
|
Hey.
The reason for this is that depending on how you approach writing your code or addressing the behavior you’re after, you may not be getting all of the ‘instant’ or ‘easy’ perf wins that following best practices have to offer. To help, I recorded you a free 30 minute talk on this topic and you can now watch it online, stream or download it in a format of your choice below.
I wanted to record this talk because I felt that there will still a number of both obvious (and occasionally less-well understood) concepts which intermediate jQuery developers could benefit with having explained or highlighted.
We see a lot of online performance guides that encourage you to use ‘selector X over Y’, but not too many explain the reasoning behind this or go into more detail – hopefully this talk will assist in taking your knowledge of some of the more optimal ways of coding in jQuery just that little bit further : )
If you find the talk useful please feel free to share it with your friends or colleagues by clicking on the ‘reweet’ button at the bottom of the post. I hope it helps!.
PS: If there are additional performance best practices or tips not mentioned which you feel would be of benefit to share with the rest of the community, please don’t hesitate to leave a comment below.
Thanks to @dabheberden for his technical review of the talk and the folks over at @internetarchive for hosting the extra video streams. I would also like to thank Matt Baker for his excellent performance post which provided great reference for some of the slides in the presentation.
Update: Some readers have been asking about a text version of the presentation to be made available. If you’re looking for text tips I recommend checking out Matt’s great article as some of the tips are mentioned there quite well but I’ll be working on getting out a text version of some of the rest of the tips in the next few days.
Thanks a lot Addy for the insights and i've realized the simple mistakes which i do quite often using jQuery. Well documented and completely useful. Keep doing the good work .
Damn awesome talk, I appreciate it. I didn't realize I was using such an ancient jQuery version :-.
Its no problem at all!. You would be surprised just how many people are still using older versions of jQuery in the wild. I'm glad the talk came in a little helpful
Some pretty darm cool tips buddy.
hot damn that's a lot of good info
Thanks Travis!
I have a Question to the $.data part:
is a Cached jQuery Object also slower?
cachedElem.data(key, value);
$.data(cachedElem, key, value);
It really depends Alex. If you're talking about the initial cachedElem.data(key, value) its going to still be a little slower using x.data(k,v) than $.data(k,v) simply because the latter is a low-level method and the former isn't. That said, if whatever collection/element cachedElem represents is being used a few times in your code, caching that (ie) cachedElem.data(k,v) is always going to be more efficient than $('.element').data(k,v) being called multiple times because you're not making the DOM go fetch it again.
Hey Alex. A cached jQuery object using x.data(key,value) would still be slower than $.data(x, key,value) as the latter is low-level and the former isn't. You would get a little more of a perf gain from caching (if the selector was otherwise being queried for multiple times) but $.data() is definitely more efficient to use.
I think ive found a gotcha, i was attempting to improve my code when i found this issue:
imaging you have a nested markup situation: OL.categories LI OL LI…
Try the following:
var el = $('.somediv');
el.children('.categories > li').each(function(){
… then try …
$('.categories > li', el).each(function(){
Notice the first instance does not even return a single element. WHY?
Hmm. If you could reproduce what you're trying to achieve on jsFiddle.net I can try taking a look to see whats going on. I don't completely follow why you're iterating over $('.categories > li', el) inside of the first loop but I may have misunderstood what you're trying to do
Feel free to reply back with a link and we'll take it from there.
Those two selectors aren't equivalent.
$('.categories > li', el).each
would be:
el.find('.categories > li').each
The children function is a filter on direct children, not a recursive search (like the context works)
Ah, you're right. Sorry about that but I do appreciate you posting the correction, Alex!
Pingback: Underbelly » jQuery performance tips and tricks 2011
Very nice presentation, thanks for the tips
You're welcome!
In regards to chained selectors:
Another reason you should nest your chained methods is because multi-line version control and file diff is considerably easier than single-line. I can't remember where I read that, but it's the greatest thing I learned this week!
In the DRY-er code there is a bug. $("input_"+v) should be $("input_"+key).
Great presentation!
Whoops. Thanks for pointing that out!
Pingback: Excellent jQuery Performance tips video | randomcopypaste.com
Quick question about .detach(): suppose I have a div on the page to which I will be appending multiple jquery objects in a loop. Do I detach the container, do the loop and append, then re-attach? How do I re-attach?
Pingback: Twitter, jQuery, and Performance « Mike Vallotton's Blog
Loved this especially the selector speed comparison.
Thanks!
Pingback: Cheatsheet: 2011 01.19 ~ 01.23 - gOODiDEA.NET
Pingback: Tips and Tricks to Improving jQuery performance | webtrendset
This was a great talk!
At times I wish you would have gone into more detail about certain things but maybe I should do a follow up and go into more depth in places I thought you could have.
Thanks for your contributions to the jQuery community!
Pingback: Feb 2nd Links: Visual Studio, ASP.NET, ASP.NET MVC, JQuery, Windows Phone « Naimish Pandya [MCTS, MCPD]
Pingback: Enlaces de Febrero: Visual Studio, ASP.NET, ASP.NET MVC, JQuery, Windows Phone « Thinking in .NET
Thanks Andy, very useful information. Use namespaces to reduce the number of globals is very helpful to the performance also. Thanks for sharing.
Loading jQuery from Google will, every now and then, cause a multiple-second delay in page loading. Ignore the possibility to save yourself a paltry 16k per visitor at your own risk…
Pingback: jQuery Performance tips & tricks | iSellaDesigns
Pingback: Resources and links – 4 March 2011
I learn…
Pingback: Feb 2nd Links: Visual Studio, ASP.NET, ASP.NET MVC, JQuery, Windows Phone « Cymes Blog
Great bit of info, really knows there stuff. Iv only recently got into JQuery but already im loving it!
Andy you make us crazy! Thank you for the info man! Resolved many problems thanks to your great tips! Please keep it up!
I retweeted your post as you ask to
and also liked on facebook as you suggested.
Is really hard to find quality JQuery tutorial videos, I am glad I found your site, I have learnt a lot with your video, bookmarked!
thanks trafis lol 😀
Wow, this was awesome. I’m just learning jquery right now and going through a book to help speed up the process. I noticed in Chrome that some of jQuery was running slow so I set out to find out why. This presentation gave me a ton of good ideas on how to fix it!
Thanks.
|
http://addyosmani.com/blog/jquery-performance-tips-2011/comment-page-1/
|
CC-MAIN-2015-48
|
refinedweb
| 1,288
| 73.58
|
BN_rand, BN_pseudo_rand − generate pseudo-random
number
#include <openssl/bn.h>
int BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom);
BN_rand() generates a cryptographically strong
pseudo-random number of bits bits in length and
stores it in rnd. If top is true, the two most
significant bits of the number will be set to 1, so that the
product of two such random numbers will always have
2*bits length. If bottom is true, the number
will be odd.
BN_pseudo_rand() does the same, but pseudo-random
numbers generated by this function are not necessarily
unpredictable. They can be used for non-cryptographic
purposes and for certain purposes in cryptographic
protocols, but usually not for key generation etc.
The PRNG must be seeded prior to calling
BN_rand().
BN_rand() and BN_pseudo_rand() return 1 on
success, 0 on error. The error codes can be obtained by
ERR_get_error(3).
bn(3), err(3), rand(3), RAND_add(3), RAND_bytes(3)
BN_rand() is available in all versions of SSLeay
and OpenSSL. BN_pseudo_rand() was added in OpenSSL
0.9.5.
|
http://alvinalexander.com/unix/man/man3/BN_rand.3.shtml
|
CC-MAIN-2019-47
|
refinedweb
| 183
| 64.61
|
digitalmars.D.bugs - [Issue 16071] New: Source file path and module name should match
- via Digitalmars-d-bugs (43/43) May 24 2016 Issue ID: 16071 Summary: Source file path and module name should match exactly Product: D Version: D2 Hardware: All OS: All Status: NEW Severity: normal Priority: P1 Component: dmd Assignee: nobody puremagic.com Reporter: pro.mathias.lang gmail.com Extract from : ``` The Identifiers preceding the rightmost are the Packages that the module is in. The packages correspond to directory names in the source file path. Package names cannot be keywords, hence the corresponding directory names cannot be keywords, either. ``` According to this definition, one cannot use a different name for the enclosing directory, nor can one introduce virtual package namespace, e.g. : src/foo/bar.d -> module hello.world.bar; However this is currently allowed. Using this kind of scheme breaks separated compilation badly, as the compiler rely on the module name for import. However, if the module is provided via command line, the compiler will first 'importAll', and the bug won't be visible. Even worst, the module declaration is ignored and the path is preferred in some cases, not others: ---- Import using the path ---- `src/main.d -> module main; import foo.bar;` Separate compilation: `dmd -c -o- -Isrc src/main.d` => Works All at once : `dmd -c -o- src/main.d src/foo/bar.d` => Doesn't work ---- Import using the given name ---- `src/main.d -> module main; import hello.world.bar;` Separate compilation: `dmd -c -o- -Isrc src/main.d` => Doesn't work All at once : `dmd -c -o- src/main.d src/foo/bar.d` => Works In addition, the specs provides the possibility to rename a file name with an invalid identifier (e.g. `foo-bar.d` -> `module foo_bar;`), and that suffers from the same problems. Even DMD is affected by this, as files are e.g. `src/mars.d` but the module name is `ddmd.mars`. --
May 24 2016
|
http://www.digitalmars.com/d/archives/digitalmars/D/bugs/Issue_16071_New_Source_file_path_and_module_name_should_match_89520.html
|
CC-MAIN-2017-51
|
refinedweb
| 327
| 50.63
|
I am proud to announce that Apache Airflow 2.0.0 has been released.
The full changelog is about 3,000 lines long (already excluding everything backported to 1.10), so for now I’ll simply share some of the major features in 2.0.0 compared to 1.10.14:
A new way of writing dags: the TaskFlow API (AIP-31)
(Known in 2.0.0alphas as Functional DAGs.)
DAGs are now much much nicer to author especially when using PythonOperator. Dependencies are handled more clearly and XCom is nicer to use
Read more here:
TaskFlow API Tutorial
TaskFlow API Documentation
A quick teaser of what DAGs can now look like:
from airflow.decorators import dag, task from airflow.utils.dates import days_ago @dag(default_args={'owner': 'airflow'}, schedule_interval=None, start_date=days_ago(2)) def tutorial_taskflow_api_etl(): @task def extract(): return {"1001": 301.27, "1002": 433.21, "1003": 502.22} @task def transform(order_data_dict: dict) -> dict: total_order_value = 0 for value in order_data_dict.values(): total_order_value += value return {"total_order_value": total_order_value} @task() def load(total_order_value: float): print("Total order value is: %.2f" % total_order_value) order_data = extract() order_summary = transform(order_data) load(order_summary["total_order_value"]) tutorial_etl_dag = tutorial_taskflow_api_etl()
Fully specified REST API (AIP-32)
We now have a fully supported, no-longer-experimental API with a comprehensive OpenAPI specification
Read more here:
Massive Scheduler performance improvements
As part of AIP-15 (Scheduler HA+performance) and other work Kamil did, we significantly improved the performance of the Airflow Scheduler. It now starts tasks much, MUCH quicker.
Over at Astronomer.io we’ve benchmarked the scheduler—it’s fast (we had to triple check the numbers as we don’t quite believe them at first!)
Scheduler is now HA compatible (AIP-15)
It’s now possible and supported to run more than a single scheduler instance. This is super useful for both resiliency (in case a scheduler goes down) and scheduling performance.
To fully use this feature you need Postgres 9.6+ or MySQL 8+ (MySQL 5, and MariaDB won’t work with more than one scheduler I’m afraid).
There’s no config or other set up required to run more than one scheduler—just start up a scheduler somewhere else (ensuring it has access to the DAG files) and it will cooperate with your existing schedulers through the database.
For more information, read the Scheduler HA documentation.
Task Groups (AIP-34)
SubDAGs were commonly used for grouping tasks in the UI, but they had many drawbacks in their execution behaviour (primarily that they only executed a single task in parallel!) To improve this experience, we’ve introduced “Task Groups”: a method for organizing tasks which provides the same grouping behaviour as a subdag without any of the execution-time drawbacks.
SubDAGs will still work for now, but we think that any previous use of SubDAGs can now be replaced with task groups. If you find an example where this isn’t the case, please let us know by opening an issue on GitHub
For more information, check out the Task Group documentation.
Refreshed UI
We’ve given the Airflow UI a visual refresh and updated some of the styling.
We have also added an option to auto-refresh task states in Graph View so you no longer need to continuously press the refresh button :).
Smart Sensors for reduced load from sensors (AIP-17)
If you make heavy use of sensors in your Airflow cluster, you might find that sensor execution takes up a significant proportion of your cluster even with “reschedule” mode. To improve this, we’ve added a new mode called “Smart Sensors”.
This feature is in “early-access”: it’s been well-tested by Airbnb and is “stable”/usable, but we reserve the right to make backwards incompatible changes to it in a future release (if we have to. We’ll try very hard not to!)
Read more about it in the Smart Sensors documentation.
Simplified KubernetesExecutor
For Airflow 2.0, we have re-architected the KubernetesExecutor in a fashion that is simultaneously faster, easier to understand, and more flexible for Airflow users. Users will now be able to access the full Kubernetes API to create a .yaml
pod_template_file instead of specifying parameters in their airflow.cfg.
We have also replaced the
executor_config dictionary with the
pod_override parameter, which takes a Kubernetes V1Pod object for a1:1 setting override. These changes have removed over three thousand lines of code from the KubernetesExecutor, which makes it run faster and creates fewer potential errors.
Read more here:
Docs on pod_template_file
Docs on pod_override
Airflow core and providers: Splitting Airflow into 60+ packages:
Airflow 2.0 is not a monolithic “one to rule them all” package. We’ve split Airflow into core and 61 (for now) provider packages. Each provider package is for either a particular external service (Google, Amazon, Microsoft, Snowflake), a database (Postgres, MySQL), or a protocol (HTTP/FTP). Now you can create a custom Airflow installation from “building” blocks and choose only what you need, plus add whatever other requirements you might have. Some of the common providers are installed automatically (ftp, http, imap, sqlite) as they are commonly used. Other providers are automatically installed when you choose appropriate extras when installing Airflow.
The provider architecture should make it much easier to get a fully customized, yet consistent runtime with the right set of Python dependencies.
But that’s not all: you can write your own custom providers and add things like custom connection types, customizations of the Connection Forms, and extra links to your operators in a manageable way. You can build your own provider and install it as a Python package and have your customizations visible right in the Airflow UI.
Our very own Jarek Potiuk has written about providers in much more detail on Jarek’s blog.
Docs on the providers concept and writing custom providers
Docs on the all providers packages available
Security
As part of Airflow 2.0 effort, there has been a conscious focus on Security and reducing areas of exposure. This is represented across different functional areas in different forms. For example, in the new REST API, all operations now require authorization. Similarly, in the configuration settings, the Fernet key is now required to be specified.
Configuration
Configuration in the form of the airflow.cfg file has been rationalized further in distinct sections, specifically around “core”. Additionally, a significant amount of configuration options have been deprecated or moved to individual component-specific configuration files, such as the pod-template-file for Kubernetes execution-related configuration.
Thanks to all of you
We’ve tried to make as few breaking changes as possible and to provide deprecation path in the code, especially in the case of anything called in the DAG. That said, please read through UPDATING.md to check what might affect you. For example: We have re-organized the layout of operators (they now all live under airflow.providers.*) but the old names should continue to work - you’ll just notice a lot of DeprecationWarnings that need to be fixed up.
Thank you so much to all the contributors who got us to this point, in no particular order: Kaxil Naik, Daniel Imberman, Jarek Potiuk, Tomek Urbaszek, Kamil Breguła, Gerard Casas Saez, Xiaodong DENG, Kevin Yang, James Timmins, Yingbo Wang, Qian Yu, Ryan Hamilton and the 100s of others who keep making Airflow better for everyone.
|
http://airflow.apache.org/blog/airflow-two-point-oh-is-here/
|
CC-MAIN-2021-17
|
refinedweb
| 1,225
| 54.12
|
C++ Practice
Description of sum of digits problem
In this sum of digits problem we have to find the sum of all the digits of an integer given by the user. We already have discussed about determining sum of digits in our C++ programming section. You can take the idea to solve this problem from there.
However, in this guide we will see the solution of this sum of digits problem. We have taken this problem from CodeChef for practice and learning purpose only. After taking the number form the user we will calculate the the sum of digits of that number here.
Solution to sum of digits problem
For determining the sum we will take the input first which will be the test case of this program. Ten each test case will take a number and calculate the sum of digits like bellow;
Assume, the user gives 5634 to find the sum of digits. The program will calculate,
(5 + 6 + 3 + 4) = 18
We can implement the logic to find the sum in different way which we have discussed in our sum of digits in C and sum of digits in C++ articles. If you have successfully completed those two guide then this program will be very simple to solve for you.
Now, let’s see the source code to find the sum of digits in C++ bellow.
// sum of digits problem solving in C++ #include <iostream> using namespace std; int main(){ int t, sum = 0; cin >> t; for(int i = 1; i <= t; i++){ int num; cin >> num; while(num > 0){ sum += num % 10; num /= 10; } cout << sum << endl; sum = 0; } }
Compile and run the above program in your editor to get the output like this.
3 12345 15 31203 9 2123 8
- Here, the first line contains the test case.
- Second line contains the number for first test case of which we have to calculate the sum of digits.
- Third line is the output for the first test case which have printed 15.
- Because (1 + 2 + 3 + 4 + 5 = 15).
- Similar process for other test case also.
|
https://worldtechjournal.com/cpp-practice/solution-sum-of-digits-cpp/
|
CC-MAIN-2022-40
|
refinedweb
| 350
| 76.15
|
02 September 2011 10:45 [Source: ICIS news]
SINGAPORE (ICIS)--Thai MMA is planning to shut its 90,000 tonne/year No 2 methyl methacrylate (MMA) line at Map Ta Phut on 5-15 September, a company source said on Friday.
The producer is operating the line at 95% capacity because of a feedstock shortage.
Meanwhile, Thai MMA is ramping up the operating rates at its 90,000 tonne/year No 1 MMA line after restarting it on 30 August, the source added.
The MMA producer was expected to restart the line on 27 August, but had taken slightly longer to complete it, the source said.
The company operated the line at 95% capacity before shutting it on 22 August because of the same feedstock shortage, the source added.
The producer is expected to resume 100% production capacity at the plant after restarting it, according to the source.
Thai MMA is a joint venture between ?xml:namespace>
For more on methyl
|
http://www.icis.com/Articles/2011/09/02/9489675/thai-mma-to-shut-no-2-mma-line-on-5-sep-restarts-no-1-mma.html
|
CC-MAIN-2014-35
|
refinedweb
| 161
| 60.55
|
ThisConciseness & Names).
There are many facets to the term Type Safety . You could spend an entire career studying the theoretical foundations for the type-systems of the Haskell or Scala programming languages, and could spend another entire career studying the implementation of types inside the Haskell runtime or the Java Virtual Machine. We will ignore both those fields.
Instead, this post explores the practical side of how to use the Scala language in a “type safe” way, where the compiler’s knowledge of Types lets you mitigate the consequences of your mistakes, often turning them into straightforward-to-fix-during-development compilation errors, thus provides Safety in developing your code. An experienced Scala programmer will likely find everything in this post “basic” or “obvious”, but anyone less experienced will hopefully find these useful techniques to add to the toolbox they use for solving problems in Scala.
Each of the techniques described here will have trade-offs: added verbosity, complexity, extra class files, poorer runtimes performance. We’ll ignore those trade-offs for this post, as usually they’re pretty clear. This post will only enumerate the possibilities, and not go into deep discussions on whether the trade-offs are worth it. Furthermore, this post only applies to Vanilla Scala , and not extensive third-party libraries like Scalaz or Cats or Shapeless . Those libraries would have their own idioms or techniques that deserve their own post, if someone with expertise is willing to write it up!
Like theother two posts in this series, hopefully none of the guidelines will be too controversial, and I aim to document what people experienced with the Scala language may count as “common sense”. Hopefully this post will lay a foundation of common principles that people share and basic techniques to be aware of, which you can combine with your own project-specific guidelines, preference and judgement when designing your Scala programs.
Fundamentals
Before we discuss concrete techniques and tradeoffs around type-safety, it makes sense to step back for a moment and ask what this is all about. What is a type? What does it mean to be “safe”?
What is a Type?
A Type is something you know about a value in our program at compile time.
Basically every programming language has a different type-system. Some have generics, some have reified generics. Some, like Java, have reified types, where the “type” of a value always corresponds to a class or interface can be checked at runtime. Others, like C, don’t. Dynamic languages like Python do not have static types, and so a type only exists at runtime.
The Scala language, that this post is about, has its own, relatively complex, ad-hoc type-system. There are also some attempts to formalize it, e.g. in the Dotty project . This post will ignore all of that.
For this post, I will be using the definition above. A Type is something you know about a value in your program at compile-time. For example:
- Something which is an
Intdefinitely contains a 32 bit integer from
-2147483648to
2147483647
- Something which is a
Option[T]definitely contains either a
Some[T], or
None
- Something which is a
CharSequencedefinitely contains
Chars and lets me call
.length,
.chatAt, and
.subsequencemethods, but i don’t know whether it is a
String, a
StringBuffer, or something else. You don’t know if it’s mutable or immutable, how it stores its contents, or what the performance characteristics are.
- Something which is a
Stringalso has characters, but you know it’s immutable, stores its contents in an internal array of characters, and has O(1) lookup to look up
Chars by index
The type of a value tells you both what something can be, and what it cannot be. A
Option[String] can be
Some or
None , but it cannot be a 32 bit integer! In Scala, this is not something you need to check in your code: it is something you can rely on being correct, with the compiler checking for you during compilation.
This knowledge is exactly what comprises the “Type” of a value.
What is a Type not?
A Class
By this definition, a type is not a class. Yes, in Java, and Scala on the JVM, all types are represented by classes (or interfaces). This does not hold true in e.g. Scala.js , where you can define types to be synthetic (
trait s extending
js.Any ) with no remnants left behind to inspect after everything is compiled, or in other programming languages.
While the types being backed by classes is a true fact, it is an implementation detail that is mostly irrelevant to this post.
The Scala Type System
The idea of a “Type” we discuss here is vague, broad, and applies to more languages than just Scala. Scala’s own type system is complex, with classes, abstract types, refinement types, traits, type-bounds, context bounds, and other even more obscure things.
From the perspective of this post, these all are details that serve the same purpose: to let you describe to the compiler things you know about the values in your program, and let it check that what you’re doing is consistent with what you said you wanted to do.
What is Safety?
Safety means that when you make a mistakes, the consequences are minor.
There are probably even more definitions of Safety than there are of Types. The above definition is broader than types: it applies to security practices, isolation, robustness & resilience in distributed systems, and many other things.
People make all sorts of mistakes: typos in code, poor load-estimation, copy-pasting the wrong command. When you make a mistake, what happens?
- You see a red squiggly in your editor and fix it in 5 seconds
- You want for a full compile, taking 10s, then fix it
- You run the test suite, which takes 10s, then fix it
- You deploy the mistake, notice the bug a few hours later, fix it, and deploy the fix
- You deploy the mistake, the bug goes un-noticed for weeks, and even when noticed and fixed it takes weeks to clean up the mess of corrupted data that it left behind
- You deploy the mistake, and
find your company totally bankrupt 45
minutes later
Ignoring the idea of “types” and “compile time”, it is obvious that different environments have different levels of safety. even runtime errors can have smaller impact if caught early and are easy to debug, making Python’s habit of throwing
TypeError at runtime when something doesn’t match significantly “Safer” than PHP’s habit of coercing values when things don’t match (which tends to mask/hide problems resulting in data-corruption and obscure/hard-to-trace bugs).
What is Type Safety?
Type-safety is making use of what we know of our values at compile-time to minimize the consequences of most mistakes.
For example, one “minor consequence” could be seeing an easy-to-understand compile error during development, and taking 30s to fix it.
This definition follows straightforwardly from our definitions of “Types” and “Safety” above. It is significantly broader than most definitions of type-safety. In particular:
Type-safety is not writing Haskell; the idea is much broader than that.
Type-safety is not avoiding mutable state, unless it contributes to our goal stated above.
Type-safety is not an absolute to reach, but a property to try and optimize
Type-safety is not the same for everyone; if different people tend to make different sorts of mistakes, and their mistakes have different levels of harm, they should optimize for different things to try and minimize the overall harm of those mistakes.
Even compile errors can have serious consequences if the error-messages are inscrutable and resolving them is difficult! A nice compile error that you can fix in 10 seconds is different from a humongous compile error that might take you half an hour to understand before you can fix it
There are a wide variety of definitions of type-safety; if you ask a developer working in C++, a web developer writing Python, and a professor studying programming-languages, each one will have their own distinct definition. For this post, we will use the arbitrary, broad definition above:
Type-safety is making use of what we know of our values at compile-time to minimize the consequences of most mistakes.
Scalazzi Scala
Many people have thought a lot about how to write Scala in a way that is “type safe”. The so-called ” Scalazzi Subset ” of the Scala language is one of those philosophies:
While there is a lot to discuss about these guidelines, we’ll spend time reviewing a few of them I find the most interesting:
Avoid Null
It is very tempting to use
null to represent some data that is missing, un-initialized, or not available, e.g. as an uninitialzied value
class Foo{ val name: String = null // override this with something useful if you want }
Or a “no value” argument to pass into a function
def listFiles(path: String) = ... listFiles("/usr/local/bin/") listFiles(null) // no argument, default to current working directory
tells us to avoid doing this, and for good reason:
nulls can appear anywhere in your program, in any variable or value, and there is no way to control what variable is or is-not
null
nulls propagate throughout your program: you can pass
nulls into functions, assign them to other variables, and store them in collections.
Together, this means that
null values tend to cause errors far away from where they where initialized, and are difficult to track down. When something blows up with a
NullPointerException , you have to first find the misbehaving variable (there may be many variables in use in a single line of code!) and then trace it through as it gets passed in and out of functions and stored-in/retrieved-from collections, until you can figure out where the
null initially came from.
In a dynamic language like Python, this sort of accidental wrong-value-propagation is common, and it’s not unusual to spend hours tracing through the program, adding
user_id instead of
user_email or something equally trivial, but nonetheless it takes a significant effort to track down and fix.
In a compiled language with a type-checker, like Scala, many such mistakes are caught before you even run your code by the compiler: passing in an
Int or a
Seq[Double] where a
String is expected results in a type-error. Not all things are caught, but many of the more egregious mistakes are. Except for passing in
null when no-
null was expected.
Here are some alternatives to
null s:
If you are trying to represent a value that may-or-may-not exist, whether are a function argument or as a class attribute to override:
class Foo{ val name: String = null // override this with something useful if you want }
Consider using an
Option[T] instead:
class Foo{ val name: Option[String] = None // override this with something useful if you want }
Some("foo") and
None instead of
"foo" and
null seems similar, but by doing so everyone knows it can be
None , and unlike with
null s you get a compilation error if you try to put the
Some[String] somewhere a
String was expected.
If you are using
null in a
var as a placeholder for an un-initialized variable
def findHaoyiEmail(items: Seq[(String, String)]) = { var email: String = null // override this with something useful if you want for((name, value) <- items){ if (name == "Haoyi") email = value } if (email == null) email = "Not Found" doSomething(email) }
Consider how you could replace it with a
val and declare-and-initialize it all at one go.
def findHaoyiEmail(items: Seq[(String, String)]) = { val email = items.collect{case (name, value) if name == "Haoyi" => value} .headOption .getOrElse("Not Found") doSomething(email) }
Even if you can’t initialize the
{...} s when declaring a
val , so in most cases any code you were going to use to initialize your
var “later” you should be able to place inside the
{...} s to declare-and-initialize your
val at one go.
def findHaoyiEmail(items: Seq[(String, String)]) = { val email = { ... } doSomething(email) }
And in doing so, we manage to prevent
null .
By simply avoid
null in your program, you do not change the theoretical situation: in theory someone could pass in
null and you would be in the same spot tracing down hard-to-debug problems. But you change the practical environment: you spend much less time tracing down hard-to-debug
NullPointerException s. Every once in a while you still do (due to
null s appearing due to initialization order, or third-party libraries using
null s) but on overall the consequences for making mistakes tends to be lower. More bugs become straightforward compilation errors to fix during development, rather than expensive runtime exceptions to track down.
Avoid Exceptions
Exceptions are basically additional return-values for a piece of code. Any code you write can return the “normal” way via the
return keyword or simply returning the last expression in a block, or it could throw an exception. And that exception can contain arbitrary data.
While other languages like Java have tried to have the compiler check that you make sure to catch the exceptions that can be thrown, their “checked exceptions” feature has generally not been a success: the inconvenience of having to declare what checked exceptions you throw often leads to people just declaring their methods to have a blanket
throws Exception , or to catch the checked exceptions and re-throw them as un-checked runtime exceptions. Later languages like C# or Scala have dropped the idea of checked exceptions entirely.
Why shouldn’t you use exceptions?
You have no way of statically knowing all the different kinds of exception a piece of code can throw. You thus don’t know if you’ve handled all the possible “return” cases for that code
Annotations for what exceptions you throw are optional and trivially fall out of sync with reality as development happens and refactorings occur.
They propagate, so even if a library you’re using has gone through the discipline of annotating all its methods with the exceptions they throw, the chances are in your own code you’ll get sloppy and won’t
As a replacement for exceptions, you can return
Option[T] to represent the result of a function with only one failure mode, or
Either[T, V] or your own custom sealed-trait hierarchy to represent results with more than one failure mode:
sealed trait Result case class Success(value: String) extends Result case class InvalidInput(value: String, msg: String) extends Result case class SubprocessFailed(returncode: Int, stderr: String) extends Result case object TimedOut extends Result def doThing(cmd: String): Result = ???
Using a sealed trait hierarchy, you can easily communicate to the user exactly what failure modes exist, what data is available in each case, and the compiler will provide a warning if the user failed to handle a case when they
match on the result of
doThing .
In general, though, you will never get rid of all exceptions:
Any non-trivial program has enough different failure modes that it’s impractical to list them out exhaustively
Many are uncommon enough that you actually do want to catch them in bulk and handle generic “something went wrong” behavior to e.g. log or report them, or re-try the logic, even if you don’t know exactly what caused it.
For these uncommon failure modes, logging them with debugging information so you can examine them manually is the best you can do, and exceptions with their stack-trace generation do it by default.
However, even with a stack trace, figuring out why un-wanted exceptions keep appearing takes significantly more time than seeing compile-errors due to trying to use an
Option[T] where a plain-old
T is desired.
Programming in Scala is living in a world with exceptions:
NullPointerExceptions
MatchErrors from bad pattern matches
IOExceptions for any sort of arbitrary filesystem or network failure
ArithmeticExceptions when you divide by 0
IndexOutOfBoundsExceptionwhen you mess up your arrays
IllegalArgumentExceptionwhen you mis-use third-party code
And many more! Nevertheless, just because they are everywhere doesn’t mean you should add to the problem. In your own code, avoid using exceptions to improve type-safety and give the compiler more chances to catch your mistakes when you forget to handle failure cases in your
Option[T] s or
Either[T, V] s or
sealed trait data types.
Avoid Side Effects
Side effects are, at least in Scala, not tracked by the compiler. While they superficially don’t have anything to do with “types”, it can be argued that they undermine the type-safety we’ve defined.
As an example, let’s consider a piece of code like:
var result = 0 for (i 10) result = result + 5 println(result) // 50 makeUseOfResult(result)
While simpler than what happens in real codebases, it illustrates the point: we initialize
result to some placeholder value, and then use side-effects to modify
result to get it ready for the
makeUseOfResult function which presumably does something important we care about.
There are many things that can go wrong. You could accidentally leave out one of the mutations
var result = 0 for (i <- 0 until 10){ results += 1 } println(result) // 45 makeUseOfResult(result) // getting invalid input!
This may seem like an “obvious” mistake, but when the snippet is 1000 lines instead of 10, it’s an easy mistake to make in the middle of a refactoring effort. It means that
makeUseOfResult gets invalid input and might do the wrong thing. Here’s another, equally common failure mode:
var result = 0 foo() for (i 10) result = result + 5 println(result) // 50 makeUseOfResult(result) ... def foo() = { ... makeUseOfResult(result) ... }
Here, instead of accidentally botching the initialization code during a refactoring, we are accidentally making use of the
result variable before it’s finished being initialized! Maybe we’re using it indirectly, in this example through the
foo() helper, but the effect is the same: at some point in our program, we’ll “see”
result having the wrong value, and later on we’ll see it having a different, right value.
In this case, a “solution” would be to eliminate the side effects, and giving the different “stages” of
result different names:
val summed = (0 until 10).sum val result = if (summed > 10) summed + 5 else summed println(result) // 50 makeUseOfResult(result)
Although equivalent when done correctly, it is immune to the two accidental failure-modes shown above. Accidentally leaving out one stage in the computation results in a compile error:
val summed = (0 until 10).sum println(result) // Compilation Failed: not found: value result makeUseOfResult(result)
And similarly using
result before it’s ready, even indirectly , results in a compilation error:
foo() // Compilation Failed: // forward reference extends over definition of value summed val summed = (0 until 10).sum val result = if (summed > 10) summed + 5 else summed println(result) // 50 makeUseOfResult(result) def foo() = { makeUseOfResult(result) } def makeUseOfResult(i: Int) = ()
Although these may not be considered “type errors” in the sense of a value’s type not lining up with an expected type, it is a case of the compiler using its knowledge of the code to catch our mistakes and making them easy to fix early, minimizing their impact. That definitely falls under the extra-broad umbrella of Type Safety we defined.
Limitations of Scalazzi Scala
Here’s some code that is perfectly validas defined above, but will definitely upset people if it appeared in a code review:
def fibonacci(n: Double, count: Double = 0, chain: String = "1 1"): Int = { if (count >= n - 2) chain.takeWhile(_ != ' ').length else{ val parts = chain.split(" ", 3) fibonacci(n, count+1, parts(0) + parts(1) + " " + chain) } } for(i <- 0 until 10) println(fibonacci(i)) 1 1 1 2 3 5 8 13 21 34
This code is correct, and follows theguidelines to the letter:
- No
null
- No exceptions
- No
isInstanceOfor
asInstanceOf
- No side-effects and all values are immutable
- No
classOfor
getClass
- No reflection
Yet most people would agree it’s terrible, unsafe code. Why is that? The answer lies in…
Structured Data
Not all data has the same “shape”: if you have some data containing pairs of
(name, phone-number) , there are a variety of ways you can store them:
- In a
Array[Byte]: this is the format that the filesystem stores them in, after all! If you dump your data to disk, this is what it becomes.
- In a
String: when you open your data-file in a text editor, this is what you see.
- In a
Seq[(String, String)]
- In a
Set[(String, String)]
- In a
Map[String, String]
All of these are valid data-structures for our name/phone-number pairs. How do we choose which representation to use?
Avoid Strings in favor of Structured Data
It is often tempting to treat
String s as your data-store, storing data by concatenating them together, extracting data by slicing them apart. For example, you may want to get the hashcode of an object in hexadecimal form, and notice that it’s already part of the
toString :
@ println((new Object).toString) [email protected]
And may decide that splitting it on the
@ will be enough to get what you want:
@ val myHashCode = (new Object).toString.split("@")(1) myHashCode: String = "36de8d79"
And you’d be right! However, while this works “sometimes”, it fails in many other cases, e.g. when the object has a custom
toString :
@ case class Foo() defined class Foo @ val myHashCode = (new Foo).toString.split("@")(1) java.lang.ArrayIndexOutOfBoundsException: 1 cmd33$.(Main.scala:349) cmd33$.(Main.scala:-1)
The solution is to avoid trying to take apart the
toString string to get the data you want, and instead compute it yourself using the same technique that
toString does: using the
.hashCode and converting it to base 16:
@ Integer.toHexString((new Object).hashCode) res36: String = "a58a099" @ Integer.toHexString((new Foo).hashCode) res37: String = "114a6"
To use the example above, imagine we take in a string with user names and phone-numbers as comma-separated values, and want to find everyone whos phone number starts with
415 indicating they’re from California:
val phoneBook = """ Haoyi,6172340123 Bob,4159239232 Charlie,4159239232 Alice,8239239232 """
We may come up with a piece of code like:
val lines = phoneBook.split("n") val californians = lines.filter(_.contains(",415")) // Bob,4159239232 // Charlie,4159239232
And it will work. Until the text format changes, e.g. to tab-separated values, and your code silently starts returning nothing:
val phoneBook = """ Haoyi 6172340123 Bob 4159239232 Charlie 4159239232 Alice 4159239232 """ val lines = phoneBook.split("n") val californians = lines.filter(_.contains(",415")) //
In such situations, the better thing to do would be to first parse the
phoneBook into some structured data format (here a
Seq[(String, String)] ) you expect, before working with the structured data to get your answer:
val parsedPhoneBook = for(line <- phoneBook.split("n")) yield { val Seq(name, phone) = line.split(",") (name, phone) } // Seq( // ("Haoyi", "6172340123"), // ("Bob", "4159239232"), // ("Charlie", "4159239232"), // ("Alice"," 8239239232") // ) parsedPhoneBook.filter(_._2.startsWith("415")) // Seq( // ("Bob", "4159239232"), // ("Charlie", "4159239232") // )
In such a scenario, if the input data format changes unexpectedly, your code will fail loudly when computing
parsedPhoneBook . Furthermore, the compiler can statically check to make sure that once you’re passed that point, your code won’t misbehave due to the data being in the wrong shape! Thus you can be sure that data-format errors will only happen in one place, and after that you can be confident your code is “safe”: it won’t blow up randomly in the middle of your logic due to invalid input.
Here we’re only dealing with tuples of strings, but as the data-format gets more complex with more fields of more different types, it gets even more important to structure your data and make sure it fits the shape you expect before you start trying to do work with it.
This may seem obvious to some people, but plenty of people would consider slicing apart the
toString to get what they want an acceptable solution. For example, if you have a shell-scripting background, or a Perl background, this sort of string-spicing is the normal way of doing things. You can actually achieve quite a lot with it, once you start including regexes and other more-advanced string-slicing techniques.
Nevertheless, this has no place in Scala programs. When you assume data is “in the string”, this is something that may or may not be true, and the compiler cannot help you verify. On the other hand, if you access and transform data via the methods and attributes of your objects, such as
.hashCode or
toHexString , you can be pretty sure that these will exist and will work on whatever you pass in. And if you make a mistake and use them in some incorrect way, the compiler is likely to be able to tell you, whereas if you make a mistake string-slicing you get runtime errors. This is one way to improve the type-safety of your Scala code.
Encode Invariants in Types
Even if you’re out of the “storing things in strings” mindset, and are storing/accessing your values in the form of structured data (objects with methods and attributes, collections) there is still a wide range of different ways you can represent things. For example, in the, we chose to use a
Seq[(String, String)] to store the phone-book containing users and their phone numbers. But we could also easily pick a
Map[String, String] or a
Set[(String, String)] . So which one should we use?
It turns out that apart from having different performance characteristics (
Set having a fast
contains to check if a tuple exists in it, map has a fast
contains to check if a key exists) each of these data structures promises different things:
Seq[(String, String)]: it’s possible to have duplicate entries (names, phone-numbers, or both) and the order of the entries matters
Set[(String, String)]: you can have duplicate names, duplicate phone-numbers, but each (name, phone-number) pair is unique. Order of entries doesn’t matter
Map[String, String]: you can have duplicate phone-numbers but no duplicate names; the order of entries doesn’t matter.
Just by looking at which data-structure you store your code in you can be sure, at compile time, of certain properties. If you have a
Map , you know you never need to worry about the same person having multiple phone-numbers, whereas if you have a
Set or a
Seq it could happen and you may need to write code to handle that case.
Similarly, if you find yourself writing a
lookup function to get a user’s phone-number based on their name:
def lookup(name: String): ???
What should it return? It could return
Stringif you are sure there is a 1 to 1 correspondence between names and phone-numbers, and the name being looked up will always exist
Option[String]if there’s a 1 to 1 correpsondence between names and phone-numbers but the name may not exist in the phonebook sometimes
Both of these return types correspond to the
Map[String, String] case abpve. But that’s not all it could return, it could also return:
Seq[String]if the name may correspond to multiple phone-numbers in the phone-book (possibly with duplicates), or not exist, and the order matters
Set[String]if the name may correspond to multiple phone-numbers in the phone-book without duplicates, or not exist, and the order does not matter
These correspond to the
Seq[(String, String)] and
Set[(String, String)] cases above. But there are still other possibilities for the return type:
(String, Seq[String])if the name may correspond to multiple phone-numbers in the phone-book (possibly with duplicates), but at least one must exist , and the order matters
(String, Set[String])if the name may correspond to multiple phone-numbers in the phone-book without duplicates, but at least one must exist , and the order does not matter
By returning a tuple of
(String, Seq[String]) , you are guaranteeing to the caller of your
lookup function that you will always return at least one item, never zero. That can be useful for the caller: they may use
val (first, rest) = lookup(name) rest.foldLeft(first)(...)
instead of
val numbers = lookup(name) numbers.reduce(...)
And can be 100% confident that their code will not throw a
java.lang.UnsupportedOperationException: empty.reduceLeft due to an empty list being returned.
By the time you’re returning a tuple
(String, Seq[String]) , the API starts to get slightly inconvenient, and so many people will not go to such extents to strictly define exactly what their values can contain. Nevertheless, if you want to optimize for extreme safety, this is a possible technique.
Libraries like Scalaz provide NonEmptyList data-structures that make this slightly more convenient to use. Internally it is basically the same (a tuple of a single element and a list) but they provide nice APIs to make it less clunky to work with.
Even if you’re not going to return
(String, Seq[String]) from your functions to enforce the non-emptiness of the result, or aren’t going to depend on Scalaz for these convenient data-types, this kind of analysis is still very useful for improving the type-safety of your code. Rather than picking an arbitrary type that “can” contain the data you want, it is often worth thinking for a moment about what exactly can appear in that value, and choosing from the possible data-types the type that most precisely represents what you mean.
Self-describing data
Even data with the same “shape”, not all of it is the same! For example, a
Double representing a value in Newtons is very different from a
Double representing a value in Pounds, even though they’re both
Double s, and confusing the two can cause your $327,000,000 space-craft to crash and burn . Similarly, an
Int containing a timestamp, an
Int containing an ID, and an
Int containing a enum or flag-value are not the same thing, despite all being
Int s. You certainly aren’t going to add your ID
Int to your enum
Int : you can, but it’s basically never what you want.
There is a solution to this: teach the compiler that these values have different meanings, even if they are the same shape! This means giving them different types. Here are some common cases where you can do this
Avoid Integer Enums
It is not an uncommon pattern to define an enumeration of possible values via:
val UNIT_TYPE_UNKNOWN = 0 val UNIT_TYPE_USERSPACEONUSE = 1 val UNIT_TYPE_OBJECTBOUNDINGBOX = 2
This has several advantages:
Ints are cheap, take minimal memory to store or pass around
- By using constants instead of literals, it becomes a bit more obvious “what” you are trying to do instead of seeing magic values like
2pop up everywhere within your code
Not bad. However, this code is “less safe” than it could be. For example, the following is meaningless, and basically incorrect, but does not cause a compile error:
UNIT_TYPE_UNKNOWN + 10
Nor does
UNIT_TYPE_USERSPACEONUSE - UNIT_TYPE_OBJECTBOUNDINGBOX
In both of these cases, the result of the computation can’t really be used anywhere a
UNIT_TYPE is expected. If I have a function taking a
UNIT_TYPE and pass in
UNIT_TYPE_UNKNOWN + 10 , I can’t expect it to work.
Although the
UNIT_TYPE values are declared as
Int s, none of the normal operations on
Int s really apply to them. Similarly, while an
Int can be anywhere from
+2147483647 to
-2147483648 , only three our of those four billion values can be used somewhere one of these
UNIT_TYPE constants is being used. And like how there’s nothing stopping you from performing invalid
Int operations on a
UNIT_TYPE constant, there’s also nothing stopping you from passing in invalid
Int s (for example,
15 ) where a
UNIT_TYPE constant from
0 to
2 is expected.
A more type-safe solution may be
sealed trait UnitType object UnitType{ case object Unknown extends UnitType case object UserSpaceOnUse extends UnitType case object ObjectBoundingBox extends UnitType }
Or perhaps
// You can also make it take a `name: String` param to give it a nice toString case class UnitType private () object UnitType{ val Unknown = new UnitType val UserSpaceOnUse = new UnitType val ObjectBoundingBox = new UnitType }
Both of these cases accomplish the same thing: by making
UnitType an actual type. That means if we try to perform
Int operations on them it gives a compile error:
@ UnitType.Unknown + 10 type mismatch; found : Int(10) required: String UnitType.Unknown + 10 ^ Compilation Failed
And so does trying to pass an invalid
Int where a
UnitType is expected:
@ val currentUnitType: UnitType = 15 type mismatch; found : Int(15) required: UnitType val currentUnitType: UnitType = 15 ^ Compilation Failed
Naturally, it will always be possible to intentionally convert
UnitType s to
Int s and vice versa:
@ def unitTypeToInt(ut: UnitType): Int = ut match{ case UnitType.Unknown => 0 case UnitType.UserSpaceOnUse => 1 case UnitType.ObjectBoundingBox => 2 } defined function unitTypeToInt @ unitTypeToInt(UnitType.Unknown) res46: Int = 0 @ unitTypeToInt(UnitType.ObjectBoundingBox) res47: Int = 2
And this will no doubt be necessary if you’re serializing the
UnitType s to send over the network, or you’re passing them to third-party libraries that rely on the integer constants. Nevertheless, when you perform this conversion you have to do so explicitly, and it’s unlikely that you would “accidentally” call
unitTypeToInt (or the converse
intToUnitType ) to convert something you didn’t meant to.
As in our definition ofabove, it doesn’t just matter what the theoretical problems are, but also the practical chances of bumping into them. And you are much less likely to accidentally call a conversion function than you are to put a value in the wrong place!
Avoid String Flags
For the same reason you want to, you may also want to avoid using passing strings around to represent flags. To use the same example, but tweaked to represent a common pattern of passing around strings:
val UNIT_TYPE_UNKNOWN = "unknown" val UNIT_TYPE_USERSPACEONUSE = "user-space-on-use" val UNIT_TYPE_OBJECTBOUNDINGBOX = "object-bounding-box"
This has the same problem as using integers; you can call
.subString ,
.length ,
.toUpperCase and all other string methods on these
UNIT_TYPE flags, and they’re all meaningless and definitely not what you want. Similarly, you can pass in all sorts of
String s into places where a
UNIT_TYPE flag is required, almost all invalid except for these three special values.
The solution is the same as we used to: define a type to represent
UnitType and then use that instead of
String s:
sealed trait UnitType object UnitType{ case object Unknown extends UnitType case object UserSpaceOnUse extends UnitType case object ObjectBoundingBox extends UnitType } // Or perhaps class UnitType private () object UnitType{ val Unknown = new UnitType val UserSpaceOnUse = new UnitType val ObjectBoundingBox = new UnitType }
Box Integer IDs
IDs of varioues sorts are often stored as primitives; auto-incrementing IDs are often
Int s or
Long s, while UUIDs are often
String s or
java.util.UUID . However, unlike
Int s or
Long s, IDs have certain unique properties:
All the arithmetic operations generally don’t make sense: given a
userId: Int,
userId * 2or is something you basically never do.
Different IDs are not interchangeable: if I have a
userId: Intand a function
def deploy(machineId: Int), calling
deploy(userId)is basically never what I want
Although the IDs are probably stored in memory as
Int s or
Long s or
String s or
java.util.UUID s, and maybe stored in the database or caches in the same way, they really can’t be substituted for primitives, or used in primitive operations, and can’t even be substituted for each other. Thus, it may make sense to box the IDs of various sorts into distinct classes, e.g.
case class UserId(id: Int) case class MachineId(id: Int) case class EventId(id: Int) ...
This has some memory overhead, and some performance overhead, but it does ensure that if I have a
userId: UserId and a
def deploy(machine: MachineId) , accidentally calling
deploy(userId) would be come a compilation error rather than a runtime error. Or worse, having no error at runtime and instead silently deploying the wrong machine ! It’s not bulletproof – a “malicious” programmer can easily call
deploy(MachineId(userId.id)) to work around this barrier – but nevertheless would catch most cases of accidental re-use.
While the example given is short and “obvious”, in real code, written by other people, possibly months or years ago, things are a lot less clear than
def deploy(machineId: Int) = ... deploy(myUserId) // wrong deploy(myMachineId) // right
In a more realistic scenario we may be looking at:
def deploy(machineId: Int, deployingUser: Int, proxyMachine: Int, timeout: Int, machineType: String, ipAddress: String, timeout: Int) = ... deploy( myMachineId, myProxyId, myUserId, 1000, "c3.xlarge", "192.168.1.1" ) // wrong deploy( myMachineId, myUserId, myProxyId, 1000, "c3.xlarge", "192.168.1.1" ) // right
And in such a scenario, we may be glad to pay the cost of boxing the different sorts of IDs into different types:
def deploy(machineId: MachineId, deployingUser: UserId, proxyMachine: MachineId, timeout: Int, machineType: String, ipAddress: String, timeout: Int) = ... deploy( myMachineId, myProxyId, myUserId, 1000, "c3.xlarge", "192.168.1.1" ) // type mismatch; // found : MachineId // required: UserId // myProxyId, // ^ // Compilation Failed
In order to have the
// wrong example be a compilation error rather than a runtime-error or runtime-misbehavior!
This sort of technique can be taken arbitrarily far. For example, should
machineId and
proxyMachine be different types, instead of both
MachineId ? The answer to that depends on how often you re-use one as the other. If you do make them different types (e.g.
DeployTargetId and
ProxyMachineId ), re-using them isn’t impossible: you simply need to write some extra boilerplate to unwrap one via it’s
.id attribute and then wrap it again in the desired wrapper:
case class DeployTargetId(id: Int) case class ProxyMachineId(id: Int) val deployTargetId: DeployTargetId = ??? val proxyId = ProxyMachineId(deployTargetId.id)
Practically, if you almost never wrap/unwrap the IDs when passing them around, it’s more worth giving them separate wrappers. If you find that you would need to wrap/unwrap the IDs continuously throughout your code, then it’s not worth giving them separate wrapper-types.
Conclusion
In this post we’ve talked about what it means to be “type safe” from a practical point of view, and gone over a number of techniques that help improve the type-safety properties of your Scala code. In all these cases, the added safety is approximate: there isn’t any theoretical barrier stopping people from reaching around “behind” your code to do bad things, e.g. unwrapping your boxed integer IDs or converting your non-string flags back into strings with by
match ing on it. We just hope that the added inconvenience of unwrapping these when we really need to is outweighed by the added safety of eliminating these “easy” mistakes in other situations.
But how do you know if the benefit actually does outweight the cost?
That is an empirical question depending on how you are using the code: how often you would get inconvenienced vs how often you’d be saved from your mistakes. Basically all of these techniques have trade-offs, whether in terms of performance or convenience, and it’s up to each developer to use their judgement to decide what’s the right trade-off for each scenario.
Hopefully by reading this post, you’ve learned some useful techniques that you can make use of in your own Scala code to get the compiler to help catch your mistakes and improve type-safety.
What other tips or techniques to you use to increase type-safety when you’re writing Scala? Let us know in the comments below!
|
http://colabug.com/944089.html
|
CC-MAIN-2017-47
|
refinedweb
| 6,684
| 54.56
|
Summary
The
nsACString abstract class represents a character string composed of single-byte storage units. This class is typically used to represent ASCII or UTF-8 character arrays.
#include "nsStringAPI.h" class nsACString { ... };
Typedefs
char_type [char]
- Storage unit for this class.
self_type [nsACString]
- An alias for the type of this class.
size_type [PRUint32]
- Type used to represent the number of bytes stored in the string.
index_type [PRUint32]
- Type used to represent an offset into the string.).
Operators
operator+=
- This operator is a shortcut for the Append family of functions.
Remarks
The
nsACString class is never instantiated directly. It should be instantiated using a subclass, such as
nsEmbedCString.
nsACString corresponds to the
ACString and
AUTF8String XPIDL data types.
nsACString by itself does not imply a particular character encoding. That is, it may be used to store UTF-8 characters, ASCII characters, or any random binary data. The character encoding in use for a particular
nsACString instance depends on the context in which it is used. If used with XPIDL, then the character encodings of the corresponding XPIDL data types applies.
nsACString may even hold data with embedded null bytes. Thus, the length of the data contained in the
nsACString should be determined by calling the
nsACString::Length() method.
The methods defined on
nsACString are implemented as inline wrappers around the XPCOM string functions, prefixed with
NS_CString. See, for example,
NS_CStringGetData.
|
https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Glue_classes/nsACString
|
CC-MAIN-2015-32
|
refinedweb
| 229
| 51.04
|
I am having problems with this code and im nooby what im trying to do
Create a game where the computer picks a random word and the player has to guess that word. The computer tells the player how many letters are in the word. Then the player gets five chances to ask if a letter is in the word. The computer can only respond with "yes" or "no". Then, the player must guess the word. im trying to learn python from a text book the michael dawson one
i think i didnt do a good job putting it together every letter i guess it just keeps telling me to guess
import random print "Hello President Bush, I will give you 5 chances to guess letters of one of my secret words.\n On the final chance, you must guess the word" WORDS = ("bush", "usa", "war", "oil", "iraq", "osama", "alla") word = random.choice(WORDS) print "The password is", len(word), "letters long." guesscount = 0 done = 0 while done <=1: guess = raw_input("guess a letter: ") if guess in word: guesscount += 1 print "yes" elif guess not in word: guesscount +=1 print "no" elif guess == " ": print "no" guesscount += 1 elif guesscount == 4: print "You have to guess the presidents passcode" guess_word = raw_input("Input code: ") guess_word = guess_word.lower() if guess_word == word: print "The CIA is are already at your house!\n President never gets it on the first try..." break elif guess_word != word: print "President Bush did you forget your password again..." break
|
https://www.daniweb.com/programming/software-development/threads/187412/problem-in-a-random-word-guessing-program
|
CC-MAIN-2017-43
|
refinedweb
| 250
| 77.98
|
Eclipse Community Forums - RDF feed Eclipse Community Forums No, this project is not dead <![CDATA[... just hibernating until Galileo activity calmed down and I had cycles to pay attention to longer-term items. With Galileo out of the way, I have spent several days on getting the project bootstrapped. I forked the relevant code from WTP, repackaged it according to this project's naming convention and got everything into CVS. If you look in CVS now (at /cvsroot/technology), you will see the structure outlined later in this message. There is quite a bit of code and content in there. Team project set files can be found at /org.eclipse.fproj/releng/psfs/. Everything in CVS HEAD currently builds (against Galileo) and runs. The existing unit tests that were brought over from WTP are all passing as well. We actually even have a working build system now, courtesy of Athena common build infrastructure and Hudson. I will post instructions later for how to run the build locally, but anyone can now access build results on Hudson via the following URL: This job is configured to always build latest from HEAD. I am not a big fan of map files, tagging and only building what's been "released". About plans. There are going to be a series of milestones over the next few months as progress is made towards 1.0. As a review item, the major goals for the 1.0 release are as follows: 1. Get setup as an independent project. 2. API refactoring and cleanup. 3. Backwards compatibility layer for WTP. 4. Join Helios release train. So, the first milestone (dubbed 0.1) will take an incremental step towards the above goals: 1. Code forked from WTP and repackaged into the new namespace... done. 2. Build system implemented and running on Hudson... done. 3. Existing unit tests passing... done. 4. Builds publishing to the download server. 5. Deprecated code removed and other mechanical cleanup items. My current estimate is that 0.1 will be ready by end of July. After that, its on to deeper API refactoring and backwards compatibility layer for WTP. This would be an excellent time for anyone who wants to be involved with this project (in whatever capacity) to get involved. We have an opportunity that doesnt happen very often in framework code to make deep changes in API, but once 1.0 ships next summer, we will have a new API contract to maintain and will be much more limited in the type of changes that can be done. So, if you are an existing user of this framework in WTP, get involved and make your opinions heard. Are there parts of API that you dislike or are giving you particular problems? Post questions and feedback on fproj-dev@eclipse.org or the newsgroup ( proj). You can also open bugs and enhancements against this project ( 20Project%2 0Framework). CVS Layout of Faceted Project Framework ======================================= org.eclipse.fproj core docs org.eclipse.fproj.doc.api features org.eclipse.fproj-feature org.eclipse.fproj.sdk-feature plugins org.eclipse.fproj org.eclipse.fproj.sdk org.eclipse.fproj.ui tests features org.eclipse.fproj.tests-feature plugins org.eclipse.fproj.tests enablement-jdt docs org.eclipse.fproj.enablement.jdt.samples org.eclipse.fproj.enablement.jdt.samples.rand.lib-1.0 org.eclipse.fproj.enablement.jdt.samples.rand.lib-2.0 features org.eclipse.fproj.enablement.jdt-feature org.eclipse.fproj.enablement.jdt.sdk-feature plugins org.eclipse.fproj.enablement.jdt org.eclipse.fproj.enablement.jdt.sdk org.eclipse.fproj.enablement.jdt.ui releng releng-features]]> Konstantin Komissarchik 2009-06-23T20:56:21-00:00
|
http://www.eclipse.org/forums/feed.php?mode=m&th=180247&basic=1
|
CC-MAIN-2015-11
|
refinedweb
| 608
| 60.51
|
N-Queens
June 11, 2010
We.
Advertisements
My Haskell solution (see for a version with comments):
[…] Praxis – N-Queens By Remco Niemeijer In today’s Programming Praxis we have to solve the classic n-queens problem. The provided Scheme solution has […]
I was trying to make a version that printed and counted, and would fit in 4 lines so you could use it as a .signature file. Didn’t quite succeed, mostly because I need to include to get printf, but here’s where I got it.
N = 8
def valid? stack
q2 = stack.length – 1
(0..stack.length-2).each do |q1|
return false if stack[q1] == stack[q2] ||
(q1-q2).abs == (stack[q1]-stack[q2]).abs
end
end
def queens stack, n
if n == N
puts “[ #{stack.join(‘, ‘)} ]”
else
(1..N).each do |rank|
stack.push(rank)
queens(stack, n+1) if valid?(stack)
stack.pop
end
end
end
queens [], 0
Here’s a ruby version (commented at) section ‘constructing a solution’ shows an algorithm that is linear in the number of columns of the board when implemented with a vector. It allows you to go to boardsizes up to N=200000000 (I can’t go higher because of memory)
Another usefull website about the N queens problem is
which has algorithms and executables for download
Here’s a different, somewhat simpler, solution in Scheme:
(define (attack? q1 q2)
(or (= (car q1) (car q2))
(= (cadr q1) (cadr q2))
(= (abs (- (car q1) (car q2)))
(abs (- (cadr q1) (cadr q2))))))
(define (safe? q qs)
(cond ((null? qs) #t)
((attack? q (car qs)) #f)
(else (safe? q (cdr qs)))))
(define (queens n)
(let queen ((n n) (x 1) (y 1) (qs '()) (qss '()))
(cond ((< n x) (cons (reverse qs) qss))
((< n y) qss)
((safe? (list x y) qs)
(queen n x (+ y 1) qs
(queen n (+ x 1) 1
(cons (list x y) qs) qss)))
(else (queen n x (+ y 1) qs qss)))))
Java implementation:
Source
can any one tell me how to convert n-queens problem to exact cover problem?
Knuth discusses this in his dancing links paper.
[…] problem with n queens on an n by n chessboard. After finding it again in older posts on both Programming Praxis and DataGenetics, I decided to go ahead and take a crack at it and I think the solution is pretty […]
Hi I am new to Ruby,I wrote a program in ruby which based on NQueen java program by Robert Sedgewick and Kevin Wayne problem is My program is not outputting the result,please help me here
my program source :
|
https://programmingpraxis.com/2010/06/11/n-queens/?like=1&source=post_flair&_wpnonce=8ef4095fcf
|
CC-MAIN-2018-22
|
refinedweb
| 428
| 79.5
|
MIDI devices (e.g., a MIDI synthesizer) can generate sounds from MIDI messages sent to them. If connected to your computer (via cable), you may use a MidiOut object to send such messages from inside your program.
First, you need to import the MIDI library:
from midi import *
Then, you can create a MidiOut object using this function:
For example,
m = MidiOut()
creates a MidiOut object called m. When executed, a display will open up to select an ouput MIDI device.
MidiOut objects may also be created with a specific device in mind:
For example,
m = MidiOut("M-Audio USB Uno MIDI Interface")
creates a connection to an output device directly (i.e., no selection display is shown – faster, if you already know the name of the device).
Once m has been created, the following functions are available:
The other Play functions are more advanced, and are intended for building interactive musical instruments.
You can also make global changes interactively on instrument, volume, panning, and pitch bend.
Playing Microtonal material
To play microtonal material, you may create Note objects using float (e.g., 443.1) pitch. Or use the following functions:
WARNING: For polyphony (to play concurrent microtonal notes), you must play notes on different MIDI channels.
The MIDI standard does not support microtones. Microtones are rendered here using MIDI pitch bend. Since there is only one pitch bend per channel, you must spread concurrent notes across channels. (Also, remember that channel 9 is special – percussion only.)
Sending arbitrary MIDI messages
It is also possible to send arbitrary MIDI messages to the MIDI synthesizer associated with m by using the following function:
NOTE: If you use a MIDI learn feature in your program (i.e., to auto-learn MIDI messages sent from JEM), do NOT press JEM’s stop button, while your program is in learn mode.
When JEM’s stop button is pressed, it sends an ALL-NOTES-OFF message (i.e., CC 123 message to all channels). This is done to turn off all sounds generated by equipment connected to JEM (as one might expect).
If your program is in MIDI learn more, first turn MIDI learning off, and then press the JEM stop button. Otherwise, your program will also learn the ALL_NOTES_OFF message (which is something you probably don’t want).
|
https://jythonmusic.me/midiout/
|
CC-MAIN-2018-09
|
refinedweb
| 384
| 54.42
|
I'm trying to find a way to get the total number of child nodes from an XmlNode recursively.
That it is to say I want to count all the children, grand children etc.
I think its something like
node.SelectNodes(<fill in here>).Count
but I don't know what the XPath is.
XPath supports something called Axis specifier, so the code you're looking for is
node.SelectNodes("descendant::*").Count
The XPath you are after is:
descendant::node() (1)
or
descendant::* (2)
The first XPath expresion (1) above selects any node (text-node, processing-instruction, comment, element) in the subtree rooted by the current node.
(2) selects any element node in the subtree rooted by the current node.
using System.Xml.Linq; node.DescendantNodes().Count();
If you're doing an unfiltered count, which your question implies, you could just traverse the them using the
ChildNodes property:
private int CountChildren(XmlNode node) { int total = 0; foreach (XmlNode child in node.ChildNodes) { total++; total += CountChildren(child); } return total; }
You could use somthing like this:
private static int CountNodes(XmlNode node) { int count = 0; foreach (XmlNode childNode in node.ChildNodes) { count += CountNodes(childNode); } return count + node.ChildNodes.Count; }
I think this will do it for you though not through xPath:
void CountNode(XmlNode node, ref int count) { count += node.ChildNodes.Count; foreach (XmlNode child in node.ChildNodes) { CountNode(child, ref count); } }
For reference here is a link to the count function in xpath.
so if you were looking for all the same type of nodes you could do
//Your_node
to select all the nodes
//*
|
http://www.dlxedu.com/askdetail/3/ee54501a1e3d1ef94fd2221a8debb92a.html
|
CC-MAIN-2018-43
|
refinedweb
| 263
| 64.2
|
Building apache 2.2.25 for OS X 10.6, how to compile apr_stat$INODE64?
- Currently Being ModeratedAug 25, 2013 3:38 PM (in response to James Bucanek)
I was finally able to get Apache 2.2.25 to build and install, but the situation isn't ideal.
Ultimately, I downloaded the version of the apr and apr-util libraries for OS X 10.8.4 <>. I copied the source into the http-2.2.25/srclib directory and used the --with-included-apr and --with-included-apr-util ./configure switches. This compiled httpd 2.2.25 against the Apple-patched versions of apr 1.4.5 and apr-util 1.3.12:
cd /Users/redqueen/Documents/Software/httpd-2.2.25
./configure --enable-layout=Darwin --sysconfdir=/private/etc/apache2 --localstatedir=/private/var --with-included-apr --with-included-apr-util --with-suexec-bin=/usr/bin/suexec --disable-authn-file --disable-authn-dbm --disable-authn-anon --disable-authn-dbd --disable-authn-default --disable-authz-host --disable-authz-groupfile --disable-authz-user --disable-authz-dbm --disable-authz-owner --disable-authz-default --disable-auth-basic --disable-include --disable-filter --disable-log-config --disable-env --disable-setenvif --disable-mime --disable-status --disable-autoindex --disable-asis --disable-cgi --disable-negotiation --disable-dir --disable-actions --disable-alias && make clean && make && sudo make install
This isn't ideal, because Apache 2.2.25 should be using apr 1.4.8 and apr-util 1.5.2. When Mavericks is finally released, I'll check to see if they've updated apr and apr-util.
- Currently Being ModeratedOct 17, 2013 4:07 PM (in response to James Bucanek)
I've been having the same problem. I got Apache 2.2.25 to build and install using your fix, but when I try to start it I get the following error:
httpd: Syntax error on line 63 of /private/etc/apache2/httpd.conf: Cannot load /usr/libexec/apache2/mod_authz_owner.so into server: dlopen(/usr/libexec/apache2/mod_authz_owner.so, 10): Symbol not found: _apr_stat$INODE64\n Referenced from: /usr/libexec/apache2/mod_authz_owner.so\n Expected in: flat namespace\n in /usr/libexec/apache2/mod_authz_owner.so
If I comment it out in the httpd.conf file it merely gives me another module that won't load and keeps leading me deeper and deeper into the config files. I believe that the config, make and install compiled erroneously and now the version is corrupted. Any suggestions?
P.S. I'm using Mac OSX 10.8.4
Message was edited by: PECraig
- Currently Being ModeratedOct 24, 2013 4:12 PM (in response to PECraig)
PECraig,
My guess is that you're still missing some pieces, or the pieces are in the wrong place. The "Symbol not found" error is because the Apple version of your (.so) modules are all linked to Apple's special version of apr/apr-util. When Apple compiles their Apache libraries, it includes two versions of the apr_stat function (equivalent to BSD stat()), named apr_stat() and apr_stat$INODE64(), the later being the 64-bit version of the function. This scheme makes it possible to access and correctly use the 64-bit version of the stat() function, which is the only way to get extended 64-bit inode information about a file or filesystem, from a 32-bit program. Conversely, 64-bit programs can still use the legacy 32-bit apr_stat() function, without having to be modified.
If you recompiled the libraries then they should have both the apr_stat and apr_stat$INODE64 symbols in them. You can verify this using the nm command (i.e. nm -arch all /path/to/libapr.dylib | grep apr_stat). If they're both there, the next step would be to make sure you put them in the correct locations and Apache isn't still loading the old libraries.
Also note that I compiled my versions of apr and apr-util directly into the apache binary (using --with-included-apr --with-included-apr-util), so my .so modules will link the copy of apr_stat that's part of the httpd binary image. This might not be necessary, but it seemed to help me.
On the other hand, you might just wait. OS X 10.7 might get updated to a later version of Apache, if it hasn't been already, so Apple might solve your problem for you.
Actions
More Like This
- Retrieving data ...
Incoming Links
Legend
- This solved my question - 10 points
- This helped me - 5 points
|
https://discussions.apple.com/message/22760577
|
CC-MAIN-2014-15
|
refinedweb
| 742
| 50.33
|
01 December 2009 16:29 [Source: ICIS news]
LONDON (ICIS news)--Gasoil floating storage in ?xml:namespace>
Recent reports had placed floating storage in Europe at around 27m barrels, but recently chartered vessels pushed amounts up by a further 8m barrels, traders said.
“I hear [floating storage] is about 25 vessels plus for gasoil – a minimum of 35m barrels. The latest chartered were two times 160,000 tonne vessels, at $20,000 per day,” said one trader.
The cost of storage is more than covered by the forward contango curve for ICE gasoil futures, as the inter-month spread has January gasoil currently $11/tonne more expensive than December gasoil – enough for those able to store material to lock in a profit on it.
“[The inter-month spread] was even wider in the past few days. End-user demand inland is very limited. However, like always, before [the front-month] expiry, every room is filled up if discounts are possible,” said another trader.
The contango structure and positional play for storage space have been in place for several months in 2009, and market participants said they believe that the situation would remain the same for the first half of 2010.
“It looks like [the contango] won’t shift before the second half of 2010, at least if prices don’t rise too much,” said the first trader.
The second trader said: “It might even hang on for longer as the financial institutions like [the contango] in their trading.”
|
http://www.icis.com/Articles/2009/12/01/9315073/europe-gasoil-floating-storage-stands-at-35m-barrels-traders.html
|
CC-MAIN-2014-41
|
refinedweb
| 248
| 66.57
|
Hi MLEnthusiasts! In this tutorial, we will learn how to implement linear regression, how to visualize our variables, i.e., do plotting and how to do mathematical computation of R squared using Python.¶
Please note that this tutorials is based on our previous tutorial “THE MATHEMATICS BEHIND UNIVARIATE LINEAR REGRESSION“. So it is highly recommended to first go through that tutorial to understand this tutorial.¶
The first step is to import Python libraries like numpy and matplotlib.
import numpy as np import matplotlib.pyplot as plt
It should be noted over here that np and plt are used as alias names for numpy and matplotlib.pyplot respectively.
The next step is to make empty vectors for X and Y where X is our input vector and Y is our output vector.
X_input = [] #Making empty list for storing input column Y_output = [] #Making empty list for storing output column
Now, we will open our file using the following code:
for line in open("data.csv"): #Reading data.csv line by line x, y = line.split(',') #splitting the line using comma: "," X_input.append(float(x)) #Appending the float values of x to empty list Y_input.append(float(y)) #Appending the float values of y to empty list
What this will do is it will read the .csv file line by line and will make the observation before ‘,’ get written into x and that after ‘,’ written into y for each line. This will, henceforth, generate two vectors x and y with x being input vector and y being output vector. After this, we will convert the values in x and y into float and will then append those values in X and Y. Therefore, X and Y will also be vectors having values of float data type.
The next step is to convert X and Y into numpy arrays since numpy makes it very easy to do mathematical computations on its matrices and vectors.
X_input = np.array(X_input) #Converting X_input list into numpy array Y_output = np.array(Y_output) #Converting Y_output list into numpy array
Now, let’s see how the relationship between X and Y looks like.
plt.scatter(X_input, Y_output) plt.title('Scatter plot showing relationship between X and Y') plt.xlabel('values of X') plt.ylabel('values of Y') plt.show()
From the above plot, we can see that the relationship is very linear. Now, let’s find out what the values of m and c are!
denominator = X_input.dot(X_input) - X_input.mean()*X_input.sum() m = (X_input.dot(Y_output) - Y_output.mean()*X_input.sum())/denominator #Slope of linear regression equation c = (Y_output.mean()*X_input.dot(X_input) - X_input.mean()*X_input.dot(Y_output))/denominator #Intercept of linear regression equation print("Value of slope m is", m) print("Value of intercept c is", c)
Value of slope m is 1.97261216748 Value of intercept c is 2.86442407566
Let’s now find our predicted values for Y or Yhat using linear regression equation.
Yhat = m*X_input + c
Let’s visualize how far our predictions are from actual values.
plt.scatter(X_input,Y_output) plt.title('Scatter plot showing relationship between X and Y') plt.xlabel('values of X') plt.ylabel('values of Y') plt.plot(X_input, Yhat, color = 'red') plt.show()
The dots are the actual values of Y and the line of best fit shows Yhat or the predicted values of Y. We see that predictions are very close to the actual values. Let’s now calculate the R square of this model.
diff1 = Y_output - Yhat #The error term diff2 = Y_output - Y_output.mean() rsquared = 1 - (diff1.dot(diff1)/diff2.dot(diff2)) print("R square of the model is", rsquared)
R square of the model is 0.991183820298
The R square turns out to be very close to 1. Thus our model is very good. It is to be noted here that X.dot(X) = sum of square of Xi where i ranges from 1 to N. N is the number of observations.
So guys, with this, we conclude our tutorial. Stay tuned for more interesting tutorials.
One comment
Lovely tutorial, in which you refer to a file data.csv. I’ve read the previous “The Mathematics Behind Univariate Linear Regression”, assuming the file would be referenced in there, but not that I can see. Can you direct me to this file?
|
https://mlforanalytics.com/2018/05/18/linear-regression-using-python/
|
CC-MAIN-2018-51
|
refinedweb
| 715
| 59.3
|
This is a discussion on Re: Agile countermeasures - DNS ; > Paul Vixie wrote: > > > > nick weaver and masataka ohta > > have each made some non-modal proposals about noncaching of data, and i > > think the WG should seriously investigate, and prefer, non-modal proposals. > ...
> Paul Vixie wrote:
> >
> > nick weaver and masataka ohta
> > have each made some non-modal proposals about noncaching of data, and i
> > think the WG should seriously investigate, and prefer, non-modal proposals.
>
> I've been giving some thought to some of the underlying vulnerabilities,
> where the following intersect:
> - the protocols involved
> - the strategies of resolvers
> - the data in the root and TLD *zones* (emphasis on zone vs domain)
>
> At the root of the Kaminsky vulnerability is the ability to feed data
> into a cache, where the data in question
> is provided in the "Additional" section.
>
> If we ignore, for the moment, when/whether/what referrals are provided
> by servers in "Authority" sections,
> and consider only the case of "if there *is* an authority section", then:
>
> The Question:
> When is it strictly necessary that Additional section data be provided
> *and* used (cached)?
>
>
> (Undoubtedly there are cases where it is absolutely necessary, to bridge
> the gap at a zone cut.
> If you have "example.com NS ns1.example.com", the only possible
> way for an empty cache to resolve the address of ns1.example.com, is via
> glue A/AAAA RR's.)
>
> But first, a quick sidebar...
>
>
> Sidebar: namespace congruity and phantom namespace
>
> The main axiom of "the Domain Name System", is the "the". (At least,
> for the public DNS sanctioned by ICANN et al.) There is only one.
> The name space is hierarchical, and delegations occur at zone cuts.
> Any legitimate, actual leaf in the name space must be reachable by
> starting at the root, and possibly crossing one or more zone cuts,
> reaching a terminal node in the label space of some leaf zone.
>
> Depending on the domain names of NS RR's used in delegations (at zone
> cuts), with attendant glue A/AAAA records, it may be possible to
> establish "phantom leaf" labels in the name space which are not
> reachable via top-down tree walking, because one or more parent domains
> of the NS RR's do not exist.
>
> If there were, for example, "example.com NS example.bar" with
> "example.bar A 10.1.2.3", if the caching resolver accepted that
> delegation, a new, non-existent TLD, "bar." with one leaf entry,
> "example.bar", would suddenly exist in the resolver's cache.
>
> Obviously, this is not something intentional, nor is it something that
> should generally be considered acceptable practice.
>
> (end of sidebar)
>
> If we exclude, axiomatically, the legitimacy of such "phantom" namespace
> elements, then we can then say the following are true:
> - every leaf entry in the public DNS exists (and is served
> authoritatively) in one zone only
> - every legitimate zone is delegated from its parent zone at a zone cut
> boundary
> - every legitimate zone is served by one or more name servers, who serve
> that zone authoritatively
> - every legitimate zone is anchored directly or indirectly at the root
> "." of the public DNS
>
> Taking the above together, then, it would be sufficient for resolving
> anything legitimate in the public DNS, for glue A/AAAA RR's to exist
> only in the immediate parent's zone.
> (I can elaborate on this if anyone wants, but I'm trying to keep this
> short).
>
> Thus, The Answer:
> If the *actual* glue A/AAAA RR's in (at a minimum) the root and all TLD
> zones met this condition, then the only time a resolver would ever
> *need* to accept "Additional" data would be in those exact cases, where
> the "Additional" data were given in the answer to a query for an A/AAAA
> RR, where the "Question" was for the RHS of a delegation, which was
> subordinate to (i.e. a child of) the LHS of the delegation.
>
> What this means:
> That the "Additional" section could be ignored in all other cases.
>
> And I *think* this would, in turn, result in the "birthday attack" race
> only being run when the TTL of glue A/AAAA RR's expires.
>
> Note also, that there will generally be orders of magnitude more NS
> entries pointing to the same RHS, and thus many fewer such races being
> run generally.
>
> As a data point, I examined a pretty big TLD (org), and verified that no
> out-of-zone glue A/AAAA RR's exist - only subordinate A/AAAA glue RR's
> exist.
> (If other TLD operators wouldn't mind checking this, and providing
> similar data points, I think we could possibly consider standardizing
> the non-use of Additional data.)
>
> Brian Dickson
>
> P.S. There is an important Corollary to the above:
> There is nothing in the naming of nameservers (in NS records) that
> restricts the levels of indirection that can occur, between the names of
> zones served, and the names of the nameservers serving those zones.
> As a practical matter, operators of nameservers *SHOULD* make reasonable
> efforts to limit the actual levels of indirection.
> And, ideally, nameservers *should*, if possible and practical, be
> authoritative for their own names. If I have ns1.foo.example.com, and
> ask it for the A RR for ns1.foo.example.com, life is easier if it gives
> the answer, and does so authoritatively, *and* is itself listed in the
> NS RR set for the domain foo.example.com.
>
> --
> to unsubscribe send a message to namedroppers-request@ops.ietf.org with
> the word 'unsubscribe' in a single line as the message text body.
> archive:.
I could have been stricter and only allowed glue under the
delegation but that would have broken configurations like
this
example1.com NS ns1.example2.com
example2.com NS ns1.example1.com
and not made the job of finding bad glue any easier. One
would still have to check all the parents.
The TLD's know named and other servers don't accept cross
zone and they also know that they won't emit it so they
don't bother collecting it.
DE and some TLD's don't event collect sibling glue.
Mark
--
Mark Andrews, ISC:
|
http://fixunix.com/dns/525527-re-agile-countermeasures.html
|
CC-MAIN-2014-15
|
refinedweb
| 1,023
| 52.49
|
import "go.chromium.org/luci/cipd/client/cipd/template"
Package template implements handling of package name templates.
Package name templates look like e.g. "foo/${platform}" and code in this package knows how to expand them into full package names.
ErrSkipTemplate may be returned from Expander.Expand to indicate that a given expansion doesn't apply to the current template parameters. For example, expanding `"foo/${os=linux,mac}"` with a template parameter of "os" == "win", would return ErrSkipTemplate.
Expander is a mapping of simple string substitutions which is used to expand cipd package name templates. For example:
ex, err := template.Expander{ "platform": "mac-amd64" }.Expand("foo/${platform}")
`ex` would be "foo/mac-amd64".
Use DefaultExpander() to obtain the default mapping for CIPD applications.
DefaultExpander returns the default template expander.
This has values populated for ${os}, ${arch} and ${platform}.
Expand applies package template expansion rules to the package template,
If err == ErrSkipTemplate, that means that this template does not apply to this os/arch combination and should be skipped.
The expansion rules are as follows:
- "some text" will pass through unchanged - "${variable}" will directly substitute the given variable - "${variable=val1,val2}" will substitute the given variable, if its value matches one of the values in the list of values. If the current value does not match, this returns ErrSkipTemplate.
Attempting to expand an unknown variable is an error. After expansion, any lingering '$' in the template is an error.
Validate returns an error if this template doesn't appear to be valid given the current Expander parameters.
This will catch issues like malformed template parameters and unknown variables, and will replace all ${param=value} items with the first item in the value list, even if the current TemplateExpander value doesn't match.
This is mostly used for validating user input when the correct values of Expander aren't known yet.
Platform contains the parameters for a "${platform}" template.
The string value can be obtained by calling String(). be parsed using ParsePlatform.
ParsePlatform parses a Platform from its string representation.
Expander returns an Expander populated with tp's fields.
Package template imports 5 packages (graph) and is imported by 8 packages. Updated 2019-08-17. Refresh now. Tools for package owners.
|
https://godoc.org/go.chromium.org/luci/cipd/client/cipd/template
|
CC-MAIN-2019-35
|
refinedweb
| 368
| 50.73
|
Dec 07, 2012 03:51 PM|LINK
I am trying to map strongly typed objects to input parameters to ApiController methods like WebApi Preview 6 OperationHandler's allowed me to do.
Lets say I have a structured way to query some of my resource endpoints. Lets say that I have a strongly typed object that I want to use to represent that query. How can you pump that input parameter into an ApiController method? Furthermore, how can you pass in multiple strongly typed objects into that same ApiController method?
Example:
Assume Query, Paging, and Properties are objects I have created that I want to pump into this method as I would with an OperationHandler in WebApi Preview 6.
public class ResourceAController : ApiController {
public List<ResourceA> GetAll(Query query, Paging paging, Properties properties){
......
}
}
1) Is there a way to do this without having the endpoint blow up when you hit it? Right now mine complains about not being able to bind the content for multiple objects.
2) What is the cleanest way to do this.
Thanks in advance
Dec 10, 2012 01:16 PM|LINK
bump.
While you ponder this take a look at a project I have out there to answer these issues:
Member
81 Points
Dec 11, 2012 10:02 AM|LINK
Are the parameter values being supplied by the caller, or do you want to create them on the server and inject them in? You might want to consider a custom model binder, and perhaps use parameter binding rules to configure them.
These links might help:
Dec 11, 2012 10:52 PM|LINK
bump.
While you ponder this take a look at a project I have out there to answer these issues:
Dec 11, 2012 10:56 PM|LINK
I am trying to evaluate the request (the query string) and create a strongly typed object to pass into the input parameter. Additionally I would like the mechanism to be something that I can drive as an Architect and have my developer use this functionality when creating new services without having to know exactly how to do some particulars.
I'll take a look at the links and letcha know what if that solves the issue.
Member
334 Points
Dec 13, 2012 07:57 AM|LINK
Take a look at this post:
This may help you get an idea.
Dec 13, 2012 01:12 PM|LINK
Thanks for that post, unfortunately I am not trying to do exactly this.
I am very familiar with REST architecture and do not want to turn it into an RPC request/response. I want to take my query string, parse it and process it into strongly typed objects, and provide those objects to the method being called. For the time being (to make it easier) I am simply creating my own base class and stuffing that parsing logic and property there. However, I would really like to leverage the pipeline and pass it in the input parameters for the method.
MyObject A = BuildObjectFromQuerystring(uri);
MyObject2 B = BuildObject2FromQuerystring(uri);
MyObject3 C = BuildObject3FromQuerystring(uri);
I would like to do this parsing before the method gets called. and I would like my method to look like this:
public SomeResourceObject Get(string id, MyObject a, MyObject2 b, MyObject3 c){
}
Thanks again for the posts thus far.
6 replies
Last post Dec 13, 2012 01:12 PM by Dot_Net_Guy
|
http://forums.asp.net/p/1864367/5236434.aspx/1?Re+Mapping+Input+Parameters+to+ApiController+methods
|
CC-MAIN-2013-20
|
refinedweb
| 561
| 67.38
|
py.
py-bcrypt requires Python 2.4. Older versions may work, but the bcrypt.gensalt() method won't - it requires the cryptographic random number generator os.urandom() introduced in 2.4.
To install, use the standard Python distutils incantation:
python setup.py build python setup.py install
Regression tests are in the test/test.py file. This is deliberately in a subdirectory so it does not mistakenly pick up the top-level bcrypt/ directory. *PLEASE* run the regress tests and ensure they pass before installing this module.
py-bcrypt is licensed under a ISC/BSD licence. The underlying Blowfish and password hashing code is taken from OpenBSD's libc. See the LICENSE file for details.
Please report bugs to Damien Miller <djm@mindrot.org>. Please check the TODO file first, in case your problem is something I already know about (please send patches!)
A simple example that demonstrates most of the features:
import bcrypt
# Hash a password for the first time.checkpw(plaintext, hashed):print "It matches"
- else:
- print "It does not match"
# Generate a 256-bit cryptographic key key = bcrypt.kdf(password, salt, 100, 256/8)
$Id$
|
https://bitbucket.org/alexandrul/py-bcrypt/src
|
CC-MAIN-2018-09
|
refinedweb
| 188
| 61.63
|
Last Site Update: 11 November 2014 |
Latest Version: 3.9, you have to click the green button pointed by '1' in the image below. After doing that, it will show a message in the console (indicated by '2') to confirm that the server is listening for incoming connections.
Note: Those buttons should be present at the debug perspective and they can be enabled in other perspectives through Window > Customize perspective > Command groups availability >.
Note that there should appear a process named 'Debug Server' in the debug view (see '1' in the image below).
Image: Debug perspective
3. Make sure pydevd.py is in your pythonpath: This file is included in the org.python.pydev plugin. So, you'll have to add it to the pythonpath. It's exact location will depend upon the eclipse location and the plugin version, being something like:
eclipse/plugins/org.python.pydev_x.x.x/pysrc/pydevd.py
(so, the container folder must be in your pythonpath). If you choose to execute it from another machine, you need to copy all the files within that folder to the target machine in order to be able to debug it (if the target machine does not have the same paths as the client machine, the file pydevd_file_utils.py must be edited to properly translate the paths from one machine to the other - see comments on that file).
4. Call pydevd.settrace(): Now that the pydevd.py module is already on your pythonpath, you can use the template provided: 'pydevd' to make the call: import pydevd;pydevd.settrace(). When that call is reached, it will automatically suspend the execution and show the debugger.
Image: pydevd.settrace called
By default, PyDev will add a --noreload flag when creating a Django run configuration, so that it works with the default debugger, but it's also possible to debug an application with auto-reload provided that some steps are followed to enable PyDev support in that case.
To do that, edit the launch that PyDev created (run > run configurations > PyDev Django) and remove the noreload flag and edit your manage.py so that the lines:
#Add pydevd to the PYTHONPATH (may be skipped if that path is already added in the PyDev configurations)
import sys;sys.path.append(r'path_to\pydev\plugins\org.python.pydev\pysrc')
import pydevd
pydevd.patch_django_autoreload(patch_remote_debugger=True, patch_show_console=True)
are added BEFORE the if _name_ == "_main_".
With that change, the breakpoints should be gotten whenever a run is done (note that from now on, launches should only be done in 'regular' mode from now on and the debug server must be already started in the Eclipse side).
To disable the debugging, those lines must be removed from manage.py.
An interesting thing to note is that when you kill the 'parent django' process from Eclipse, the subprocesses it created won't be terminated at the same time, but they should be terminated when a code-change is done (in which case the parent process would create a new 'reload process', if it was still alive).
Note that the patch_show_console=True will make a separate window be shown for each process (and not be shown in Eclipse itself) – it has a benefit that you'll be able to stop the process with Ctrl+C in that window and the downside that you won't have the output in the Eclipse console..
|
http://pydev.org/manual_adv_remote_debugger.html
|
CC-MAIN-2014-52
|
refinedweb
| 563
| 50.46
|
Let me start this post with a TL;DR for
- scientists
- Large analysis queries (like those that contain a GROUP BY clause) profit a lot from parallel execution, and you needn’t do a thing for that.
- DaCHS operators
- When you have large tables, Postgres 11 together with the next DaCHS release may speed up your responses quite dramatically in some cases.
So, here’s the story –
I’ve finally overcome my stretch trauma and upgraded the Heidelberg data center’s database server to Debian buster. With that, I got Postgres 11, and I finally bothered to look into what it takes to enable parallel execution of database queries.
Turns out: My Postgres started to do parallel execution right away, but just in case, I went for the following lines in postgresql.conf:
max_parallel_workers_per_gather = 4 max_worker_processes = 10 max_parallel_workers = 10
Don’t quote me on this – I frankly admit I haven’t really developed a feeling for the consequences of
max_parallel_workers_per_gather and instead just did some experiments while the box was loaded otherwise, determining where raising that number has a diminishing return (see below for more on this).
The
max_worker_processes thing, on the other hand, is an educated guess: on my data center, there’s essentially never more than one person at a time who’s running “interesting”, long-running queries (i.e., async), and that person should get the majority of the execution units (the box has 8 physical CPUs that look like 16 cores due to hyperthreading) because all other operations are just peanuts in comparison. I’ll gladly accept advice to the effect that that guess isn’t that educated after all.
Of course, that wasn’t nearly enough. You see, since TAP queries can return rather large result sets – on the GAVO data center, the match limit is 16 million rows, which for a moderate row size of 2 kB already translates to 32 GB of memory use if pulled in at once, half the physical memory of that box –, DaCHS uses cursors (if you’re a psycopg2 person: named cursors) to stream results and write them out to disk as they come in.
Sadly, postgres won’t do parallel plans if it thinks people will discard a large part of the result anyway, and it thinks that if you’re coming through a cursor. So, in SVN revision 7370 of DaCHS (and I’m not sure if I’ll release that in this form), I’m introducing a horrible hack that, right now, just checks if there’s a literal “group” in the query and doesn’t use a cursor if so. The logic is, roughly: With GROUP, the result set probably isn’t all that large, so streaming isn’t that important. At the same time, this type of query is probably going to profit from parallel execution much more than your boring sequential scan.
This gives rather impressive speed gains. Consider this example (of course, it’s selected to be extreme):
import contextlib import pyvo import time @contextlib.contextmanager def timeit(activity): start_time = time.time() yield end_time = time.time() print("Time spent on {}: {} s".format(activity, end_time-start_time)) svc = pyvo.tap.TAPService("") with timeit("Cold (?) run"): svc.run_sync("select round(Rmag) as bin, count(*) as n" " from ppmx.data group by bin") with timeit("Warm run"): svc.run_sync("select round(Rmag) as bin, count(*) as n" " from ppmx.data group by bin")
(if you run it yourself and you get warnings about VOTable versions from astropy, ignore them; I’m right and astropy is wrong).
Before enabling parallel execution, this was 14.5 seconds on a warm run, after, it was 2.5 seconds. That’s an almost than a 6-fold speedup. Nice!
Indeed, that holds beyond toy examples. The showcase Gaia density plot,
SELECT count(*) AS obs, source_id/140737488355328 AS hpx FROM gaia.dr2light GROUP BY hpx
(the long odd number is 235416-6, which turns source_ids into level 6-HEALPixes as per Gaia footnote id; please note that Postgres right now isn’t smart enough to parallelise ivo_healpix), which traditionally ran for about an hour is now done in less than 10 minutes.
In case you’d like to try things out on your postgres, here’s what I’ve done to establish the
max_parallel_workers_per_gather value above.
- Find a table with a few 1e7 rows. Think of a query that will return a small result set in order to not confuse . In my case, that’s a magnitude histogram, and the query would be
select round(Rmag) as bin, count(*) as n from ppmx.data group by bin;
Run this query once so the data is in the disk cache (the query is “warm”).
- Establish a non-parallel baseline. That’s easy to do:
set max_parallel_workers_per_gather=0;
- Then run
explain analyze select round(Rmag) as bin, count(*) as n from ppmx.data group by bin;
You should see a simple query plan with the runtime for the non-parallel execution – in my case, a bit more than 12 seconds.
- Then raise the number of
max_parallel_workers_per_gatherersuccessively. Make sure the query plan has lines of the form “Workers Planned” or so. You should see that the execution time falls with the number of workers you give it, up to the value of
max_worker_processes– or until postgres decides your table is too small to warrant further parallelisation, which for my settings happened at 7.
Note, though, that in realistic, more complex queries, there will probably be multiple operations that will profit from parallelisation in a single query. So, if in this trivial example you can go to 15 gatherers and still see an improvement, this could actually make things slower for complex queries. But as I said above: I have no instinct yet for how things will actually work out. If you have experiences to share: I’m sure I’m not the only person on dachs-users who’t be interested.
|
https://blog.g-vo.org/parallel-queries/
|
CC-MAIN-2020-29
|
refinedweb
| 988
| 60.14
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.