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
fresher 0.4.0 Clone of the Cucumber BDD framework for Python forked from Freshen Fresher Fresher is a fork of Freshen. As of Fall of 2013, Freshen appeared to no longer being maintained, so I decided to fork and make some much needed changes. Differences from Freshen: Fresher is tested against Python 3.3, Python 2.7 and Python 2.6. (It seems Freshen was tested against whatever Python happened to be around. It definitely did not work on Python 3.) The file to get Fresher to ignore a directory is .fresherignore. All arguments that are specific to Fresher begins with --fresher- so: - --tags is now --fresher-tags - --language is now --fresher-language - --list-undefined is now --fresher-list-undefined This change allows using fresher and freshen together in the same installation, and reduces the chances of conflicts with other nose plugins in the future. Undefined steps are fatal errors unless you pass –fresher-allow-undefined. Freshen would load steps files under fake module names. Fresher loads the whole shebang under freshen.steps. Warning Do not have a steps module loaded by Fresher also be loaded by no-step modules. (A no-step module is one which does not implement steps). Here’s a scenario where you could run into trouble: module A features/steps loads module B features/util (a nostep module) which loads module C features/nested/steps which is also a steps module for another set of features. We could call this an S-N-S scenario (steps, no-step, steps). If you do this then module C will be loaded twice: once because module B imports it and a second time when fresher finds it is needed for some features in the nested subdirectory. It will be loaded as two different modules. If the duplicated module maintains no state, you’ll only incur the cost of loading the same module twice. However, if it does maintain state, then good luck. Note that Freshen 0.2 also suffers from this problem due to the fake module names it uses. I believe behave 1.2.3 also suffers from this problem. It uses exec to load step definition files. In an S-N-S case like the one above, module A will be exec’ed, and module B will import module C so module C will show as an actual Python module. Then when behave determines that C is needed for step definitions, it will exec it, thereby loading it again. It is completely fine if a steps module or package loads a non-steps module or package. It is highly recommended to separate step definitions from broader logic. Fresher allows duplicate function names for steps. Fresher associates with a package the steps defined by all the modules that are its immediate children. Imagine the following structure: steps/ __init__.py caret.py selection.py nested/ __init__.py log.py data.py When this steps package is loaded by Fresher, all of the steps found in caret.py and selection.py will be immediately accessible. There is no need to refer to these modules individually or to add anything to the “steps/__init__.py“ file. However, what is in the **subpackage named steps.nested will not be accessible until steps.nested is itself loaded by Fresher. With Freshen steps/__init__.py would require: from .caret import * from .selection import * but this is not required when using Fresher. Generally speaking, the from ... import * method of making steps accessible in another module, which worked fine in Freshen, does not work in Fresher. It worked in Freshen because Freshen would determine the steps defined in a module by scanning the module’s global symbols. This cannot work with Fresher because it allows duplicate function names. (If @given('a') and @given('b') both decorate foo() the symbol foo is still present only once.) You have to use fresher.stepregistry.import_steps() to import the steps from another module. For instance: from freshen.stepregistry import import_steps import_steps(".defs") Or if you want to import steps from a more remote location (actual case in the test suite): from freshen.stepregistry import import_steps import_steps("..nested.steps") The old documentation follows. Keep in mind the differences above. Eventually, this will all be rewritten for Fresher. Fres Transforms. - The parser now supports several natural language aliases for a keyword. - If a natural language translation is not found for a keyword, English will be used. - “@After” hooks are now run in the opposite order of which they are registered. - Improved error handling and reporting. There are also some modifications that are incompatible with Cucumber. - Only the step definition module named “steps” is used by default. - Users can override this behavior with the “Use step definitions from” keyword. - Freshen distinguishes “Given” steps from “When” steps and “Then” steps. Freshen Documentation Most of the information shown here can also be found on the Cucumber wiki, but here it is anyway: Freshen tests are composed of two parts: feature outlines and step definitions. Feature outlines Feature outlines are text files with a .feature extension. The purpose of this file is to describe a feature in plain text understandable by a non-technical person such as a product manager or user. However, these files are specially formatted and are parsed by Freshen in order to execute real tests. You can put your feature files anywhere you want in the source tree of your project, but it is recommended to place them in a dedicated “features” directory. A feature file contains (in this order): - the step definition modules to use (optional, see specifying step definition modules); - the feature name with a free-form text description; - a background (optional, see backgrounds); - one or more scenarios or scenario outlines. Scenarios A scenario is an example of an interaction a user would have as part of the feature. It is comprised of a series of steps. Each step has to start with a keyword: Given, When, Then, But or And. Here’s an example for a calculator application (this example is included in the source code): Scenario: Divide regular numbers Given I have entered 3 into the calculator And I have entered 2 into the calculator When I press divide Then the result should be 1.5 on the screen Scenario Outlines Sometimes it is useful to parametrize a scenario and run it multiple times, substituting values. For this purpose, use scenario outlines. The format is the same as a scenario, except you can indicate places where a value should be substituted using angle brackets: < and >. You specify the values to be substituted using an “Examples” section that follows the scenario outline: | In this case, the scenario will be executed once for each row in the table (except the first row, which indicates which variable to substitute for). Backgrounds A feature may contain a background. It allows you to add some context to the scenarios in the current feature. A Background is much like a scenario containing a number of steps. The difference is when it is run. The background is run before each of your scenarios but after any of your “@Before” hooks. Here is an example: Feature: Befriending In order to have some friends As a Facebook user I want to be able to manage my list of friends Background: Given I am the user Ken And I have friends Barbie, Cloe Scenario: Adding a new friend When I add a new friend named Jade Then I should have friends Barbie, Cloe, Jade Scenario: Removing a friend When I remove my friend Cloe Then I should have friends Barbie Note that background should be added in a feature only if it has a value for the client. Otherwise, you can use tagged hooks (see Tags and Hooks). Step Definitions When presented with a feature file, Freshen will execute each scenario. This involves iterating over each step in turn and executing its step definition. Step definitions are python functions adorned with a special decorator. Freshen knows which step definition function to execute by matching the step’s text against a regular expression associated with the definition. Here’s an example of a step definition file, which hopefully illustrates this point: from freshen import * import calculator @Before def before(sc): scc.calc = calculator.Calculator() scc.result = None @Given("I have entered (\d+) into the calculator") def enter(num): scc.calc.push(int(num)) @When("I press (\w+)") def press(button): op = getattr(scc.calc, button) scc.result = op() @Then("the result should be (.*) on the screen") def check_result(value): assert_equal(str(scc.result), value) In this example, you see a few step definitions, as well as a hook. Any captures (bits inside the parentheses) from the regular expression are passed to the step definition function as arguments. Specifying Step Definition Modules Step definitions are defined in python modules. By default, Freshen will try to load a module named “steps” from the same directory as the .feature file. If that is not the desired behavior, you can also explicitly specify which step definition modules to use for a feature. To do this, use the keyword Using step definitions from (or its abbreviation: Using steps) and specify which step definition modules you want to use. Each module name must be a quoted string and must be relative to the location of the feature file. You can specify one or more module names (they must be separated by commas). Here is an example: Using step definitions from: 'steps', 'step/page_steps' Feature: Destroy a document In order to take out one's anger on a document As an unsatisfied reader I want to be able to rip off the pages of the document Scenario: Rip off a page Given a document of 5 pages And the page is 3 When I rip off the current page Then the page is 3 But the document has 4 pages Although you have the opportunity to explicitly specify the step definition modules to use in Freshen, this is not a reason to fall into the Feature-Coupled Steps Antipattern! A step definition module can import other step definition modules. When doing this, the actual step definition functions must be at the top level. For example: from other_step_module import * A step definition module can be a python package, as long as all the relevant functions are imported into __init__.py. The python path will automatically include the current working directory and the directory of the .feature file. Hooks It is often useful to do some work before each step or each scenario is executed. For this purpose, you can make use of hooks. Identify them for Freshen by adorning them with “@Before”, “@After” (run before or after each scenario), or “@AfterStep” which is run after each step. Context storage Since the execution of each scenario is broken up between multiple step functions, it is often necessary to share information between steps. It is possible to do this using global variables in the step definition modules but, if you dislike that approach, Freshen provides three global storage areas which can be imported from the freshen module. They are: - glc: Global context, never cleared - same as using a global variable - ftc: Feature context, cleared at the start of each feature - scc: Scenario context, cleared at the start of each scenario These objects are built to mimic a JavaScript/Lua-like table, where fields can be accessed with either the square bracket notation, or the attribute notation. They do not complain when a key is missing: glc.stuff == gcc['stuff'] => True glc.doesnotexist => None Running steps from within step definitions You can call out to a step definition from within another step using the same notation used in feature files. To do this, use the run_steps function: @Given('I do thing A') def do_a(): #Do something useful. pass @Given('I have B') def having_b(): #Do something useful. pass @Given('I do something that use both') def use_both(): run_steps(""" Given I do thing A And I have B """) Multi-line arguments Steps can have two types of multi-line arguments: multi-line strings and tables. Multi-line strings look like Python docstrings, starting and terminating with three double quotes: """. Tables look like the ones in the example section in scenario outlines. They are comprised of a header and one or more rows. Fields are delimited using a pipe: |. Both tables and multi-line strings should be placed on the line following the step. They will be passed to the step definition as the first argument. Strings are presented as regular Python strings, whereas tables come across as a Table object. To get the rows, call table.iterrows(). Step Argument Transforms Step definitions are specified as regular expressions. Freshen will pass any captured sub-expressions (i.e. the parts in parentheses) to the step definition function as a string. However, it is often necessary to convert those strings into another type of object. For example, in the step: Then user bob should be friends with user adelaide we may need to convert “user bob” to the the object User(name=’bob’) and “user adelaide” to User(name=”adelaide”). To do this repeatedly would break the “Do Not Repeat Yourself (DRY)” principle of good software development. Step Argument Transforms allow you to specify an automatic transformation for arguments if they match a certain regular expression. These transforms are created in the step definition file. For example: @Transform(r"^user (\w+)$") def transform_user(name): return User.objects.find(name) @Then(r"^(user \w+) should be friends with (user \w+)") def check_friends(user1, user2): # Here the arguments will already be User objects assert user1.is_friends_with(user2) The two arguments to the “Then” step will be matched in the transform above and converted into a User object before being passed to the step definition. Named Step Argument Transformation Another imperfection of step definitions from the DRY perspective is that they require repeated regular expressions to read “the same thing”. By keeping expressions extremely simple the damage can be minimized, but sometimes it can be useful to centralize the pattern specifications for certain argument types. Named Step Argument Transforms allow the use of a unique name a substitution point for the regular expression associated with a transform. For example, for the step: Then these users should be friends: "bob, adelaide, samantha" The following definitions can be used: from itertools import combinations @NamedTransform( '{user list}', r'("[\w\, ]+")', r'^"([\w\, ]+)"$' ) def transform_user_list( slist ): return [ User.objects.find( name ) for name.strip() in slist.split( ',' ) ] @Then(r"these users should be friends: {user list}" ) def check_all_friends( user_list ): for user1, user2 in combinations( user_list, 2 ): assert user1.is_friends_with( user2 ) The arguments to NamedTransform are name, in_pattern and out_pattern, respectively. NamedTranform is equivalent to having in_pattern substituted for all occurrences of name in step specifications, and defining a standard Transform with out_pattern as its pattern. The distinction between in_pattern and out_pattern is that the in_pattern can be used to match surrounding context to uniquely identify parameters, while the out_pattern searches within the text recognized by the in_pattern to pull out the semantically relevant parts. When this distinction is not relevant, specify only one pattern, and it will be used for both in and out patterns. Ignoring directories If a directory contains files with the extension .feature but you’d like Freshen to skip over it, simply place a file with the name “.freshenignore” in that directory. Using with Django Django is a popular framework for web applications. Freshen can work in conjunction with the django-sane-testing library to initialize the Django environment and databases before running tests. This feature is enabled by using the --with-django option from django-sane-testing. You can also use --with-djangoliveserver or --with-cherrypyliveserver to start a web server before the tests run for use with a UI testing tool such as Selenium. Using with Selenium Selenium is not supported until plugin support is implemented. If you need to use Selenium, try version 0.1. Running Freshen runs as part of the nose framework, so all options are part of the nosetests command- line tool. Some useful flags for nosetests: - --with-freshen: Enables Freshen - -v: Verbose mode will display each feature and scenario name as they are executed - --tags: Only run the features and scenarios with the given tags. Tags should follow this option as a comma-separated list. A tag may be prefixed with a tilde (~) to negate it and only execute features and scenarios which do not have the given tag. - --language: Run the tests using the designated language. See the Internationalization section for more details You should be able to use all the other Nose features, like coverage or profiling for “free”. You can also run all your unit, doctests, and Freshen tests in one go. Please consult the Nose manual for more details. Internationalization Freshen now supports 30 languages, exactly the same as cucumber, since the “language” file was borrowed from the cucumber project. As long as your .feature files respect the syntax, the person in charge of writing the acceptance tests may write it down in his/her mother tongue. The only exception is the new keyword for specifying step definition modules since it is not available in Cucumber. For the moment, this keyword is available only in English, French, and Portuguese. If you use another language, you must use the English keyword for this particular keyword (or translate it and add it to the languages.yml file). The ‘examples’ directory contains a French sample. It’s a simple translation of the English ‘calc’. If you want to check the example, go to the ‘calc_fr’ directory, and run: $ nosetests --with-freshen --language=fr The default language is English. Additional notes Why copy Cucumber? - Because it works and lots of people use it. Life is short, so why spend it on coming up with new syntax for something that already exists? Why use Nose? - Because it works and lots of people use it and it already does many useful things. Life is short, so why spend it re-implementing coverage, profiling, test discovery, and command like processing again? Can I contribute? - Yes, please! While the tool is currently a copy of Cucumber’s syntax, there’s no law that says it has to be that forever. If you have any ideas or suggestions (or bugs!), please feel free to let me know, or simply clone the repository and play around. - Author: Louis-Dominique Dubeau - License: GPL - Categories - Development Status :: 4 - Beta - Environment :: Plugins - Intended Audience :: Developers - License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) - Operating System :: OS Independent - Programming Language :: Python :: 2.6 - Programming Language :: Python :: 2.7 - Programming Language :: Python :: 3.3 - Topic :: Software Development :: Quality Assurance - Topic :: Software Development :: Testing - Package Index Owner: lddubeau - DOAP record: fresher-0.4.0.xml
https://pypi.python.org/pypi/fresher/0.4.0
CC-MAIN-2016-26
refinedweb
3,137
55.74
Opened 6 years ago Last modified 6 years ago #4897 defect new twisted.web server keeps caching headers if an exception is raised Description If a resource sets caching headers but then raises an exception, twisted.web.server serves an error page with the existing caching headers. This may cause the error page to be cached. For example: def render_GET(self, request): request.responseHeaders.setRawHeaders('cache-control', ['max-age=172800, private']) request.responseHeaders.setRawHeaders('expires', ['Sun, 20 Feb 2011 01:57:40 GMT']) if random.random() < 0.05: # Pretend this is a database failure or something 1/0 In this case, the error page served by twisted.web.server.processingFailed might be cached. If this problem can be solved by clearing or overriding cache-related headers, twisted.web could help users avoid a non-obvious pitfall. If the right thing to do is to keep the cache-related headers, this behavior should be documented so that users know to catch their own exceptions. Change History (3) comment:1 Changed 6 years ago by comment:2 Changed 6 years ago by comment:3 Changed 6 years ago by Note: See TracTickets for help on using tickets.
https://twistedmatrix.com/trac/ticket/4897
CC-MAIN-2017-04
refinedweb
195
58.48
Instructions for Form CT-1 Employer’s Annual Railroad Retirement Tax Return Section references are to the Internal Revenue Code unless otherwise noted. Department of the Treasury Internal Revenue Service General Instructions What’s New for 2002 work-hour tax and the special supplemental annuity tax (sections 3221(c) and (d)), effective for years beginning after December 31, 2001. Lines 1-4 and line 18 on the 2001 Form CT-1 have been deleted and the remaining lines renumbered. • The filing address for Form CT-1 has changed. See Where To File below. the cost of group-term life insurance over $50,000 and the amount of railroad retirement taxes owed by the former employee for coverage provided after separation from service. See section 2 of Pub. 15-B, Employer’s Tax Guide to Fringe Benefits, a prior year is taxable at the current year’s tax rates; you must include the compensation with the current year’s compensation on lines 1 through 10 of Form CT-1, as appropriate. Exceptions. Compensation does not include: • Any benefit provided to or on behalf of an employee if at the time the benefit is provided it is reasonable to believe the employee can exclude such benefit from income. For information on what benefits are excludable, see Pub. 15-B. Examples of this type of benefit include: 1. Certain employee achievement awards under section 74(c), 2. Certain scholarship and fellowship grants under section 117, 3. Certain fringe benefits under section 132, and 4. Employer payments to an Archer MSA under section 220. • Payments made to or on behalf of an employee or dependents under a sickness or accident disability plan or a medical or hospitalization plan in connection with sickness or accident disability. This applies to Tier II taxes only. Note: For purposes of employee and employer Tier I taxes, compensation does not include sickness or accident disability payments made — 1. Under a workers’ compensation law, 2. Under section 2(a) of the Railroad Unemployment Insurance Act for days of sickness due to on-the-job injury, 3. Under the Railroad Retirement Act, or 4. More than 6 months after the calendar month the employee last worked. • Recent legislation repealed the supplemental annuity Purpose of Form Use this form to report taxes imposed by the Railroad Retirement Tax Act (RRTA). Who Must File File Form CT-1 if you paid one or more employees compensation subject to RRTA. Also, an employer that pays sick pay or a third-party payer of sick pay that is subject to Tier I railroad retirement and Medicare taxes must file Form CT-1. See section 6 in Pub. 15-A, Employer’s Supplemental Tax Guide, for details. However, see the exceptions under the definition of compensation below. Report sick pay payments on lines 7 through 10: • By its owner (as if the employees of the disregarded entity are employed directly by the owner) using the owner’s name and taxpayer identification number (TIN) or • By each entity recognized as a separate entity under state law using the entity’s own name and TIN. If the second method is chosen, the owner retains responsibility for the employment tax obligations of the disregarded entity. For more information, see Notice 99-6, 1999-1 C.B. 321. Where To File Send Form CT-1 to: Internal Revenue Service Center Cincinnati, OH 45999-0007 When To File File Form CT-1 by February 28, 2003.. Cat. No. 16005H • Payments made specifically for traveling or other bona fide and necessary expenses that meet the rules in the regulations under section 62. • Payments for service performed by a nonresident alien temporarily present in the United States as a nonimmigrant under subparagraphs (F), (J), (M), or (Q) of the Immigration and Nationality Act. • 15.6% of first . . . . . . . . . . . . . . . . . . . Employee: Pays 4.9% of first . . . . . . . . . . . . . . . . . . . $63,000 $63,000 All $84,900 Compensation Paid in 2002 Tips are considered to be paid at the time the employee reports them to you. You must collect both income tax and employee railroad retirement tax on tips reported to you ($84,900 for 2002). However, your liability for Tier I employer tax on compensation continues until the compensation, not including tips, totals $84,900 for the year. If, by the 10th of the month after the month you received an employee’s tip income report, you do not have enough employee funds available to deduct the employee tax, you no longer have to collect it. See section 6 in Circular E (Pub. 15). Depositing Taxes For Tier I and Tier II taxes, you are either a monthly schedule depositor or a semiweekly schedule depositor. There are also two special rules explained on page 3 — the $2,500 rule and the $100,000 next-day deposit rule. The terms “monthly schedule depositor” and “semiweekly schedule depositor” do not refer to how often your business pays its employees, or to how often you are required to make deposits. The terms identify which set of rules you must follow when a tax liability arises (e.g., when you have a payday). Before each year begins, you must determine which deposit schedule to follow. Your deposit schedule for the year is determined from the total Form CT-1 taxes reported in the lookback period. Lookback period. Which deposit schedule you must follow for depositing Tier I and Tier II taxes for a calendar year is determined from the total taxes reported on your Form CT-1 for the calendar year lookback period. The lookback period is the second calendar year preceding the current calendar year. For example, the lookback period for calendar year 2003 is calendar year 2001. Use the table below to determine which deposit schedule to follow for the current year. IF you reported taxes for the lookback period of... $50,000 or less More than $50,000 THEN you are a... Employer taxes. Employers must pay both Tier I and Tier II taxes. Tier I tax is divided into two parts. The amount of compensation subject to each tax is different. See the table above for the tax rates and compensation bases. still pay the tax. If you withhold too much or too little tax because you cannot determine the correct amount,. Tips. An employee who receives tips must report them to you by the 10th of the month following the month the tips are received. Tips must be reported for every month, unless the tips for the month are less than $20. your business. Example. Employer A reported Form CT-1 taxes as follows: • 2001 Form CT-1 — $49,000 • 2002 Form CT-1 — $52,000 Employer A is a monthly schedule depositor for 2003 because its Form CT-1 taxes for its lookback period (calendar year 2001) were not more than $50,000. However, for 2004, Employer A is a semiweekly schedule depositor because A’s taxes exceeded $50,000 for its lookback period (calendar year 2002). -2- (2001). B discovered in March 2003 that the tax during the lookback period was understated by $10,000 and will correct this error with an adjustment on the 2003 Form CT-1. B is a monthly schedule depositor for 2003 because the lookback period Form CT-1 taxes are based on the amount originally reported, which was not more than $50,000. The $10,000 adjustment is treated as part of the 2003 Form CT-1 taxes. When to deposit. If you are a monthly schedule depositor, deposit employer and employee Tier I and Tier II taxes accumulated during a calendar month by the 15th day of the following month., C does not have a tax liability for the month. If you are a semiweekly schedule depositor, use the table below to determine when to make deposits. Deposit Tier I and Tier II taxes for payments made on... Wednesday, Thursday, and/or Friday Saturday, Sunday, Monday, and/or Tuesday No later than... The following Wednesday The following Friday CAUTION ! The last day of the calendar year ends the semiweekly deposit period and begins a new one. See Semiweekly Deposit Schedule in section 11 of Circular E (Pub. 15). Example of a semiweekly schedule depositor. Employer D, a semiweekly schedule depositor, pays wages on the last Saturday of each month. Although D is a semiweekly schedule depositor, D will deposit just once a month because D pays wages only once a month. The deposit, however, will be made under the semiweekly deposit schedule as follows: D’s taxes for the January 25, 2003 (Saturday) payday must be deposited by January 31, 2003 (Friday). Under the semiweekly deposit rule, taxes arising on Saturday through Tuesday must be deposited by the following Friday. Deposits on banking days only. If a deposit is required to be made on a day that is a nonbanking day, it a nonbanking nonbanking day, you have 1 additional day to deposit. For example, if you have Form CT-1 taxes accumulated for payments made on Friday and the following Monday is a nonbanking day, the deposit normally due on Wednesday may be made on Thursday (allowing 3 banking days to make the deposit). Exceptions to the deposit rules. Two exceptions apply to the above deposit rules, the • $2,500 rule and • $100,000 next-day deposit rule. $2,500 rule. If your total Form CT-1 taxes for the year are less than $2,500 and the taxes are fully paid with a timely filed Form CT-1, no deposits are required. However, if you are unsure that you will accumulate less than $2,500,, E accumulates taxes of $110,000 and must deposit this amount by Tuesday, the next banking day. On Tuesday, E accumulates additional taxes of $30,000. Because the $30,000 is not added to the previous $110,000, E must deposit the $30,000 by Friday using the semiweekly deposit schedule. Example of $100,000 next-day deposit rule during the first year of business. Employer F started its business on January 31, 2003. Because this was the first year of its business, its Form CT-1 taxes for its lookback period are considered to be zero, and F is a monthly schedule depositor. On February 6, F paid compensation for the first time and accumulated taxes of $40,000. On February 13, F paid compensation and accumulated taxes of $60,000, bringing its total accumulated (undeposited) taxes to $100,000. Because F accumulated $100,000 on February 13 (Thursday), F must deposit the $100,000 by February 14 (Friday), the next banking day. F became a semiweekly schedule depositor on February 14. F will be a semiweekly schedule depositor for the rest of 2003 and for 2004., G must deposit $95,000 by Friday and $10,000 by the following Wednesday. Accuracy of deposits rule. You are required to deposit 100% of your railroad retirement taxes on or before the deposit. • Monthly schedule depositor. Deposit the shortfall or pay it with your return by the due date of Form CT-1. You may pay the shortfall with Form CT-1 even if the amount is $2,500 or more. • Semiweekly schedule depositor. Deposit the shortfall by the earlier of the first Wednesday or Friday that comes on or after the 15th of the month following the month in which the shortfall occurred or the due date of Form CT-1. For example, if a semiweekly schedule depositor has a deposit shortfall during January 2003, the shortfall makeup date is February 19, 2003 (Wednesday). How to make deposits. In general, you must deposit railroad retirement taxes with an authorized financial institution. If you are not making electronic deposits (explained below), use Form 8109, Federal Tax Deposit Coupon, with each deposit to -3- taxes (such as employment tax, excise tax, and corporate income tax) using the Electronic Federal Tax Payment System (EFTPS) or RRBLINK in 2003 if: • The total of deposits of such taxes in 2001 were more than $200,000 or • You were required to use EFTPS/RRBLINK in 2002. If you are required to use EFTPS/RRBLINK and use Form 8109 instead, you may be subject to a 10% penalty. If you are not required to use EFTPS/RRBLINK, you may participate voluntarily. To enroll in or get more information about EFTPS, call 1-800-555-4477 or 1-800-945-8400, or visit the EFTPS Web Site at. To enroll in or get more information about RRBLINK, call 1-888-273-2265. Depositing on time. For deposits made by EFTPS/ RRBLINK to be on time, you must initiate the transaction at least one business day before the date the deposit is due. Line 4. Tier I Employee Tax Enter the compensation, including tips reported, subject to employee Tier I tax. Do not enter more than $84,900 per employee. Multiply by 6.2% and enter the result. Stop collecting the 6.2% Tier I employee tax when the employee’s wages and tips reach the maximum for the year ($84,900 for 2002). However, your liability for Tier I employer tax on compensation continues until the compensation, not including tips, totals $84,900 for the year. Line 5. Tier I Employee Medicare Tax Enter the compensation, including tips reported, subject to employee Tier I Medicare tax. Multiply by 1.45% and enter the result. For information on reporting tips, see Tips on page 2. Line 6. Tier II Employee Tax Enter the compensation, including tips reported, subject to Tier II employee tax. Only the first $63,000 of the employee’s compensation for 2002 is subject to this tax. Multiply by 4.9% and enter the result. For information on reporting tips, see Tips on page 2. Any compensation paid during the current year that was earned in prior years (reported to the Railroad CAUTION Retirement Board on Form BA-4, Report of Creditable Compensation Adjustments) is taxable at the current year tax rates. Include such compensation with current year compensation on lines 1 through 6, as appropriate.. See Circular E (Pub. 15) for more information. Order in which deposits are applied. Generally, for deposit periods beginning after December 31, 2001, tax deposits are applied first to the most recently ended deposit period(s) within the specified tax period to which the deposit relates. This application of deposits to the most recently ended deposit period will, in some cases, prevent the cascading of penalties where a depositor fails to make a deposit or makes a late deposit. However, to further minimize a failure to deposit penalty, you may designate the period to which a deposit applies if you receive a penalty notice. You must respond within 90 days of the date of the notice. Follow the instructions on the notice you receive. See Rev. Proc. 2001-58, 2001-50 I.R.B. 579, for more information. Trust fund recovery penalty. If taxes that must be withheld are not withheld or are not deposited or paid to the United States Treasury, the trust fund recovery penalty may apply. The penalty is 100% of the Circular E (Pub. 15) for more information. ! Lines 7 Through 10. Tier I Taxes on Sick Pay Enter any sick pay payments during the year that are subject to Tier I taxes and Tier I Medicare taxes. If you are a railroad employer paying your employees sick pay, or a third-party payer who did not notify the employer of the payments (thereby subject to the employee and employer tax), make entries on lines 7 through 10. If you are subject to only the employer or employee tax, complete only the applicable lines. Multiply by the appropriate rates and enter the results. Line 12. Adjustments to Taxes Based on Compensation Use line 12 to show: • Corrections of underpayments or overpayments of taxes reported on prior year returns, • Credits for overpayments of penalty or interest paid on tax for earlier years, • A fractions of cents adjustment (see Fractions of cents on page 5), and • For 2002 only, the total monthly adjustment of employee supplemental annuities under section 2(h)(2) of the Railroad Retirement Act of 1974 (see Adjustments to supplemental annuity work-hour tax on page 5). • For 2002 only, adjustments to the special supplemental annuity tax reported on Form(s) G-241, Summary Statement of Quarterly Report of Railroad Retirement Supplemental Annuity Tax Liabilities (see Adjustments to special supplemental annuity tax on page 5). You cannot make an adjustment for any excess supplemental annuity work-hour tax credit that was CAUTION carried forward from your 2001 Form CT-1 if the adjustment on line 3 exceeded the tax on line 1 in 2001. Do not include the 2001 overpayment that is applied to this year’s return (this is included on line 14). If you are reporting both an addition and a subtraction, enter only the difference between the two on line 12. Enter: 1. Adjustments for sick pay and fractions of cents in their entry spaces, 2. The amount of all other adjustments, including adjustments to the supplemental annuity work-hour tax and the special supplemental annuity tax, in the “Other” entry space, and Specific Instructions Final return. If you stop paying taxable compensation and will not have to file Form CT-1 in the future, you must file a final return and check the Final return box at the top of the form under “2002.” Line 1. Tier I Employer Tax Enter the compensation (other than tips and sick pay) subject to Tier I tax. Do not show more than $84,900 per employee. Multiply by 6.2% and enter the result. ! Line 2. Tier I Employer Medicare Tax Enter the compensation (other than tips and sick pay) subject to Tier I Medicare tax. Multiply by 1.45% and enter the result. Line 3. Tier II Employer Tax Enter the compensation (other than tips) subject to Tier II tax. Do not show more than $63,000 per employee. Multiply by 15.6% and enter the result. -4- 3. The total of the three types of adjustments in the line 12 entry space to the right. Explanation of line 12 adjustments. Except for adjustments for fractions of cents, the supplemental annuity work-hour tax, and the special supplemental annuity tax, explain amounts entered on line 12 in a separate statement. Attach a full sheet of paper that shows at the top your name, employer identification number, calendar year of the return, and “Form CT-1.” Include in the statement the following information: • An explanation of the item the adjustment is intended to correct showing the compensation subject to Tier I and Tier II taxes and the respective tax rates. • The year(s) to which the adjustment relates. • The amount of the adjustment for each year. • The name and account number of any employee from whom employee tax was undercollected or overcollected. • How you and the employee have settled any undercollection or overcollection of employee tax. A timely filed return is considered to be filed on the last Enter on your check or money order your employer identification number, “Form CT-1,” and “2002.” Pay to the “United States Treasury.” You do not have to pay if line 15 is less than $1. Line 16. Overpayment If you deposited more than the correct amount of taxes for the year, check the first box if you want the overpayment applied to your 2003 Form CT-1. Check the second box if you want the overpayment refunded. If line 16 is less than $1, we will send you a refund or apply it to your next return only on written request. Third Party Designee If you want to allow an employee of your business or an individual paid preparer to discuss your 2002 Form CT-1 with the IRS, check the “Yes” box in the Third Party Designee section of the return. Also, enter the designee’s name, phone number, and any five digits that person chooses as his or her personal identification number (PIN). The designation must specify an individual and may not refer to your payroll office or a tax preparation firm. By checking the “Yes” box, you are authorizing the IRS to call the designee to answer any questions that may arise during the processing of your return. You are also authorizing the designee to: • Give the IRS any information that is missing from your return, • Call the IRS for information about the processing of your return or the status of your refund or payment(s), and • Respond to certain IRS notices that you have shared with the designee about math errors and return preparation. The notices will not be sent to the designee. cannot be revoked. However, the authorization will automatically expire on the due date for filing your 2003 Form CT-1., Part I, 9 hr., 34 1. TIP day of February of the year after the close of the tax year. Generally, adjustments for prior year returns may be made only within 3 years of that date. Fractions of cents. If there is a difference between the total employee tax on lines 4, 5, 6, 9, and 10 and the total actually deducted from your employees’ compensation (including tips) plus the employer’s contribution due to fractions of cents added or dropped in collecting the tax, report this difference on line 12 as a deduction or an addition. If this is the only entry on line 12, do not attach a statement to explain the adjustment. Adjustments to supplemental annuity work-hour tax. You may take an adjustment on line 12 in 2002 for the total monthly adjustment of employee supplemental annuities under section 2(h)(2) of the Railroad Retirement Act of 1974. The Railroad Retirement Board will furnish you with Form G-245, Summary Statement of Quarterly Report of Railroad Retirement Supplemental Tax Credits, showing your supplemental annuity work-hour tax credit. For 2002, Form G-245 will show adjustments for months prior to January 2002. Total the amounts shown on Form(s) G-245 and enter the total on line 12. Attach a copy of each Form G-245 to Form CT-1. The supplemental annuity work-hour tax credit cannot exceed the supplemental annuity work-hour tax imposed CAUTION for the year giving rise to the credit (as shown on Form G-245) and for any subsequent years. Adjustments to special supplemental annuity tax. You may take an adjustment on line 12 in 2002 for any adjustments shown on Form G-241. These adjustments relate to amounts reported in quarters prior to 2002. Total the amounts shown on Form(s) G-241 and enter the total on line 12. Attach a copy of each Form G-241 to Form CT-1. ! Line 13. Total Railroad Retirement Taxes Based on Compensation • A decrease, subtract line 12 from line 11. • An increase, add line 12 to line 11. If the net adjustment on line 12 is: Line 14. Total Deposits for the Year Enter the total Form CT-1 taxes you deposited. Also include any overpayment applied from your 2001 return. Line 15. Balance Due Subtract line 14 from line 13. You should have a balance due only if line 13 is less than $2,500, unless the balance due is a shortfall amount for monthly schedule depositors as explained under the Accuracy of deposits rule on page 3. -5-
https://www.scribd.com/document/545176/US-Internal-Revenue-Service-ict1-2002
CC-MAIN-2018-47
refinedweb
3,900
62.78
8.7. array — Efficient arrays of numeric values¶ This. Nouveau dans la version 3.3. The actual representation of values is determined by the machine architecture (strictly speaking, by the C implementation). The actual size can be accessed through the itemsize attribute. Le module définit le type suivant : - class array. array(typecode[, initializer])¶: array. buffer_info()¶.. array. frombytes(s)¶ Appends items from the string, interpreting the string as an array of machine values (as if it had been read from a file using the fromfile()method). Nouveau dans la version 3.2: fromstring()is renamed to frombytes()for clarity. array. fromfile(f, n)¶ Read n items (as machine values) from the file object f and append them to the end of the array. If less than n items are available, EOFErroris raised, but the items that were available are still inserted into the array. f must be a real built-in file object; something else with a read()method won’t do. array. fromlist(list)¶ Append items from the list. This is equivalent to for x in list: a.append(x)except that if there is a type error, the array is unchanged. array. fromstring()¶ Alias déprécié de frombytes(). array. fromunicode(s)¶ Extends this array with data from the given unicode string. The array must be a type 'u'array; otherwise a ValueErroris raised. Use array.frombytes. tobytes()¶ Convert the array to an array of machine values and return the bytes representation (the same sequence of bytes that would be written to a file by the tofile()method.) Nouveau dans la class has been imported using from array import array. Examples: array('l') array('u', 'hello \u2641') array('l', [1, 2, 3, 4, 5]) array('d', [1.0, 2.0, 3.14]) Voir aussi -.
https://docs.python.org/fr/3/library/array.html
CC-MAIN-2018-05
refinedweb
293
67.65
(POST, CommonMiddleware middleware to set the ETag header. When the client next requests the same resource, it might send along a header such as If-modified-since, containing the date of the last modification time it was sent, or If-none-match, containing the ETag it was sent. If the current version of the page matches the ETag sent by the client, or if the resource has not been modified, a 304 status code can be sent back, instead of a full response, telling the client that nothing has changed.. Using this feature usefully is probably best explained with an example. Suppose you have this pair of models, representing a simple blog system: import datetime from django.db import models class Blog(models.Model): ... class Entry(models.Model): blog = models.ForeignKey(Blog) POST, request to /foo/ to update the resource. It also sends an If-Match: "abcd1234" header to specify the version it is trying to update. - Server checks to see if the resource has changed, by computing the ETag the same way it does for a GET request (using the same function). If the resource has changed, it will return a 412 status code code, meaning “precondition failed”. - Client sends a GET request. Comparison with middleware conditional processing¶ You may notice that Django already provides simple and straightforward conditional GET handling via the django.middleware.http.ConditionalGetMiddleware and CommonMiddleware. Whilst certainly being easy to use and suitable for many situations, those pieces of middleware functionality have limitations for advanced usage: - They are applied globally to all views in your project - They don’t save you from generating the response itself, which may be expensive - They are only appropriate for HTTP GET requests..
https://docs.djangoproject.com/en/1.6/topics/conditional-view-processing/
CC-MAIN-2015-18
refinedweb
283
53.41
OK, so saying that SQL Server isn't really my thing is kind of lame, but I'm not one to pretend I know everything. Generally I use a procedure like this to get paged data (parameters replaced with actual values for simplicity). CREATE TABLE #PageIndex ( idnum int IDENTITY(1, 1), TopicID int) INSERT INTO #PageIndex (TopicID) SELECT TopicID FROM Topics WHERE Topics.ForumID = 11ORDER BY Topics.LastPostTime DESC SELECT #PageIndex.idnum, Topics.* FROM #PageIndex JOIN Topics ON #PageIndex.TopicID = Topics.TopicID WHERE #PageIndex.idnum > 5000 AND #PageIndex.idnum < 5031ORDER BY #PageIndex.idnum This returns results quickly enough, but it seems to result in a bit of a CPU hit that I'm not entirely comfortable with. Is there a better way to go about this? Awhile back I was crying about how LoginView is designed wrong. Apparently Microsoft doesn't agree with me. At issue is the fact that controls inside of a LoginView are created late in the page lifecycle so they can't be accessed directly from PageLoad or postback events. The stated purpose of the control, according to the documentation, says: "Displays the appropriate content template for a given user, based on the user's authentication status and role membership." I don't know if that sentence represents the broad requirements of the control, but I suppose it depends on how you define "content." The first thing that comes to mind when wanting to use this control is putting a login box in the anon template and some kind of navigation for logged in users in the authenticated template. Or in a feedback mechanism under an article, put the text box for logged in folks and a link to register for the anon folks. As it stands now, the static content is fine, but anything else requires more work. This is eventually what the Web platform team came up with: So I guess it won't work the way I think it should, and that's a bummer. The next best thing is to use a MultiView control, or a derived version thereof, to duplicate this functionality. Last month I went inside of my bank to make a deposit and get some cash, somehing I almost never do because I use the ATM. That particular day, the ATM was broken, so I had little choice. So wouldn't you know it, the one time I go in during a span of like three years, the teller manages to debit my savings account $200 on behalf of the next customer. How stupid is that? The one time I deal with humans, they screw it up? Back when I used Overture, I always thought it was kind of a cool security feature where you had to type in letters in a graphic that is, theoretically, not machine readable. This deters automated attacks. It occurred to me that'd be a nice feature for the forum registration. I never really played with anything graphical in .NET, aside from reading a little of the Managed DirectX 9 Kick Start. I also did some image resizing on the crappy little game site I did. From what little I knew about stuff in the Drawing namespace, I figured it couldn't be that hard to generate a GIF out of an HttpHandler with some text on it. I was right. It's like a dozen lines of code, and that includes code to draw some random lines on it and move the characters around. It generates the text and saves it to Session. Once you can find a good example, or encounter some of the better documentation, it's like you can do anything on .NET. What's even more exciting is that once you learn one area, you adapt quickly to other areas. I'm an ASP.NET guy, but Windows forms are easy enough. Graphics aren't that hard, and after reading a little of a beginning game programming book, that's not hard either. I'm generally too busy creating things to get as academic as a lot of bloggers do, but it's fun to see that new stuff can come so easily in .NET. Responses in my last post about this were either, "Threading in a Web app isn't a good idea," or a lengthy example that works, but wasn't really what I was after. After looking a little harder, I realized the error of my ways. The goal was to launch a Timer from an HttpModule. This is where I started: public void Init(HttpApplication application){ myTimer = new Timer(new TimerCallback(this.TimerMethod), application.Context, 60000, 60000);} static Timer myTimer; private void TimerMethod(object sender){ HttpContext context = ((Application)sender).Context; MyClass.StaticMethod(context);} Then in the class being called by the timer, something like this: public static void StaticMethod(HttpContext context){ Cache cache = context.Cache;} The problem there was that the cache object was always null. So at some point someone on the asp.net forums suggested this to me: public void Init(HttpApplication application){ appHandle = GCHandle.Alloc(application.Context, GCHandleType.Normal); myTimer = new Timer(new TimerCallback(this.TimerMethod), application.Context, 60000, 60000);} static Timer myTimer;protected GCHandle appHandle; private void TimerMethod(object sender){ HttpContext context = (HttpContext)appHandle.Target; MyClass.StaticMethod(context);} This did indeed work. I wasn't sure why, but I did get that it prevented the GC from disposing of the HttpContext object, which otherwise would die. After some toying around, mostly through chance Intellisense encounters, I arrived at this, which works as it should, without the GCHandler: private void TimerMethod(object sender){ HttpContext context = (HttpContext)sender; MyClass.StaticMethod(context);} ...with the static method establishing the cache this way: Cache cache = HttpRuntime.Cache; What do you know, it works. Watching the output in the debugger, it keeps doing its thing, on and on and on. I'm not sure if the context object in the static method can access the Application object, but seeing as how I have the cache, that's more than adequate. Doing stuff in seperate threads in a Web app is a pain when you need a reference to general application state. Why does it have to be so hard? The first time I did something in this realm, I was trying to make an asynchronous mailer to notify people in a forum thread that there was a reply to the thread. With some help from someone in the ASP.NET forums, I eventually arrived at something like this in the class (the GCHandle class is in System.Runtime.InteropServices, if you're curious): public void Send(){ appHandle = GCHandle.Alloc(HttpContext.Current, GCHandleType.Normal); // notify by email those who are hooked up ThreadStart workerstart = new ThreadStart(Mailer); Thread myThread = new Thread(workerstart); myThread.Start();} protected GCHandle appHandle; private void Mailer(){ HttpContext context = (HttpContext)appHandle.Target; // mail work here} This works perfectly, though I'm still not clever enough to understand exactly why. Adapting this same logic to a static Timer object in an HttpModule wasn't much harder, provided I kept passing along the context through whatever objects and code I wanted to run: private void TimerMethod(object sender){ HttpContext context = (HttpContext)appHandle.Target; // do whatever} So now that I'm clever enough to follow this pattern, can anyone explain why exactly it works? I'm not satisfied without knowing the "why" along with the "how." I'm sure that 90% of people running SP2 will not have any problems, but we've already had a lot of issues. First is the default IE security. My wife decided to upload photos to Ofoto on her machine (usually it's on mine), and for whatever reason, the browser would not allow her to install the ActiveX control under any circumstances. It didn't even prompt for it. She changed the settings to at least allow for the prompt. That's going to piss-off a lot of site publishers I'm sure. She's also a big City of Heroes player, and since installing SP2, the game slowed to an unplayable state when things got busy. It wasn't the video driver (had the latest from Nvidia). We don't know if it was something else in the graphics or motherboard pipelines, or a network issue, but it sucked to epic proportions. While checking to see what the pagefile settings were (which seem to be arbitrarily set to follow a range of a half-gig to a gig, same settings on my machine), I noticed the "Data Execution Prevention" tab. Never heard anything about that, but it's on, and you can't turn it off without modifying the boot.ini file (which also happens to be read-only). The theory is to apparently stop the execution of any program that tries to write to memory it shouldn't. I assume this is a catch-all for buffer overrun vulnerabilities. It's just weird that I've never heard anything about it. Regardless, turning it off had no effect, but I'm curious to know how it affects performance. We ended up uninstalling SP2 on her machine. City of Heroes runs great again. They're going to be in a world of hurt as it rolls out. I still have the issue with Avid Xpress. Avid, in a shocking move given their reluctance to do anything to maintain compatibility (they wouldn't support XP for ages), posted in their forum that they're working on "the few remaining issues." I've done nested grids before, something like this: <asp:Repeater <ItemTemplate> <p><%# Eval("Name") %></p> <asp:GridView </asp:GridView> </ItemTemplate></asp:Repeater> I tried to do it in a more event driven manner today like this: <script runat="server"> void Page_Load(object sender, EventArgs e) { CategoryCollection c = Category.GetCategories(false); c.Insert(0, new Category(0)); CatRepeater.DataSource = c; CatRepeater.DataBind(); } void CatRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { GridView g = (GridView)e.Item.FindControl("ForumGrid"); ForumCollection f = ((Category)e.Item.DataItem).GetForumCollection(false, false); g.DataSource = f; g.DataBind(); Trace.Warn(g.Rows.Count.ToString()); Trace.Warn(f.Count.ToString()); }</script>...<asp:Repeater <ItemTemplate> <p><%# Eval("Name") %></p> <asp:GridView </asp:GridView> </ItemTemplate></asp:Repeater> Here's what I don't get. In the two traces of the binding handler, the rows in the grid return 0 after databinding, yet the ForumCollection does indeed show the actual count. Am I missing something? This is actually going to change later on, because I don't want to be making multiple hits to the data every time, but I'm experimenting with something else. [Note: If you check the date on this post, it's from 2004. The 2008 site is much, much better. -J] It's absolutely astounding to me that important commercial sites can go into production without any usability testing. NBCOlympics.com comes to mind. I'm not that much of a sports fan, but seeing as how I coach junior Olympic volleyball in the ridiculously competitive Ohio Valley Region, and 17's at that, I can't get enough of the stuff during the Olympics. It's also really fun to watch Misty May and Kerri Walsh on the beach. There's one problem though: NBC's online schedule absolutely sucks. If you search TV listings for a time span and by sport, you get a result list of links and vague summaries. If you click on these links, you get a pop-up with a little more detail, and you're still stuck with a vague four-hour time block. What's worse is that there is no grid that shows if something is on one of the other channels at the same time. What the hell would've been so difficult about either: Oh, it's also slow as hell. If you work independently, I'm sure you feel as strongly as I do that with all of the mediocre crap out there, it's a crime that someone out there gets paid for something you could probably do ten times better and for less money. In my post yesterday there were some interesting comments about the code sample I posted regarding the use of StringBuilder vs. straight concatenation. Yes, I created a ridiculous scenario that would probably not ever occur in real life, but the intention was to illustrate a point. David Hayden made the comment that, "Not every website is Match.com." I totally agree with that, and I especially take issue with the thing about stored procedures always being "right." The code sample is for my book, and it comes with a liberal disclaimer that such a situation is fairly extreme. (And oh yeah, I argue against the use of sprocs too as the "right" thing.) That's one of the hardest things to confront when you're trying to teach. Do you go with the ultimate best practice when there's an easier way that doesn't perform as well but is still adequate? I've never used any kind of drag-and-drop data access because I fear for its performance, but clearly it's adequate for someone out there or Microsoft wouldn't keep including it.
http://weblogs.asp.net/jeff/archive/2004/08.aspx?PageIndex=2
CC-MAIN-2014-10
refinedweb
2,197
63.59
Microsoft is previewing F# 5, an upgrade to the company’s open source, “functional-first” language that emphasizes interactive, analytical programming. The preview is available via the .NET 5 Preview SDK or Jupyter Notebooks for .NET. Visual Studio users on Windows will need the .NET 5 preview SDK and Visual Studio Preview. Aligning with improved .NET support in Jupyter notebooks, a number of improvements in F# 5 including language changes were aimed at making the interactive programming experience better overall. More features in this vein are planned for a future preview. New and improved F# features, with the intent of improving interactive programming, include: - Easier package references via the new #r "nuget:..."command. - Enhanced data slicing in three areas: built-in FSharp.Core data types, 3D and 4D arrays in FSharp.Core, and reverse indexes and slicing from the end. - Applicative computation expressions that allow for more efficient computations provided that every computation is independent and results are merely accumulated at the end. When computations are independent of each other, they also are trivially parallelizable. One restriction: Computations are disallowed if they depend on previously computed values. - A new nameoffunction for logging or validating parameters to functions. By using actual F# symbols instead of string literals, refactoring names over time becomes less difficult. - A static class can be opened as if it were a module or namespace. This applies to any static class in .NET or .NET packages, or a developer’s own F#-defined static class. Other features planned for F# 5 include witness passing for trait constraints with respect to quotations. Suggestions for the language will be tracked in a language suggestions repository.
https://thousandrobots.com/microsoft-previews-f-5-infoworld/?amp=1
CC-MAIN-2022-05
refinedweb
275
50.73
23 April 2013 22:44 [Source: ICIS news] ?xml:namespace> According to Abiplast, production in the plastic packaging and mixed plastics sectors rose by 8% and 6.2% respectively, while laminate production was down by 5.5%. The apparent consumption of processed plastics -- the sum of production and imports minus exports -- in January and February stood at Brazilian reais (R) 9.7bn ($4.8bn, €3.7bn), a 13% increase compared with the same period in 2012. Domestic production met 86% of the country’s demand for processed plastics, with imports accounting for the remaining 14%, the association said. Exports of plastic products for the two-month period were down 7.3% year on year to $195m, while imports rose by 11.5% to $606m, with the trade deficit widening 23.4% to $411m, Abiplast said. In an article published earlier this month, Abiplast president Jose Ricardo Roriz Coelho predicted that the country’s plastics processing industry would increase production by 1% in 2013. Revenues are also expected to rise by 6.6%, or 1.4% in real terms, while investments in the industry would be on a par with 2012 levels, Coelho said. However, he warned that the industry continued to face a number of long-term challenges, in particular the lack of competitiveness and the growing trade
http://www.icis.com/Articles/2013/04/23/9661908/brazil-plastics-production-up-4.8-in-jan-feb.html
CC-MAIN-2014-49
refinedweb
218
57.77
Agenda See also: IRC log <scribe> scribe: DanC -> Edited Minutes for review: Aug 23 2006 15:00Z GRDDL WG meeting Vipul Kashyap is excused <ryager> I may need to leave in half hour. <harryh> ryager: that's fine! RESOLUTION: to accept as a true record <harryh> Rachel, Are you okay with scribing? PROPOSED: to meet 11:00am-12:30 ET Boston Time Wed 6 Sep, and weekly thereafter at 11am Boston time so RESOLVED scribe for 6 Sep is ryager <scribe> ACTION: Ian to discuss using meeting-scheduling for the primer [CONTINUES] [recorded in] briansuda: I've been working on the hreview/guitar details... haven't found much real hreview data, but I expect to be able to work around that ... I have a draft in progress... how to share...? harryh: just mail a pointer or copy to the mailing list <chimezie> ty harryh: do you think we can get a primer done in Sep? briansuda: depends... I'm not aware of an aggregator; building one would be tricky DanC: well, the xmlarmyknife service will aggregate real-time, if you give it the URIs briansuda: well, does that match the use case? DanC: well, just start with whatever works. <scribe> ACTION: BrianS to discuss using guitar-buying for the primer [CONTINUES] [recorded in] 1.17 harryh: I read it, and I like it DanC: I like what I've read in detail; I skimmed some parts. The W3C/Digital library case doesn't motivate GRDDL so much; I haven't found inspiration to contribute. FabienGandon: note that isn't just the W3C /TR/ case; it's got 2 others merged in (querying ) <ryager> I'm leaving now... ryager: I intend to copyedit a draft; let me know exactly which draft, ok? harryh: how about taking the W3C-specific stuff out of use case #4? FabienGandon: well, OK, but I'd prefer to integrate real experience from someone else. I'm inclined to withdraw, since I need to catch up on testing work DanC: one approach is to say "here's what the W3C does with RDF and /TR/; here's how it could be better with GRDDL" <harryh> ACTION: Harry to review digital library use case [recorded in] <scribe> ACTION: Fabien to review/reconsider digital library use case [recorded in] harryh: so we still need an XML Schema use case...? DanC: I think the clinical data use case covers XML Schema; another one would be nice, but not essential for 1st release. ... there are two cases Ben and I have discussed... I think it's ok to defer them to later drafts... <scribe> ACTION: FabienGandon to note that "Plus: ... " part of scheduling use case #1 needs work, and ask Ben for help whenever he becomes availble and drop it from the draft, meanwhile [recorded in] <harryh> Chime is going to talk to danja <harryh> to make sure Xforms use case works well with Atom, but otherwise he's happy poll: what to do between now and pub? Harry: I think the digial lib use case needs work, and then it's ready <chimezie> FabienGandon (off topic) but *how* do you create those diagrams? :) <harryh> ACTION: Ryager to read draft thoroughly [recorded in] DanC: I'd like to make a decision maybe next week, after having somebody read it top-to-bottom this week FabienGandon: we need an intro... ... [missed?] ... need help with seealso applications <chimezie> pointers to 'see also' <harryh> 2 more diagrams FabienGandon: need help from BenA. Harry: we don't need seealso pointers if there aren't apps FabienGandon: the seealso pointers are brand new; I need to let people know. ... feels like we're 2 weeks from shipping, to me briansuda: looks pretty good; I'd like to go over it one time... ... in the review use case, there's some talk of switching to hotels from guitars; I don't know if the primer has to exactly match... Chime: need to check with danja about atomol, [missed], diagram for clinical data use case Harry: Dan, last week you were interested in an XML/XML-schema primer? DanC: yes, 2 audiences for primer stuff: microformats, XML/schema data ... Chime, does the clinical data have namespace pointers? Chime: yes... mostly HL7. Not URIs that cleveland clinic owns. Harry: so this looks desireable, but I don't see commitment in the form of immediate action. ok to skip XML/schema it for 1st draft primer? [yes] <scribe> ACTION: DanC to enumerate options for base issue, pick one, and propose it in the form of a test case [CONTINUES] [recorded in] Danc: options include: (a) no specific mechanism, just use relative URIs in and out ... (b) use the XSLT 2 base-something() function ... (c) use a GRDDL-specified Base param ... (a1) use xml:base and/or <base href="..." /> in the instance Brian: hmm... consider the case of the tidy service... relative URIs might not get the right treatment there Chime: there's also the RSS case that Dom mentioned; I dind't completely understand... DanC: I think the norm in the RSS world is to have absolute URIs in <link> elements poll... preferred option Chime: let's stick to existing XSLT 1 mechanisms. (a) Brian: I'm currently relying on (c) in the case that (a) isn't enough FabienGandon: we're currently using a parameter in combination with base DanC: I have a mild preference for no new mechanism (a), but I'm not sure yet. FabienGandon: ah... I see the issue around stanrdizing the parameter name now... I think I prefer that GRDDL doesn't specify a new mechanism. Harry: I don't want the parameter to override xml:base. ... and since xslt2 alreayd standadizes a base uri function, we should mention that. DanC: I think I'll make a test case with the xslt2 function too. <scribe> ACTION: Harry to propose minimum set of transformation formats that must be supported by grddl processors. [DONE] [recorded in] -> GRDDL and transformations (take 2) Harry: in sum: SHOULD support XSTL 1; MAY support others. DanC: yes. PROPOSED: to address [#issue-whichlangs] as per the current draft (1.83 2006/08/25 20:23:09). SHOULD support XSLT 1; MAY support others. Chime: <?xml-stylesheet ?> introduces some ambiguity... DanC: yes... we should be clear on that [I'll probably add a new issue] <scribe> ACTION: DanC to add issue for relationship to <?xml-stylesheet ?> [recorded in] <harryh> Harry: We need to add the media type story to GRDDL spec <scribe> ACTION: Harry to draft some elaboration on how media types work with GRDDL [recorded in] <harryh> ACTION: Harry to write a few sentences on media type draft and run by DanC [recorded in] (oops; dup) RESOLUTION: to address [#issue-whichlangs] as per the current draft (1.83 2006/08/25 20:23:09). SHOULD support XSLT 1; MAY support others. "While javascript, C, or any other programming language technically ..." [scribe got too involved in the discussion] <scribe> ACTION: BenA to flesh out HTML RDF/A output of GRDDL use cases [CONTINUES] [recorded in] agenda points to ... scribe: I'm editing <scribe> ACTION: Chime to suggest which conformance labels, if any, the GRDDL spec should include [recorded in] AJDOURN. action -11 <scribe> ACTION:Harry to discuss with BenA and DanC the XML Schema use-case in context of Creative Commons and OAI. See clarification from DanC. [CONTINUES] [recorded in] <scribe> ACTION:Danja to discuss wiki usecase, query usecase, and e-learning usecase [DONE] [recorded in] yeah... rephrase "how a GRDDL client interacts with a document whose root element is an XSLT literal result element" to include xinclude <harryh> \away off to dinner
http://www.w3.org/2006/08/30-grddl-wg-minutes.html
CC-MAIN-2016-22
refinedweb
1,270
70.33
HCI/HCP-IS: IDoc Adapter Deciphered – Part 1 – Trigger IDoc from SAP ERP to HCI Using Basic Authentication Background Hana Cloud Integration / Hana Cloud Platform – Integration Services provides a IDoc adapter that enables you to Integrate with your back end SAP ERP system using IDoc Adapters. This blog series is a detailed startup guide for the set up tweaks required to Integrate HCI and ERP using IDocs.In this multi part series we will look at sending IDoc’s from SAP ERP to HCI and vice versa. There already exists a few blogs on SCN that covers the various individual pieces of this puzzle but the intent of this series is to collate this info from a PI Developer’s perspective. Where required I will also point to additional links / references that had helped me in my journey! Due credit to those content as well. In Part 1 (this blog), we will look at steps to trigger an IDoc from SAP ERP to HCI from the scratch using Basic Authentication. In Part 2 – we will look at using IDoc Number to search for IDocs in HCI In Part 3 – we will then extend this to use Client Authentication. In Part 4 – we will look at the steps to trigger an IDoc from HCI to SAP ERP using Basic Authentication. HCI Configuration SAP ERP Configuration Test Your Flow You are done! Trigger the IDoc using either your standard transaction or using We19. The IDoc should now be sent to HCI and processed by HCI. Test Case#1 : HCI Integration Flow Executes Successfully - IDoc triggered using WE19 - HCI Integration Flow Status - IDoc Status in WE02 Test Case#2 – HCI Integration Flow Fails - Make HCI Integration Flow Fails ( In my case SFTP Adapter is updated to have a invalid User Name ) - HCI returns a status HTTP 500 back to SAP ERP - IDoc in WE02 will go into status 02 ( Failure ) - As the Integration happens using SOAP Over HTTP this is technically a Synchronous Integration and if a HTTP 202 / 200 is not received back from HCI, SAP will mark the IDoc status as failed. Test Case#3 – IDoc triggered in WE19 with No of IDocs to be repeated as 2 - Single Message received at HCI. - IDoc XML will contain 2 IDoc tags – 1 for Each IDoc Summary - HCI’s IDoc adapter uses SOAP over HTTP and hence this ends up becoming a Synchronous Flow. - In SAP ERP, - Make sure your Port in WE21 is of type XML HTTP & has SOAP Protocol Enabled. - Make sure your RFC Destination in of Type G - The status of your IDoc in WE02 will be 03 / 02 depending on the status of your Integration Flow in HCI. - If HCI Integration Flow successful, Status = 03 - If HCI Integration Flow fails, Status = 02 the complete details of end to end flow. Thanks for sharing Bhavesh. Great Blog Bhavesh, looking forward to other parts of this series. 🙂 The entire series is now Out! Hope you enjoy reading the same Sanjeev! Any inputs on possible gaps are welcome! Regards Bhavesh Thanks for the wonderful blog Bhavesh!! Excellent as always! Thanks ! Good to see you back blogging 🙂 Keep up the momentum Hi Bhavesh. I followed your blogs on configuring the keystore to remove the error in the CXF-endpoint-IFLMAP-hcisbp component. The error got removed fine. then I followed this blog here to send an idoc to HCI. However the idocs are failing in ECC with status 02. In Partner profile, if I select Content type as text/xml and checked SOAP Protocol check box,I get the error as "Problem with Soap Class". I unchecked it, and I am getting "Communication error over HTTP". Please help me with this. Also the RFC destination fails for Server Hangup 502, when I disable the SSL conectivity and make it as "Inactive". If I keep it as "Active", the connection test does not return anything, I mean when I click the test button, nothing happens. Hello Shankar, With regards to the error - you need to make sure SOAP protocol is selected. If you are getting a error after that would suggest you check the HCI Message Monitoring and see if the message has failed. Also would suggest you look at the HCI tenant Tail Log and check if the Tail Log has info on why the request was rejected by HCI. For subsequenet followup on this, Would suggest you raise this as a question on the forum. Will respond there accordingly. Regards, Bhavesh Also, if your SM59 connection is failing, then this is a network issue. Please check with your Basis and Network team to see if the Ports are open or if a proxy server is to be used. Regards, Bhavesh Hi Bhavesh, The error is resolved, when we tried with a different ECC. Now am having issue in mapping. I don't see contents in the incoming idoc. In my IDOC adapter config, I have only configured the endpoint address, and not uploaded any WSDL in adapter. In the mapping, I downloaded the wsdl(DEBMAS) from ECC(removed the version parameter and kept as blank while downloading), and used it in the mapping. I have used the same structure for source and target, and mapped just the control records .Receiver is a mail. Earlier I got error in mapping as IllegalInstance Exception, and that the idoc segment was not getting created. Hence I gave map with default for the control record mandatory fields, Eg: SNDPOR-->Map With Default-->SNDPOR.. The trace is not enabled in the tenant and hence with the data I received as email, I see only blank values in all fields. In the runtime config, i tried with empty namespace and also as xmlns:ns2="urn:sap-com:document:sap:idoc:soap:messages", since this the xml namespace in the target xml I received as mail. I also changed the source adapter as "SOAP", instead of IDOC, and triggered the same. The result is same, except the idoc in we05 is in error. Though, the message in HCI is with status "COMPLETED" Hello Shankar, You can use a Groovy script to log your payload. Check this blog of mine: HCI - Payload Logging using Groovy Scripts - Part 1 Use the script before and after your mapping step and then you can see the Input XML from SAP and the output XML from your mapping and understand the corresponding impact. Using this, you should be able to figure out why your mapping is not working and the changes required to your Integration Flow as needed. Regards, Bhavesh Hi Bhavesh, I was able to solve it, by following this blog : Handling Extended/Custom IDOC in HCI with standard content. Anyways, thanks for your info on the using the scripts to log the messages. Yet to get my hands on the script, and I shall always look up to you for reference 🙂 Thanks again 🙂 Hi Shankar/Bhavesh, I am also facing the same issue. Status 02, SSL handshake error - 1023:SRT: Processing error in Internet Communication Framework: ("SSL handshake with p1015-iflmap.hcisbp.ap1.hana.ondemand.com:443 failed: SSSLERR_PEE We have in our ECC system, self signed certificate. Do we need CA authorized certificate? Please suggest. Thanks, Nidhi Hi Nidhi, Were you able to resolve this? Regards, Hi Manu, Yes, it was certificate issue. It was resolved. Thanks, NIdhi Srivastava Hi Nidhi, Does the self signed certificate worked or you got it signed by authority. Regards, Manu Hi, Does somebody know if a CA signed certificate is mandatory? Regards, Marco Silva Very helpful document thanks for sharing this kind of document, Bhavesh Kantilal Hi Bhavesh, I followed your blog and getting Status 02 error when triggering IDOC from we19 in SAP ECC system. Also, I cannot see any logs in HCI and no messages in Message Monitoring in HCI. In RFC destination, when testing the connection getting the below status - Not sure what is the issue, and what I am missing. I cross checked everything and it is same as you suggested. In the IDoc Sender Channel we have the below screen. Do we need to enter any user credentials(deployed artifacts?) I am not sure, if this is correct. Thanks, NIdhi Hi Bhavesh, Thanks for this blog, I have some concern over the design limitation that we have in HCI - In case we want to have 50 IDOC type going from ECC to HCI, then 50 RFC connections in ECC system and 50 Iflows in HCI should be created if the endpoint is IDOC specific - cxf/orders05. I understand that we don't have isolated receiver determination or ICOs like PI, but if we go for one connection for all IDOCs - cxf/IDOCs and create condition expression for finding the receiver and corresponding mapping(all the flows for every IDOC will be part of single Iflow in HCI). Is it a good idea, or do we have any alternative to avoid n RFC connections for n IDOCs in ECC system? Regards, Rohit Hi Rohit, I am also having same doubt. Did you manage to get clarification regarding your query? BR, Shashank Exactly. I would develop a router iFlow in HCI. Did you decide on your approach? Regards, VJ Thank you for this blog. I was able to follow it and successfully sent an IDOC to an IFLOW. I've hit a snag within the mapping that I'm hoping that you can assist with me. I need to loop thru a specific E1EDKT2 segment group and concatenate all of the TDLINE's into one XML "comment" field tag that is defined as <xsd:element. I'm fairly new to mapping in CPI so any step by step instructions would be extremely helpful. Hi, Thanks alot for the nice article. However I am facing a strange problem. In SM59 I can not change the selection in the "SSL Certificate" drop down list to be "Anonym SSL Client (Anonymous)". Whenever I try, it is always reverted to the "Default SSL Client (Standard)" Option. Any idea what could be the reason? Appreciating your help Rasha Hello Rasha, May be a GUI issue. Just trying logging out and logging in and try. Regards, Nitin Deshpande Hi Nitin, I already have tried to logout / login multiple times ? I noticed also that whenever I activate the SSL the page becomes uneditable. Showing the warning: SSL client PSE DEFAULT does not exist. Also I tried to change the certificate selection while the ssl is inactive, but no success. Seems like the Anonym option is disabled. I wonder whether it could be something with my user rights? Hi, One question regarding the fact that when idocs are sent out over SOAP from ERP to CPI it works in synchronous mode..When there is a big amount of idocs sent out this is not reasonable to work in synchronous mode because the processing is so slow. So do you have any ideas how to make this idoc sending to CPI to work asynchronously so that when CPI receives the idoc it sends the HTTP 202 right away. (And don´t wait the whole process to go through..) Even switching from the idoc adapter to the SOAP adapter with Processing mode set to asynchronous won´t help..I mean setting the Message Exchange Pattern = One-Way" and Service Definition = Manual" and Processing Settings = WS Standard..This setting works okey if you try it from example SOAP UI but when triggering the idoc from ERP it is still synchronous.. Any ideas? Hi Bhavesh, I just started reading blogs and likes your efforts on Idoc adapter. Can you please let me know is there any blog on using Idoc adapter to update information in SAP ERP in idoc format ? I not an expert in idoc setup but aware of the configurations in case of Outbound. So, I would like know about inbound settings in CPI, SAP HCM to receive idocs from other system to SAP HCM. Hi Bhavesh, One query please... why we need to import certificates only in SSL Client SSL Client ( Anonymous)?All three or only last *hana.xxxx certificate needs to be imported? BR, Rashmi Hi!!! i have a question, in the SM59, the Target Host typing “” or just “A1111-iflmap.hcisbp.us2.hana.ondemand.com” in my case when wrote “” sent me a message “Connect to 443 failed: NIEHOST_UNKNOWN(-2) ” but when y wrote “A1111-iflmap.hcisbp.us2.hana.ondemand.com” sent me a box to capture user and password What is wrong? Great blog, thank you for sharing. Hi Bhavesh, Great blog! Congratulations. I face a problem. Maybe you can help? I send an IDOC from ECC via CPI to SalesForce using the Advantco Adapter. Everything works fine and the message is correctly processed in SalesForce. But I think CPI is trying to connect back to ECC to update the IDOC status and that is failing. I get an error like this: Outbound processing in endpoint at /Idoc failed with message "NullPointerException:while trying to invoke the method java.util.Map.get(java.lang.Object) of a null object loaded from local variable 'headers'" Do you have any idea what this could mean? Thank you! Hi Jurgen I don't think the IDoc adapter updates the status of the idoc in the sender system. Instead, it returns 200/202 http status codes (http standard) which tells the sender that the Idoc message was successfully received. The sender then updates the idoc status. In your case I guess you have already solved the issues since it's a while ago. Otherwise I would replace the sender adapter by a plain HTTPS channel and test with soapUI or similar to analyze it further. Philippe
https://blogs.sap.com/2016/08/09/hci-hcp-is-idoc-adapter-deciphered-part-1-trigger-idoc-from-sap-to-hcc-using-basic-authentication/
CC-MAIN-2021-43
refinedweb
2,284
71.85
q q how to add 2 numbers in java Hi, Try this: class Test{ public int add(int a,int b){ return a+b; } public static void main(String []args){ Calculation cal=new Calculation(); int java q? java q? how to get the average and rank of 1 million student records using threads q in java q in java Designed a program that allows the user to enter a name Then the program prints the characters of a-z and after each letter means... f 0 g 0 h 1 i 0 j 1 k 0 l 0 m 0 n 1 o 1 p 0 q 0 r 0 . . . . z 0 up Please help with this Q ASAP Please help with this Q ASAP The University wants to make a basic graphical display to show how many people received different grades for a piece of work on a module. You are required to write a program in Java that achieves Popup dialog box in java Popup dialog box in java How to display popup dialog box in java? Dialog Box- A dialog box is an independent small window which appear... can create popup dialog box. Java swing toolkit provide tow types of dialog box Java Print Dialog Java Print Dialog Using java.awt.print.PrinterJob and javax.print.attribute.PrintRequestAttributeSet. I call .printDialog(ps) and the standard print dialog is displayed with options preset to my chosen attributes. Now I can dialog box Java show series of at least four interview questions hello. write an application that displays a series of at least four interview questions.... at the end of the interview, use a dialog box to ask whether the user wants Show Font Dialog and Color Dialog Show Font Dialog and Color Dialog In this section, you will learn creating color dialog box and font dialog in Java. SWT allows to show Color Dialog and Font Dialog Interview Tips - Java Interview Questions Interview Tips Hi, I am looking for a job in java/j2ee.plz give me interview tips. i mean topics which i should be strong and how to prepare. Looking for a job 3.5yrs experience examples - Java Beginners dialog indicating the problem to the user and allow the user to enter another number. use input dialog and message dialog to input data and display the program Java error dialog Java error dialog A Java dialog box is an independent sub window that is used to notice a temporary message to the user. The dialog box find its extensive Show Dialog Box in Java Show Dialog Box in Java - Swing Dialogs Message dialog box is used to display informative... the message Dialog box. Our program display "Click Me" button on the window Dojo Dialog Box Dojo Dialog Box In this section, you will learn about the dialog box with tool tips and how to create it in dojo. Dialog Box : Dialog box Java Tutorial with examples Java Tutorial with examples What is the good urls of java tutorial with examples on your website? Thanks Hi, We have many java tutorial with examples codes. You can view all these at Java Example Codes Show input dialog box Swing Input Dialog Box Example - Swing Dialogs Input dialog box is very important and interactive feature of Java Swing. You have been using the System.in for inputting Q, 12 WAP to calculate addition of two distances in feets and inches using objects as functions arguments in java Q, 12 WAP to calculate addition of two distances in feets and inches using objects as functions arguments in java Q, 12 WAP to calculate addition of two distances in feets and inches using objects as functions arguments in java java - Java Beginners the following links:... output. Therefore in Java suggest how to accept input from the user and display Java file dialog Java file dialog In this section, you will learn how to display a dialog... FileDialog that displays the modal dialog. It blocks the rest of the application... setDirectory("C:/") method. This method opens the dialog with the specified Display a dialog box with Java Error Display a dialog box with Java Error  ... you a code that help you in implementation of dialog box with Java Error... the execution of a program using javaw ,the program code display a dialog box name Java Q - Java Terms Q - Java Terms Java Quartz Framework Quartz is an open source job... Micro Systems. Java Queue A queue is a collection examples - Java Beginners examples as am new to java can you please help me with basic programs on java with their examples Hi Friend, Please visit the following link: Hope Java programming 1 - Java Beginners :// class examples...Java programming 1 Thx sir for reply me ^^ err how bout if using Ajax examples Ajax examples Hi, I am Java programmer and I have done programming in Java. Now I am learning ajax from scratch. Tell me the good examples of Ajax. Thanks Hi, Since you have already experience in development Real time examples - Java Beginners ,constructor overloading concept in java and explain with real time examples? .../java/master-java/method_overloading.shtml Java Tutorial for Beginners in Java Programming language. page, where you will find many examples...Java Tutorial for Beginners - Getting started tutorial for beginners in Java programming language These tutorials for beginners in Java will help you Dojo Tool tips Dojo Tool tips In this section, you will learn about the tool tips and how to developed it in dojo. Tool tips : This is a GUI Java examples for beginners In this tutorial, you will be briefed about the word of Java examples, which... of examples. Java examples for beginners: Comparing Two Numbers The tutorial provide you the simple form of examples of Java, which will highlight you the method Tips & Tricks Tips & Tricks Splash Screen in Java 6.0 Splash screens... of the application. AWT/Swing can be used to create splash screens in Java. Prior to Java SE Java 9 Tutorial, news and examples News, articles and example of the Java 9 Programming Language After the release of the Java 8, Oracle is discussing about the proposal of the development of the Java 9 programming Language. Here we will be discussing about the news Java tutorials for beginners with examples Java Video tutorials with examples are being provided to help the beginners... programs are accompanied with Java video that displays Java examples..., methods, interface, variables, etc. Java tutorials for beginners with examples need ENUM examples need ENUM examples i need enum sample examples Hi Friend...{ C, Java, DOTNET, PERL } public static void main(String[] args){ int... the following link: Flex Examples the for each loop in other languages like C#, Java etc. For more Examples...Flex Examples In this section we will see some examples in Flex. This section... the various examples in Flex which will help you in to understand that how Tips and Tricks Tips and Tricks Send data from database in PDF file as servlet response... is a java library containing classes to generate documents in PDF, XML, HTML, and RTF Java Java What is the immediate superclass of the Dialog class Java util package Examples retaining save dialog box even after clicking save button - Java Beginners retaining save dialog box even after clicking save button I am... when i open save dialog box and input a file name that is already present... "no" to that dialog box i'm unable to get the save dialog box again.how coulg Can you give few examples of final classes defined in Java API? Can you give few examples of final classes defined in Java API? Hi, Can you give few examples of final classes defined in Java API? thanks javascript loop examples javascript loop examples While running a javascript loop function i am getting an error ..can any one post an example of writing loops in javascript? Looping In Java Script Input/Output Examples Java Input/Output Examples In this tutorial you will learn about how the Inputs and outputs are managed in java. To understand the Java Input & Output there is a package in java named java.io which provides the classes Examples of Wrapper Class Examples of Wrapper Class In this page we are giving you the links of tutorials on wrapper classes in Java. Wrapper classes are the classes present...) char 8) boolean Following are the example of wrapper classes in Java.  Tips 'n' Tricks Tips 'n' Tricks Download files data from many URLs This Java program... arguments separated by space. Java provides URLConnection class that represents Free JSP Books ; Web Server Java: Servlets and JSP This chapter covers Web Server Java, but you won't find anything about writing CGI programs in Java here. Although... it; this is inefficient. If it's interpreted in Java, the program has to be translated Iterator in java, Iterator Java Examples The Iterator is an java interface, it can be used to iterate the java collection objects. In this Java iterator tutorial you will learn how to define of Java Iterator interface JSF Examples JSF Examples In this section we will discuss about various examples of JSF. This section describes some important examples of JSF which will help you... examples, I have tried to list these examples in a sequence that will help you JAVA JAVA Q)Tell me some Java Exception types that you got so far and explain the Scenarios? Q)Suppose if you type wrong tag syntax in your JSP. When you run the JSP what exception will throw? Q)Suppose in your java coding part you Java I/O Examples Java I/0 Examples What is Java I/O? The Java I/O means Java Input/Output. It is provided by the java.io package. This package how to copy file or directory one drive and paste another drive using GUI componets in java?first i want open dialog box then copy file and paste to another drive JPA Examples In Eclipse JPA Examples In Eclipse In the JPA Examples section we will provide you almost all the examples of JPA framework. This complete JPA tutorials will illustrate you Java I/0 Examples java - Java Beginners :// Thanks RoseIndia Team...java Java always provides default constructor to ac lass is it true... constructor.If we don't create any constructor for a class java itself creates java will find several examples related to java database connectivity. Thanks...java Hi good Morning wil u please give me the some of the examples of java connection to the database to the java program Hello Friend java : what is meant by constructor? A java constructor File Upload Tutorial With Examples In JSP File Upload Tutorial With Examples In JSP  ... such types of examples with the complete code in JSP. This tutorial also provides the output of each and every examples for cross checking for your Java SAX Examples Java SAX Examples XML Well-Formed Verifier In this section we are going to develop a simple java... or not. Get XML Elements In this section you will learn to develop a simple java program Ajax Examples Ajax Examples There are a few AJAX demos and examples on the web right now. While... with this solution is that it limits your audience to those that have a Java Java Security Java Security Java Security Packages JCA/JCE ( an outline... and packages in JDK, with code examples. Many of the concepts and technical terms thus...; JCA/JCE (Java Cryptography Architecture & Java Cryptography Extensions Java Java I am using Java netbeans ide. Q 1.Every Time i execute a query My ResultSet points to zero. is there any mechanism to make my cursor point to the last row i viewed.or traveresd through.. Q 2.Whenever a new Record Java Util Examples List Java Util Examples List - Util Tutorials The util package or java provides many... examples that demonstrate the syntax and example code of java util package java java write a java program to compare two integer variables and display the largest one using input and message dialog boxes. import javax.swing.*; class CompareIntegers { public static void main(String[] args Java BigDecimal divide examples Java BigDecimal divide examples In this example, Java bigdecimal class divide(BigDecimal...(bigdecimal_objectDivisorName, int scale, int roundingMode); Java_BigDecimal java i want some examples for arrays... and some examples about for loop statements... Please visit the following link: Array Tutorials java Principle:</td><td><input type="text" name="pr"></td></tr> java to this: Hi friends and how are you? i have a problem i need to write a java program which has a two java packages, one has the interface and the other has classes...; and locale. When i run it must show a dialog box of all the conversions java java Hi friends and how are you? i have a problem i need to write a java program which has a two java packages, one has the interface and the other... and date format; and locale. When i run it must show a dialog box of all Java Get Example ; In this section of Java Examples, we are going to illustrate various Java... examples to get the things fast and practice these code at your end to learn java.... Java Get Examples.. Get host name in Java: This example Linux tutorials and tips Linux is of the most advanced operating system. Linux is being used to host websites and web applications. Linux also provide support for Java and other programming language. Programmers from all the over the world is developing many java java 3.write an algorithem and the java program that declars aminutes variable that represents minutes worked on ajob and reads avalue using Dialog.... for example 197mintes becomes 3 hours ad 17 minutes save the program as time java Apache MyFaces Examples Apache MyFaces Examples Examples provided by the myfaces-example... Downloading and exploring MyFaces examples integrated with Tomahawk. Just go java java can you give an example of how to use servlet context Hi, You can get the servlet context in your java application using...", "My Furniture"); Check the examples: Context attributes in Servlet Servlet Dojo Dialog Box Dojo Dialog Box In this section, you will learn about the dialog box with tool tips and how to create it in dojo. Try Online: Dialog Box Dialog Box : Dialog box java - Java Beginners the following links: java java sir, please send me the some of the examples in jsp... several jsp and servlet examples. Thanks Hi Friend, Please visit... and servlet examples. Thanks Examples of POI3.0 Examples of POI3.0  ... Java (XLS). We can use HWPF for Word Documents , HSLF for PowerPoint... In this program we are setting data format in excel file using Java.   java java how to you implement interfaces Hi Friend, An Interface is the collection of methods with empty implementations and constants... link: Interface Examples Thanks JPA 2.1 CRUD examples Learn how to create CRUD operation examples in JPA 2.1 In this section you... for Create, Retrieve (Read), Update and Delete operations on an Entity. From Java... actually developing the examples. Following 4 concepts you should understand Java Exceptions Tutorials With Examples Java Exceptions Tutorials With Examples Exceptions in Java Exceptions... in Java is to use try and catch block. How Java Swing Tutorials in Java Swing. Dialog Box In Swing Application... of Java Graphic examples, we are going to show you how to draw simple bar chart... Java Swing Tutorials   Inheritance program in java In this tutorial we will discuss examples of Simple Inheritance in Java and Multilevel Inheritance in Java. Inheritance is an OOPS (Object Oriented... in Java. The concept of inheritance is used to make the things from general to more Java ArrayList, Java Array List examples The Java ArrayList (java.util.ArrayList) is resizable implementation... the ArrayList in Java with the example code. SampleInterfaceImp.java import... list.add("Java "); list.add("is "); list.add("very "); list.add("good Java String Examples Java String Examples  .... Java Count Vowels In this program you will learn how to count... and then you will get the number of vowels from that String. Java java ().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); frame.setSize(500,150...:// java - Java Beginners example. class q { int a,b; q() { a=0;b=0; } q(int x) { a=x; b=x; } q(int x,int y) { a=x; b=y; } public... { public static void main (String[] args) { q q1=new q(); q1.print(); q Java Java How to retrieve image from MySQL database using java? Java Swing retrieve image: import java.sql.*; import java.awt.*; import..., 300); f.setVisible(true); } } catch (Exception e) { } } } For more Examples java java how to get values from jtable and save in database ? Insert JTable data to database Here is an example that reads the jtable data...(JRootPane.PLAIN_DIALOG); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT java java Hi 1) in arraylist i have sorted salary ,id last , first then how can i display last name, and id. in java 2)how to restrict multiple submission in struts framework. Here is a java examples that stores java to be placed in the ?\apache-tomcat-6.0.16\webapps\examples\jsp folder in the system... in ?\apache-tomcat-6.0.16\work\localhost\examples\jsp as myjsp_jsp.java. The contents java - Java Interview Questions Friend, Please visit the following links: multi-threaded Java program - Java Beginners multi-threaded Java program Write a multi-threaded Java program... examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers... extends Thread { private PipedReader pr; private PipedWriter pw
http://www.roseindia.net/tutorialhelp/comment/94311
CC-MAIN-2014-42
refinedweb
2,935
54.12
How To Shutdown PC using Python Hey my geeky friend today I'm going to tell you something special & geeky. Today you are going to learn that how can you shutdown your PC just using few lines of python code, so without wasting time let's get started. Here's the our simple python code to ShutDown PC immediately. #importing OS import os #asking from user shutdown = input("Do You Want to ShutDown You PC ? (YES / NO): ") #if user input is NO then if shutdown == 'NO': exit() #if user input is YES then else: os.system("shutdown /s /t 1") Explanation : Here in this code we had first import os library and used os.system function with shutdown /s /t 1 code actually its a shell command. . If you hadn't imported os system in your ide import it using command prompt. One more important thing this program would directly shutdown your PC within few seconds so please make sure you have saved and closed your all important programs and applications before executing this code. Hope you had liked our article please share with your programmer friends and Follow us on social media to get updated with latest updates, tips and tricks for programmers and developers.
https://www.coderzadda.tech/2020/12/how-to-shutdown-pc-using-python.html
CC-MAIN-2021-21
refinedweb
206
59.84
In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with inheritance? 18 The official tutorial may be of some use to you. + : accessible blank : not accessible 19 - 9 World is within your project. I should explain further. Libraries are within your project, and if you’re creating a library, they would expose these public classes and methods as well. So, saying just within your project is a bit off. “Everything that uses it” is a better description. May 3, 2018 at 13:02 - 7 For example, if I have MyClassand I’m doing AnotherClass extends MyClassI will have access to all protected and public methods and properties from within AnotherClass. If I do MyClass myClass = new MyClass();in AnotherClasssomewhere – let’s say the constructor – I will only have access to the public methods if it is in a different package. Note that if I do = new MyClass() { @Override protected void protectedMethod() { //some logic } };it appears that I can access protected methods, but this kind of the same as extending it, but inline instead. May 4, 2018 at 12:25 - 9 Unfortunately, this answer is a gross oversimplification. Reality is a bit more complicated, especially when you consider protected(which is actually quite a difficult access modifier to fully understand – most people who think they know what protectedmeans really don’t). Also, as Bohemian pointed out, it doesn’t answer the question – it says nothing about when to use each access modifier. In my opinion, this answer isn’t quite bad enough to downvote, but close. But over 4000 upvotes? How did this happen? Jul 11, 2018 at 6:26 - 19 - 8 @Jack Yeah, niks’ comment is wrong despite the many upvotes stating otherwise. The Java Tutorials link in the answer clearly says that protected members can also be accessed within subclasses from a different package. It seems that he/she meant “package-level” instead of “protected”, or was referring to a different edit. Feb 5, 2021 at 2:57 worrying that someone was using that code you just overhauled. So, the rule of thumb is to make things only as visible as they have to be. Start with private and only add more visibility as needed. Only make public that which is object and make just your object getter/setter public. In this way being stingy about exposing your guts encourages good composition and separation of concerns I stick with just “private” and “public”. Many OO languages just have that. “Protected” can be handy, but it’s. 8 - 27 friends -> “The less you know about it the better” —> It gives selective visibility, which is still superior to package privacy. In C++, it has its uses, because not all functions can be member functions, and friends is better than public’ing. Of course there is a danger of misuse by evil minds. Jun 7, 2011 at 10:13 - 33 It should also be noted that “protected” in C++ has a different meaning – a protected method is effectively private, but can still be called from an inheriting class. (As opposed to Java where it can be called by any class within the same package.) Oct 2, 2011 at 12:34 - 9 @RhysvanderWaerden C# is the same as C++ in this aspect. I find it pretty odd that Java doesn’t allow to declare a member that’s accessible to the subclass but not the entire package. It’s sort of upside down to me – a package is broader scope than a child class! Oct 15, 2013 at 17:36 - 15 @KonradMorawski IMHO package is smaller scope than subclass. If you haven’t declared your class final, users should be able to subclass it – so java protected is part of your published interface. OTOH, packages are implicitly developed by a single organization: e.g. com.mycompany.mypackage. If your code declares itself in my package, you implicitly declare yourself part of my organization, so we should be communicating. Thus, package publishes to a smaller/easier to reach audience (people in my company) than subclass (people who extend my object) and so counts as lower visibility. May 22, 2014 at 20:37 - 2 friendis good for defining special relationships between classes. It allows superior encapsulation in many cases when used correctly. For example it can be used by a privileged factory class to inject internal dependencies into a constructed type. It has a bad name because people who don’t care about correctly maintaining a well designed object model can abuse it to ease their workload. Dec 8, 2014 at 10:05 Here’s a better version of the table, that also includes a column for modules.? 7 - 22 - 7 - 12 colourblindawareness.org/colour-blindness/… … The 8% of colour blind men can be divided approximately into 1% deuteranopes, 1% protanopes, 1% protanomalous and 5% deuteranomalous. And as I am one of those 50% of that 5%, rest assured: red/green sucks. Nov 14, 2018 at 14:13 - 7 @GhostCat Ok.. that’s a larger part of the population than I expected. I uploaded the image in this color blindness simulator and tested all different modes. Even in monochromacy/achromatopsia mode the color difference is reasonable. Can you see the difference or is the simulator off? (I’m still of the opinion that red/green is very intuitive for color seeing people.) Nov 14, 2018 at 14:32 - 5 privatehides from other classes within the package. publicexposes to classes outside the package. protectedis a version of publicrestricted only to subclasses. Feb 13, 2013 at 9:56 @Tennenrishin — No ; contrary to C++, in Java protectedmakes the method also accessible from the whole package. This stupidity in Java’s visiblity model breaks the goal of protected. Aug 21, 2013 at 9:51 @Nicolas It is accessible from the whole package, with or without protected. As an access modifier, all that protecteddoes is to expose to subclasses outside the package. Mar 14, 2014 at 10:59 @tennenrishin – well, that is what Nicolas said… and you are just repeating it now. What you originally said was that protected– and I quote – ‘is a version of public restricted only to subclasses’ which is not true by your own admission since protected also allows access through the whole package (ergo, it does not restrict access to subclasses.) Apr 7, 2014 at 13:45 I also agree with Nicolas in that the protected access mode in Java is idiotic. What happened is that Java conflated horizontal (lattice) and vertical access restriction qualifiers. Default scope is a horizontal/lattice restriction with the lattice being the package. Public is another horizontal restriction where the lattice is the whole world. Private and (C++) protected are vertical. It would have been better if we had a cross-cut access, say, protected-packagefor the rare cases where we actually needed it, leaving protectedto be equivalent to the C++ version of protected. Apr 7, 2014 at 13:53 | Show 13 more comments
https://coded3.com/what-is-the-difference-between-public-protected-package-private-and-private-in-java/
CC-MAIN-2022-40
refinedweb
1,175
54.93
One of the more common questions I see on forums and get from colleagues is how to debug Error 1009, also known as the “Null Object Reference Error.” Or, as I call it, the “Annoying Mosquito Error From Hell.” It crops up a lot, and unfortunately the error itself does not contain much information about the source of the error. In this quick tip, we’ll take a look at some steps you can take to track down this mosquito and squash it good. Introduction This piece is the first followup to the more general “Fixing Bugs in AS3” tutorial. If you wish to better understand some of the techniques in this tip, you may wish to read that in full first. Step 1: Understand the Error It’s too bad that Adobe doesn’t (or can’t) provide more information about the root of this error. First of all, it’s rather obtusely worded (much like all of their errors, but this more so than most): TypeError: Error #1009: Cannot access a property or method of a null object reference Let’s try to put this in everyday terms. Error 1009 means that you’ve tried to do something with a variable that you assume has a value, but really does not. Flash doesn’t like that. You wouldn’t like it either; imagine you had a glass that you assumed was full of the tasty beverage of your choice, but really was empty. You grab the glass, expecting a refreshing swig, but you feel the disappointing weight of an empty glass instead. That’s your own personal Error 1009. In ActionScript, if you do this: var s:String; trace(s.toUpperCase()); Flash will bum hard (a technical term for “produce an error”) when you run the code. The variable s may have been declared, but its value is null (we never set the value, just declared the variable), so calling the toUpperCase method on it is troublesome. To be clear, because s is declared as a String, the compiler takes no issue with the code: there is a variable called s, it’s a String, and toUpperCase is a valid method to call on Strings. The error we get is a run-time error, which means we only get it when we run the SWF. Only when the logic is performed do we now get to see how this turns out. Step 2: Permit Debugging As with any run-time error, sometimes it’s pretty easy to tell what’s going on without any extra information. But other times it’s helpful to narrow this down further. At this point, try turning on “Permit Debugging.” When this is enabled, you get errors that also give you line numbers. Alternatively, you may be able to “Debug Movie” by pressing Command-Shift-Return / Control-Shift-Enter. To do so, see the general debugging tips article, “Fixing Bugs in AS3” Sometimes this is enough. Knowing the specific line might be all the information you needed. If not, we’ll dig a little deeper in the next step. Our dear editor, Michael James Williams, encapsulated the point of this step in a limerick, which I’m happy to present to you now with his kind permission: AS3 error one-oh-oh-nine Is never a very good sign. No need for concern, Hit Ctrl-Shift-Return And it’ll pinpoint the cause (well, the line). Step 3: Start Tracing If you’ve located the offending line but are still unsure what’s going on, pick apart the line. Take every variable in that line and trace them out prior to the error. Because the error comes when accessing a property or calling a method on a null variable, to cover your bases you should trace any variables and properties that are immediately followed by a dot. For example, take this line of code: myArray.push(someSprite.stage.align.toLowerCase()); Admittedly, that’s a rather contrived piece of code that I can’t imagine a practical use for, but you should identify four total possible null values that are being accessed with the dot: myArray: we are calling the pushmethod on this variable someSprite: we are accessing the stageproperty stage: we are accessing the alignproperty align: we are calling the toLowerCasemethod So your debugging code might look like this: trace("myArray: ", myArray); trace("someSprite: ", someSprite); trace("someSprite.stage: ", someSprite.stage); trace("someSprite.stage.align: ", someSprite.stage.align); Order is important; if someSprite is the null object, but you test for someSprite.stage.align before testing for someSprite, you end up with less definitive results. Now, common sense also plays into this. In my example, if stage exists, then align will most assuredly have a value; the Stage always has an align setting, even if it’s the default value. Typically, you’ll see something like the following: myArray: [...stuff in the array...] someSprite: [object Sprite] someSprite.stage: null Error #1009: ... Which should clue you in that the stage property is null, and now you can go about fixing it. Step 4: Finding a Solution The easiest solution is to wrap up the offending statement in an “if” block, and only run the block if the variable in question is not null. So, assuming that in our previous example, it was in fact stage that was null, we could do something like this: if (someSprite.stage) { myArray.push(someSprite.stage.align.toLowerCase()); } This test — if (someSprite.stage) — will return true if there is a value (regardless of the value), and false if it’s null. In general this notation works; you can always use if (someSprite.stage != null) if you prefer. Numbers present a slightly different situation, though. If the Number has a value of 0, then technically it has a value, but testing if (someNumberThatEqualsZero) will evaluate to false. For Numbers you can use the isNaN() function to determine if a valid numeric value is stored in a given variable. At any rate, this technique is a simple way to sidestep the error. If the variable we want to perform an operation on is not set, then don’t do the operation. If there is no tasty beverage in our glass, don’t pick up the glass. Simple enough. But that approach is only feasible if the logic is optional. If the logic is required, then perhaps you can provide a default value to the questionable variable before the error-ing operation. For example, if myArray has the potential to be null, but it’s imperative that it’s not, we can do this: if (!myArray) { myArray = []; } myArray.push(someSprite.stage.align.toLowerCase()); This will first check to see if the array is null. If it is, initialize it to an empty array (an empty array is a valid value. It may be empty, but it’s an array, and not null) before running the contrived line of code. If it’s not null, skip straight to the contrived line of code. In real-life terms, if our glass is empty, then fill it with a tasty beverage before picking it up. In addition, if myArray is an instance property of the class in which this line of code is running, you can pretty safely ensure a valid value by initializing your properties when the object initializes. What if the logic is required, but the variable in question is not so readily under our control? For example, what if our contrived line of code is required, but the questionable variable is someSprite.stage? We can’t just set the stage property; that’s controlled internally to DisplayObject and is read-only to us mere mortals. Then you may need to get crafty, and read the next step. Step 5: Dealing with a null stage There are probably an infinite number of scenarios where a given variable or property could be null. Obviously, I can’t cover them all in a Quick Tip. There is one specific situation, however, that crops up again and again. Let’s say you write some code that looks like this: public class QuickSprite extends Sprite { public function QuickSprite() { stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove); } private function onMove(e:MouseEvent):void { var color:ColorTransform = new ColorTransform(); color.color = stage.mouseX / stage.stageWidth * 0xFFFFFF; this.transform.colorTransform = color; } } Another contrived bit of code (which might induce seizures — consider yourself warned), but basically the idea is that you have a Sprite subclass and you set this as the class for a clip on the stage, using the Flash IDE. However, you decide you want to work with these QuickSprites programmatically. So you try this: var qs:QuickSprite = new QuickSprite(); addChild(qs); And you get the accursed Error 1009. Why? Because in the QuickSprite constructor, you access the stage property (inherited from DisplayObject). When the object is created entirely with code, it is not on the stage at the point that that line of code runs, meaning stage is null and you get the error. The QuickSprite gets added the very next line, but it’s not soon enough. If the instance is created by dragging a symbol out of the library and onto the stage, then there’s a little bit of magic at work behind the scenes that ensure that the instance is on the stage (that is, the stage property is set) during the constructor. So here’s what you do: you test for the existence of a value for stage. Depending on the result, you can either run the set up code right away, or set up a different event listener for when the QuickSprite does get added to the stage. stage line to a different function, and only call that function when we have a stage, then we’re set. If stage exists from the start, go ahead and run init() right away. If not, we’ll use init() as an event listener function for ADDED_TO_STAGE, at which point we will have a stage value and can run the code. Now we can use the class for either connecting to IDE Sprite or completely programmatically. This works well in document classes, too. When you run a SWF by itself, the document class has immediate access to stage. If you load that SWF into another SWF, though, the code in the document class’s initialization stack gets executed before the loaded SWF is added to the display. A similar stage-checking trick will allow you to work with the SWF as both a standalone piece and as a SWF loaded into a containing SWF. That Is All Thanks for reading this Quick Tip! I hope you are enlightened a bit about how Error 1009 occurs, and how you can debug it. Stay tuned for more Quick Tips on other common errors. Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
http://code.tutsplus.com/tutorials/quick-tip-how-to-debug-an-as3-error-1009--active-9354
CC-MAIN-2016-30
refinedweb
1,822
70.43
In Python, this code is valid: class A: def __init__(me): me.foo = 17 def print_foo(myself): print(myself.foo) def set_foo(i, v): i.foo = v self me __init__ myself print_foo i set_foo self self PEP 8 addresses this pretty clearly: Always use self for the first argument to instance methods. Always use cls for the first argument to class methods. Although remember that being the python style guide this is not enforced However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. Sometimes, like in fractions.py, it might be clearer to you to use something like a,b instead of self,other because <your specific reasons> the style guide actually lists a few reasons you might break usual convention right below the above quote:.
https://codedump.io/share/K2vBCXicd5qJ/1/naming-the-self-parameter-something-else
CC-MAIN-2018-09
refinedweb
147
66.13
All of you know WCF (Windows Communication Foundation). A WCF service can communicate with any application like Silverlight, webforms in Asp.Net, Console Application. So this article is an introduction to WCF for beginners with a simple sample Console application for communication using WCF.So, let's see step by step how to do WCF.Step 1: Go to Visual Studio 2010 – crete a new website; select WCF service; give it a name.Step 2: Go to Iservice.cs and write this code:{ [OperationContract] int Add(int a, int b); [OperationContract] int Mul(int a, int b); }Step 3: Now go to Service .cs and write this one:{ public int Add(int a, int b) { return a + b; throw new NotImplementedException(); } public int Mul(int a, int b) { return a * b; throw new NotImplementedException(); } }Step 4: Now add a Console application; go to file on IDE; add New project; Console application.Step 5: Go to the Console application and right-click; add a service reference; use the Discover option; click on Discover; give a namespace like SR.Step 6: Now write this code in the program.cs:{ public int Add(int a, int b) { return a + b; throw new NotImplementedException(); } public int Mul(int a, int b) { return a * b; throw new NotImplementedException(); }}Step 7: Run the Application. WCF Address Types and Formats Uploading a File Using WCF REST Service Please elaborate more step-5. in discover tab nothing appera :( can nt proceed further.... see maybe u create console application,right,now do 1 thing,whenever add console app in right click and add service refrence there two option reference also bt dont select that ok.when u select service reference then give some namespace SR u can give any name that u have access in console app Good article, but could you elaborate more on steps 5-7? How I should code this console application?
http://www.c-sharpcorner.com/uploadfile/0b8108/wcf-application-communicate-with-console-application/
CC-MAIN-2013-20
refinedweb
317
62.27
SymPy 0.7.0¶ 28 Jun 2011 Major Changes¶ - this report) - A lot of stuff was being imported with from sympy import *that shouldn’t have been (like sys). This has been fixed. - Assumptions: - Concrete -, sympy/sympy#4877) - Major changes to factoring of integers (see 273f450, sympy/sympy#5102) - Optimized .has()(see c83c9b0, sympy/sympy#5079, d86d08f) - Improvements to power (see c8661ef, sympy/sympy#5062) - e.g. sympy/sympy#4871, sympy/sympy#5098, sympy/sympy#5091, sympy/sympy#5086) - isympy - Logic - implies object adheres to negative normal form - Create new boolean class, logic.boolalg.Boolean - Added XOR operator (^) support - Added If-then-else (ITE) support - Added the dpll algorithm - Functions: -, sympy/sympy#5221 - sympy/sympy#5223) - Improvements to Gruntz algorithm - Simplify: - Solvers: - report, 3383aa3, 7ab2da2, etc) Compatibility breaks¶ - sympy/sympy#4029) - Renamed sum()to summation()(see 3e763a8, sympy/sympy#4475, sympy/sympy#4826). This was changed so that it no longer overrides the built-in sum(). The unevaluated summation is still called Sum(). - Renamed abs()to Abs()(see 64a12a4, sympy/sympy#4826)., sympy/sympy#5252) - Changed behaviour of symbols(). symbols('xyz')gives now a single symbol ( 'xyz'), not three ( 'x', 'y'and 'z') (see f6452a8). Use symbols('x,y,z')or symbols('x y z')to get three symbols. The each_charoption. Use the cancel()function instead. - The assume_pos_realoption to logcombine()was renamed to forceto be consistant with similar forceoptions to other functions..
https://diofant.readthedocs.io/en/latest/release/notes-0.7.0.html
CC-MAIN-2019-13
refinedweb
232
58.69
episode, we'll take a tour of Dijit, Dojo's UI library. What is Dijit? So, what exactly is Dijit? According to the docs, "Dijit is Dojo's UI Library." It builds on what we've seen in Dojo Core and it's very extensive: pretty much every UI widget you can think of is available. And, if you want to build your own, specialized widget, that's certainly possible. If you're following along with the Premium screencast, we'll be building a Tuts+ widget. So, if you're not a Premium member, now's a good time to sign up. Dijit is Dojo's UI Library For terminology's sake, remember that Dijit is the namespace under which Dojo's UI widgets live. Here's how this is going to go down: just showing you how to use a bunch of Dijits would be akin to showing you how to use a bunch of jQuery plugins. Of course, Dijits aren't really comparable to jQuery plugins, but the point stands: once you've used one, you've used 'em all (caveats aside). So, we'll be talking about the diverse and sundry ways to create and use Dijits. Then, we'll take a brief look at some specific Dijits, just to whet your appetite. Of course, we'll need to use some Dijits as examples while we learn. We'll keep it basic and use a plain button widget. Why Should I Use Dijit? After you learn how to use widgets, you might think it's a lot easier to not use many of them; after all, why not just use the <button> element, instead of the button widget? There are a couple of reasons to consider here: - Theming: by using Dijit widgets, you'll be able to use Dojo's built-in themes. Four themes are included with the toolkit; or, you can make your own or find others online. Simply add link in the theme CSS file, add the theme name as a body class, and all your widgets are given matching uniforms. Ten-hut! - Accessibility: All widgets (at least, the "blessed" ones, distributed with the Dojo toolkit) are made for accessibility. They've got high-contrast themes, keyboard accessibility, and are screen reader friendly. - Internationalization: Widgets are also made to work well with any language, text-direction, and representation (think numbers and dates). So, now that you know the benefits of using Dijit, let's learn how to use it. How do I Use Dijit? There are two ways to instantiate widgets: the programmatic way, and the declarative way. Dijit widgets are actually just Dojo classes that inherit from Dijit._Widget, and often Dijit._Templated. I know we haven't discussed Dojo's object-oriented side, and we won't be able to in this session (you'll learn some in the Premium screencast), but just know that Dojo can make JavaScript classes. Of course, they aren't really classes, they're JavaScript constructor functions; however, you can flex some serious OO muscle with Dojo's methods. So, back to widgets. There are two ways to instantiate widgets: the programmatic way, and the declarative way. If you've used UI widgets in other libraries, you're probably familiar with the programmatic method: put some widget markup up in your HTML, and interact with it from the JavaScript. Let's try it! I'll assume you've set up a working page, loading Dojo from a CDN, as we have before. So, let's make a Dijit button. Before we start, you'll definitely want to make sure you have a theme loaded; otherwise, your widgets will stick out like nobody's business. <link rel="stylesheet" href="" /> That's the Claro theme; you can replace both instances of "claro" with "tundra," "soria," or "nihilo." to try the other bundled themes. To use the loaded theme, you'll have to add the theme's name as a class on your <body> (technically, it doesn't have to be the <body>, but some element that is a parent of any widgets that should be themed.) Now that our theme is loaded, let's programmatically create a button. First, we'll add the button markup to our document: <button id="btn" type="submit">Click Me!</button> Now, let's instantiate this in our JavaScript. dojo.require("dijit.form.Button"); dojo.ready(function () { var btn = new dijit.form.Button({ onClick: handleClick}, "btn"); }); function handleClick () { alert("clicked"); } The dijit.formnamespace includes any form widgets you might need. We have to load the file containing the widget class before we can use; then, we can instantiate the button with new dijit.form.Button. Notice that the "class" (constructor function) is stored at the same "path" we required. While this isn't forced technically, it's very much the standard way to do it. The exception to that is when a single file loads multiple classes: this "dojo.form.Button" file is a great example: it loads dijit.form.Button, dijit.form.ComboButton, dijit.form.DropDownButton, and dijit.form.ToggleButton. Let's look a little more closely at the parameters we've passed to dijit.form.Button. In this case, we've passed an object, and a string, which is the id of the widget node in our DOM; we could instead have passed a reference to the node itself, if we wanted to. Of course, any widget options can be set in that first parameter object; here, we're setting the click handler via the onClick option. You've probably figured this out by now, but know that the dijit.form namespace includes any form widgets you might need. Now, load up the page and you should see something like this: Behold, a programmatically-created, Claro-themed, Dijit button. That wasn't too hard, now, was it? Now, open your browser console and check out the DOM; specifically, look at that <button> node. You'll see that our instantiation have removed our node and replaced it with a <span> with child <span>s, all with many attributes. This is part of how Dijit widgets work: more often than not, they replace the nodes you have with a template of their own. In fact, if we left out the second parameter (the id string or DOM node reference), the new nodes would be made, but just not injected into the DOM. Then, we could place it ourselves: var btn = new dijit.form.Button({ label: "Hello" }); dojo.place(btn.domNode, dojo.body()); Notice that we give the button a label (otherwise, it would be blank); then, our dijit.form.Button instance has a domNode property that reference the nodes it created for itself. So, if we can do it this way, and Dijit gets rid of our initial nodes anyway, why not always do it this way? Well, don't forget that you want your app to work without JavaScript. If you have the nodes in the DOM, you have a basic experience for people with JavaScript turned off. Then, Dojo will replace that with the better experience if it can. Of course, the other benefit is that using hard-coded DOM nodes does fill a lot of the default parameters, depending on widget class, of course. As we saw, when we didn't use a node, we have to define a label property to get text in the button. All this seems pretty natural, right? If you've used UI widgets in other libraries, this seems pretty run-of-the-mill. However, Dojo ups the ante by allowing you to put all the properties for the widget in your HTML. This is that declarative way of which I spoke. Here's how you do it. Remove the JavaScript we'd written previously, leaving only this: dojo.require("dijit.form.Button"); function handleClick () { alert("clicked"); } Now, fix up our <button> element so that it looks like this: <button id="btn" type="submit" data-Click Me!</button> We've added HTML5 data-* attributes to our <button>: data-dojo-type and data-dojo-props. I think you're starting to see how these are related: the type is the widget class "path"; the props are the properties, in key-colon-value-comma format. What does this do? It instantiates our widget for us. Since we aren't creating it in our JS, the data-dojo-id attribute gives us a change to create a variable that points to the widget instance. Notice, it can be as a property of an object, if you want. Not so fast though. Dojo isn't magic after all, so we do have to let it know that we want it to parse out any widgets declared in our HTML when the library loads. Of course, it will only find widgets whose class we have dojo.required. The most common way to do this is to set parseOnLoad: true in your djConfig. Let's take a quick detour and talk about djConfig. This objects sets a few configuration options for Dojo; besides parseOnLoad, there are a number of debugging, localization, and resource-finding settings. There are three ways of settings djConfig. First, you can make a custom build of Dojo, which is beyond the scope of this session. Second, you can create a global djConfig object; if you do this, you have to be sure that it appears before the Dojo base file is loaded. <script>djConfig = { parseOnLoad: true };</script> <script src=""></script> The other way, which is much more common, is to use the data-dojo-config property on the script node that loads Dojo Base: <script src="" data-</script> So djConfig: it's the most common way to parse declared widgets. The other way is to manually call the method that parseOnLoad calls: dojo.parser.parse(). This will parse your HTML, find the widgets and create them. We're just about done with our general overview of how Dijit widgets are used, so I want to wrap up a few loose ends. First, note that all the HTML5 data-* goodness ain't always been so. Dojo used to use plain, non-standard attributes, and will still accept them. So, instead of data-dojo-type, you would use dojoType. Instead of data-dojo-config, you'd use djConfig. Instead of data-dojo-id, you've got jsid. And data-dojo-props was split into individual properties. So, using our button example, this: <button id="btn" type="submit" data-Click Me!</button> Would be, with old, non-standard attributes, this: <button id="btn" type="submit" dojoType="dijit.form.Button" onClick="handleClick" iconClass="dijitIconCopy" jsid="my.btn">Click Me!</button> Notice how onClick and iconClass are two separate properties in old-style. Both these styles work, but I'll be sticking with the HTML5 attributes. Second, I'll note that if you don't set a property when you create a widget, you can do so with the widget instance's set method: var btn = new dijit.form.Button({}); btn.set("label", "Click here!"); btn.set("onClick', function () { alert("clicked!"); }); There's also a get method, so retrieve your properties; of course, this works with those read-only properties, too. And the watch method is pretty cool: pass it the property you want to watch, and then a function: if that property is changed, your function will get called: var btn = new dijit.form.Button({}, "btn"); btn.set("onClick", function () { this.set("label", "clicked") }); btn.watch("label", function (property, oldValue, newValue) { alert("Property " + property + " was changed from " + oldValue + " to " + newValue + "."); }); I sure was caught off guard by declaratively creating widgets and I'm still not exactly sure how I feel about it. Of course, there are other methods and properties that widgets have in common, as well as widget-specific ones; we can't cover them all here, of course, but skip to the end if you can't wait for some tips on learning about the specific widgets of your choice. Finally, what do you think of this declarative way of creating widgets? I sure was caught off guard when I first saw it, and I'm still not exactly sure how I feel about it. With the programmatic way—the way every other library I've seen does it—you have to either match up HTML and JavaScript (which requires work in two places) or place new nodes from the JavaScript (which isn't no-JS-friendly). The benefit of the declarative method is that all the information about a widget is in one place; the UI and the logic. However, is that what you want? I've done a bit of desktop programming, but from what I've seen on both Windows and Mac, UI and logic are separated, in different files even. So it's not like this is a throwback to anything. In any case, you've got the power to do it however you want. Choose wisely . . . A Dijit Amuse-boche Let's wrap this tutorial up by looking at a couple of Dijit widgets, and then talk about how you can learn to use 'em practically. Remember, however I show you the widgets, they can be created in declaratively or programmatically. dijit.ColorPalette Exactly what it says, this is a simple little colour picker. <div id="colors"></div> <p>The selected colour is <span id="selectedColor"></span>.</p> dojo.require("dijit.ColorPalette"); dojo.ready(function () { var selectedColorEl = dojo.byId("selectedColor"), colors = new dijit.ColorPalette({ onChange : function () { selectedColorEl.innerHTML = this.value; } }, "colors"); }); This is a good example of a widget that takes very little information from a DOM node, unless you give it the Dojo attributes. It's also a good example of how you can work with widgets that accept / set some kind of value (like a dijit.form.FilteringSelct and dijit.form.verticalSlider). dijit.Editor A rich text editor: this is a good example of how easy Dijit makes creating complex UI pieces a breeze. <div id="editor" data-</div> <button data- Get Text </button> dojo.require("dijit.Editor"); dojo.require("dijit.form.Button"); dojo.parser.parse(); function handleEditor () { dojo.create("div", { innerHTML: editor.value }, dojo.byId("main"), "last"); editor.set("value", ""); // editor.value = "" doesn't clear the text } Note, I probably wouldn't ever connect an event handler via an attribute in real life; however, it's a good example of Dojo's flexibility. dijit.ProgressBar A handy progress bar, useful when doing lengthy AJAX stuff or heavy calculating action: <div id="progbar"></div> dojo.require("dijit.ProgressBar"); dojo.ready(function () { var progbar = new dijit.ProgressBar( { maximum: 150 }, "progbar"); function updateProgressBar() { progbar.set("value", parseInt(progbar.get("value")) + 1); if (progbar.get("value") === 150) { progbar.set("label", "Complete!"); } else { setTimeout(updateProgressBar, 100); } } updateProgressBar(); }); Learning More For the most part, you'll learn by osmosis butwhen you're ready to dive deeper, you'll want to check out the API docs. Of course there are a ton of Dijits; I can't teach you to use them all. So, let's close up by looking at how you can learn to use the widgets your hankering after. For the most part, you'll learn by osmosis (isn't that the way most dev work is, though?). For example, while reading the reference guide page for dijit.ColorPalette, I learned that most widgets that set some value have an onChange event. In fact, the reference guides are the first of the two best places to get documentation for Dijits. If you head over to the Dojo documentation page, you'll see three links: Tutorials, Reference Guides, and API Documentation. The tutorials are listed on that page, and they're great, but we're interested in the reference guides and API docs. So, click Reference Guides, and then Dijit on the right sidebar. Here's a great place to start when you're trying to figure out how to use a widget; most articles give you examples of both programmatic and declarative creation, as well as common properties. If you're ready to dive deeper, though, you'll want to check out the API docs. This neat web app is Dojo Documentation: The Complete Series. Navigate the namespaces on the left, and you'll get all the details on the right. This can be somewhat cryptic when you're starting, though, so certainly default to the reference guides. Of course, Googling "Dijit <widget-name> tutorial" often serves up something tasty. Conclusion And that's a wrap for this third episode of Dig into Dojo. If you're interested in creating a widget of your own, you'll want to check out the premium screencast that goes with this tutorial. Otherwise, I'll see you in the final episode of Dig into Dojo, where we'll discuss Dojox.
http://code.tutsplus.com/tutorials/dig-into-dojo-dijit--net-23198
CC-MAIN-2014-15
refinedweb
2,801
64.91
This is an excerpt from Learning IPython for Interactive Computing and Data Visualization, second edition. Previously in this Chapter 3, we analyzed trip and fare data of nearly one million NYC taxi journeys. Here, we make a density plot of evening trips in Manhattan. In order to run this notebook locally, you'll need to download the nyc_taxidataset from the data repo, and extract it to ../chapter2/data/nyc_data.csv(or just change the path in the second code cell below). We now get to the substance of array programming with NumPy. We will perform manipulations and computations on ndarrays. Let's first import NumPy, pandas, matplotlib, and seaborn: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import matplotlib; matplotlib.rcParams['savefig.dpi'] = 144 We load the NYC taxi dataset with pandas: data = pd.read_csv('../chapter2/data/nyc_data.csv', parse_dates=['pickup_datetime', 'dropoff_datetime']) We get the pickup and dropoff locations of the taxi rides as ndarrays, using the .values attribute of pandas DataFrames: pickup = data[['pickup_longitude', 'pickup_latitude']].values dropoff = data[['dropoff_longitude', 'dropoff_latitude']].values pickup array([[-73.955925, 40.781887], [-74.005501, 40.745735], [-73.969955, 40.79977 ], ..., [-73.993492, 40.729347], [-73.978477, 40.772945], [-73.987206, 40.750568]]) Let's illustrate selection and indexing with NumPy. These operations are similar to those offered by pandas on DataFrame and Series objects. In NumPy, a given element can be retrieved with pickup[i, j], where i is the 0-indexed row number, and j is the 0-indexed column number: print(pickup[3, 1]) 40.755081 A part of the array can be selected with the slicing syntax, which supports a start position, an end position, and an optional step, as shown here: pickup[1:7:2, 1:] array([[ 40.745735], [ 40.755081], [ 40.768978]]) Here, we've selected the elements at [1, 1], [3, 1], and [5, 1]. The slicing syntax in Python is start:end:step where start is included and end is excluded. If start or end are omitted, they default to 0 or the length of the dimension, respectively, whereas step defaults to 1. For example, 1: is equivalent to 1:n:1 where n is the size of the axis. Let's select the longitudes of all pickup locations, in other words, the first column: lon = pickup[:, 0] lon array([-73.955925, -74.005501, -73.969955, ..., -73.993492, -73.978477, -73.987206]) The result is a 1D ndarray. We also get the second column of pickup: lat = pickup[:, 1] lat array([ 40.781887, 40.745735, 40.79977 , ..., 40.729347, 40.772945, 40.750568]) Let's now illustrate filtering operations in NumPy. Again, these are similar to pandas. As an example, we're going to select all trips departing at a given location: lon_min, lon_max = (-73.98330, -73.98025) lat_min, lat_max = ( 40.76724, 40.76871) In NumPy, symbols like arithmetic, inequality, and boolean operators work on ndarrays on an element-wise basis. Here is how to select all trips where the longitude is between lon_min and lon_max: in_lon = (lon_min <= lon) & (lon <= lon_max) in_lon array([False, False, False, ..., False, False, False], dtype=bool) The symbol & represents the AND boolean operator, while | represents the OR. Here, the result is a Boolean vector containing as many elements as there are in the lon vector. How many True elements are there in this array? NumPy arrays provide a sum() method that returns the sum of all elements in the array. When the array contains boolean values, False elements are converted to 0 and True elements are converted to 1. Therefore, the sum corresponds to the number of True elements: in_lon.sum() 69163 We can process the latitudes similarly: in_lat = (lat_min <= lat) & (lat <= lat_max) Then, we get all trips where both the longitude and latitude belong to our rectangle: in_lonlat = in_lon & in_lat in_lonlat.sum() 3998 The np.nonzero() function returns the indices corresponding to True in a boolean array, as shown here: np.nonzero(in_lonlat)[0] array([ 901, 1011, 1066, ..., 845749, 845903, 846080]) Finally, we'll need the dropoff coordinates in the following: lon1, lat1 = dropoff.T This is a more concise way of writing lon1 = dropoff[:, 0]; lat1 = dropoff[:, 1]. The T attribute corresponds to the transpose of a matrix, which simply means that a matrix's columns become the corresponding rows of a new matrix, just as the new columns are the original matrix's rows. Here, dropoff.T is a (2, N) array where the first row contains the longitude and the second row contains the latitude. In NumPy, an ndarray is iterable along the first dimension, in other words, along the rows of the matrix. Therefore, the syntax unpacking feature of Python allows us to concisely assign lon1 to the first row and lat1 to the second row. We have the coordinates of all pickup and dropoff locations in NumPy arrays. Let's compute the straight line distance between those two locations, for every taxi trip. There are several mathematical formulas giving the distance between two points given by their longitudes and latitudes. Here, we will compute a great-circle distance with a spherical Earth approximation. The following function implements this formula. EARTH_R = 6372.8 def geo_distance(lon0, lat0, lon1, lat1): """Return the distance (in km) between two points in geographical coordinates.""" # from: # and: We have made extensive use of trigonometric functions provided by NumPy: np.radians() (converting numbers from degrees into radians), np.cos(), np.sin(), np.arctan2(x, y) (returning the arctangent of x/y), and so on. These mathematical functions are defined on real numbers, but NumPy provides vectorized versions of them. These vectorized functions not only work on numbers but also on arbitrary numerical ndarrays. As we have explained earlier, these functions are orders of magnitude faster than Python loops. You will find the list of mathematical functions in NumPy at. All in all, NumPy makes it quite natural to implement mathematical formulas on arrays of numbers. The syntax is exactly the same as with scalar operations. Now, let's compute the straight line distances of all taxi trips: distances = geo_distance(lon, lat, lon1, lat1) Below is a histogram of these distances for the trips starting at Columbus Circle (the location indicated by the geographical coordinates above). Those trips are indicated by the in_lonlat boolean array obtained earlier in this section. plt.hist(distances[in_lonlat], np.linspace(0., 10., 50)) plt.xlabel('Trip distance (km)') plt.ylabel('Number of trips') <matplotlib.text.Text at 0x113d36780> matplotlib's plt.hist() function computes a histogram and plots it. It is a convenient wrapper around NumPy's np.histogram() function that just computes a histogram. You will find more statistical functions in NumPy at. We have reviewed the most common array operations in this section. We will now see a more advanced example combining several techniques. We will compute and display a 2D density map of the most common pickup and dropoff locations, at specific times in the day. First, let's select the evening taxi trips. This time, we use pandas, which offers particularly rich date and time features. We eventually get a NumPy array with the .values attribute: evening = (data.pickup_datetime.dt.hour >= 19).values n = np.sum(evening) n 242818 TIP (Pandas and NumPy): Remember that pandas is based on NumPy, and that it is quite common to leverage both libraries in complex data analysis tasks. A natural workflow is to start loading and manipulating data with pandas, and then switch to NumPy when complex mathematical operations are to be performed on arrays. As a rule of thumb, pandas excels at filtering, selecting, grouping, and other data manipulations, whereas NumPy is particularly efficient at vector mathematical operations on numerical arrays. The n variable contains the number of evening trips in our dataset. Here is how we are going to create our density map: We consider the set of all pickup and dropoff locations for these n evening trips. There are 2n of such points. Every point is associated with a weight of -1 for pickup locations and +1 for dropoff locations. The algebraic density of points at a given location, taking into account the weights, reflects whether people tend to leave or to arrive at this location. To create the weights vector for our 2n points, we first create a vector containing only zeros. Then, we set the first half of the array to -1 (pickup) and the last half to +1 (dropoff): weights = np.zeros(2 * n) weights[:n] = -1 weights[n:] = +1 INFO (Indexing in NumPy): Indexing in Python and NumPy starts at 0, and excludes the last element. The first half of weightsis made of weights[0], weights[1], up to weights[n-1]. There are nof such elements. The slice weights[:n]is equivalent to weights[0:n]: it starts at weights[0], and ends at weights[n]excluded, so the last element is effectively weights[n-1]. We could also have used array manipulation routines provided by NumPy, such as np.tile() to concatenate copies of an array along several dimensions, or np.repeat() to make copies of every element along several dimensions. You will find the list of manipulation functions at. Next, we create a (2n, 2) array defined by the vertical concatenation of the pickup and dropoff locations for the evening trips: points = np.r_[pickup[evening], dropoff[evening]] points.shape (485636, 2) The concise np.r_[] syntax allows us to concatenate arrays along the first (vertical) dimension. We could also have used more explicit manipulation functions such as np.vstack() or np.concatenate(). Now, we convert these points from geographical coordinates to pixel coordinates, using the same function as in the previous chapter. def lat_lon_to_pixels(lat, lon): lat_rad = lat * np.pi / 180.0 lat_rad = np.log(np.tan((lat_rad + np.pi / 2.0) / 2.0)) x = 100 * (lon + 180.0) / 360.0 y = 100 * (lat_rad - np.pi) / (2.0 * np.pi) return (x, y) lon, lat = points.T x, y = lat_lon_to_pixels(lat, lon) We now define the bins for the 2D histogram in our density map. This defines a 2D grid over which to compute the histogram. lon_min, lat_min = -74.0214, 40.6978 lon_max, lat_max = -73.9524, 40.7982 x_min, y_min = lat_lon_to_pixels(lat_min, lon_min) x_max, y_max = lat_lon_to_pixels(lat_max, lon_max) bin = .00003 bins_x = np.arange(x_min, x_max, bin) bins_y = np.arange(y_min, y_max, bin) These two arrays contain the horizontal and vertical bins. Finally, we compute the histogram with the np.histogram2d() function. We pass as arguments the y, x coordinates of the points (reversed because we want the grid's first axis to represent the y coordinate), the weights, and the bins. This function computes a weighted sum of the points, in every bin. It returns several objects, the first of which is the density map we are interested in: grid, _, _ = np.histogram2d(y, x, weights=weights, bins=(bins_y, bins_x)) You will find the reference documentation of this function at. Before displaying the density map, we will apply a logistic function to it in order to smooth it: density = 1. / (1. + np.exp(-.5 * grid)) This logistic function is called the expit function. It can also be found in the SciPy package at scipy.special.expit(). scipy.special provides many other special functions such as Bessel functions, Gamma functions, hypergeometric functions, and so on. Finally, we display the density map with plt.imshow(): plt.figure(figsize=(8, 8)) plt.imshow(density, origin='lower', interpolation='bicubic' ) plt.axis('off') plt.tight_layout() matplotlib's plt.imshow() function displays a matrix as an image. It supports several interpolation methods. Here, we used a bicubic interpolation. The origin argument is necessary because in our density matrix, the top-left corner corresponds to the smallest latitude, so it should correspond to the bottom-left corner in the image. We only scratched the surface of the possibilities offered by NumPy. Further numerical computing topics covered by NumPy and the more specialized SciPy library include: The IPython Cookbook covers many of these topics. Here are a few references:
http://nbviewer.jupyter.org/github/ipython-books/minibook-2nd-code/blob/master/chapter3/34-computing.ipynb
CC-MAIN-2018-13
refinedweb
2,007
58.08
Opened 3 years ago Closed 3 years ago Last modified 3 years ago #26566 closed Bug (fixed) Wrong example of Cache-Control in the docs Description Django’s caching docs provide the following example of setting the Cache-Control header: In this example, cache_controltells caches to revalidate the cache on every access and to store cached versions for, at most, 3,600 seconds: from django.views.decorators.cache import cache_control @cache_control(must_revalidate=True, max_age=3600) def my_view(request): # ... This is wrong. What it really tells caches is: - max-age=3600: the response is “fresh,” and can be served directly from cache (without revalidation), for 3600 seconds; - must-revalidate: after these 3600 seconds, when the response becomes “stale,” it cannot be served from cache (without revalidation) even if otherwise that would be allowed, such as when the cache is disconnected from the network. In my tests, with these directives, both Chrome and Firefox serve the page from cache after the first access. The right directive for “revalidate on every access” is no-cache. And as far as I know, there is no directive to limit the time for which a response is stored; only the no-store directive that forbids storage entirely. Change History (7) comment:1 Changed 3 years ago by comment:2 follow-up: 3 Changed 3 years ago by I don't understand why correcting the description of the existing example isn't a good idea? comment:3 Changed 3 years ago by I don't understand why correcting the description of the existing example isn't a good idea? Because readers won’t see the motivation for such an example. Normally max-age is set automatically by the caching middleware, and when people want to prevent caching, they just use @never_cache. Maybe something along these lines would work: Even if you’re not using Django’s server-side caching features, you can tell clients to cache a view for a certain amount of time: from django.views.decorators.cache import cache_control @cache_control(max_age=3600) def my_view(request): # ... comment:4 Changed 3 years ago by Sure, feel free to submit a pull request as you see fit. I can’t come up with a correct example that would also be convincing. Maybe it’s best to remove the example and just mention that you can directly set Cache-Controlwith that decorator.
https://code.djangoproject.com/ticket/26566
CC-MAIN-2018-51
refinedweb
393
57.5
- NAME - SYNOPSIS - DESCRIPTION - CONFIGURATION - METHODS - namespace - config - request - response - dispatch - log - egg_startup ( [CONFIG_HASH] ) - is_model ( [MODEL_NAME] ) - is_view ( [VIEW_NAME] ) - models - views - model_class - view_class - regist_model ( [MODEL_NAME], [PACKAGE_NAME], [INCLUDE_FLAG] ) - regist_view ( [VIEW_NAME], [PACKAGE_NAME], [INCLUDE_FLAG] ) - default_model ( [MODEL_NAME] ) - default_view ( [VIEW_NAME] ) - model ( [MODEL_NAME] ) - view ( [VIEW_NAME] ) - run - stash ( [KEY_NAME] ) - flag ( [FLAG_NAME] ) - path ( [CONF_KEY], [PATH] ) - uri_to ( [URI], [ARGS_HASH] ) - page_title ( [TITLE_STRING] ) - finished ( [RESPONSE_STATUS], [ERROR_MSG] ) - snip - action - debug - mp_version - debug_out ( [MESSAGE] ) - OPERATION METHODS - SUPPORT - SEE ALSO - AUTHOR NAME Egg - WEB Application Framework. SYNOPSIS # The helper script is generated. perl -MEgg::Helper -e 'Egg::Helper->out' > egg_helper.pl # The project is generated. perl egg_helper.pl Project MyApp # Confirming the operation of project. ./MyApp/bin/tirigger.cgi # The project object is acquired. use lib './MyApp/lib'; require MyApp; my $e= MyApp->new; DESCRIPTION Egg is WEB application framework. The composition of the module operates at comparatively simply and high speed. It is MVC framework of model and view and controller composition. * It was a plug-in etc. and there were Catalyst and some interchangeability in the version before. Interchangeability was completely lost from the change of the method name in this version. However, there might not be transplant in the difficulty. CONFIGURATION The setting of the configuration of Egg is a method of passing HASH to the method of 'egg_startup' directly and the definition. There is a method to read to a semiautomatic target by it and 'Egg::Plugin::ConfigLoader'. Please refer to the document of Egg::Plugin::ConfigLoader for details. root Route PATH of project. * It is not route PATH of the template. * There is no default. Please set it. title Title of project. Default is a class name of the project. content_type Contents type used by default. Default is 'text/html'. content_language Language used by default There is no default. template_extention Extension of template used by default. * There is no '.' needing. Default is 'tt'. template_default_name Template name used by default. Default is 'index'. static_uri Route URI for static contents. * Please end by '/'. Default is '/'. template_path Passing for template. * The thing set by the ARRAY reference can be done. * There is no default. Please set it. dir PATH setting of various folders. lib Local PATH where library of project is put. Default is '< $e.root >/lib'. static Local PATH where static contents are put. Default is '< $e.root >/htdocs'. etc For preservation of configuration file etc. Default is '< $e.root >/etc'. cache For preservation of cash data. Default is '< $e.root >/cache'. template The main template depository. Default is '< $e.root >/root'. comp Template depository for include. Default is '< $e.root >/comp'. tmp Temporary work directory PATH. Default is '< $e.root >/tmp'. lib_project Project directory PATH in dir->{lib}. Egg compulsorily sets it based on the value of dir->{lib}. root Copy of root. accessor_names The accessor to stash is generated with the set name. MODEL It is a setting of MODEL. As for the content, the setting of each MODEL becomes ARRAY further by ARRAY, too. The setting of the first is treated as MODEL of default. MODEL => [ [ DBI => { dsn => '.....', user => '...', ... } ], ], VIEW It is a setting of VIEW. As for the content, the setting of each VIEW becomes ARRAY further by ARRAY, too. The setting of the first is treated as VIEW of default. VIEW => [ [ Mason => { comp_root => [ ... ], data_dir => '...', } ], ], ... others. Please refer to the module document of each object for other settings. METHODS namespace The project name under operation is returned. config Configuration is returned by the HASH reference. request The request object is returned. Alias: req response The response object is returned. Alias: res dispatch The dispatch object is returned. * It is necessary to load the plug-in with the dispatch method. Egg::Plugin::Dispatch::Standard and Egg::Plugin::Dispatch::Fast are prepared by the standard. log The log object is returned. * When the plugin with the log method is not loaded, Egg::DummyLog is used. - new, notes, debug, error egg_startup ( [CONFIG_HASH] ) Necessary for operating the project prior is prepared. CONFIG_HASH is set to 'config' method. If Egg::Plugin::ConfigLoader is loaded, it is CONFIG_HASH omissible. However, it is a thing that the configuration file is arranged in an appropriate place in this case. __PACKAGE__->egg_startup; is_model ( [MODEL_NAME] ) If specified MODEL is loaded, the package name is returned. is_view ( [VIEW_NAME] ) If specified VIEW is loaded, the package name is returned. models The loaded MODEL name list is returned by the ARRAY reference. views The loaded VIEW name list is returned by the ARRAY reference. model_class The loaded MODEL management data is returned by the HASH reference. view_class The loaded VIEW management data is returned by the HASH reference. regist_model ( [MODEL_NAME], [PACKAGE_NAME], [INCLUDE_FLAG] ) The use of specified MODEL is enabled. * MODEL_NAME is not omissible. * PACKAGE_NAME is an actual package name of object MODEL. Egg::Model::[MODEL_NAME] is used when omitting it. * If INCLUDE_FLAG is true, require is done at the same time. $e->regist_model('MyModel', 'MyApp::Model::MyModel', 1); regist_view ( [VIEW_NAME], [PACKAGE_NAME], [INCLUDE_FLAG] ) The use of specified VIEW is enabled. * VIEW_NAME is not omissible. * PACKAGE_NAME is an actual package name of object VIEW. Egg::View::[VIEW_NAME] is used when omitting it. * If INCLUDE_FLAG is true, require is done at the same time. $e->regist_view('MyView', 'MyApp::View::MyView', 1); default_model ( [MODEL_NAME] ) The MODEL name of default is returned. * A high setting of the priority level defaults most and it is treated. When MODEL_NAME is specified, default is temporarily replaced. default_view ( [VIEW_NAME] ) The VIEW name of default is returned. * A high setting of the priority level defaults most and it is treated. When VIEW_NAME is specified, default is temporarily replaced. model ( [MODEL_NAME] ) The object of specified MODEL is returned. When MODEL_NAME is omitted, the MODEL object of default is returned. view ( [VIEW_NAME] ) The object of specified VIEW is returned. When VIEW_NAME is omitted, the VIEW object of default is returned. run The project is completely operated, and the result code is returned at the end. * Do not call this method from the code inside of the project. stash ( [KEY_NAME] ) The value of the common data specified with KEY_NAME is returned. When KEY_NAME is omitted, the common data is returned by the HASH reference. flag ( [FLAG_NAME] ) The value of the flag specified with FLAG_NAME is returned. path ( [CONF_KEY], [PATH] ) The result of combining the value of $e->config->{dir} specified with CONF_KEY with PATH is returned. $e->path('static', 'images/any.png'); => /path/to/myapp/htdocs/images/any.png uri_to ( [URI], [ARGS_HASH] ) The URI object generated based on [URI] is returned. The URI object of the query_form setting when ARGS_HASH is passed is returned. page_title ( [TITLE_STRING] ) The value set to $e->dispatch->page_title is returned. $e->config->{title} is returned if there is no setting. The title can be set by passing TITLE_STRING. finished ( [RESPONSE_STATUS], [ERROR_MSG] ) $e->reqonse->status is set when RESPONSE_STATUS is passed and finished is made effective. RESPONSE_STATUS is 500 or $e->log->error is done any more. At this time, if ERROR_MSG has been passed, it is included in the argument. 0 It is $e->reqonse->status(0) when is passed, and finished is invalidated. snip $e->request->snip is returned. action $e->dispatch->action is returned. debug The state of the debugging flag is returned. mp_version $Egg::Request::MP_VERSION is returned. debug_out ( [MESSAGE] ) If the debugging flag is effective, MESSAGE is output to STDERR. Nothing is done usually. OPERATION METHODS When the project module is read, Egg generates the handler method. And, dynamic contents are output from the handler method via the following method calls and processing is completed. _start_engine If $e->debug is effective, it replaces with _ start_engine_debug. After the call of each method, '_start_engine_debug' measures the execution time. This measurement result is reported to STDERR at the end of processing. _prepare_model Prior because MODEL is operated is prepared. _prepare_view Prior because VIEW is operated is prepared. _prepare It is a prior hook for the plugin. _dispatch_start It is a prior hook for dispatch. If it is effective, $e->finished has not already done anything. _dispatch_action It is a hook for correspondence action of dispatch. If it is effective, $e->finished has not already done anything. If an appropriate template has been decided, and $e->response->body is undefined, $e->view->output is done. _dispatch_finish It is a hook after the fact for dispatch. If it is effective, $e->finished has not already done anything. _finalize It is a hook after the fact for the plugin. _finalize_output If it seems to complete the output of contents that are effective $e->finished and have defined $e->response->{header}, nothing is done. Contents are output, and $e->finished is set. _finalize_error When some errors occur by '_start_engine', it is called. The plug-in for which the processing when the error occurs is necessary prepares this method. This method finally writes the log, and outputs contents for debugging. _finalize_result They are the last processing most. $e->response->result is called and the Result code is returned. SUPPORT Distribution site. L<>. sourcefoge project. L<>. SEE ALSO Egg::Base, Egg::Request, Egg::Response, Egg::Model,.
https://metacpan.org/pod/release/LUSHE/Egg-Release-2.04/lib/Egg.pm
CC-MAIN-2020-05
refinedweb
1,492
61.93
- NAME - SYNOPSIS - DESCRIPTION - IMPORTS - METHODS - SEE ALSO - BUGS - AUTHORS - LICENSE NAME AnyEvent::DNS::EtcHosts - Use /etc/hosts before DNS SYNOPSIS use AnyEvent::DNS::EtcHosts; use AnyEvent::DNS; my $cv = AE::cv; AnyEvent::DNS::any 'example.com', sub { say foreach map { $_->[4] } grep { $_->[1] =~ /^(a|aaaa)$/ } @_; $cv->send; }; use AnyEvent::Socket; my $cv = AE::cv; AnyEvent::Socket::resolve_sockaddr $domain, $service, $proto, $family, undef, sub { say foreach map { format_address((AnyEvent::Socket::unpack_sockaddr($_->[3]))[1]) } @_; $cv->send; }; DESCRIPTION AnyEvent::DNS::EtcHosts changes AnyEvent::DNS behavior. The /etc/hosts file is searched before DNS, so it is possible to override DNS entries. The DNS lookups are emulated. This resolver returns the standard DNS reply based on /etc/hosts file rather than real DNS. You can choose different file by changing PERL_ANYEVENT_HOSTS environment variable. This module also disables original AnyEvent::Socket's helper function which reads /etc/hosts file after DNS entry was not found. It prevents to read this file twice. The AnyEvent::Socket resolver searches IPv4 and IPv6 addresses separately. If you don't want to check the addresses in DNS, both IPv4 and IPv6 addresses should be placed in /etc/hosts or the protocol family should be set explicitly for resolve_sockaddr function. IMPORTS use AnyEvent::DNS::EtcHosts %args; use AnyEvent::DNS::EtcHosts server => '8.8.8.8'; $ perl -MAnyEvent::DNS::EtcHosts script.pl Enables this module globally. Additional arguments will be passed to AnyEvent::DNS constructor. no AnyEvent::DNS::EtcHosts; Disables this module globally. METHODS require AnyEvent::DNS::EtcHosts; $guard = AnyEvent::DNS::EtcHosts->register(%args); undef $guard; Enables this module in lexical scope. The module will be disabled out of scope. Additional arguments will be passed to AnyEvent::DNS constructor. If you want to use AnyEvent::DNS::EtcHosts in lexical scope only, you should use require rather than use keyword, because import method enables AnyEvent::DNS::EtcHosts globally. request $resolver->request($req, $cb->($res)) This is wrapper for AnyEvent::DNS->request method. SEE ALSO AnyEvent::DNS, AnyEvent::Socket. BUGS This module might be incompatible with further versions of AnyEvent module. If you find the bug or want to implement new features, please report it at The code repository is available at AUTHORS Piotr Roszatycki <dexter@cpan.org> Helper functions taken from AnyEvent::Socket 7.05 by Marc Lehmann <schmorp@schmorp.de> LICENSE This is free software; you can redistribute it and/or modify it under the same terms as perl itself. See
https://metacpan.org/pod/AnyEvent::DNS::EtcHosts
CC-MAIN-2015-11
refinedweb
405
58.58
Chapter 2 Learning R 2.1 Links to R tutorials There are many, many online resources available for learning how to use R. To name a few: - The R for data science book, which is a fairly enjoyable read though it focuses heavily on a specific dialect of the R language. - A free course from Codecademy, which uses a web-based console; this allows people to start learning without actually installing R on their own computers. - A free course from EdX, which focuses on the use of R’s statistical functionality. - An Introduction to R, a definitive description of R that is best read after some basic familiarity has been established. We will not attempt to repeat the contents of these resources here, as they already do a good job of explaining themselves. 2.2 Code formatting This book contains code chunks interspersed with results, plots and explanatory text. Code chunks contain R code that is to be evaluated, and interested readers can copy-paste these lines into the R console to try it out themselves. Each code chunk looks like this: Terms are colored differently depending on their category - this is mostly aesthetic and can be ignored for the time being. If a code chunk produces any visible output, it is shown in another chunk like so: ## [1] 10 Alternatively, as a figure: Any text after a # is considered a comment and is ignored when running the code. The content of output chunks is always prefixed with # so that users can just copy-paste sections of code without having to explicitly remove the lines containing the results. In some chapters, chunks may also be hidden in collapsible boxes. This usually contains code to set up objects for later steps but is otherwise not particularly interesting (e.g., downloading files, formatting data), and so is hidden to avoid distracting the reader. All chapters will finish with a printout of the session information. This describes the system on which the chapter was compiled and the versions of all packages that were used, which is useful for reproducing old results and diagnosing changes due to package updates. 2.3 Getting help If you have a question about how a function works, it can often be answered by the function’s documentation. This is accessible by prepending the function name with ?. More general questions on how to use a package may be answered by the package’s vignette, if it is available. (One aspect of Bioconductor software that distinguishes it from CRAN packages is the required documentation of packages and workflows.) vignette(package='SingleCellExperiment') # list all available vignettes vignette(package='SingleCellExperiment', topic='intro') # open specific vignette Beyond the R console, there are myriad online resources to get help. The R for Data Science book has a great section dedicated to looking for help outside of R. For example, Stack Overflow’s R tag is a helpful resource for asking and exploring general R programming questions. For Bioconductor specifically, the support site contains a question and answer-style support site that is actively updated by both users and package developers. This should generally be the first port of call for questions that are not answered by any existing documentation. Users can also connect to the Bioconductor community through our Slack group, which hosts various channels dedicated to packages and workflows. The Bioc-community Slack is a great way to stay in the loop on the latest developments happening across Bioconductor, and we recommend exploring the “Channels” section to find topics of interest. 2.4 Beyond the basics Once comfortable with the basic concepts of the language, we take things to the next level: - Advanced R, as its name suggests, goes through some of the more advanced concepts in the language. - The aptly named What They Forgot to Teach You About R discusses topics such as file naming, maintaining an R installation, and reproducible analysis habits. - The R Inferno dives into many of the unique quirks of R and some of the common user mistakes. - Happy Git and Github for the useR, which describes how to use the Git version control system with R. Over time, you may accumulate a collection of your own functions that you might want to re-use across projects or even share with other people. This can be done easily by creating your own R package. The R Packages book provides a user-friendly guide for doing so; more experienced developers will consult Writing R extensions, the definitive documentation for the R packaging system. Bioconductor itself also provides some educational resources for package development within the Bioconductor context. Session Info R version 4.1.0 (2021-05-18) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 20.04.2 LTS Matrix products: default BLAS: /home/biocbuild/bbs-3.13-bioc/R/lib/libRblas.so LAPACK: /home/biocbuild/bbs-3.13.20.0 rebook_1.2.0 loaded via a namespace (and not attached): [1] graph_1.70.0 knitr_1.33 magrittr_2.0.1 [4] BiocGenerics_0.38.0 R6_2.5.0 rlang_0.4.11 [7] highr_0.9 stringr_1.4.0 tools_4.1.0 [10] parallel_4.1.0 xfun_0.23 jquerylib_0.1.4 [13] htmltools_0.5.1.1 CodeDepends_0.6.5 yaml_2.2.1 [16] digest_0.6.27 bookdown_0.22 dir.expiry_1.0.0 [19] BiocManager_1.30.15 codetools_0.2-18 sass_0.4.0 [22] evaluate_0.14 rmarkdown_2.8 stringi_1.6.2 [25] compiler_4.1.0 bslib_0.2.5.1 filelock_1.0.2 [28] XML_3.99-0.6 stats4_4.1.0 jsonlite_1.7.2
http://bioconductor.org/books/3.13/OSCA.intro/learning-r.html
CC-MAIN-2021-49
refinedweb
922
54.93
The best result so far was for a python module called pexpect . It has a module script.py which can script.py This implements a command similar to the classic BSD "script" command. This will start a subshell and log all input and output to a file. This demonstrates the interact() method of Pexpect. Other than that I found some code examples like this. import subprocess, os PIPE = subprocess.PIPE p = subprocess.Popen("example.exe", stdin=PIPE) p.stdin.write("10") #p.stdin.flush() p.stdin.write("\r") #This might be unecessary #p.stdin.flush() p.stdin.write("\n") #p.stdin.flush() print "End of Execution" os.system("PAUSE") So from that i determine that subprocess is the best docs to review?
http://www.dreamincode.net/forums/topic/303801-python-running-external-programs/
CC-MAIN-2018-05
refinedweb
122
55.4
I am trying to count the number of lines and characters whatever they may be in a file that I specify from argv. But I get a segmentation fault when I hit the while loop for some reason. The program runs fine without the while loop, though it only goes through once. #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if(argc != 2) { return 0; } FILE *fp; char c; int lines = 0; int chs = 0; fp = fopen(argv[1], "r"); //Segmentation Fault happens here on the while loop while((c = fgetc(fp)) != EOF) { if(c == '\n') { lines += 1; } else { chs += 1; } } printf("Charaters: %d\n", chs); printf("lines: %d\n", lines); if(fp){ fclose(fp); } return 0; } fopenimmediately, instead of after you've already attempted to use fp. fgetcreturns int, not char. This is because it needs to return side-channel information about the status of the stream (i.e. EOF), this information cannot be represented by char, but you can safely cast the intvalue to charif the value is not EOF. \ras a regular character when it is commonplace for \r\nto represent a line-break (not just a solitary \n), you might want to consider how you handle different character classes. Better: FILE* fp = fopen( argv[1], "r" ); if( !fp ) { printf( "Could not open file \"%s\" for reading.\r\n", argv[1] ); return 1; } int lines = 0; int chars = 0; int nc; while( ( nc = fgetc( fp ) ) != EOF ) { char c = (char)nc; if ( c == '\n' ) lines++; else if( c != '\r' ) chars++; } printf( "Characters: %d\r\nLines: %d\r\n", chars, lines ); fclose( fp ); return 0;
https://codedump.io/share/wbm3lQfz2EZz/1/segmentation-fault-on-my-while-loop
CC-MAIN-2017-47
refinedweb
270
81.53
Forgot your password? Or sign in with one of these services By Linguica, June 11 in Doom Eternal Thoughts? It has Arachnotrons, Pain Elementals, and what looked like Hell Knights wielding energy swords and some other new demons. Also its Hell on Earth and its not called Doom 2 (thankfully) They also said it will be revealed further at Quakecon and will also be shown online, unlike when Doom 16 was first revealed behind closed doors. Looking forward to it. Did I see an arch-vile that looks like the original Doom2 arch-vile¿¿¿¿¿¿ ARCHVILE BABY That name isn't going to be confusing at all. I enjoyed Doom 2016 a lot, so I'm really looking forward to this myself. I'm 'bout to have a whole fresh batch of desktop wallpapers I think. 7 minutes ago, Ledillman said: Did I see an arch-vile that looks like the original Doom2 arch-vile¿¿¿¿¿¿ Did I see an arch-vile that looks like the original Doom2 arch-vile¿¿¿¿¿¿ I saw it, it's true It appears that the Barons are going to have laser swords akin to the Cyberdemon, the Arch-Vile makes a glorious return (as does the Pain Elemental), Arachnotrons are back (and actually bear a resemblance to their Doom 64 version but with their plasma gun being like a scorpion's tail). Also, the Imps have more spikes and are far closer to their classic appearances (complete with red eyes). We're in for a full homecoming. I would of loved some gameplay but it looks like we will have to wait a couple months. I'm ambivalent toward it, really. I can't really form much of an opinion on it until I see gameplay firsthand. What we've seen in the teaser looks good, but teasers always look good, so I'm a little cautious about it. Doom (2016) was good, but not the best, I don't think. So, I'm going to wait to see if Eternal proves itself. Oh fuck yes give it too me now baby! *Edit For the record I thought Doom 2016 was a thoroughly enjoyable experience. The music alone made it worth the ticket price. Rip and Tear Doom Nukem Eternal? Looking forward to people looking up the game's name and then stumbling upon Eternal Doom 19 minutes ago, dobu gabu maru said: ARCHVILE BABY ARCHVILE BABY OMG, yes!!!!! Thanks for this, Dobu. Funny thing, I finally got around to buying Doom 2016. It should arrive this week, along with Wolfenstein New Order and Old Blood. I'm psyched for seeing some different environments. I also like the looks of Rage 2. But seeing Archie in Doom Eternal made my heart soar. Looking forward to this. I'm very excited about a sequel, but somehow the name just doesn't sit right with me... Im excited, hope they don't pull the same BS they did with the QuakeCon 14 reveal for the previous game It looks like the missing monsters are in the game now This is the greatest announcement in the past five hundred years. This game will be epic! And gameplay in a couple months at QuakeCon, they've been keeping busy these past two years. I mean, it has graphics. Not sure about the title, though. I think we all remember Duke Nukem Forever's fate. I think we established that those kinds of titles were cursed. Ok, I've watched the trailer 4 times and I got goose bumps every time. It seems to tick all the right boxes for the sequel. Bring in the missing monsters from Doom 2? Tick Hell on Earth? Tick Still essentially the same kick arse game? Tick tick tick. Suffice it to say I am very excited. I'm just hoping they don't fuck it up as hard as Machinegames fucked up Wolf 2... I'm really excited, hope it'll be great. A better multiplayer mode would be nice too. And that Archie looks F'ing gorgeous Arch-vile, arachnotrons, and pain elementals YESYESYESYESYESYES I am very excited, let's just say Y'know, this makes me think of an obvious update to D4D: THE ETERNAL UPDATE! Monsters will have randomizers that will spawn either their D4D versions or their Doom Eternal versions (i.e., Lightsaber Barons can spawn in place of regular ones). I am glad they are not calling it Doom 2 or Doom Hell on Earth. Doom (2016) already made Google results for classic Doom hard enough. Do Id Software realise Eternal Doom is a thing? I imagine Eternal Doom is going to get a bunch of downloads from people who confuse it with the new game. Going to be interesting to see how the Arch-vile will play out in Doom Eternal considering how the Summoner is a thing in Doom 4. Mentioning Eternal Doom reminds me that Eternal Doom IV might never be finished, unfortunately. But anyways, so far looks really promising, glad to see the Arch-Vile return! Although I wonder if we can see it reviving corpses of dead monsters since they disappear quickly in DOOM (2016). >Archvile Hunter You stay away from my glorious Archies. >8-( Damn glad to see them make a return, for a while it felt like the Summoner was going to occupy that niche for the foreseeable future and to me those didn't have as much impact. Fingers crossed that Archie kicks ass! 1 hour ago, Breezeep said: Looking forward to people looking up the game's name and then stumbling upon Eternal Doom Looking forward to people looking up the game's name and then stumbling upon Eternal Doom "This game is NOTHING like the original Eternal Doom, Id fucked up!" You need to be a member in order to leave a comment Sign up for a new account in our community. It's easy! Already have an account? Sign in here.
https://www.doomworld.com/forum/topic/101069-doom-eternal-is-a-game-that-exists/
CC-MAIN-2018-26
refinedweb
992
82.04
Define the models of your RSS reader Once the project is created, we can focus on its features. Now, we can define our first User Story. In the purpose of our project, we’ll want to follow RSS feeds. We’ll need to inform our software about those feeds. Usually, the first User Story is “I want to see a form to submit my data“. Usually, to complete this User Story, developers focus on the form. That is not the approach with Django. The data is most important than the form, so we’ll start with the data, Django will make the rest much easier. Django also makes the data manipulation easy with the Model Layer. This is the abstraction layer where you are going to define and manipulate your data model. So first we have to define and tell Django what our data is. At this step, we plan to build an app which will load, parse and display RSS feeds. So, the system will need to know where to find the feeds, and then to parse all the items. The user should just have to provide the URL of the feed. This will be our first model and form. A very simple model which will let us see how Django deals with it. Creating our first model We will create a model (a class definition) for the URL of one feed. This model will have three fields: the URL of course, a human readable name and the last updated date. Edit the models.py file in the reader package as follow : from django.db import models class SourceUrl(models.Model): name = models.CharField(max_length = 100) url = models.URLField(max_length = 200); lastVisited = models.DateTimeField(auto_now = True) For the best understanding of the models, there are two important pages in the documentation: the one explaining the models, and the one explaining the fields. What you must remember is that each model is a class that subclasses django.db.models.Model. Thus, each attribute represents a database field. So, a model is just a class with attributes ? No, Models are real classes and you can use methods. It is a good practice to redefine the __unicode__ method of your classes. Lets do it. from django.db import models class SourceUrl(models.Model): name = models.CharField(max_length = 100) url = models.URLField(max_length = 200); lastVisited = models.DateTimeField(auto_now = True) def __unicode__(self): return self.name The attributes are the most important elements of a model. A model defines a table in the database and its attributes defines the fields. You can see that all the attributes defined here are represented by instances of Field classes, and each type of field tells Django what type of data the field holds. We also gave some arguments to each field. Some are required, others are optional. For instance, the max_length is required as it will be used for the database schema and for data validation. Once again, to get the entire list of fields available and their arguments, you can check the documentation’s reference. As homework, you can modify this model to fit other constraints you may see. Creating the database table With this model declared and the application activated, Django is available to create a database-access API to access the objects in the database. But at this point, there is no sourceurl table in the database. Django can create it automatically for you. You remember the last command we run in the previous post ? You can execute it once again. python manage.py syncdb The output will indicate that the table reader_sourceurl has been created. What is the SQL executed ? Just run the command python manage.py sql reader And the output should be something similar to BEGIN; CREATE TABLE "reader_sourceurl" ( "id" integer NOT NULL PRIMARY KEY, "name" varchar(100) NOT NULL, "url" varchar(200) NOT NULL, "lastVisited" datetime NOT NULL ) ; Of course, this output is specific to the database you have declared. As you can see, in the process of creating the tables, Django follows some conventions. In our case, it named the table by concatenating the application name to the model name and added a primary key. Of course, all of those conventions can be overridden. Should you or not ? For a simple application like this one, you really don’t have to care about it, just keep the convention names and let Django define your database model. Just focus on the applicative code. Remember that Django may create the tables for you, but you are free to design your database by yourself, and that is certainly what you would do in larger projects. Just keep in mind that if the database was designed outside Django, you just have to inform Django of the connection. What Django does for you, and what you should do by yourself As we are in the database creation subject, you may wonder what was the action of the syncdb we executed in the previous post. Syncdb creates all the tables for all apps defined in INSTALLED_APPS. So, the previous execution created the tables for the default applications. For every app in INSTALLED_APPS, you can execute python manage.py sql appname where appname is the name of an application. You will then see the SQL Django executed. Remember that syncdb will only create missing tables. So you will have to execute it each time you add an application or a model. Syncdb will not alter a table, if you need to update a database schema, you’ll have to do it yourself. Well, during the development process, you’ll most certainly drop the database and recreate it, but remember to provide a SQL update script when you’ll go in production. So, we have written our first model, what will happen if we launch our server ? Try it, and no, nothing changed as we haven’t declared any view. Besides, we have created a model, but we still don’t have the form to enter the data. With the help of Django, we are just one step away from fulfilling the UserStory. As usual, if you have any question, feel free to ask them in the comments. About Darko Stankovski Darko Stankovski is the founder and editor of Dad 3.0. You can find more about him trough the following links. 2 Responses […] This will create all the necessary database tables. We’ll see it with the model once we will have designed it. And this is coming in the next post. […] […] have defined our model and created the database tables. But we still didn’t completed the User Story we’ve defined. Using Django, having our model, we’ll just let the framework do the […]
https://geekgarage.dad3zero.net/define-the-models-of-your-rss-reader/
CC-MAIN-2021-39
refinedweb
1,120
75.4
This article tells about the process of creation and usage face recognition library for Go language. Neural networks are highly popular today, people use them for a variety of tasks. One particularly useful appliance is face recognition. Recently I’ve realized that my hobby project, a forum software with Go backend, would benefit from face recognition feature. It would be really neat to have a way to recognize people on uploaded photos (pop singers) so that newcomers don’t need to ask who’s on the photo. This sounded like a good idea so I decided to give it a try. One thing to note is that I try to keep system requirements of that software pretty low, so that more people can install it, using a cheap server. That’s why implementation can’t use CUDA or require GPU. While you can easily rent such a server today it will cost more, thus reducing the potential auditory. It would be much better if it can work just on CPU, preferably without exotic dependencies. Choosing the language If you ask data scientist or person involved in practical experience with neural networks, almost all of them will recommend you to grab Python language for solving machine learning task. It’s definetely a smart choice because of the community, amount of libraries available, simplicity of the language and so on. Needless to say you’ll easily find extremely popular face recognition libraries in Python with great examples and documentation. However I decided to choose Go for several reasons: - My forum is written in Go, I really like the convenience of single-binary backend so it would be nice to have simple integration of face recognition routines with the rest of backend, instead of implementing some IPC and requiring Python dependencies. - Go is generally faster and more importantly consumes less memory than Python. Of course critical parts of any performant Python library are written in C/C++ but you will have overhead of Python VM anyway. You can always rent machine with more memory if we’re speaking about hosting but I prefer faster languages unless it significantly hurts development time. I won’t use C or C++ as my main language for writing web applications but Go is fine, almost as simple as Python. - I haven’t found face recognition libraries for Go so writing one would be both fun and helpful for community. Choosing the framework As said earlier, neural networks and thus frameworks implementing them are massively widespread. Only in computer vision you have Caffe, Torch, TensorFlow and others. But there is one particularly cool library dlib that almost immediately attracted my attention. First, it’s written in C++ so you can easily create Go bindings with cgo. Second, it claims 99.38% accuracy on the Labeled Faces in the Wild benchmark which sounds quite impressive. Third, popular face recognition libraries such as face_recognition and openface use dlib underneath so it looks like a really good choice. Installing dependencies Framework is chosen, but how would we get it on development and production machines? C++ dependencies might be tricky to install, you can’t use convenient “go get” or “pip install” commands. Either it’s provided in the repository of your OS or expect a tedious compilation process. The issue is even more nasty if you are library owner and asking your users to compile software by themselves. E.g. you can see how many real people experience problems with dlib compilation. Fortunately there is better option: in case if user’s target system is known we can build binary package of dlib which would greatly simplify the installation. Since we’re speaking about server software, Ubuntu is almost the standard here, so you really want to support it in the first place. Ubuntu has dlib in its standard repos but the version is too old: face recognition support was added only in dlib 19.3. So we need to build our own package. I’ve created PPA (custom repository) for Ubuntu 16.04 and 18.04, the two latest LTS versions. Installation is as simple as: sudo add-apt-repository ppa:kagamih/dlibsudo apt-get updatesudo apt-get install libdlib-dev It will install latest dlib (19.15 at the moment) and Intel’s Math Kernel Library, which seems to be the fastest implementation of standard BLAS and LAPACK interfaces, at least for Intel processors. Good news for Debian sid and Ubuntu 18.10 (not yet released), pretty fresh dlib is available in standard repos. All you need is: sudo apt-get install libdlib-dev libopenblas-dev This will use OpenBLAS implementation instead of MKL which is pretty fast too. Alternatively you could enable non-free packages and install libmkl-dev instead. Also we will need libjpeg to load JPEG images, install libjpeg-turbo8-dev package on Ubuntu and libjpeg62-turbo-dev on Debian for that (don’t ask me why names are so different). Right now I don’t have instructions for other systems so let me know if you have problems with getting dlib. It makes perfect sense to provide short and precise recipes at least for the most popular of them. I’m considering to also provide Docker image for dlib (few of them already exist), many projects with complex dependencies tend to use that method of distribution. But in my opinion a native package will always provide better user experience. You don’t need to write long commands in console or deal with sandboxed environment, everything works like it used to. Writing the library Modern face recognition libraries work by returning a set of numbers (vector embedding or descriptor) for each face on the photo so you can compare them to each other and find the name of person on passed image by comparing that numbers (normally by Euclidean distance between vectors, the two faces with minimal distance should belong to the same person). That concept is already described in other articles so I won’t go into details here. Basic code for creating face descriptor from the passed image is trivial, it pretty much follows official example. Check out facerec.cc. The corresponding header facerec.h defines 5 functions and several structures for interaction between Go and dlib. Here I discrovered one unfortunate thing with dlib. While it supports all popular image formats, it can only load them from file. This can be very confusing restriction, because often you keep image data only in memory and writing it to temporal file is a mess. So I had to write my own image loader using libjpeg. Since most photos are stored in that format it should be enough for now, other formats might be added later. A tiny glue layer that connects C++ and Go is placed in face.go. It provides Face structure that holds coordinates of the face on the image and its descriptor. And the Recognizer interface for all actions such as initialization and the actual recognition. What do we do once we have descriptor? In the simplest case you would compare the Euclidean distance between unknown descriptor and all known descriptors as said earlier. It’s not perfect, on the current state of the art sometimes you will get wrong answers. If we want to improve results a bit, we would use many images for each person and check if at least several of them were pretty close to the provided face. It’s exactly that classify.cc does. First it computes distances, then sorts them, then counts hits of the same person in top 10 minimal distances. They’re better algorithms for this task exist, e.g. support vector machines are often used. dlib even provides convenient API for training such models. I’ve seen few mentions that SVM on huge datasets might be slow though, so I need to test it on large collection first which I haven’t done yet. Usage Resulting library is available at github.com/Kagami/go-face, include it in your Go project as usual: import "github.com/Kagami/go-face" See GoDoc documentation for overview of all structures and methods. There’re not many of them, a typical workflow is: - Init recognizer - Recognize all known images, collect descriptors - Pass known descriptors with corresponding categories to the recognizer - Get descriptor of unknown image - Classify its category Here is working example that illustrates all steps described above: package main import ("fmt""log""path/filepath" "github.com/Kagami/go-face") // Path to directory with models and test images. Here it's// assumed it points to the// <> clone.const dataDir = "testdata" // This example shows the basic usage of the package: create an// recognizer, recognize faces, classify them using few known// ones.func main() {// Init the recognizer.rec, err := face.NewRecognizer(dataDir)if err != nil {log.Fatalf("Can't init face recognizer: %v", err)}// Free the resources when you're finished.defer rec.Close() // Test image with 10 faces.testImagePristin := filepath.Join(dataDir, "pristin.jpg")// Recognize faces on that image.faces, err := rec.RecognizeFile(testImagePristin)if err != nil {log.Fatalf("Can't recognize: %v", err)}if len(faces) != 10 {log.Fatalf("Wrong number of faces")} // Fill known samples. In the real world you would use a lot of// images for each person to get better classification results// but in our example we just get them from one big image.var samples []face.Descriptorvar cats []int32for i, f := range faces {samples = append(samples, f.Descriptor)// Each face is unique on that image so goes to its own// category.cats = append(cats, int32(i))}// Name the categories, i.e. people on the image.labels := []string{"Sungyeon", "Yehana", "Roa", "Eunwoo", "Xiyeon","Kyulkyung", "Nayoung", "Rena", "Kyla", "Yuha",}// Pass samples to the recognizer.rec.SetSamples(samples, cats) // Now let's try to classify some not yet known image.testImageNayoung := filepath.Join(dataDir, "nayoung.jpg")nayoungFace, err := rec.RecognizeSingleFile(testImageNayoung)if err != nil {log.Fatalf("Can't recognize: %v", err)}if nayoungFace == nil {log.Fatalf("Not a single face on the image")}catID := rec.Classify(nayoungFace.Descriptor)if catID < 0 {log.Fatalf("Can't classify")}// Finally print the classified label. It should be "Nayoung".fmt.Println(labels[catID])} To run it do: mkdir -p ~/go && cd ~/go # Or cd to your $GOPATHmkdir -p src/go-face-example && cd src/go-face-examplegit clone testdataedit main.go # Paste example codego get .../../bin/go-face-example It will take some time to compile go-face (~1 minute on my i7) because of extensive use of C++ templates in dlib’s code. Luckily Go caches build outputs so future builds will be much faster. Example should print “Nayoung” indicating that unknown image was recognized correctly. Models go-face requires shape_predictor_5_face_landmarks.dat and dlib_face_recognition_resnet_model_v1.dat models for work. You may download them from dlib-models repository: mkdir models && cd modelswget shape_predictor_5_face_landmarks.dat.bz2wget dlib_face_recognition_resnet_model_v1.dat.bz2 They’re also available in go-face-testdata repository which you’ve cloned to run example. Future ideas I’m pretty satisfied with the result, library has simple API, decent recognition quality and can be easily embedded into Go application. But of course there is always room for improvements: - go-face currently don’t jitter face images when creating descriptor for simplicity and speed, but it’s definetely worth to add option for that as it might improve recognition quality. - dlib supports a lot of image formats (JPEG, PNG, GIF, BMP, DNG) but go-face currently implements only JPEG, would be good to support more. - As suggested by Davis, the author of dlib, multiclass SVM might give better classification result than search for minimal distance, so this needs additional testing. - In go-face I’m trying not to copy values unless really necessary, but haven’t actually tested performance for huge (10,000+) collection of face samples, there might be some bottlenecks. - Extracting feature vector from face is a powerful concept because you don’t need to collect your own train data which is quite ambitious task (Davis mentions dataset of 3 million faces used to create dlib’s ResNet model) but this may be inevitable to get higher quality of recognition, so it’s worth to provide tool for training your own model.
https://hackernoon.com/face-recognition-with-go-676a555b8a7e?gi=31ad70fb00d3
CC-MAIN-2022-33
refinedweb
2,031
55.64
Hi, Is there any benefit to using the old method when using summary indexing? Basically I would like to the know differences in terms of performance or any value the one way may have over the other, between using si commands/the new way and | collect/the old way. Thanks I see only one difference. Summary indexes(SI) can be created only based existing reports, whereas we create collect through searches by appending teh command "| collect index=" at the end. I don't think I've compared the performance of the two but I always prefer selecting Summary indexing in Saved search Option versus using Collect command in-line. The former does the summary indexing (processing result, generating raw events etc) in background and should be better than in-line option. Love hear thoughts from others. Using Summary indexing I found a large benefit in terms of performances (also ten times quicker!), for example with BlueCoat logs that have billions of events every day! Problems are that it's impossible to delete a part of summarized logs, but only the full tsixd file (I asked to Splunk to take in consideration the opportunity to insert the delete functionality), this means that you cannot do errors in summarizing, because you cannot delete them. In addition using Summary indexing there is a delay in data access because logs are indexed two times and you have to wait that logs are indexed before to summarize them. In my case I have a larger delay because I have to be sure that logs are really all arrived before summarizing. There aren't many checks on the summary indexing operation, so there is the risk to index twice a log or lost it. At the end there is a greater disk space occupation, but in my case is less of the problem. In conclusion: use it because is really useful but attention! Bye. Giuseppe Hi Guiseppe, Thanks for the reply, however I am interested in the difference between the two methods of implementing summary indexes(si commands vs | collect) rather than using summary indexing itself. I used tscollect. your_search | table fields... | tscollect namespace=blueacoat_stats and in searches I used | tstats count FROM blueacoat_stats | ... Bye. Giuseppe if you're satisfied of the answer, please, accept the answer. Bye. Giuseppe
https://community.splunk.com/t5/Splunk-Search/si-versus-collect/td-p/221581
CC-MAIN-2021-10
refinedweb
383
52.6
Get a network host entry, given an Internet address #include <netdb.h> struct hostent * gethostbyaddr( const void * addr, socklen_t len, int type ); The gethostbyaddr() function searches for information associated with a host, which has the address pointed to by addr within the address family specified by type, opening a connection to the database if necessary. This function returns a pointer to a structure of type hostent that describes an Internet host. This structure contains either the information obtained from a name server, or broken-out fields from a line in /etc/hosts. You can use sethostent() to request the use of a connected TCP socket for queries. If the stayopen flag is nonzero, all queries to the name server will use TCP and the connection will be retained after each call to gethostbyaddr() or gethostbyname(). If the stayopen flag is zero, queries use UDP datagrams. Use the gethostbyaddr() function to find a host: struct sockaddr_in client; struct hostent* host; int sock, fd, len; … len = sizeof( client ); fd = accept( sock, (struct sockaddr*)&client, &len ); if( fd == -1 ) { perror( "accept" ); exit( 1 ); } host = gethostbyaddr( (const void*)&client.sin_addr, sizeof(struct in_addr), AF_INET ); printf( "Connection from %s: (%s)\n", host ? host->h_name : "<unknown>", inet_ntoa( client.sin_addr ) ); … Standard Unix; removed from POSIX.1-2008 This function uses static data storage; if you need the data for future use, copy it before any subsequent calls overwrite it. Currently, only the Internet address format is understood.
https://www.qnx.com/developers/docs/7.1/com.qnx.doc.neutrino.lib_ref/topic/g/gethostbyaddr.html
CC-MAIN-2022-05
refinedweb
240
53.71
A small utility to get the actual number of threads used by OpenMP via Cython bindings. Project description OpenMP Thread Counter A small Python module to get the actual number of threads used by OMP via Cython bindings. - Free software: MIT license - Documentation:. Why Because GCC/Cython always returned 1 when calling openmp.get_thread_num or openmp.get_max_threads. Installation To install run: pip install omp-thread-count In OSX, and possibly other platforms, you may need to specify a compiler with OpenMP support, like this: CC=gcc-4.8 pip install omp-thread-count Usage Importing from python code: import omp_thread_count n_threads = omp_thread_count.get_thread_count() Importing from cython code: from omp_thread_count._omp cimport get_thread_count Use omp_thread_count.get_includes() in your extensions’ include_dirs to use the header files. Credits This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template. History 0.2.1 (2016-06-21) - Improved packaging and CI support. - Simplified cython code. - Fixed support for python 3.5. 0.2.0 (2016-06-19) - Added pxd files for third-party cimports. 0.1.0 (2016-06-18) - First release on PyPI. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/omp-thread-count/
CC-MAIN-2021-25
refinedweb
211
52.76
Time is an essential component of nearly all geoscience data. Timescales span orders of magnitude from microseconds for lightning, hours for a supercell thunderstorm, days for a global weather model, millenia and beyond for the earth's climate. To properly analyze geoscience data, you must have a firm understanding of how to handle time in Python. In this notebook, we will examine the Python Standard Library for handling dates and times. We will also briefly make use of the pytz module to handle some thorny time zone issues in Python. TimeVersus DatetimeModules and Some Core Concepts¶ Python comes with time and datetime modules. Unfortunately, Python can be initially disorienting because of the heavily overlapping terminology concerning dates and times: datetimemodule has a datetimeclass datetimemodule has a timeclass datetimemodule has a dateclass timemodule has a timefunction which returns (almost always) Unix time datetimeclass has a datemethod which returns a dateobject datetimeclass has a timemethod which returns a timeobject This confusion can be partially alleviated by aliasing our imported modules: import datetime as dt # we can now reference the datetime module (alaised to 'dt') and datetime # object unambiguously pisecond = dt.datetime(2016, 3, 14, 15, 9, 26) print(pisecond) 2016-03-14 15:09:26 import time as tm now = tm.time() print(now) 1467053657.6353862 timemodule¶ The time module is well-suited for measuring Unix time. For example, when you are calculating how long it takes a Python function to run (so-called "benchmarking"), you can employ the time() function from the time module to obtain Unix time before and after the function completes and take the difference of those two times. import time as tm start = tm.time() tm.sleep(1) # The sleep function will stop the program for n seconds end = tm.time() diff = end - start print("The benchmark took {} seconds".format(diff)) The benchmark took 1.0026235580444336 seconds (For more accurate benchmarking, see the timeit module.) datetimemodule¶ The datetime module handles time with the Gregorian calendar (the calendar we are all familiar with) and is independent of Unix time. The datetime module has an object-oriented approach with the date, time, datetime, timedelta, and tzinfo classes. dateclass represents the day, month and year timeclass represents the time of day datetimeclass is a combination of the dateand timeclasses timedeltaclass represents a time duration tzinfo(abstract) class represents time zones The datetime module is effective for: The time and datetime modules overlap in functionality, but in your geoscientific work, you will probably be using the datetime module more than the time module. Unix time is an example of system time which is the computer's notion of passing time. It is measured in seconds from the the start of the epoch which is January 1, 1970 00:00 UTC. It is represented "under the hood" as a floating point number which is how computers represent real (ℝ) numbers . We have been talking about object-oriented (OO) programming by mentioning terms like "class", "object", and "method", but never really explaining what they mean. A class is a collection of related variables, similar to a struct, in the C programming language or even a tuple in Python) coupled with functions, or "methods" in OO parlance, that can act on those variables. An object is a concrete example of a class. For example, if you have a Coord class that represents an earth location with latitude, and longitude, you may have a method that returns the distance between two locations, distancekm() in this example. import math class Coord: """Earth location identified by (latitude, longitude) coordinates. distancekm -- distance between two points in kilometers """ def __init__(self, latitude=0.0, longitude=0.0): self.lat = latitude self.lon = longitude def distancekm(self, p): """Distance between two points in kilometers.""" DEGREES_TO_RADIANS = math.pi / 180.0 EARTH_RADIUS = 6373 # in KMs phi1 = (90.0 - self.lat) * DEGREES_TO_RADIANS phi2 = (90.0 - p.lat) * DEGREES_TO_RADIANS theta1 = self.lon * DEGREES_TO_RADIANS theta2 = p.lon * DEGREES_TO_RADIANS cos = (math.sin(phi1) * math.sin(phi2) * math.cos(theta1 - theta2) + math.cos(phi1) * math.cos(phi2)) arc = math.acos(cos) return arc * EARTH_RADIUS To create a concrete example of a class, also known as an object, initialize the object with data: timbuktu = Coord(16.77, 3.00) Here, timbuktu is an object of the class Coord initialized with a latitude of 16.77 and a longitude of 3.00. Next, we create two Coord objects: ny and paris. We will invoke the distancekm() method on the ny object and pass the paris object as an argument to determine the distance between New York and Paris in kilometers. ny = Coord(40.71, 74.01) paris = Coord(48.86, 2.35) distance = ny.distancekm(paris) print("The distance from New York to Paris is {:.1f} kilometers.".format( distance)) The distance from New York to Paris is 5517.0 kilometers. The old joke about OO programming is that they simply moved the struct that the function takes as an argument and put it first because it is special. So instead of having distancekm(ny, paris), you have ny.distancekm(paris). We have not talked about inheritance or polymorphism but that is OO in a nutshell. datetime.strptimeMethod¶ Suppose you want to analyze US NLDN lightning data. Here is a sample row of data: 06/27/07 16:18:21.898 18.739 -88.184 0.0 kA 0 1.0 0.4 2.5 8 1.2 13 G Part of the task involves parsing the 06/27/07 16:18:21.898 time string into a datetime object. (The full description of the data are described here.) In order to parse this string or others that follow the same format, you will employ the datetime.strptime() method from the datetime module. This method takes two arguments: the first is the date time string you wish to parse, the second is the format which describes exactly how the date and time are arranged. The full range of format options is described in the Python documentation. In reality, the format will take some degree of experimentation to get right. This is a situation where Python shines as you can quickly try out different solutions in the IPython interpreter. Beyond the official documentation, Google and Stack Overflow are your friends in this process. Eventually, after some trial and error, you will find the '%m/%d/%y %H:%M:%S.%f' format will properly parse the date and time. import datetime as dt strike_time = dt.datetime.strptime('06/27/07 16:18:21.898', '%m/%d/%y %H:%M:%S.%f') # print strike_time to see if we have properly parsed our time print(strike_time) 2007-06-27 16:18:21.898000 datetime.strftimeMethod¶ Let's say you are interested in obtaining METAR data from the Aleutian Islands with the MesoWest API. In order to retrieve these data, you will have to assemble a URL that abides by the MesoWest API reference, and specifically create date time strings that the API understands (e.g., 201606010000 for the year, month, date, hour and minute). For example, typing the following URL in a web browser will return a human-readable nested data structure called a JSON object which will contain the data along with additional "metadata" to help you interpret the data (e.g., units etc.). Here, we are asking for air temperature information from the METAR station at Eareckson air force base (ICAO identifier "PASY") in the Aleutians from June 1, 2016, 00:00 UTC to June 1, 2016, 06:00 UTC. { "SUMMARY": { "FUNCTION_USED": "time_data_parser", "NUMBER_OF_OBJECTS": 1, "TOTAL_DATA_TIME": "5.50103187561 ms", "DATA_PARSING_TIME": "0.313997268677 ms", "METADATA_RESPONSE_TIME": "97.2690582275 ms", "RESPONSE_MESSAGE": "OK", "RESPONSE_CODE": 1, "DATA_QUERY_TIME": "5.18608093262 ms" }, "STATION": [ { "ID": "12638", "TIMEZONE": "America/Adak", "LATITUDE": "52.71667", "OBSERVATIONS": { "air_temp_set_1": [ 8.3, 8.0, 8.3, 8.0, 7.8, 7.8, 7.0, 7.2, 7.2 ], " ] }, "STATE": "AK", "LONGITUDE": "174.11667", "SENSOR_VARIABLES": { "air_temp": { "air_temp_set_1": { "end": "", "start": "" } }, "date_time": { "date_time": {} } }, "STID": "PASY", "NAME": "Shemya, Eareckson AFB", "ELEVATION": "98", "PERIOD_OF_RECORD": { "end": "", "start": "" }, "MNET_ID": "1", "STATUS": "ACTIVE" } ], "UNITS": { "air_temp": "Celsius" } } // GET // HTTP/1.1 200 OK // Content-Type: application/json // Date: Mon, 27 Jun 2016 18:17:08 GMT // Server: nginx/1.4.6 (Ubuntu) // Vary: Accept-Encoding // Content-Length: 944 // Connection: keep-alive // Request duration: 0.271790s Continuing with this example, let's create a function that takes a station identifier, start and end time, a meteorological field and returns the JSON object as a Python dictionary data structure. We will draw upon our knowledge from the Basic Input and Output notebook to properly construct the URL. In addition, we will employ the urllib.request module for opening and reading URLs. But first, we must figure out how to properly format our date with the datetime.strftime() method. This method takes a format identical to the one we employed for strptime(). After some trial and error from the IPython interpreter, we arrive at '%Y%m%d%H%M': import datetime as dt print(dt.datetime(2016, 6, 1, 0, 0).strftime('%Y%m%d%H%M')) 201606010000 Armed with this knowledge of how to format the date and time according to the MesoWest API reference, we can write our metar() function: import urllib.request import json # json module to help us with the HTTP response def metar(icao, starttime, endtime, var): """ Retrieves METAR with the icao identifier, the starttime and endtime datetime objects and the var atmospheric field (e.g., "air_temp".) Returns a dictionary data structure that mirros the JSON object from returned from the MesoWest API. """ fmt = '%Y%m%d%H%M' st = starttime.strftime(fmt) et = endtime.strftime(fmt) url = "?"\ "stid={}&start={}&end={}&vars={}&token=demotoken" reply = urllib.request.urlopen(url.format(icao, st, et, var)) return json.loads(reply.read().decode('utf8')) We can now try out our new metar function to fetch some air temperature data. import datetime as dt pasy = metar("pasy", dt.datetime(2016, 6, 1, 0, 0), dt.datetime(2016, 6, 1, 6, 0), "air_temp") print(pasy) {'SUMMARY': {'DATA_QUERY_TIME': '5.33509254456 ms', 'METADATA_RESPONSE_TIME': '52.8740882874 ms', 'DATA_PARSING_TIME': '0.19907951355 ms', 'TOTAL_DATA_TIME': '5.53607940674 ms', 'NUMBER_OF_OBJECTS': 1, 'FUNCTION_USED': 'time_data_parser', 'RESPONSE_CODE': 1, 'RESPONSE_MESSAGE': 'OK'}, 'UNITS': {'air_temp': 'Celsius'}, 'STATION': [{'MNET_ID': '1', 'STID': 'PASY', 'STATUS': 'ACTIVE', 'ID': '12638', ]}, 'LATITUDE': '52.71667', 'ELEVATION': '98', 'SENSOR_VARIABLES': {'air_temp': {'air_temp_set_1': {'end': '', 'start': ''}}, 'date_time': {'date_time': {}}}, 'LONGITUDE': '174.11667', 'NAME': 'Shemya, Eareckson AFB', 'STATE': 'AK', 'PERIOD_OF_RECORD': {'end': '', 'start': ''}, 'TIMEZONE': 'America/Adak'}]} The data are returned in a nested data structure composed of dictionaries and lists. We can pull that data structure apart to fetch our data. Also, observe that the times are returned in UTC according to the ISO 8601 international time standard. print(pasy['STATION'][0][]} We could continue with this exercise by parsing the returned date time strings in to datetime objects, but we will leave that exercise to the reader. timedeltaClass¶ Let's suppose we are looking at coastal tide and current data perhaps in a tropical cyclone storm surge scenario. The lunar day is 24 hours, 50 minutes with two low tides and two high tides in that time duration. If we know the time of the current high tide, we can easily calculate the occurrence of the next low and high tides with the timedelta class. (In reality, the exact time of tides is influenced by local coastal effects, in addition to the laws of celestial mechanics, but we will ignore that fact for this exercise.) The timedelta class is initialized by supplying time duration usually supplied with keyword arguments to clearly express the length of time. Significantly, you can use the timedelta class with arithmetic operators (i.e., +, -, *, /) to obtain new dates and times as the next code sample illustrates. This convenient language feature is known as operator overloading and again illustrates Python's batteries-included philosophy of making life easier for the programmer. (In another language such as Java, you would have to call a method significantly obfuscating the code.) Another great feature is that the difference of two times will yield a datetime object. Let's examine all these features in the following code block. import datetime as dt high_tide = dt.datetime(2016, 6, 1, 4, 38, 0) lunar_day = dt.timedelta(hours=24, minutes=50) tide_duration = lunar_day / 4 next_low_tide = high_tide + tide_duration next_high_tide = high_tide + (2 * tide_duration) tide_length = next_high_tide - high_tide print("The time between high and low tide is {}.".format(tide_duration)) print("The current high tide is {}.".format(high_tide)) print("The next low tide is {}.".format(next_low_tide)) print("The next high tide {}.".format(next_high_tide)) print("The tide length is {}.".format(tide_length)) print("The type of the 'tide_length' variable is {}.".format(type( tide_length))) The time between high and low tide is 6:12:30. The current high tide is 2016-06-01 04:38:00. The next low tide is 2016-06-01 10:50:30. The next high tide 2016-06-01 17:03:00. The tide length is 12:25:00. The type of the 'tide_length' variable is <class 'datetime.timedelta'>. In the last timedelta object. Time zones can be a source of confusion and frustration in geoscientific data and in computer programming in general. Core date and time libraries in various programming languages inevitably have design flaws (Python is no different) leading to third-party libraries that attempt to fix the core library limitations. To avoid these issues, it is best to handle data in UTC, or at the very least operate in a consistent time zone, but that is not always possible. Users will expect their tornado alerts in local time. UTC is an abbreviation of Coordinated Universal Time and is equivalent to Greenwich Mean Time (GMT), in practice. (Greenwich at 0 degrees longitude, is a district of London, England.) In geoscientific data, times are often in UTC though you should always verify this assumption is actually true! datetimeObjects¶ When you create datetime objects in Python, they are so-called "naive" which means they are time zone unaware. In many situations, you can happily go forward without this detail getting in the way of your work. As the Python documentation states: "Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality". However, if you wish to convey time zone information, you will have to make your datetime objects time zone aware. In order to handle time zones in Python, you will need the third-party pytz module whose classes build upon, or "inherit" in OO terminology, from the tzinfo class. You cannot solely rely on the Python Standard Library unfortunately. Here, we create time zone naive and time zone aware datetime objects: import datetime as dt import pytz naive = dt.datetime.now() aware = dt.datetime.now(pytz.timezone('US/Mountain')) print("I am time zone naive {}.".format(naive)) print("I am time zone aware {}.".format(aware)) I am time zone naive 2016-06-27 18:54:19.249738. I am time zone aware 2016-06-27 12:54:19.264678-06:00. The pytz.timezone() method takes a time zone string and returns a tzinfo object which can be used to initialize the time zone. The -06:00 denotes we are operating in a time zone six hours behind UTC. If you have data that are in UTC, and wish to convert them to another time zone, Mountain Time Zone for example, you will again make use of the pytz module. First, we will create a UTC time with the utcnow() method which inexplicably returns a time zone naive object so you must still specify the UTC time zone with the replace() method. We then create a "US/Mountain" tzinfo object as before, but this time we will use the astimzone() method to adjust the time to the specified time zone. import datetime as dt import pytz utc = dt.datetime.utcnow().replace(tzinfo=pytz.utc) print("The UTC time is {}.".format(utc.strftime('%B %d, %Y, %-I:%M%p'))) mountaintz = pytz.timezone("US/Mountain") ny = utc.astimezone(mountaintz) print("The 'US/Mountain' time is {}.".format(ny.strftime( '%B %d, %Y, %-I:%M%p'))) The UTC time is June 27, 2016, 6:54PM. The 'US/Mountain' time is June 27, 2016, 12:54PM. We also draw upon our earlier knowledge of the strftime() method to format a human-friendly date and time string.
http://nbviewer.jupyter.org/github/Unidata/online-python-training/blob/master/notebooks/Times%20and%20Dates.ipynb
CC-MAIN-2018-09
refinedweb
2,700
57.06
A discussion in the Subtle Bugs forum concerning floating point number comparisons caused me to recall some code I wrote about 15 years ago. Back then, I was writing code that calculated federal and stats estate/inheritance taxes, as well as charitable giving scenarios. We needed to compare floating point values at various levels of precision depending on what we were doing and where in the calculation cycle we happened to be. Anyone that's been writing code for any length of time knows what a pain in the butt it is to compare floating point numbers because they're mere approximations of their true value. For this reason, I wrote, and present you now with my AlmostEqual() function. AlmostEqual() My approach centers around converting the floating point values to something a bit more reliable where comparisons are concerned - strings. In the example shown in this article, I use CStrings because I'm a fan of MFC. You could certainly use stdio functions or even STL for your strings if you don't (or can't) use MFC. I admit that this isn't some fancy thing that magically evaluates all of the parts of a floating point number, but it does work and it's handy if you need to compare floating point values to a specific level of precision. CString bool AlmostEqual(double nVal1, double nVal2, int nPrecision) { CString sVal1; CString sVal2; nPrecision = __max(__min(16, nPrecision), 0); sVal1.Format("%.*lf", nPrecision, nVal1); sVal2.Format("%.*lf", nPrecision, nVal2); bool bRet = (sVal1 == sVal2); return bRet; } There's really not much to say about the function. You merely pass in the two values that need to be compared along with the desired precision value. After being hounded about speed issues, I decided to try different methods for comparison. Here's a function similar to the first, but that uses stdio functions for the string formatting. bool AlmostEqualStdIO(double nVal1, double nVal2, int nPrecision) { char sVal1[40]; char sVal2[40]; nPrecision = __max(__min(16, nPrecision), 0); sprintf_s(sVal1, sizeof(sVal1), "%.*lf", nPrecision, nVal1); sprintf_s(sVal2, sizeof(sVal2), "%.*lf", nPrecision, nVal2); bool bRet = (strcmp(sVal1, sVal2) == 0); return bRet; } The function above requires less than half the time the CString version needs to perform the same task. Keep in mind that this is using VS2005, and that (I think) the MFC CString class is actually using STL now. Finally, here a version of the function that doesn't do any string manipulation at all. bool AlmostEqualDoubles(double nVal1, double nVal2, int nPrecision) { nPrecision = __max(__min(16, nPrecision), 0); double nEpsilon = 1.0; for (int i = 1; i <= nPrecision; i++) { nEpsilon *= 0.1; } bool bRet = (((nVal2 - nEpsilon) < nVal1) && (nVal1 < (nVal2 + nEpsilon))); return bRet; } When I watched this function work in the debugger, I noticed that performing ANY math of the nEpsilon value caused it to become impure. The very last digit of the mantissa was some random value. This almost guarantees that at some point, the value will be such that it returns an incorrect result. Given the aim of this article (RELIABLE equality comparisons), this is not adequate. Finally, here's a version of the function that accepts a direct value for nEpsilon in the form of an appropriate value. For instance, if you want a precision of 3, you would pass in 0.001. bool AlmostEqualDoubles2(double nVal1, double nVal2, double nEpsilon) { bool bRet = (((nVal2 - nEpsilon) < nVal1) && (nVal1 < (nVal2 + nEpsilon))); return bRet; } I didn't watch all 250,000 iterations in my test app, but none of the ones I traced through presented any value other than 0.0010000000000000, but that does not preclude the possibility that it could happen (given the nature of floating point values). Again - given the aim of this article (RELIABLE equality comparisons), this is not adequate. Finally, the non-string versions of the function were admittedly very fast. My 250,001 iteration tests revealed an execution time of ZERO seconds (obviously more than 0 seconds but less than 1 second) compared to two seconds for the stdio and five seconds for the CString version. Again, my admittedly chunky timing code should probably be replaced by something with a far higher resolution, but you get the idea. So, here we are with four versions of the comparison function. I still have to say that the string comparison is far more consistent than the non-string versions. Take that for what it's worth. Is everyone happy now? It's apparent that the original single disclaimer (the last one in this list) was not sufficient , so I've added a couple more: true false AlmostEqual stdio sprintf_s stdio COleDateTime This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) public static bool DoublesAlmostEqual(double compare, double compareTo) { const double EPSILON = 0.001; return ((compareTo - EPSILON) < compare) && (compare < (compareTo + EPSILON)); } Mr Nukealizer wrote:m John Simmons / outlaw programmer wrote:what resembles a grunt from someone with a sloped forehead, one eyebrow, and that breathes through their mouth richarno wrote:The method used is not very useful, and is very heavy on the CPU. double dValue = atof("0.1"); double dTest = 0.1; ASSERT ( ((*((LONGLONG*)&dValue))&0xFFFFFFFFFFFFFF00) == ((*((LONGLONG*)&dTest)) &0xFFFFFFFFFFFFFF00) ); double dSecondValue = (1 + dValue + dValue + dValue + dValue); double dTest2 = 1.4; ASSERT ( (*((LONGLONG*)&dSecondValue)&0xFFFFFFFFFFFFFF00) == (*((LONGLONG*)&dTest2) &0xFFFFFFFFFFFFFF00) ); // *NO* Crash float dValue = atof("0.1"); float dTest = 0.1; ASSERT ( ((*((int*)&dValue))&0xFFFFFFF0) == ((*((int*)&dTest)) &0xFFFFFFF0) ); float dSecondValue = (1 + dValue + dValue + dValue + dValue); float dTest2 = 1.4; ASSERT ( (*((int*)&dSecondValue)&0xFFFFFFF0) == (*((int*)&dTest2) &0xFFFFFFF0) ); // *NO* Crash double dTest = 0.1 double dValue = atof("0.1") #define DCMP(x,y) ((*((LONGLONG*)&x))&0xFFFFFFFFFFFFFF00)==((*((LONGLONG*)&y))&0xFFFFFFFFFFFFFF00) #define FCMP(x,y) (*((int*)&x)&0xFFFFFFF0)==(*((int*)&y)&0xFFFFFFF0) DCMP FCMP ASSERT(DCMP(atof("0.1"),0.1)); // atof returns a value which have to be stored... #define FCMP(x,y) (*((int*)&x)&0xFFFFF000)==(*((int*)&y)&0xFFFFF000) float dSecondValue = atof("1.4"); // RAW : 0x3FB332DF float dTest2 = 1.39999; // RAW : 0x3FB33333, last 12 bits are differents, so don't compare them ASSERT(FCMP(dSecondValue,dTest2)); // *NO* Crash memcmp John Simmons / outlaw programmer wrote:You're missing the point. John Simmons / outlaw programmer wrote:Equal_At_The_Specified_Number_Of_Digits_To_The_Right_Of_The_Decimal_Point General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/16646/Reliable-Floating-Point-Equality-Comparison?msg=3696063
CC-MAIN-2014-52
refinedweb
1,057
53.81
When I introduce a programmer to Rails I encourage them to read the article Skinny Controller, Fat Model. My only complaint about this article is that it applies the Skinny/Fat Pattern in a vague way, proceeding as if by intuition. I’ve found instead that there is a formulaic way to produce excellent Controller code–the Controller Formula Skinny/Fat: Code Complexity vs. Abstraction Boundaries vs. The Formula The Skinny/Fat pattern is typically stated in terms of Lines of Code. Your Controllers should have few Lines of Code; where there are many, move them to the Model. This rule has more exceptions than it has applications, so we can state the intent of the Pattern more precisely in terms of Abstraction Boundaries. Remove all Business Logic from your Controllers and put it in the model. Your Controllers are only responsible for mapping between URLs (including other HTTP Request data), coordinating with your Models and your Views, and channeling that back to an HTTP response. Along the way, Controllers may do Access Control, but little more. These instructions are precise, but following them requires intuition and subtle reasoning. The purpose of this post is to avoid subtle heuristics like Abstraction and Code Complexity. There is a Formula. Let’s see an example that follows the Formula: def create model = Model.new(params[:model]) raise SecurityTransgressionError.new unless logged_in_user.can_update?(model) if model.save render ... else ... end end What’s going on here? The Action channels user input to the model. It raises an Exception if the user lacks permission to perform this Action. Validation is performed by the model. Given the results, the Controller renders the appropriate Template to the HTTP Response. Note a few things about this example. All of the access control rules (i.e., Business Logic) are specified in the Model (in this case, in the can_update? method on User). All data validation rules (again, Business Logic) are specified in the Model. There are three benefits to this approach: 1) the Logic in the Model is easier to test as it’s isolated. 2) Our Abstraction Boundaries are respected. 3) Our Controller is brief, i.e. Skinny. The resulting Controller some call anorexic. But I think it is like a conductor: all of the rhythm and melody comes from the players but the conductor keeps the whole orchestra in sync. But metaphors, testing strategies, and hoity-toity talk of Abstraction Boundaries aside, this example is good code because it follows the Formula. Let’s consider a more sophisticated example. Transactions and Compound Creations Suppose that when creating a model of type Model, we always also want to create another type, DependentModel. We might be tempted to write something like: def create model = Model.new(params[:model]) dependent_model = model.dependents.build(params[:dependent_model]) if model.save ... end Two Models created in one Action! This looks nothing like the Formula. Just push the creation of the DependentModel into Model and we have: def create model = Model.new(params[:model]) if model.save ... end Voila! The Formula. How assigns fit into the Formula Let’s consider another Action, one of the non-side-effecting persuasion. def edit model = Model.find(params[:id]) raise SecurityTransgressionError.new unless logged_in_user.can_update?(model) @colors = Color.find :all end We can see the same access control pattern as in the previous example, but absent is any input validation as the user is not modifying anything. Something new here is the assignment of @colors. Typically, when we are displaying something to the user (in this case, an edit form), we will be listing various data; in this case, these data are the possible colors a model can be. Years ago, DHH issued a bull stating that “Thou Shalt Not Call Find in Thine Template”. This commandment is not without its problems, but that’s an issue for another blog post. This loading of the data is part of the Formula. Push all your Find logic into the Model Let’s take this edit action one step further. Suppose Users of type Admin can assign a certain set of colors to a Model, but other Users can select from a smaller set. Let’s rewrite edit to support these new business rules: def edit model = Model.find(params[:id]) raise SecurityTransgressionError.new unless logged_in_user.can_update?(model) @colors = logged_in_user.admin?? Color.fabulous_colors : Color.drab_colors end Something has gone wrong here: we’ve put Business Logic in the Controller, ack! But rather than appeal to some ethereal Abstraction Boundaries, just notice that it doesn’t follow the formula exemplified above–it’s got an extra conditional in the assignment of @colors. Let’s redesign this a bit, just aiming to adhere to the Formula: def edit model = Model.find(params[:id]) raise SecurityTransgressionError.new unless logged_in_user.can_update?(model) @colors = Color.find_by_user_role(logged_in_user.role) end Much better. We’ve put the rules of determining which color set to select based into the Model, and we have no more Control Flow than our original definition of edit above. This is Skinny as can be. We haven’t violated any Abstraction Boundaries. The color logic is easier to Unit Test. But these ends can be accomplished on auto-pilot just by following the Formula. Let’s complexify this example one step further. Conditional Logic Based on Session Data or other HTTP Request Data def edit ... if logged_in_user.admin? render :action => 'edit_admin' else render :action => 'edit_normal' end end This is not Skinny at all. But, rendering different templates based on the User role is not Business Logic per-se. Rather, it is logic concerning what information is directed to the HTTP response. This properly belongs in the Controller. We could push this into the model: render :action => model.edit_action_for_user_role(logged_in_user.role) But this would make the model know about the View, which is unethical. We could use something like the Visitor Pattern to maintain abstraction boundaries but that is ridiculous overkill here. We could put our Fat edit action on a diet by breaking the two conditions into different edit actions on different Controllers. This approach is, perhaps, more RESTful in spirit: class AdminModelsController ... end class UserModelsController ... end All of these concerns: violating Abstraction Boundaries, Lines of Code, the complexity of the Visitor Pattern, whether one approach is more RESTful than another… in the end it’s just a judgement-call between unappealing alternatives, and no two programmers will make the same choice, and I on any given day will choose variously. So just follow the Formula. Break it out into two controllers so we can have two edit actions, each well behaved. The Full Formula Let’s look at a ‘grammar’ for the Formula, and we’ll soon be done. def non_side_effecting_action model = Model.find(params[:id]) raise SecurityTransgressionError.new unless logged_in_user.can_action?(model) @assign1 = Foo.find :all ... @assignN = Bar.find_for_user(logged_in_user) end def side_effecting_action model = Model.new(params[:model]) # or: model = Model.find(params[:id]); model.attributes = params[:model] raise SecurityTransgressionError.new unless logged_in_user.can_action?(model) if model.save @assign1 = Foo.find :all ... @assignN = Bar.find_for_user(logged_in_user) render :action => ... # or redirect_to ... else ... end end Some details are left out here… And obviously, there will be cases where the Formula needs to be elaborated. There might even be a few cases where the Formula needs to be abandoned. But I think you’ll find it useful most of the time. Nice article! Liked the compound creation example. “Thou Shalt Not Call Find in Thine Template”. This commandment is not without its problems, but that’s an issue for another blog post. When have you found it necessary to do a find from a view? December 12, 2007 at 11:50 pm Very nice write up. A good extension of Jamis’ post. December 12, 2007 at 11:50 pm There’s a typo in the last example in the first method. raise raise. December 12, 2007 at 11:50 pm
http://pivotallabs.com/the-controller-formula/?tag=rubymine
CC-MAIN-2014-10
refinedweb
1,318
60.21
In this second installment of the series on Angular and the REST, I implement authentication on the backend ASP.NET Core Web API using JWT (JSON Web Token). In addition, I add a new authentication module on the Angular app side, so access is restricted to authenticated users only by way of a Login. Let's recap what we have achieved so far in this series. We built the backend ASP.NET Core Web API app that defines a Movie Tracker Endpoint with a full implementation of the CRUD actions and movie search. On the client-side, we built an Angular v8 app that communicates with the backend RESTful Web API by means of a Movie Tracker Service that we generated using Swagger API Documentation, NSwag and NSwagStudio. The app displays all movies, allows the user to filter the movies, adds a new movie, edits an existing movie and can delete a movie. Here’s a link to the first article in this series Angular and the REST. Today, let's start first by adding JWT authentication to our ASP.NET Core Web API. Adding JWT Authentication to ASP.NET Core Web API To start building Web APIs with ASP.NET Core, make sure you have the following tools and frameworks locally installed on your machine. We, for all intents and purposes, will be developing this app on a Windows machine. Feel free to use a Macbook or any other machine you like. In the remaining part of this section, we will go through a step by step guide on how to add JWT authentication to the ASP.NET Core Web API app. The source code for the backend Web API can be found on this Github repo. Step 1 To start authenticating users in our app we need to first start managing users. Therefore, let's amend the MovieTrackerContext to cater to Users in our app. Change the header of the context class to look like this: public class MovieTrackerContext : IdentityDbContext<ApplicationUser> By inheriting from IdentityDbContext class we guarantee that Entity Framework (EF) Core will create all the necessary User-related tables in the database. The IdentityDbContext requires a User class defined in the application in order to create the Users table in the database. By default, the IdentityDbContext class makes use of the IdentityUser that defines a number of standard User fields as follows: In general, you can use the IdentityUser as long as you are satisfied by the fields defined. However, if you want to manage more fields, you can create a new class, inherit from the IdentityUser and add any additional fields. For the sake of this demonstration, let's create a new ApplicationUser class inheriting from IdentityUser as follows: public class ApplicationUser : IdentityUser { } For this article, we won't be adding any additional fields. Step 2 Let's register the User Management services inside the Startup class as follows: With this registration, the UserManager class is now available to use in the application to manage and authenticate users. The UserManager will use the MovieTrackerContext class to connect to the database and store all users' data. Step 3 Creating users is outside the scope of this article. Therefore, I will seed a user record and base our tests on this user. Add a new Models\SeedUser.cs file with the following content: The code defines a static Initialize method that starts by retrieving a MovieTrackerContext and UserManager instance respectively from the ASP.NET Core Dependency Injection system. Then, it checks the Users table to confirm whether or not that user exists. If there is no record, it creates and adds a new User. Let's call the SeedUser.Initialize() method inside the ASP.NET Core Pipeline: The moment we run the application, a new user is added to the system. Step 4 Now that the User Management is properly configured in our app, let's add a new migration so that all User-related tables are created in the database. Open the Package Manager Console and run the following command: Add-Migration AddUserManagement The command generates the following migration: Now run the following command to create all the above tables in the database: Update-Database Step 5 To allow the user to login and authenticate with our app, we need to add a new AuthController Endpoint with a single Login action for now: The AuthController is an ApiController with a default Endpoint route as /api/auth. It requests a UserManager instance in its constructor via Dependency Injection. On the other hand, the Login action accepts as input a LoginModel instance. The LoginModel class is defined as follows: public class LoginModel { public string Username { get; set; } public string Password { get; set; } } Inside the Login action, the code queries the database for a user by a given username. If the user doesn't exist, a proper error message is returned to the caller. In case the user exists, the code then checks if the password matches, the one received from the HTTP Post request versus the one stored in the database. If this check fails, an Unauthorized response is generated and returned. On the other hand if the user exists and the password matches, the code uses the JwtSecurityToken class to create a new token. A token usually defines a set of standard fields like the Issuer of the token, Audience, Claims (if any), Expiration Date and others. In addition, a token is usually signed and encrypted and never sent as plain text. Therefore, the JwtSecurityToken requires that you define an instance of the SigningCredentials class that basically wraps a secret key (of your choice) that is used eventually to sign a token. Finally, the Login action returns a new object containing the token, expiration date and the username associated with the token. To read more about JWT and understand the details, I recommend checking out this article: JWT Introduction Step 6 So far, the application can login a user and generate a respective JWT. However, we want to configure our app to also check and validate a JWT so that if an HTTP Request contains a header key for Authentication with a value in the form of Bearer {TOKEN}, we want the app to automatically check and validate the token and if everything is okay, to automatically login the user and mark the current HTTP Request as authenticated. To do so we start by registering the Authentication services in the ASP.NET Core Dependency Injection system inside the Startup class as follows: To register the Authentication services in an ASP.NET Core Web API, you add a call to services.AddAuthentication() method specifying that JWT Authentication Scheme will be used. In addition, you need to configure the ASP.NET Core Pipeline to authenticate a given request just before hitting the ASP.NET Core MVC engine: Step 7 To test our work, let's open a new Postman session and try to login to the application using the single user credentials we have created so far. Start by running the application by hitting F5 and then open the Postman application and send the following request: You send an HTTP Post request to the URL /api/auth/login with a request body of: { "username": "bhaidar", "password": "MySp$cialPassw0rd" } The backend API returns a valid Token together with the expiration date and the username associated with the token as follows: { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjMxMzgwMDcsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0MzQyIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNDIifQ.OZ_0cIt1Df3Wq6TFoyJDItXJZ04vjo3jmcEQmRGiCpA", "expiresIn": "2019-07-14T21:00:07Z", "username": "bhaidar" } You can now grab this token, appended to any HTTP Request you want to be authenticated and you're done. Finally, to protect a RESTful API Endpoint in ASP.NET Core, you simply decorate a Controller with the [Authorize] attribute. This attribute applies to an entire Controller or to a specific action inside a Controller. In the next section, we add the authentication feature for the Angular app and start authenticating users before allowing them to manage movies. Stay tuned! Integrating Authentication in the Angular app To start working on the Angular app, make sure you have the following tools and frameworks locally installed on your machine. - Angular CLI v8.x What's new in Angular CLI 8 - Node.js 10.x Node.js Download - Visual Studio Code (or any other editor of choice) [VS Code]( In the remaining part of this section, we will go through how to integrate authentication in the Angular app and connect it to the backend Web API Auth Endpoint we just developed. The source code for the Angular app can be found on this Github repo. Step 1 Create an Auth Module to hold all the services related to authenticating users in the Angular app. Run the following command in a terminal window: ng generate module app-auth This command creates a new app-auth.module.ts file inside the path \src\app\app-auth. Step 2 Let's create the authentication service that handles signing in the user and managing the token state across the application. Run the command inside a terminal window to generate a new service: ng g service app-auth/authentication --skipTests=true The above command creates a new authentication.service.ts file inside the path \src\app\app-auth\. To login a user, we use: The login() method uses the HttpClient class to send a POST request to the backend Web API Endpoint /api/auth/login with a request payload in the body containing the username and password of the user trying to login. Upon a successful login, the token returned from the backend API is stored inside LocalStorage to be used on subsequent requests to send it over as a Bearer authentication header. In addition, the currentUserSubject of type BehaviorSubject is triggered with the user payload. This subject is defined as follows inside the authentication service: The currentUserSubject is defined as a BehaviorSubject with an initial value equal to whatever user is stored in the LocalStorage. Also, the currentUservariable is defined as an Observable on top of the currentUserSubject. Other components and services in the application can now subscribe to the currentUser Observable since every time a successful login operation executes, it is guaranteed that this Observable will execute with the latest user signed in as a payload. In addition, the currentUserValue is defined as a public getter to retrieve the value of the currentUserSubject variable. Later on we will use this value inside the Auth Guard as you will see very soon. To logout a user, we simply delete the entry from the LocalStorage and populate the currentUserSubject with a null value signaling to all components and services that the user has signed out of the application. Step 3 To restrict access to the MovieTrackerList component let's rearrange the routing a little bit in our application as follows: The default route now lives under admin/movie-tracker. The path /admin now has a related component the AppMainComponent. This component renders an Angular Material layout for the entire application. In addition, any access to /admin is now restricted by the AuthGuard defined by using the canActivate handler that is executed before navigating to the requested route. The movie-tracker route is now defined as an admin child route. Finally, a new route is added to route requests to the Login component that we will build shortly. All routing configurations have been removed from within the MovieTracker module and have been centralized inside the AppModule. Step 4 Let's define the AuthGuard by first creating a new guard by running this command in a terminal window: ng generate guard app-auth/auth --skipTests=true The command creates a new auth.guard.ts file inside the path \src\app\app-auth\. Paste in the following code: The AuthGuard implements the CanActivate and provides implementation for the CanActivate handler. The handle calls the authenticationService.currentUserValue getter to check if there is an existing user (stored in the LocalStorage). If there is one, the code returns true meaning that it is safe to allow the route navigation. Otherwise, the user is redirected to the Login route. This AuthGuard is provided at the root of the application and hence it is accessible everywhere in the application. Step 5 Let's create a new Shared module inside the path \src\app\shared to hold a couple of components that are shared across the application. Then, you can import this module inside the MovieTracker module or any other module that needs to use any of the components defined in this module. Then, let's add the *AppMainComponent that contains HTML Markup which guarantees a standard UI layout for the entire app. Paste in the following inside the newly created app-main.component.ts file: The component uses the Angular Material Toolbar component, to define a toolbar header for the entire application. Remember, this component is rendered for any route starting with /admin. Then, the actual route the user is navigating to, gets rendered under the <router-outlet></router-outlet> marker component. This guarantees a standard UI across all routes and components in the application. The component also defines a Logout button so that the user can logout from the current session anytime they decide so. Step 6 It's time to build the Login component. Generate a new Login component inside the Shared module by running this command in a terminal window: ng g component shared/login --module=shared --skipTests=true --inlineTemplate=true --inlineStyle=true Paste in the following code: The HTML markup of the Login component defines a simple form to collect the username and password from the user. It also validates the form by requiring the user to enter a username and password. In addition, it notifies the user of any errors returned from the backend Web API in case the login process fails. This component makes use of the ReactiveFormsModule module from Angular. It defines the form as an object and binds it to the HTML form element. On form submission, it calls on the authenticationService.login method defined above to actually login the user. In the case a user is successfully authenticated, the code redirects the user to the home page of the application or to whatever URL the user had an intention to visit prior to being redirected to the Login route. Otherwise, if the user was not successfully authenticated, the errors returned from the backend Web API are displayed to the user. Step 7 Before running the application and trying things out, two things remain pending. We need to add an HTTP Interceptor to inspect a 401 Unauthorized response Status Code and redirect the user to the Login route accordingly. This occurs when a token is still available at the Angular app level, while in fact this token has expired on the backend Web API and the Angular app has no clue that it has expired. Create a new errors.interceptor.ts file inside the app-auth module with the following content: An HTTP Interceptor is defined as a Service and provided at the root module of the application. After a response is received from the backend server, the interceptor checks if the Status Code equals to 401. It first logs out the user (clear the LocalStorage) and then it refreshes the entire page causing the user to be redirected to the Login route. Finally, the service is provided in the HTTP_INTERCEPTORS collection. Switch back to the AppModule and add this interceptor provider as follows: … providers: [ errorInterceptorProvider ], … }) export class AppModule { } Step 8 Lastly, we need to guarantee that for each and every request sent to the backend Web API, an Authentication Bearer header is attached to the request when a user is authenticated to the application. Let's start by adding a new Jwt Interceptor that inspects the request before sending it to the server. In case there is a valid user with a valid token stored locally, an Authentication Bearer header is added to the current request and its value is set to Bearer {TOKEN}. Where token is being retrieved from the LocalStorage (if any). Create a new jwt.interceptor.ts file inside the app-auth module with the following content: The interceptor above clones the current request and sets the Authentication Bearer header on the new request before sending it to the server. Finally, the service is provided in the HTTP_INTERCEPTORS collection. Switch back to the AppModule and provide this interceptor provider as follows: … providers: [ jwtInterceptorProvider, ... ], … }) export class AppModule { } The Angular app is ready to start authenticating users. Let's give it a try. Step 9 Let's run the application using the command yarn run start. Make sure the backend API is also running. Once the application starts, the first thing you are redirected to is the Login route: Let's try an invalid combination of a username and password and see how the Login component behaves. Now let's try to sign in with the user credentials that we have previously seeded into the backend Web API and notice how the application now redirects us to the Movie Tracker route: You are now redirected successfully. You can see the new UI layout and also click the Logout button whenever you want to sign out of the application. You may now continue managing your movies after you've signed in to the application. Conclusion This second article concludes the first series of articles on Angular and the REST. The next series will cover the same stuff covered so far in the first two installments however by using a Node.js backend Web API instead of ASP.NET Core Web API and more specifically, it will use Nest.js to develop the backend Web API. This post was written by Bilal Haidar, a mentor with This Dot. You can follow him on Twitter at @bhaidar. Need JavaScript consulting, mentoring, or training help? Check out our list of services at This Dot Labs. Discussion Hi, Thank you for this helpful article. Using VS 2017 I could authenticate user only after disabled the ssl for IIS Express and used http: //localhost:44342 instead of https: //localhost:44342. Also when used Bearer token as type in the Authorization tab and pasted the token, I got 401 Unauthorized for the endpoints: localhost:44342/api/MovieTracker localhost:44342/api/MovieTracker/u... Also from the client I could not authenticate because the endpoint is taken from 4200 instead of 44342. Any fix for the above please ? Hi, in Startup.cs add "app.UseRouting();" instead of "app.UseMvc();" and "app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); });" That worked for me. Hi, Thanks for your comment, The code you implemented in startup class is to upgrade to version 3.0 of .Net Core, maybe there's something else missing, but I'll give it a try again with 3.0 asap.
https://dev.to/thisdotmedia/angular-and-the-rest-authentication-with-jwt-5em0
CC-MAIN-2020-45
refinedweb
3,134
53.1
tag:blogger.com,1999:blog-5743983044224833668.post1158871735078076122..comments2022-03-19T05:16:40.634-07:00Comments on Fatvat: Metadata in ClojureJeff Patrick, I'm not too versed in the literat...Hi Patrick,<br /><br />I'm not too versed in the literature either I'm afraid. <br /><br />I looked at chapter 30 of <a href="" rel="nofollow">Programming Languages: Application and Interpretation</a> for a basic description. <br /><br /><a href="" rel="nofollow">TAPL</a> is the bible of types in programming languages, but I confess I haven't got a copy (yet!).<br /><br />In terms of a particular implementation, Hindley–Milner inference is the only algorithm I've looked at.<br /><br />Unfortunately I never got very far with this idea. I think there's definitely some scope to do some cool stuff there, but I never have the time to do anything other than toy projects :(<br /><br />If anyone wants to start some kind of project looking at this, then I'd be happy to contribute :)Jeff Jeff, That sounds like a killer applicatio...Hello Jeff, <br /><br /?<br />PatPatrick Mahoney Pat, Thanks for the comments and pointing out ...Hi Pat,<br /><br />Thanks for the comments and pointing out some of the possible applications of metadata in the future.<br /><br /.<br /><br />Of course, this wouldn't force you into static typing, it's just be like Clojure Lint.<br /><br />I wonder if this would allow you to layer something like Typed Scheme over the top whilst minimizing the syntactic overhead of types.<br /><br />I think I'll remain pondering this idea for some time :)Jeff Jeff, I enjoyed your post. One of the poten...Hello Jeff, <br /. <br />I think Clojure macros hit a sweet spot between CL macros and Scheme macros - I think the mandatory namespace qualification is a win,as you get certain aspects of hygiene, and metadata might allow for more contextual info to be attached to symbols a la syntax case. <br />I will continue to follow your blog :) have fun with lisp.Patrick Mahoney
http://www.fatvat.co.uk/feeds/1158871735078076122/comments/default
CC-MAIN-2022-27
refinedweb
348
61.77
As hackers, we like to think of ourselves as a logical bunch. But the truth is, we are as subject to fads as the general public. There was a time when the cool projects swapped green LEDs out for blue ones or added WiFi connectivity where nobody else had it. Now all the rage is to connect your project. Admittedly, my example skill isn’t performing a particularly difficult task, but it is a good starter and if you want to develop your own, it will give you a head start. Although I used a particular tool, there’s no reason you could not move from that tool to your own infrastructure later, if you had the need to do so. One nice thing about Glitch is that you can share code live and people can remix it. Think of a GitHub fork, but where you can try running my copy and your copy is instantly live, too. Turns out for the Alexa skills, having it live isn’t as useful as you’d like because you still have to tell Amazon about it. But it does mean there are example Alexa skills (including mine) that you can borrow to get yours started, just like I borrowed one to start mine. Do You Need It? The first question you might ask yourself is do you even need an Alexa skill? I recently got Alexa to control my 3D printers by using IFTTT with no software development at all required. However, if you really want to claim you work with a virtual assistant, you are going to have to write some code somewhere. Of course, there’s the bigger philosophical question: do you need to do any of this? I’ll admit, I find it useful to have my 3D printers on voice control because I might be making adjustments with both hands and I don’t have to fumble with buttons to have the machine do a homing cycle, for example. I’m less sold that I need a virtual assistant to launch my drone. Then again, maybe that’s what you want to do and that’s up to you. Getting Started If you don’t already have one, you might as well go ahead and sign up for an Amazon developer’s account. Then head over to Glitch and register there, too. There are at least two templates for building an Alexa skill. There are a bare-bones one and a more involved one that retrieves weather forecasts. If you are looking at the page, it might not make much sense. Remember, the web server is meant to talk to Alexa, not people. In the top right corner is an icon with a pair of fish. If you click there, you can view the source or you can remix it. I decided to remix the weather forecast service since I thought it was a better example. Then I cut away all the weather-related code (except some of the documentation) and wrote a simple Javascript function: function get_fact() { var factArray = [ 'Hackers read Hackaday every day', 'You know you are 3D printing too much when you tell someone you are extruding mustard on your hot dog', 'The best microcontroller is the one already programmed to do what you want', 'We can all agree. All software has bugs. All software can be made simpler. Therefore, all programs can be reduced to one line of code that does not work.', 'I hate talking to flying robots. They just drone on.', 'If you call your morning cup of coffee installing Java, you need a hobby', 'I have heard that in C functions should not call each other because they usually have arguments', 'I refused to learn C plus plus. I saw see-out being shifted left hello world times and gave up', 'If cavemen had thought of binary we could all count to 1023 on our fingers', 'If you can\'t hack it, you don\'t own it.' ]; var randomNumber = Math.floor(Math.random()*factArray.length); return factArray[randomNumber]; } The only thing left to do is to hook the code up to the Web service framework. Express Glitch automatically sets up a library called Express in this project. It essentially is a simple Web server. Once you create the main app object, you can set up routes to have your code execute when someone calls a particular web service. It also includes an object that represents an Alexa service. I didn’t have to write the code to set this up, but here it is: app = express(), // Setup the alexa app and attach it to express before anything else. alexaApp = new alexa.app(""); // POST calls to / in express will be handled by the app.request() function alexaApp.express({ expressApp: app, checkCert: true, // sets up a GET route when set to true. This is handy for testing in // development, but not recommended for production. debug: true }); There are two methods I wanted to provide. One for when someone opens my skill (I called it Hacker Fact, by the way — it gives mildly humorous facts about hacking and related things). The other method will fire when someone says, “Alexa, tell Hacker Fact to give me a fact.” Or anything similar. That last bit is known as an intent. Intents can have utterances (like “give me a fact”) and they can have slots. I didn’t use any slots (but the weather example did). Using slots you can have some part of the person’s command fed to you as an argument. For example, I could make it so you could say, “Alexa, tell Hacker Fact to give me a fact about Arduinos.” Then I could build the intent so that the next word after it hears “about” is a slot and parse it in my code. You probably won’t need it, but if you are curious to learn more about Express, check out this video. The Two Methods Here are the two methods: alexaApp.launch(function(request, response) { console.log("App launched"); response.say('Hi from your friends at Hackaday. Ask me for a fact to learn something interesting or possibly funny.'); }); alexaApp.intent("HackerFact", { "slots": { }, "utterances": [ "Tell me a hacker fact", "Give me a hacker fact", "tell me a fact", "give me a fact", "go", "fact" ] }, function(request, response) { console.log("In Fact intent"); response.say(get_fact()); } );<span data-</span> Note the “HackerFact” intent has an array of utterances that will be sent to Amazon. You can find the entire HackerFact code online. Don’t forget, you can view the source or remix with the two fish icon at the top right of the page. All of the code is in the index.js file. There are a few other files, but for this task, you probably won’t make any changes to them other than perhaps changing some text in the package file or documentation. On to Amazon Oddly enough, the next part is probably harder. From the front page of the Amazon developer’s site, you’ll want to select Alexa skills and then press the “Add a New” Skill button. A lot of the entries you’ll see have to do with more complex skills. Also, I’m not going to publish my skill, but it will still show up in my account. If you do some paperwork, you can submit your skill for testing with selected users or even publish it outright. Here’s a rundown of the fields you need to fill in on the Skill Information tab: - Skill type = Custom Interaction Model - Name = Whatever display name you like - Invocation Name = This is what people will ask Alexa to use (e.g., “Alexa, tell Hacker Fact…” would mean my invocation name was Hacker Fact) I’ve had bad luck, by the way, changing the invocation name after it has been set, so think hard about that one. The next page (Interaction Model) looks complicated, but it isn’t, thanks to the libraries provided by Glitch. Open your Glitch project. If you are looking at the source, click “show” in the upper part of the screen. The default project causes a data dump to appear on the main page (which, normally, no one sees) that includes the information you need for this page. The Intent Schema box needs everything after “Schema:” and before “Utterances:” from your main page. That includes the braces. My Intent Schema looks like this: { "intents": [ { "intent": "HackerFact" }, { "intent": "AMAZON.CancelIntent" }, { "intent": "AMAZON.StopIntent" } ] } The rest of the page has some lines after “Utterances:” and those lines are what the last box needs. The middle box can remain empty, for this example. More Steps to Connect Glitch with Amazon In the Configuration tab, you can select HTTPS and then enter the URL from Glitch. To find that URL, open the project name at the top left of the screen and you’ll see it along with a copy button. Mine, for example, is. You don’t allow account linking and you can leave all the optional boxes alone. On the next screen, you’ll want to pick “My development endpoint is a sub-domain of a domain that has a wildcard certificate from a certificate authority” because that’s how Glitch works. That’s all you need on that page. At this point, your skill should show up on any Alexa associated with your account (including Alexa apps like Reverb on your phone). You can also do tests here in the console to see if things work. Release the Hounds This is enough to get your code working with your Alexa. I won’t go into releasing the skill for others to use, but that is an option if you want to keep going on your own. You can use Glitch for other things too, including some Raspberry Pi and a few other IoT-type platforms. If you look around, you’ll probably find something interesting. Of course, you could set up your own server to do all the things that Glitch is doing for you — maybe even on a Raspberry Pi. You can also let Amazon host your code as a Lambda function (that is, a web service with no fixed web server; see the video, below). If you get a taste for writing skills, the Amazon documentation isn’t bad, but sometimes there’s value to just jumping in and getting something working. 18 thoughts on “Custom Alexa Skill In A Few Minutes Using Glitch” Any charge for using Amazon’s Cloud? Only fi you exceed a certain amount of processor time or something, which is pretty large. And if you’re using that much, they are probably monetising your skill anyway, which should allow you to keep developing. Alexa torrent network incoming… Do we need Alexa? Why? It’s been a while since I tried to install and run any voice recognition software. I think I remember doing so as early as the 1990s. Of course at that time it was pretty rough and not really up to the task of being much more than a curiosity. Surely the situation has improved though. Between home computers becoming more powerful and developers having had 20 some years to continue development are there no good free, open source voice recognition programs out there? If not, are there no affordable commercial ones? I’m a little uncomfortable with the idea of installing a microphone that streams to some third party in my home. Why isn’t anyone doing these sorts of projects using their own instance of some voice recognition software running on their own raspberry pi or old desktop computer sitting in their own home? With so many makers rolling Alexa or Google Talk projects it seems like this should be a thing already! I know, I could start Googling “voice recognition open source.”. I probably will but I don’t really have the time to install a bunch of applications and test out their performance. I’m guessing the community here already knows what is missing to make this happen. There are a few out there but the quality is low and installation is often painful. Closest thing is Mycroft although it uses cloud back ends also, but I think you can host your own backends, it just isn’t the default and probably not well supported. There’s also Jasper. Maybe a few others. The problem is Google and Amazon and even Apple have spoiled us. CMSSphinx is probably the best open voice recognition and it is nowhere near the speed an accuracy that we have with the cloud services. I must lead a boring life, but I don’t think anyone wants to hear what goes on in my house. Phones were/are notoriously insecure, but we forgot about it because we are lost in the volume of calls (usually). In the movie Gorky Park, the characters jammed pencils in the dial phone to break the connection back to the central office before having forbidden conversations for fear of eavesdropping. Harder to do that now. “I must lead a boring life, but I don’t think anyone wants to hear what goes on in my house.” Incorrect, advertisers definitely WANT to hear what goes on in your house and not for nefarious purposes, but quite simply so that you can help make their jobs easier. It has nothing to do with how boring or exciting your life is because either end of the spectrum helps them gather demographic data as well as better insight into motivations and how to sell you on a thing or idea. The really scary thought is the similarities between advertising and population control, both take the same input data and have the same goals. They want as much information about you and your habits and then want to take that information to effect your emotions and decisions. That is really what makes these home assistants so creepy and was quintessentially a major plot point in Orwell’s 1984. Oh man, Mycroft! Takes me back to Lirc and GIRDER days :) My earliest fussing with voice recognition ended up going in a totally different route. I ended up setting up my first one with a microphone pointed out the window that could identify(some of) my apartment neighbors’ cars by the sound of their engine. It could also identify birds by their chirps but my main problem was with filtering background noise and bogus events. I would probably shudder if I fired it up and looked at my old “work” haha. Great fun back then though :) I’m sure VADs are fun. Page 7, SnR difficulties was definitely my rig’s problem. Good PDF, Ostracus. As you can imagine with an outdoor mic, the gain was untameable by myself for unattended usage. I tried a couple of tricks like running it thru an outboard gate that helped but meh the software wasn’t really designed for my usage. Indeed it was fun :) I had it able to control my mouse by humming a freq from mid to higher and amplitude as the Y axis but it only worked very close to the mic/computer so it was kinda pointless (thus LiRC and GiRDER with a remote mouse) and of course various macros to impress the 1990s crowd haha. I kinda wish I had pursued it and AI a bit more than a hobby these days but hindsight is 20/20. I’m curious how many people here use home-assistant and snips (), it looks promising. Biggest issue is probably training offline voice recognition, the large companies have huge data sets to work with. Great article! I was a skeptic who didn’t believe the hype about Alexa, but then I got one for christmas. It turns out to be sort of magical to be able to give orders to play this song or skip that one while I’m in the middle of cooking or doing dishes. what could possibly go wrong… Is there a site where you can see more creative things do e with these intruders? Seriously, skipping songs while cooking dinner is not a selling point, turning lights on and off is not a selling point. Alexa bringing up a recipe on my tv in my kitchen might be. Reading it to me might be more impressive. Fetching messages from emails might. Perform some serious number crunching? Activate my pump house light if the temp falls below 25. Tell me what my power usage is for the day? Week? Month? Glitch? Skill? Huh? *crawls back under rock* If you want a self-hosted option, check out the Flask-Ask project. I run this on a Pi and I can execute arbitrary code with voice commands. The downside to Alexa is that the commands for custom skills are clunky. i.e. all commands have to be of the format “ask appname to [do action]”. There is some way to do better, but I haven’t looked into it. They may even restrict it to keep from polluting the namespace. When I first got the Alexa, it had to do that for Harmony remotes. “Computer, ask Harmony to turn on TV.” But they later released a skill where Alexa now knows when I say “Turn on TV” I mean to use Harmony. The problem is it only knows about one Harmony and the other one you have to do something strange like IFTTT or Younomi or… And Google Home not only still makes you ask for Harmony, but worse if you forget it will say “Sounds like you want Harmony. Do you want to try that?” I guess that’s OK but I find it a little offensive that it KNOWS what I want and still wants to confirm. I could see if it were “Sounds like you want ICBM launch application. Do you want to try that?” But for my TV. It also frustrates me that if I am sleepy and it can’t recognize my voice, it won’t operate Harmony — I really don’t care if people change my TV. I get it for door locks or what not. One of the things I dislike about both is they are dumbed down. Why can’t I have a “hacker” section in the web site configuration that lets me do things like enable/disable voice identification for particular services (you must recognize my voice to unlock the door but anyone can change TV channels). Or, as some have said, point to an arbitrary web service. I really want to be excited about this, but it looks incredibly complex to get such a simplistic end result. Like the previous comment, I quickly got frustrated with the “Alex ask APPNAME to” format of commands. Using “Alexa run APPNAME” is a little better, but only works if you have no commands to pass along. Plus the whole setup is too convoluted for my tastes. I want the thing to run a Python script on the Pi that’s sitting 5 feet away from it. The idea that to do that I need to go out to the Internet and come back, and set the Skill up with Amazon as if I was going to release it publicly…ugh. I actually agree with you Dan – I am working on a project that would create an Alexa skill that would allow her to be used with ANY computer capable of communicating over a LAN (TCP, UDP). If there are any Alexa developers out there willing to help (including AI Williams) please email me at RobotBASIC@yahoo.com.
https://hackaday.com/2018/01/17/an-alexa-skill-among-other-things-in-a-few-minutes/?replytocom=4310187
CC-MAIN-2019-47
refinedweb
3,277
71.14
Pull Files from Remote to Local¶ Connecting to Pipes¶ To pull and push files, you first connect to a data pipe. A data pipe lets you manage remote and local data files. import d6tpipe api = d6tpipe.api.APIClient() api.list_pipes() # show available pipes pipe = d6tpipe.Pipe(api, 'pipe-name') # connect to a pipe Show remote files¶ To show files in the remote storage, run pipe.scan_remote(). pipe = d6tpipe.Pipe(api, 'pipe-name') pipe.scan_remote() # show remote files Pulling Files to Local¶ Pulling files will download files from the remote data repo to the local data repo. Typically you have to write a lot of code to download files and sync remote data sources. With d6tstack you can sync pull with just a few lines of python. pipe = d6tpipe.pipe.Pipe(api, 'pipe-name') pipe.pull_preview() # preview pipe.pull() # execute Your files are now stored locally in a central location and conveniently accessible. See Accessing Pipe Files to learn how to use files after you have pulled them. Which files are pulled?¶ Only files that you don’t have or that were modified are downloaded. You can manually control which files are downloaded or force download individual files, see advanced topics. Advanced Topics¶ Pull Modes¶ You can control which files are pulled/pushed default: modified and new files new: new files only mod: modified files only all: all files, good for resetting a pipe pipe = d6tpipe.pipe.Pipe(api, 'test', mode='all') # set mode pipe.pull() # pull all files pipe.setmode('all') # dynamically changing mode Useful Pipe Operations¶ Below is a list of useful functions. See the reference Module Index for details. # advanced pull options pipe.pull(['a.csv']) # force pull on selected files pipe.pull(include='*.csv',exclude='private*.xlsx') # apply file filters # other useful operations api.list_local_pipes() # list pipes pulled pipe.files() # show synced files pipe.scan_remote() # show files in remote pipe.scan_remote(sortby='modified_at') # sorted by modified date pipe.is_synced() # any changes? pipe.remove_orphans() # delete orphan files pipe.delete_files() # reset local repo
https://d6tpipe.readthedocs.io/en/latest/pull.html
CC-MAIN-2021-49
refinedweb
334
61.93
The functions in this section are always available to the interpreter and are contained within the __builtin__ module. In addition, the __builtins__ attribute of each module usually refers to this module. _ (underscore) By default, the _ variable is set to the result of the last expression evaluated when the interpreter is running in interactive mode. __import__(name [, globals [, locals [, fromlist]]]) This function is invoked by the import statement to load a module. name is a string containing the module name, globals is an optional dictionary defining the global namespace, locals is a dictionary defining the local namespace, and fromlist is a list of targets given to the from statement. ... No credit card required
https://www.safaribooksonline.com/library/view/python-essential-reference/0672328623/0672328623_ch12lev1sec1.html
CC-MAIN-2018-09
refinedweb
114
52.39
Opened 9 years ago Closed 9 years ago #5592 closed (invalid) HttpResponseRedirect dosen't work anymore with Squid Reverse Proxy Description After changes os revision 6164 from django.http.init.py the method HttpResponseRedirect dosent works anymore with a Reverse Proxy. I have a Squid in frontend two Apache servers and the redirects don't work more after revision 6164. I'm using revision 6163 now :) Thanks Change History (8) comment:1 Changed 9 years ago by mir - Keywords squid added - Needs documentation unset - Needs tests unset - Patch needs improvement unset - Triage Stage changed from Unreviewed to Accepted comment:2 Changed 9 years ago by mir lzanuz, can you add please information about your exact setup, like: - mod_python or what? - the relevant parts of the apache configuration (especially rewrite rules etc.) - the squid setup - how the redirects don't work (what do you get?) comment:3 Changed 9 years ago by mtredinnick - Resolution set to invalid - Status changed from new to closed Yeah, we definitely need more information here. The change in [6164] makes us follow the HTTP spec correctly (previously we were not), so it's not really negotiable. Closing for now, since it's been a month since the request for more information. Please reopen if you can provide more details about how to repeat the problem. comment:4 Changed 9 years ago by anonymous - Resolution invalid deleted - Status changed from closed to reopened comment:5 Changed 9 years ago by anonymous After the revision 6164 django stoped to work with a squid proxy reverse. I have a application running in two server and a squid proxy making load balance in front of the apaches: I needed to make this path for squid work again after the revison 6164. Thanks from django.core.handlers import base def fix_location_header(request, response): """ Path for correct squid proxy reverse after django rev.6164. ---Removed--- if 'Location' in response and request.get_host(): responseLocation? = request.build_absolute_uri(responseLocation?) """ return response base.fix_location_header = fix_location_header comment:6 Changed 9 years ago by mtredinnick No, that doesn't give us more information about how to repeat the problem. That just tells us what you changed to make it work with your particular -- completely unknown to us -- installation. What are the relevant Squid configuration lines for example? What is an example of the HTTP response being sent across the wire that doesn't work? As I mentioned above, we are now sending (or should be sending, barring some minor bug) correct Location headers. So I strongly suspect a configuration problem on your end somewhere. Try to capture the response that is causing the problem (use wireshark or something similar, for example). Try to replicate the problem in a small example. Print out the value of !responseLocation that we construct to see what it looks like. Any of this would be information we could use to debug the problem further. Suggesting that we just remove the very line that fixes the bug is not information that helps anybody debug further. comment:7 Changed 9 years ago by anonymous Sorry, but I can't send the squid rules and full http wire, but I will send the specific part where is the error. Hypertext Transfer Protocol HTTP/1.0 503 Service Unavailable\r\n Request Version: HTTP/1.0 Response Code: 503 Server: squid/2.6.STABLE16-20070912\r\n Date: Mon, 22 Oct 2007 20:09:04 GMT\r\n Content-Type: text/html\r\n Content-Length: 1209 Expires: Mon, 22 Oct 2007 20:09:04 GMT\r\n X-Squid-Error: ERR_DNS_FAIL 0\r\n X-Cache: MISS from ucs\r\n X-Cache-Lookup: MISS from ucs:3028\r\n Via: 1.0 ucs:3028 (squid/2.6.STABLE16-20070912)\r\n Proxy-Connection: close\r\n And the html returned in portuguese: A URL solicitada nao pode ser recuperada Na tentativa de recuperar a URL: O seguinte erro foi encontrado: Incapaz de determinar o endereço IP atraves do nome do host backendpool O servidor DNS retornou: DNS Domain 'backendpool' is invalid: Host not found (authoritative). Isso significa que: O cache foi incapaz de resolver o nome do host presente na URL. Verifique se o endereço esta correto. Generated Mon, 22 Oct 2007 20:09:04 GMT by ucs (squid/2.6.STABLE16-20070912) My impression is that apache take this url "" and send it back to squid. Thanks for your help until now! comment:8 Changed 9 years ago by mtredinnick - Resolution set to invalid - Status changed from reopened to closed So this is a configuration error on your side and the Squid error message is telling you exactly what the problem is. The domain name must be valid. Django builds up the domain name from these HTTP headers (in this order; the first one present is the hostname): - The "X-Forwarded-Host" HTTP header - The "Host" HTTP header (Required in all HTTP/1.1 requests) - The server name (if using the mod_python handler) Somewhere (and I guess it's the ServerName directive in you Apache config), you're setting the name to backendpool. You have to fix that to make it something Squid can resolve. This is not a Django bug. I didn't test this, but this looks plausible enough.
https://code.djangoproject.com/ticket/5592
CC-MAIN-2016-22
refinedweb
877
62.88
For the OpenCV developer team it’s important to constantly improve the library. We are constantly thinking about methods that will ease your work process, while still maintain the libraries flexibility. The new C++ interface is a development of us that serves this goal. Nevertheless, backward compatibility remains important. We do not want to break your code written for earlier version of the OpenCV library. Therefore, we made sure that we add some functions that deal with this. In the following you’ll learn: When making the switch you first need to learn some about the new data structure for images: Mat - The Basic Image Container, this replaces the old CvMat and IplImage ones. Switching to the new functions is easier. You just need to remember a couple of new things. OpenCV 2 received reorganization. No longer are all the functions crammed into a single library. We have many modules, each of them containing data structures and functions relevant to certain tasks. This way you do not need to ship a large library if you use just a subset of OpenCV. This means that you should also include only those headers you will use. For example: #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> All the OpenCV related stuff is put into the cv namespace to avoid name conflicts with other libraries data structures and functions. Therefore, either you need to prepend the cv:: keyword before everything that comes from OpenCV or after the includes, you just add a directive to use this: using namespace cv; // The new C++ interface API is inside this namespace. Import it. Because the functions are already in a namespace there is no need for them to contain the cv prefix in their name. As such all the new C++ compatible functions don’t have this and they follow the camel case naming rule. This means the first letter is small (unless it’s a name, like Canny) and the subsequent words start with a capital letter (like copyMakeBorder). Now, remember that you need to link to your application all the modules you use, and in case you are on Windows using the DLL system you will need to add, again, to the path all the binaries. For more in-depth information if you’re on Windows read How to build applications with OpenCV inside the Microsoft Visual Studio and for Linux an example usage is explained in Using OpenCV with Eclipse (plugin CDT). Now for converting the Mat object you can use either the IplImage or the CvMat operators. While in the C interface you used to work with pointers here it’s no longer the case. In the C++ interface we have mostly Mat objects. These objects may be freely converted to both IplImage and CvMat with simple assignment. For example: Mat I; IplImage pI = I; CvMat mI = I; Now if you want pointers the conversion gets just a little more complicated. The compilers can no longer automatically determinate what you want and as you need to explicitly specify your goal. This is to call the IplImage and CvMat operators and then get their pointers. For getting the pointer we use the & sign: Mat I; IplImage* pI = &I.operator IplImage(); CvMat* mI = &I.operator CvMat(); One of the biggest complaints of the C interface is that it leaves all the memory management to you. You need to figure out when it is safe to release your unused objects and make sure you do so before the program finishes or you could have troublesome memory leeks. To work around this issue in OpenCV there is introduced a sort of smart pointer. This will automatically release the object when it’s no longer in use. To use this declare the pointers as a specialization of the Ptr : Ptr<IplImage> piI = &I.operator IplImage(); Converting from the C data structures to the Mat is done by passing these inside its constructor. For example: Mat K(piL), L; L = Mat(pI); Now that you have the basics done here's an example that mixes the usage of the C interface with the C++ one. You will also find it in the sample directory of the OpenCV source code library at the samples/cpp/tutorial_code/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.cpp . To further help on seeing the difference the programs supports two modes: one mixed C and C++ and one pure C++. If you define the DEMO_MIXED_API_USE you’ll end up using the first. The program separates the color planes, does some modifications on them and in the end merge them back together. Here you can observe that with the new structure we have no pointer problems, although it is possible to use the old functions and in the end just transform the result to a Mat object. Because, we want to mess around with the images luma component we first convert from the default BGR to the YUV color space and then split the result up into separate planes. Here the program splits: in the first example it processes each plane using one of the three major image scanning algorithms in OpenCV (C [] operator, iterator, individual element access). In a second variant we add to the image some Gaussian noise and then mix together the channels according to some formula. The scanning version looks like: Here you can observe that we may go through all the pixels of an image in three fashions: an iterator, a C pointer and an individual element access style. You can read a more in-depth description of these in the How to scan images, lookup tables and time measurement with OpenCV tutorial. Converting from the old function names is easy. Just remove the cv prefix and use the new Mat data structure. Here’s an example of this by using the weighted addition function: As you may observe the planes variable is of type Mat. However, converting from Mat to IplImage is easy and made automatically with a simple assignment operator. The new imshow highgui function accepts both the Mat and IplImage data structures. Compile and run the program and if the first image below is your input you may get either the first or second as output: You may observe a runtime instance of this on the YouTube here and you can download the source code from here or find it in the samples/cpp/tutorial_code/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.cpp of the OpenCV source code library.
https://docs.opencv.org/2.4.13.3/doc/tutorials/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.html
CC-MAIN-2020-24
refinedweb
1,081
61.36
From: David Abrahams (dave_at_[hidden]) Date: 2007-04-06 07:21:26 on Thu Apr 05 2007, Stephen Pietrowicz <srp-AT-ncsa.uiuc.edu> wrote: > I ran ./configure and then make to on Boost 1.33.1, and reported 10 > errors on an Intel Mac. I get 6 errors on a PPC Mac. I've seen > other messages similar to this on the list, but I haven't seen any > solutions posted. One of the problems reported in that build is > listed below after this main message. (the other errors were similar). > > I looked around for a solution to this, and it appears that there's a > patch from Adobe that fixes a V2 version of darwin.jam that might > help with this problem. I applied that patch, but I wasn't able to > get that to run either. I know I'm invoking it incorrectly, and it > tells my that Python isn't configured, no toolsets are configured, You'll need the darwin toolset > and to consult the documention. I haven't found anything that > says: Out of the box, here's how to build boost using V2 instead of > V1. See > All I'd like to do is point at my Python install (which is in a local > directory), and get this to build, but I keep running into roadblocks. You'll likely only need one additional thing to configure python: a user-config.jam file in your home directory containing: import toolset : using ; using python : : /path/to/your/python/interpreter ; I'm currently working on updating the Boost.Python build docs. HTH, --
https://lists.boost.org/boost-build/2007/04/16377.php
CC-MAIN-2022-27
refinedweb
265
74.39
#include <wx/toplevel.h> wxTopLevelWindow is a common base class for wxDialog and wxFrame. It is an abstract base class meaning that you never work with objects of this class directly, but all of its methods are also applicable for the two classes above. Note that the instances of wxTopLevelWindow are managed by wxWidgets in the internal top level window list. Event macros for events emitted by this class: wxEVT_MAXIMIZEevent. See wxMaximizeEvent. wxEVT_MOVEevent, which is generated when a window is moved. See wxMoveEvent. wxEVT_MOVE_STARTevent, which is generated when the user starts to move or size a window. wxMSW only. See wxMoveEvent. wxEVT_MOVE_ENDevent, which is generated when the user stops moving or sizing a window. wxMSW only. See wxMoveEvent. wxEVT_SHOWevent. See wxShowEvent. Default ctor. Constructor creating the top level window. Destructor. Remember that wxTopLevelWindows do not get immediately destroyed when the user (or the app) closes them; they have a delayed destruction. See Window Deletion for more info. Returns true if the platform supports making the window translucent. Reimplemented from wxWindow. A synonym for CentreOnScreen(). Centres the window on screen. Creates the top level window. Enables or disables the Close button (most often in the right upper corner of a dialog) and the Close entry of the system menu (most often in the left upper corner of the dialog). Returns true if operation was successful. This may be wrong on X11 (including GTK+) where the window manager may not support this operation and there is no way to find out. Enables the maximize button to toggle full screen mode. Prior to OS X 10.10 a full screen button is added to the right upper corner of a window's title bar. Currently only available for wxOSX/Cocoa. Enables or disables the Maximize button (in the right or left upper corner of a frame or dialog). Currently only implemented for wxMSW and wxOSX. The window style must contain wxMAXIMIZE_BOX. Returns true if operation was successful. Note that a successful operation does not change the window style flags. Enables or disables the Minimize button (in the right or left upper corner of a frame or dialog). Currently only implemented for wxMSW and wxOSX. The window style must contain wxMINIMIZE_BOX. Note that in wxMSW a successful operation will change the window style flags. Returns true if operation was successful. Note that a successful operation does not change the window style flags. Returns a pointer to the button which is the default for this window, or NULL. The default button is the one activated by pressing the Enter key. Get the default size for a new top level window. This is used internally by wxWidgets on some platforms to determine the default size for a window created using wxDefaultSize so it is not necessary to use it when creating a wxTopLevelWindow, however it may be useful if a rough estimation of the window size is needed for some other reason. Returns the standard icon of the window. The icon will be invalid if it hadn't been previously set by SetIcon(). Returns all icons associated with the window, there will be none of them if neither SetIcon() nor SetIcons() had been called before. Use GetIcon() to get the main icon of the window. Gets a string containing the window title. Iconizes or restores the window. Reimplemented in wxDialog. Returns true if this window is currently active, i.e. if the user is currently working with it. Returns true if this window is expected to be always maximized, either due to platform policy or due to local policy regarding particular class. Reimplemented in wxMDIChildFrame. Returns true if the window is in fullscreen mode. Returns true if the window is maximized. This method is specific to wxUniversal port. Returns true if this window is using native decorations, false if we draw them ourselves. See wxWindow::SetAutoLayout(): when auto layout is on, this function gets called automatically when the window is resized. Reimplemented from wxWindow. Maximizes or restores the window. Reimplemented in wxMDIChildFrame. MSW-specific function for accessing the system menu. Returns a wxMenu pointer representing the system menu of the window under MSW. The returned wxMenu may be used, if non- NULL, to add extra items to the system menu. The usual wxEVT_MENU events (that can be processed using EVT_MENU event table macro) will then be generated for them. All the other wxMenu methods may be used as well but notice that they won't allow you to access any standard system menu items (e.g. they can't be deleted or modified in any way currently). Notice that because of the native system limitations the identifiers of the items added to the system menu must be multiples of 16, otherwise no events will be generated for them. The returned pointer must not be deleted, it is owned by the window and will be only deleted when the window itself is destroyed. This function is not available in the other ports by design, any occurrences of it in the portable code must be guarded by preprocessor guards. Returns the current modified state of the wxTopLevelWindow on OS X. On other platforms, this method does nothing. This function sets the wxTopLevelWindow's modified state on OS X, which currently draws a black dot in the wxTopLevelWindow's close button. On other platforms, this method does nothing. Use a system-dependent way to attract users attention to the window when it is in background. flags may have the value of either wxUSER_ATTENTION_INFO (default) or wxUSER_ATTENTION_ERROR which results in a more drastic action. When in doubt, use the default value. This function is currently implemented for Win32 where it flashes the window icon in the taskbar, and for wxGTK with task bars supporting it.. Restores the window to the previously saved geometry. This is a companion function to SaveGeometry() and can be called later to restore the window to the geometry it had when it was saved. Save the current window geometry to allow restoring it later. After calling this function, window geometry is saved in the provided serializer and calling RestoreToGeometry() with the same serializer later (i.e. usually during a subsequent program execution) would restore the window to the same position, size, maximized/minimized state etc. This function is used by wxPersistentTLW, so it is not necessary to use it if the goal is to just save and restore window geometry in the simplest possible way. However is more flexibility is required, it can be also used directly with a custom serializer object. Changes the default item for the panel, usually win is a button. Sets the icon for this window. Sets several icons of different sizes for this window: this allows to use different icons for different situations (e.g. task switching bar, taskbar, window title bar) instead of scaling, with possibly bad looking results, the only icon set by SetIcon(). Reimplemented in wxDialog. Sets the file name represented by this wxTopLe. Allows specification of minimum and maximum window sizes, and window size increments. If a pair of values is not set (or set to -1), no constraints will be used. Reimplemented from wxWindow. Allows specification of minimum and maximum window sizes, and window size increments. If a pair of values is not set (or set to -1), no constraints will be used. Reimplemented from wxWindow. Sets the window title.. Depending on the value of show parameter the window is either shown full screen or restored to its normal state. style is a bit list containing some or all of the following values, which indicate what elements of the window to hide in full-screen mode: wxFULLSCREEN_NOMENUBAR wxFULLSCREEN_NOTOOLBAR wxFULLSCREEN_NOSTATUSBAR wxFULLSCREEN_NOBORDER wxFULLSCREEN_NOCAPTION wxFULLSCREEN_ALL(all of the above) This function has not been tested with MDI frames. Show the wxTopLevelWindow, but do not give it keyboard focus. This can be used for pop up or notification windows that should not steal the current focus. This method is specific to wxUniversal port. Use native or custom-drawn decorations for this window only. Notice that to have any effect this method must be called before really creating the window, i.e. two step creation must be used: This method is specific to wxUniversal port. Top level windows in wxUniversal port can use either system-provided window decorations (i.e. title bar and various icons, buttons and menus in it) or draw the decorations themselves. By default the system decorations are used if they are available, but this method can be called with native set to false to change this for all windows created after this point. Also note that if WXDECOR environment variable is set, then custom decorations are used by default and so it may make sense to call this method with default argument if the application can't use custom decorations at all for some reason.
https://docs.wxwidgets.org/3.1.2/classwx_top_level_window.html
CC-MAIN-2019-09
refinedweb
1,468
57.57
abs() vs fabs() function in Python This tutorial will teach you about the working of abs() and fabs() method in Python and their differences. The primary purpose of both of these functions is to find the absolute value of a given positive or negative number. But these are a little different in their functioning. Let’s see more about abs() and fabs() functions further in this tutorial. abs() vs fabs() method in Python We will discuss these two functions separately in this tutorial. abs() method Python abs() method is a built-in method and does not require importing any Python module. It has the following syntax. abs(number); In the above syntax, the number can be integer or float. The return type is the same as the input number. This method accepts a number as input and returns its absolute value. See the below implementation of the abs() method in Python. number = 5.7 print(abs(number)) number = -18.9 print(abs(number)) number = 5 print(abs(number)) number = -4 print(abs(number)) Output: 5.7 18.9 5 4 Now let’s see how fabs() method behaves. fabs() method This function has the following syntax. math.fabs(number); This method is defined in the math module of Python. Which is why we need to import the math module before using the fabs() method. To know about more methods in the math module, refer here: Math module of Python Like the abs() method, this function also converts a given input number, which can be integer or float, into its absolute value. The only difference is that its return type is float. Therefore, irrespective of the given input number, the function returns a float value. Please have a look at the below python program to understand the concept. Here it is. import math number = 5.7 print(math.fabs(number)) number = -18.9 print(math.fabs(number)) number = 5 print(math.fabs(number)) number = -4 print(math.fabs(number)) And the output is: 5.7 18.9 5.0 4.0 As you can see, we have imported the math module to use fabs() method in our program. And this function has returned the absolute value in float for the given inputs. Thank you and keep coding. Also read: Move all the files from one directory to another in C++
https://www.codespeedy.com/abs-vs-fabs-function-in-python/
CC-MAIN-2020-29
refinedweb
389
68.36
Details - AboutActuary, dev, generalist - SkillsC#, JS, VBA (Urgh!) - LocationLondon, UK Joined devRant on 5/17/2016 - - - I’m all for writing boolean statements that are readable, quick to grasp the real life case they’re representing and align with the spec rather than being ultra-reduced, but sometimes the spec is written by someone who clearly can’t reduce logic. So when the spec says “if it’s not the case that any of them are false” and you write: !(!a || !b || !c || !d) then I think you should try harder. At least put a note against the spec to say “i.e. if they’re all true” and then write the sensible code. Just think of the poor developer that might have to augment your code at a later date and has to follow and intercept that shite. - - !dev What's the difference between the middle two options? Surely 'a few weeks' is about as long as or longer than a month?11 -. - - Clients: give them some free extra cheese and they'll just complain they don't have enough crackers.1 - How about adding a downvote category for wrong category? It could work something like: - Hit downvote - Select "Wrong category" - Choose which of the main tags are misused - Once you have over 100,000++ of cumulative downvotes on a particular tag (with a minimum of three people to stop the big guns going autonomous) that category gets permanently removed from the post Example of cumulative downvotes: - Downvotes from 100 users each with 1,000++ - Downvotes from 10 users each with 10,000++ - Downvotes from 3 users each with 33,334++ But not: - Downvotes from 2 users each with 50,000++ Thoughts?15 - - Attribute "label" in element "label" in the namespace "label" in a file called "labels.xml"... Cool, thanks for that.2 - - - 3. After that I take a decent break (e.g. an hour) because my productivity and efficiency reduce, and I'm not paid by the hour so a sustainable, high quality output that fits in with my life is the objective.3 - - !dev Wife had a dream last night that I cheated on her and we got divorced. She woke up mad at me. It’s now 12 hours later and I just picked her up from work... she’s still mad at me.15 - - -. - I've been staring at the same section of code for about two hours now. I want to solve this puzzle and design it properly. I'm desperately trying to resist the urge to hack it. Not sure I can hold out much longer...4 - It would appear that having the same application open for 14 hours a day everyday takes its toll on your monitor.11 - Came out to the country with my wife and her friends. We were all sat around in the sun and I asked what we were going to do. She said we can do whatever we want. So I got my laptop and sat in the shade. She then had a go at me for being unsociable. FFS
https://devrant.com/users/joycestick
CC-MAIN-2019-51
refinedweb
513
80.62
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. Create a new invoice sequence Hi there i'm creating a module to make 2 kinds of invoice with 2 different sequence ...first one with tax and the other with out i create a Boolean field to check the kind of invoice and when i press Validate i got that error here is my module code the .py file and here is my view xml file and here is my sequence file may i have some help please ? Try this This code works for us :) def invoice_validate(self, cr, uid, ids, context=None): for invoice in self.browse(cr, uid, ids, context=context): try: if not invoice.custom_field: raise openerp.exceptions.Warning("Custom error") except ValueError: raise openerp.exceptions.Warning("Custom") super(account_invoice,self).invoice_validate(cr, uid, ids, context=context) 1. You declared different class, invoice_edits, so calling super to invoice_validate makes no sense.. declare account_invoice class ( and _inherit = 'account.invoice') 2. overriding invoice_validate method does nothing, since the original method only writes state=open and has nothing to do with selecting sequence for invoice... Maybe the easiest way to achieve what you want.. is to define 2 different journals, and assign different number sequences to each journal... that way, you can easily add more sequences/journals, and define the sequence simply by selecting appropriate journal before validating invoice... no coding needed at all for it.. or, if you want you can code come check on selected journal.. The invoice_validate function of account.invoice takes only 1 arguments (self). This function is called from account_invoice_workflow.xml with only 1 argument. You override the function with a different signature, just like the purchase and portal_sale modules do. But I think you also need to rework the workflow XML
https://www.odoo.com/forum/help-1/question/create-a-new-invoice-sequence-86651
CC-MAIN-2017-09
refinedweb
316
59.3
Replying to myself... On Wed, Nov 26, 2008 at 12:59 AM, Greg Hellings <greg.hellings at gmail.com> wrote: > I'm building the current SVN on my Mac and have the following issue - > autogen.sh does not find libtoolize, but the autogen.sh script > continues anyway, generating a configure script, but no Makefile.in > because of missing ltmain.sh. Now, with Macports intsalled, I have > glibtoolize in my path, which I just linked to libtoolize, and > everything seems to be churning along just fine. Perhaps, though, > autogen.sh should error out as soon as it fails to find libtoolize. > Also, since many systems which have built-in BSD tools and also the > possibility of added GNU tools of the same name (Mac OS X and Solaris > come to mind first) will use the convention of prepending the letter > 'g' to the GNU version of the tools, perhaps the autogen.sh should > look for both libtoolize and glibtoolize? > > Also, after building the library, I get the following lovely message: > sword-svn-build hellings1$ utilities/diatheke/diatheke > dyld: Symbol not found: > __ZN5sword10InstallMgr32refreshRemoteSourceConfigurationEv > Referenced from: > /Users/hellings1/Documents/build/sword-svn-build/lib/.libs/libsword-1.5.11.dylib > Expected in: flat namespace > > Trace/BPT trap > > Am I the only one, and does this seem relegated to OS X? > > --Greg > The problem exists also in Linux, where I got an error at linking time as I usually expect. sword::InstallMgr::refreshRemoteSourceConfiguration() is declared as virtual in the header, but absolutely no instantiation of the method is ever given (aren't they usually set as = 0; in the header if there truly is no default implementation?). For now I just set InstallMgr::refreshRemoteSourceConfiguration() { return -1; } in installmgr.cpp since I couldn't find the method referenced from any other files with a grep and moved on, since I'm actually interested in the issue with the filters. --Greg
http://www.crosswire.org/pipermail/sword-devel/2008-November/029745.html
CC-MAIN-2014-42
refinedweb
315
55.74
Migrating to the New Flash Filesystem Migrating to the New Flash Filesystem Target OS: 6.2.1 Supplemental and 6.3.0 The purpose of this technote is to help you migrate to the new flash filesystem (FS) efficiently. This new flash FS supports a compatibility mode and enhances the reliablity of your driver at a small performance cost. The main benefits of this new FS include: - Stronger resistance to file corruption due to power loss. - Ability to write-protect your flash with new APIs. The following discussion is intended for users of BSP flash FS drivers from a previous version of Neutrino. Using this technote, you can modify your drivers to support either the old or the new flash FSs. These two flash FSs, however, are not compatible. New and old libraries In this release, you get a brand new flash FS library (libfs-flash3.a) in addition to the flash library (libfs-flash.a) you already purchased with your previous version of QNX Neutrino. While writing the flash FS driver, you use the FS library along with the low-level flash library (libmtd-flash.a), also called the memory technology driver (MTD). This particular MTD library is hardware dependent, and is required to access particular flash devices. Like the FS library, the MTD library has also two versions. Unlike the FS libraries, however, the new MTD version is fully backward compatible with the old MTD version. In fact, the new version is a superset of the old one with additional interface APIs. This is also the reason QNX has shipped only one version of the libmtd-flash.a library. Versioning The source code for the FS and MTD libraries contains different API versions: - libfs-flash.a - v2 - libfs-flash3.a - v3 - libmtd-flash.a - v1, v2 In order for your driver to work, you should employ only the following working combinations of these versions: Each combination describes the driver as follows: - FSv2 MTDv1 - Original driver. - FSv3 MTDv1 - Driver that provides: - compatibility with v1 MTD drivers - minimal MTD changes - new reliable FS - improper error reporting of HW errors - no block write protection. - FSv3 MTDv2 - Driver with full features (i.e. reliable FS, proper error reporting, and block write protection). Updating the variant code In order to migrate to the new flash FS, you need to update the variant code. The variant code is linked with the FS and MTD libraries to build the driver (e.g. devf-generic). Look for the variant code in the bsp_working_dir/src/hardware/flash/boards directory -- you'll find a subdirectory for each board we support. The variant code describes what combinations of MTD callouts the flash FS should use. To update the variant code: - Fix the includes in all .c and .h files: Include <sys/f3s_mtd.h> instead of <sys/f3s_api.h>, <sys/f3s_spec.h>, <sys/f3s_socket.h>, <sys/f3s_comp.h>, or <sys/f3s_flash.h>. - Add MTD v2 callouts to support compatibility mode. For example, you add the following compatibility code snippets in the main.c file: #if MTD_VER == 2 . . #else . #endif - Place the original f3s_flash_t definition between the #else and #endif statements. - Copy the entire original f3s_flash_t definition and place it between the #if and #else statements. - In the copied code, you'll need to: - Change f3s_flash_t to f3s_flash_v2_t for each array element. - For each array element, insert six NULL entries between the _reset() and _read() structure members. - Insert four NULL entries after the _sync() entry, or the corresponding flash lock/unlock routines, if applicable. - Change every _write(), _erase(), _suspend(), _resume(), and _sync() function to its corresponding "v2" function. For example, f3s_a29f040_write changes to f3s_a29f040_v2write. This ensures that each of the combinations works properly. See the updated main.c example below for details. It is important to note that due to the nature of the new MTDv1 API, certain MTDv1 callouts have been combined into a single new MTDv2 callout. The table below lists these consolidations: - Update the common.mk file. This file is included with the MTD source. cp bsp_root/libs/src/hardware/flash/boards/common.mk bsp_working_dir/src/hardware/flash/boards/common.mk - Copy two files as follows: cp bsp_root/libs/src/hardware/flash/mtd-flash/usagev2.use bsp_working_dir/src/hardware/flash/mtd-flash/usagev2.use cp bsp_root/libs/src/hardware/flash/mtd-flash/usagev3.use bsp_working_dir/src/hardware/flash/mtd-flash/usagev3.use Example of updated file: main.c #include <sys/f3s_mtd.h> #include "f3s_800fads.h" int main(int argc, char **argv) { int error; static f3s_service_t service[] = { { sizeof(f3s_service_t), f3s_800fads_open, f3s_800fads_page, f3s_800fads_status, f3s_800fads_close }, { 0, 0, 0, 0, 0 /* mandatory last entry */ } }; #if MTD_VER == 2 static f3s_flash_v2_t flash[] = { { sizeof(f3s_flash_v2_t), f3s_a29f040_ident, /* Common Ident */ f3s_a29f040_reset, /* Common Reset */ /* v1 Read/Write/Erase/Suspend/Resume/Sync (Unused) */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* v2 Read (Use default) */ f3s_a29f040_v2write, /* v2 Write */ f3s_a29f040_v2erase, /* v2 Erase */ f3s_a29f040_v2suspend, /* v2 Suspend */ f3s_a29f040_v2resume, /* v2 Resume */ f3s_a29f040_v2sync, /* v2 Sync */ /* v2 Islock/Lock/Unlock/Unlockall (not supported) */ NULL, NULL, NULL, NULL }, { /* mandatory last entry */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; #else static f3s_flash_t flash[] = { { sizeof(f3s_flash_t), f3s_a29f040_ident, /* Common Ident */ f3s_a29f040_reset, /* Common Reset */ NULL, /* v1 Read (Use default) */ f3s_a29f040_write, /* v1 Write */ f3s_a29f040_erase, /* v1 Erase */ f3s_a29f040_suspend, /* v1 Suspend */ f3s_a29f040_resume, /* v1 Resume */ f3s_a29f040_sync /* v1 Sync */ }, { /* mandatory last entry */ 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; #endif /* init f3s */ f3s_init(argc, argv, flash); /* start f3s */ error = f3s_start(service, flash); return error; } Updating MTD overrides In rare circumstances, you may have to override an MTD callout implementation to support your hardware. In this case, you will have to modify your overrides to conform to the new MTDv2 API. Please refer to the Building Embedded Systems guide for the new behavior and bsp-dir/libs/hardware/flash/mtd-flash for examples. As an alternative, you can use your existing MTD overrides with the new file system via the compatibility mode. Building the drivers Use any of the following commands to make the driver: make F3S_VER=3 MTD_VER=1 or: make F3S_VER=2 MTD_VER=1 or: make F3S_VER=3 MTD_VER=2 The first command is called the compatibility mode -- you use it to build the driver using version 3 of the FS library and version 1 of the MTD library. The second command is the original mode -- you use it to build the driver using version 2 of the FS library along with version 1 of the MTD library. The last command will build the latest version of the driver. Creating the image for the new and old flash filesystem: The mkefs utility will create the image for different flash FS as follows:
http://www.qnx.com/developers/docs/6.3.2/neutrino/technotes/flash_customization.html
CC-MAIN-2015-18
refinedweb
1,101
55.64
I didn’t add much in the way of new stuff this week. I spent a lot of time refining and polishing and bug-fixing, hoping to get a new build out to my testers* before the weekend. I’m spending a lot of time fussing with stuff I’ve already written about. * For the record: I’m SLOWLY adding to my list of testers. I know people will get sick of playing the same broken game week after week, so I’m trying to add new people as the old ones lose interest. So! Let’s talk about something controversial. Even better: Let’s talk about something incredibly controversial to programmers, and completely tedious, esoteric, and impenetrable to non-coders! Let’s talk about programming paradigms. Some people have asked about how my program is structured, and since I know the answer will leave some people deeply offended, I might as well discuss the “why” before I get to the “what”. Just to bring normal people up to speed: At first, basically all programming was imperative. Programs would be structured in the form of do thing1, do thing2, do thing3, etc. Or whatever. The idea being that in the above code, space_marine is probably a structure of properties. Like: By calling this code, you’re doing things TO the space marine. Also that code might also make changes to other things that are NOT space marines. Basically, you can’t look at this code and know what parts of the game state might change. Maybe nothing. Maybe many things. The space_marine might die. It might win the game. It might trigger a change to the next level. It might destroy a dozen other in-game things. As a programmer, you just don’t know how the state of the game might be changed or what sort of things might happen. You have to read the source. This is technically true of all languages except for a few built around the functional programming paradigm, but its particularly true of imperative languages. The problem we have is that in a big project, our marine will end up having a LOT of properties. In Good Robot, each robot has over 50 properties like this that keep track of what the AI is thinking, when the weapons are ready to fire, how it’s moving, etc. And this is a simple little 2D game. In a 3D game with more complex geometry, multiplayer, tons of weapons, vehicles, and multiple game modes, we’re likely to have a lot more. In imperative programming, we’re likely passing around this space_marine variable to every system that needs it, and any system can make changes to any part of it. So maybe some other programmer comes along and writes the grenade code. Not understanding this structure I made, he just subtracts damage from hitpoints and calls it a day. The problem is that he doesn’t update the “space_marine.dead” variable. So now we have a bug where grenades can damage you but they can’t kill you. Maybe he wants the grenade to blast you up in the air, so he just adds a bit to the “space_marine.height” variable. Except, that’s not how that variable is used. It’s not your height off the ground, it’s how tall you are. So now we have a bug where getting blasted with a grenade makes you incrementally taller. The problem here is that ANYONE (any programmer working on any section of the code) can make changes to a space_marine. And thus everyone needs to have complete knowledge of how a space marine works, what all the variables mean, and how they inter-operate. You end up needing every programmer to understand every system in perfect detail, and that’s just not reasonable. It’s not even possible in most cases. Worse, you’ve got a lot of side-effects going on. When someone notices that one character is slightly taller than another, they do some testing and find their space marine is 30cm taller than he should be. How did that happen? Anything that interacts with a space marine would have access to those variables. Which system is fiddling with the height? Saving the game? Starting a new match? Entering or exiting vehicles? Something with networking? Running, jumping, using cover, picking up weapons, dying, using guns, melee attacks, taunts, dying, leveling up, rendering, being healed, being damaged, chatting, or performing emotes? It could be ANYWHERE in the game. Have fun finding it. So then we have Object-Oriented programming. The idea is that we lock away all those marine properties and other programmers can only interact with the marine through the interface: So other programmers can’t modify hit points directly. They don’t need to know that the variable “hitpoints” exists, how it’s used, or about the “dead” flag. They just send damage values to the marine and the marine object takes care of the fussy details. It knows to kill itself if its hitpoints drop below 1, and it knows what animations to kick off, scores to change, weapons to drop, etc. Other programmers don’t need to know any of it. If another programmer wants to blow the space marine up in the air with an explosion, they won’t have access to the “height” variable but they will see something like… …and realize THAT’S what they should be using to shove the marine around the environment. The object’s interface will guide this other programmer and stop them from doing something destructive. This process of hiding the inner workings of an object is called encapsulation. This is a good solution to the above problems. It is not, however, a good solution to every problem. Java adheres to the Object-Oriented paradigm with unwavering strictness. Everything is an object, owned by an object, owned by an object, yea, even unto the nth generation shalt thy objects be owned. So you end up with this thing where you’ve got a “game” object. Just one. And it owns a “game session” object, which owns a “level” object, which owns a list of “space marine” objects. Okay, fine. Now we’ve sealed everything off so there aren’t any side-effects, every object is owned by another, and objects can’t change each other. The problem is that there aren’t any side-effects, every object is owned by another, and objects can’t change each other. Like, if I want my space marine to create a little cloud of dust when he stomps on the ground, who owns that? If the marine owns it, then killing the marine will make all of his dust particles instantly vanish, which would look odd. If he kicks off a sound effect, I might not want that sound effect to die with the marine. If he’s supposed to drop his weapon on death, then marines need to be able to give the object to some other system. Obviously we can’t have marines owning their own visual effects, sound effects, and particle effects. So we have to… what? Make a “sound effect” object and have it owned by… who? The game? The level? Should we create some master sound-owning object to act as an MC for all the sounds the game is making? Should we make a particle wrangler that keeps track of all the particles? If we make one particle wrangler object that’s in charge of all particles, then we’ve basically re-created all the old C-style imperative design but now it’s just WAY less convenient to use. We can’t just call PaticleCreate (stuff), we have to get the game object, which will give us the session object, which will give us the level object, which will give us the particle wrangler. Also, my space marines need to collide with each other. Collision is incredibly complex. To collide A with B I need access to the polygonal structure of both, the skeleton of both, the current state of both, what each one is doing (I shouldn’t be able to shove someone if they’re attached to a mounted turret or behind the wheel of a car) and how they’re currently moving. Do I have the level object (which owns all space marines) run the tests and make the marines bounce off each other? But then we would need to expose all of the inner workings and logic of the space marine, which is exactly the thing we were trying to hide. Or do we have marines themselves try to bump into each other, in which case each marine needs to be able to find all others, meaning marines need access to the data structures of their owner. We also need a way to avoid duplicate tests so that once we test for A colliding with B we don’t waste CPU testing if B has hit A. No matter which way you go, you have to poke some major holes in your encapsulation to do this efficiently, and we’ve just scratched the surface. Weapons need pointers to the marines carrying them, vehicles need two-way access to marines so they can both be driven by and run over them. Marines need access to each other and all the other objects in the game. They all need pointers to the game object so they can access game rules, but they also need a pointer to the current level so they can do collision with the level geometry. And even though the game owns the level, you probably want direct pointers to both since drilling down through levels of pointers owned by pointers can cost you performance if you do it enough times (many objects) or if the layers of objects-owning-object-owning object is annoyingly deep. In the end, we’ve imposed this rigorous top-down structure and then we spent days or weeks writing code to get around or through it. In a world of pure theory, an object hierarchy makes perfect sense and there’s always a “right” way to do things. Objects can hide behind their interfaces and we never need to worry about their innards. In practice, the right way is not always clear and even if you’re lucky enough to nail it, you may find it requires many transgressions against object-oriented design. You can end up with something that’s just as unsafe and exposed as imperative programming, while also being more cumbersome, convoluted, and perhaps even slower. In a lot of cases, those “protective layers” of OO design don’t actually protect you from anything, because you have to poke so many holes in it that the thing no longer serves the intended purpose. All of this is to say: I am not a purist when it comes to OO design. For years I thought I was bad at OO programming.. This makes it easy to manage large groups of things, but also prevents me from accidentally making more than one of something when more than one would violate the design and common sense. A good example is the player. Right now you call PlayerUpdate () to process player input. This performs non-repeatable actions and creates state changes in the I/O. Sure, I could make a class Player p; and call p->Update (); but that would make no sense. Like, if you had more than one player object, the first one would eat all of the mouse and keyboard input, leaving no clicks, mouse movement, or key presses for the other. Having more than one player is an impossible and nonsense state, so why make it possible? The presence of PlayerUpdate () makes it really clear how this should be used. Q: But Shamus, what if you wanted to make the game multiplayer? A: Then I’d have to re-write the player code. That would be true regardless of whether or not I was using a class interface. Since multiplayer isn’t even being considered, I don’t see any percentage in spending time making it easier to add features that I’m not going to add. That’s like spending money to put a boat hitch on every car you own, just in case you end up buying a boat someday. Boom! Crappy car analogy. It’s been too long since the last one. Getting back to classes. Even when we DO want more than one of something, that doesn’t mean I’m going to make it a full-fledged class. If something is a container for variables (like XYZ vector data or RGBA color data) then I make it a struct with public members. Making wrappers for individual entries in this case makes no sense to me. When I was using Qt, I didn’t bother with their built-in vector types because some silly OO zealot thought that this code… Would be SO much better as: Oh man. That still drives me crazy just looking at it. What’s the purpose of that stupid interface, anyway? If that’s a good idea, then why not: …instead of a = b + c? So much safer! Screw convenience and compact clarity, we must mindlessly adhere to class-based orthodoxy! My rule of thumb is that if variables change each other (say, setting “m_age” will impact the value of bool m_is_senior_citizen) then it needs wrappers and the members should be encapsulated. But if the members are independent then it’s just a container for values and the other programmer should be trusted to know what they’re doing. A class interface is there to hide complexity. But if there is no complexity then the class interface might hide the fact that there is no complexity! So to answer the question: Robots are a single class. The only “fancy” object inheritance stuff I’m doing is I’ve got a base class from which bullets, missiles, explosions, and powerups, are derived. Objects in the program can create these entities and then hand them off to the world management code in world.cpp. So that’s it. Mostly C-style structure with a few dozen C++ classes being thrown around. In places where I do use classes, the interfaces are very tight. Tenpenny Tower Bethesda felt the need to jam a morality system into Fallout 3, and they blew it. Good and evil make no sense and the moral compass points sideways. Skyrim Thieves Guild The Thieves Guild quest in Skyrim is a vortex of disjointed plot-holes, contrivances, and nonsense. PC Hardware is Toast This is why shopping for graphics cards is so stupid and miserable. Autoblography The story of me. If you're looking for a picture of what it was like growing up in the seventies, then this is for you. Trekrospective A look back at Star Trek, from the Original Series to the Abrams Reboot. 149 thoughts on “Project Good Robot 23: Programming Paradigms” Hey, don’t fault OO when the languages are too crappy to not implement properties like they should. :V More seriously now, the thing is that in most projects what starts simple might not always end up simple, so having everything in props means you can add whatever logic you need (notifications, events, validation, synthetic properties, data binding, logging, whatever) afterwards without breaking compatibility. It also allows different accessibility levels for getter and setter, allowing things like immutable structures by making all setters private. (Personally I hide all the setters that I don’t expect others to be changing. In your collision example, for instance, details such as polygons and skeleton ought to be purely read-only from the outside.) In general the benefits don’t really show in 1-man projects where you control the entirety of the source, but then again, Java was made for enterprises. The sane languages will make sure to write the boilerplate for you. Sadly, C++ and Java don’t fall into that category. (I kid, I kid. But seriously, Java’s got to shape up.) (One could argue C++ is a very bad OO language, at that, but I’ll leave that for others who know in more detail) Personally, I disagree with your idea of ownership. Particle effects shouldn’t belong to anybody but the particle system. Same with sound effects and so on. This is not just because of OO thinking, but it’s simple logic. Somebody is gonna have to coordinate everything, and that somebody will be the owner. Interestingly Python goes the opposite way, where you cannot make a property private, even if you want to (a truth with some modifications). So what is the right way? (Rhetorical question not ment to be answered, merely reflected upon.) The Right Way is to have a naming convention saying “Think X is not exposed surface, so if you use it you are SO on your own” (like, say, the “_foo” thing in Python or simply not exporting a symbol in Common Lisp). That way, people can peek under the hood if they need to, but are well aware of the fact that they’re inherently relying on unstable things. I’ve not uses Python very much, just barely touched it, but I like the “it’s your responsibility” approach. But I also know that I’ve more than once wished for public read only attributes in C++ to have full control while avoiding getters and setters. But maybe this is not important to good object orientation designs anyway. (None of the following is prescriptive commentary. Use whatever languages however you and any co-workers agree on a system, and write a style and conventions guide so if someone inherits it they can understand why you did it that way. There is no one true way; unfortunately there are many wrong ways: untangling this is far harder than coding working systems.) Python is an interesting language (eg mandatory stage when a function is called in Python: look at what calling means in the current context and what is available to tie to that call – so this can be defined by your program and you can write custom scope rules for your code; it isn’t like Python hard-codes calls/jumps destinations to be fast if you don’t subvert the default handling because the current context is always run-time defined) but the fact that the underscore convention exists indicates a very widespread desire for having a system of property privacy levels. In large projects (if I’m using an OO supporting language) I’m quite happy to abstract the data in the RAM from all my interfaces. And then you have to look at where full OO gets you. Take the pos example above. Say I find out my physics system needs twice the resolution my current position data can provide, I need to halve the max distance to double the density of ints in the space I care about. Only the Physics system cares but as the pos data lives with the owner objects then I need to change them. The Shamus code requires every point where the pos data points are interacted with the be changed to deal with this difference in what 1 meter in the game means in underlying RAM terms. Getters and Setters mean that I don’t need to go around changing scales of everything, I just change my methods in the objects that own pos data. This is why people pay the price (and some languages have very good semantics for making this normal and free for default getters/setters). If the pos data was abstracted to a class so everything talked about it in terms of a meter in the game engine then you’d only have on place where the underlying RAM information was being poked at and one change to the code would allow your physics system to get more fidelity of recording all game element positions. As to how to do an OO look at particles and sounds: who owns them does answer itself from the use case. The marine doesn’t kill his smoke and sound but the level (thinking traditional game levels, not streaming game level blocks – but even then I think it still mostly applies) sure does. There have been more than 0 games released where changing level did not kill all the particle and sound elements that it should have owned, with amusing results. But in the more general case strict OO hierarchies may not always work and also may not be optimal for thrashing similar data in RAM when that is needed. I just think it needs a better example than that to make the case. While I would like proper properties in C++ you get the 90% case since you can make something not writable by making it const…. void can_modify_bob(bob_t* bob); void can_not_modify_bob(const bob_t* bob); Which is something I miss in literally *every other language ever*. The only way this could be a better setup is that it’s constant by default. (Similarly, “by value” for everything by default with the *option* of referencing is incredibly useful too, and something I miss all the time) I’m not claiming to know why C++ hasn’t added properties, but I would guess from my experience that they wouldn’t be a very good fit given C++’s features, for example you can’t make a pointer or reference to a property, and compound operators (+= and friends) would be very hard to specify correctly and without being bad for performance (consider changing the transform of a few 100,000 particles). The C++ equivalent seems to be a method returning a proxy type (iterators are a particularly common proxy for weird pointer-like behavior) or just a reference to a backing variable if that’s enough (like container back() functions). In short, not having properties isn’t a big deal. In fact, I would rather have C++ style types in C# (or whatever) than properties in C++: I’ve defined property change notification setters *far* too many times, being able to simply have observable<int> or whatever that is otherwise indistinguishable from int would be soooo much nicer. Lots of other languages have const. There’s C, Ada, Go, D (which also has immutable), not to mention all the functional languages where all variables are immutable. It would be cool if you couldn’t just cast it away in C++ though. I’m not saying it’s worthless because it’s an incredibly useful tool, but this code: int foo(const int *bar) { return baz((int *)bar); } should be a shooting offense. It should also raise a compiler warning. Not to mention PHP where const is implicit, and you have to pass by reference if the function should be able to modify an object. Different solutions solves the same issue. Passing by reference versus value is a different issue than the ability to mark a variable as being const. C++ is identical to PHP in this area: pass by value by default, optionally pass by reference. As far as I know, PHP lacks the ability to pass by reference for speed (to avoid copying a large data structure), but mark it as const so you know the receiving function don’t mess with it. Or to simply mark a variable as const so you know that no one accidentally changes the value of PI. Actually, it’s a little bit different. Pass by reference in PHP is equeal to pass by reference in C++. But default in PHP is a little bit different. Superficially it’s like const. You cannot change the variable that is passed. If you want to, you must pass by reference. But you can change the variable for the local scope. When you do, PHP wil create a copy on demand. But this is lost at the end of the scope. This is true for any variable, array and object. But when it comes to an object you can modify its attributes. You cannot set the variable to another object though. Am I understanding this correctly? – If I explicitly pass by reference, the function can manipulate the variable/array/object (VAO). When the function exits, the caller will see the changes to the VAO. – If I pass normally, the function can manipulate the VAO, doing so will cause at that point a copy to be made. When the function exits, the caller’s VAO is guaranteed unchanged. Assuming that’s correct, to my mind the distinction from pass-by-copy is academic, it’s a sort of optimization to avoid unnecessary copies. (And depending on the code in question, possibly a very good optimization! Of course, I love fork()+copy-on-write shared memory, so I may be biased) As far as the code I write cares, I can treat it exactly identical to pass-by-copy. const_cast is evil, but it’s a necessary evil to get around bad programmers’ code you can’t modify for whatever reason. Say you are using a vector library that didn’t care about const correctness, and the vector has a Magnitude() method that doesn’t modify the state, but wasn’t declared const. So you have a function that takes a const reference to this vector, and you need to know it’s magnitude. Without const_cast, you’d have to remove all const correctness from your own code (insane), or create a copy (ugly, a possible performance hit for large classes, a possible source of errors if your class is particularly complex or is part of a virtual inheritance chain, and impossible if the copy constructor is defined private or protected). With const_cast, you avoid this problem. The point being, while you can use it in evil ways, you should only ever use it to call methods you KNOW won’t modify the internal state of the object. I only wish c++ defaulted to const and const& for methods and parameters. Sure, it’s necessary in C++ because C++ lets bad (and sloppy) programmers get away with things that it shouldn’t. Pointers should be restrict by default and formal arguments should be const by default. Ada, for example, doesn’t have this problem because function formal parameters are in, inout, or out. If someone says that their library function accepts an inout parameter X, but doesn’t modify X, they’re still telling you not to pass in something that you want to be const because some future version of that library call is allowed to modify that piece of memory. Well, it’s necessary in C++ because that was the way C treated const, and C++ was supposed to be a superset of C. This is why I don’t do C++. I can’t understand a word, but I’m pretty sure I don’t want to know. > having everything in props means you can add whatever logic you need (notifications, events, validation, synthetic properties, data binding, logging, whatever) afterwards without breaking compatibility. But, uh, you *will* break compatibility if you do this. It’s just like Shamus’s example of multiplayer. :-) Even something as simple as adding logging is changing the interface: you now have to point the class at something to accept the log messages (that is, a file descriptor somewhere, probably wrapped in a bunch more OO), and you’re changing the time required to get or set a given property, because (a) disk is slow, (b) you can’t just buffer the log messages in memory because of crashing bugs, and (c) even if you do buffer them in memory you have to eventually flush that out before the machine runs out of RAM. So now instead of taking an immeasurably small amount of time to change a robot’s X position, it takes an immeasurably small amount of time most of the time, and 100ms to flush all the logs out every so often. This is a problem. :-) Basically: *All* abstractions are leaky. Better to have fewer of them, all else being equal. For some things it makes sense to abstract away most of the interaction in a class, and for some things it doesn’t. (However, yes, you’re right — it does depend on how many people you’re working with, as well as how good they are…) Some functions are more transparent than others, yes. Logging will take time, but that’s because of the existence of the system itself. What I meant is that if your component is a DLL or such, you can change the underlying logic without forcing the consumer to recompile. It’s binary compatible in addition to source compatible. I found that to overcome the limitations of OO for games, many studios use some sort of Entity System (ES) with OO programming. In an ES, an entity is a sum of component, each component being a data structure representing an aspect (like “is able to move” or “has hitpoints and can die”), while systems perform the logic on all entities (like “update the hitpoints of all entities with hitpoints”). This requires a different design approach and can still produce some convoluted code (usually around the retrieval of a particular system/entity) but gives easy to write, modular and very reusable code. For those interested, more info on ES here: Some examples of game engines using ES: Unity and Merkurius (my java open-source engine based on the Artemis ES. Yup, pretty much this. I’m one of those guys who obsesses over getting the perfect design when programming – so much so that I often can’t move on with a project because I can’t decide on what direction to take. It’s a terrible thing. When I discovered ES, it was like a light shining through the clouds. Just about every design decision I made to do with my game was made easy. There are still gotchas with the architecture, but I’d say it’s a hell of a lot better than trying to do OOP. Good object oriented programming is hard. For someone self thought it takes years. Just today I read something by Linus Torvals (the creator of Linux) on git and using C (not object oriented) instead of C++ (object oriented):. … So I’m sorry, but for something like git, where efficiency was a primary objective, the “advantages” of C++ is just a huge mistake. The fact that we also piss off people who cannot see that is just a big additional advantage. — There is a lot of truth to this. While good object oriented design is fun to code, it is also very easy to produce horribly messy applications. My advice to anyone wanting to program object oriented is to use test driven development. When your objects has to fit and work both in your program, and the test environment, you are forced to avoid some of the pitfalls and bad design traps of OO. The funny thing is, the “bad C++ programmers” are most of the time those that unknowingly attempt to write C code in C++ without knowing how to do neither good C++ nor C. Who hand around raw pointers yet have no idea when they are deleted. Who write the same 5 lines for the same low level string operation hundreds of times, instead of either putting them in a function or using a function already provided by the standard library or some other library that you are using anyway. Who write classes with members that are dangerous to naively modify from the outside yet don’t declare them private nor provide member or free functions to modify them properly, but litter their code with a dozen variants of the same sequence of operation.* If C++ did not exist, the same people who keep bashing C++ as a whole would merely have a harder time bashing bad C programmers as an abstract, inconsistent fuzzy group of people that is much more difficult to point your finger. Well, it were funny if not for all the hostility involved, which I never understood and probably never will. Why can’t we just have favourite languages and accept that other people prefer different languages for many different reasons? —– *Imagine in Shamus example, whenever the space_marine receives damage, there is always is the code space_marine.hitpoints -= damage; if (space_marine.hitpoints <= 0) { space_marine.hitpoints = 0; space_marine.dead = true; } repeated dozens of times, sometimes with minor or major bugs; like checking for < 0, leading to sometimes characters ending up with 0 hitpoints yet still alive. Another place will omit space_marine.dead = true altogether, but then another place does not check that variable, but space_marine.hitpoints < 0, and suddenly you have characters in a zombie state where they are technically dead to some parts of the game, yet alive to others. Great fun. I think Linus’s problem is the impression that most programmers are not very good (something to which I can attest; past-me was a terrible programmer) and most programmers write C++ code. These two assumptions lead to the conclusion that most people who write C++ code are not very good. If you have a language (like C) that’s fallen out of the first-language-learned category, the idea is that you won’t get as many people who don’t know what they’re doing. There’s also the fact that Linus thinks that C++ is a horrible mess of a language. Note that I’m not endorsing any of these opinions (except that most software is crap) as my own, just trying to explain the reasoning Linus uses. I think irritating a goodly chunk of the programming population is just a bonus for him. Linus “problem” is that he is not a nice guy, and doesn’t want to be either. But he is right. Most programmers aren’t very good, because being a good programmer[*] is very difficult. I have many years experience, and just now I start to produce code that I can look at and feel happy about. It both does what it’s supposed to do, and it is readable, structured, maintainable and extendable. This takes experience, and I still only produce good code when I’m not working under “should be done yesterday” conditions. [*] There are more than one way to be a good programmer. Sometimes you need to make something done quickly for a stand alone application that will not be maintained further after release. A very different condition is creating maintainable code that will live for a long time and be modified and extended many times. Very different requirements. I’ve noticed there is this tendency to overestimate what it takes to be a ‘good’ programmer, where it really is just a mindset connected to knowledge. I don’t think there’s that many bad programmers, there’s just too much archaic knowledge required and usually no good ways to tell a programmer that he’s doing it wrong. That may sound like a redefinition, but it puts the blame more on the tools and less on the people. I’m still amazed by the fact where most of programming happens in a text editor, even though every programmer I know is mostly thinking of the problem in a visual way. To put it another way, programming is still largely conforming to the will of the language, instead of the language conforming to your will. In a perfect world you should only really have to think about the code that actually does useful stuff. > Well, it were funny if not for all the hostility involved, which I never > understood and probably never will. Why can't we just have favourite > languages and accept that other people prefer different languages for > many different reasons? It annoys me to see other people waste their time and potential working with bad tools. Whether or not they like it. Obligatory analogy: if you saw a carpenter building a bench, hammering in nails with an old Budweiser bottle when there was a hammer sitting not 3 feet away, wouldn’t that annoy you? Wouldn’t you say, “hey spend 30 seconds grabbing that hammer, and you could finish your nailing in a third the time and use the extra time to really make the veneer excellent!” Maybe not. Maybe I’m unique in this. Oh well. If I saw a carpenter who I knew was reasonably competent(at least as much so as I am) pounding away with a beer bottle when he’s got a hammer at hand, I’d assume he has reasons for what he’s doing. I make way too many of my own bizarre choices to begrudge anybody theirs. Agreed. There’s a very strong temptation to assume that, just because there appears to be an obvious solution, everyone who doesn’t use it is an idiot. Probably part of the reason that political discussions get so heated. Personally, I’d be quite curious about the carpenter hammering with a bottle. I mean, this is an entire possibility space of tool design and use that may be unexplored! Has he patented the bottle-shaped-hammer? What qualities about the bottle does he like? Could I, perhaps, design a new kind of hand tool that incorporated those qualities along with the durability of forged steel? You’ll never find the answers to these kinds of questions by getting annoyed at professionals for ignorant assumptions. Well… if I saw a carpenter pounding away with an empty beer bottle, I think there’s a fairly obvious explanation for that. I might intervene, but I certainly wouldn’t hand him a hammer. Best. Response. Ever. (Sorry for a useless comment but this just made my day) There is a difference between being merely annoyed and outright hostility. Although Volfram, Paul, and Retsam have all adequately addressed reasons why one should not make an assumption about the suitability of a particular tool for a particular task, none of them made any mention of the reason that Shamus has mentioned in the past for his choice of tool. To continue with the analogy, you hand the carpenter the hammer. He examines it and asks, “What do I do with this?” You explain it to him. He asks, “How is this better than the bottle?” Another explanation follows. When you are done explaining it, he starts tapping the nail gently (as he would have done with the bottle so that it doesn’t break). Exasperated, you exclaim, “No! No! No! Swing it like this.” You demonstrate how it’s used. The nail is now half way in, which is much better progress than he was making. You have now convinced the carpenter that your tool is much better than his. He winds up and swings, but because he has never used a hammer, he is unfamiliar with the weight, the grip, safety, etc. He misses, hits his hand and breaks every bone in his hand. For the next six months, he’s unable to use any tools that require two hands. His productivity is diminished. Sure, in six months when he finally recovers, he’ll be twice as productive as he was before, but in the mean time, he better have good health insurance and lots of cash on hand to pay the bills. Analogies aside, the most difficult part about learning a new language is not the syntax. Once you’ve learned a couple of languages, the syntax isn’t a big deal. The most difficult part about learning a new language is becoming productive. Becoming productive requires familiarity with the libraries. Familiarity with the libraries requires time. For most people, time is a luxury they do not have. Would you really want Shamus to put Good Robot on hold while he learns your favorite language? Then again, I would like to play Good Robot on my Android phone… But I digress. First Shamus must produce the PC version before we can talk about an Android port ;) *sigh* The old “I used C++ in 1992 and it sucked then!” and “You can do OO in C!” arguments. Even a disguised “C++ is slower!” argument. I would have hoped Linus could at least give *interesting* reasons to prefer C over C++, but it seems he’s just parroting the standard C party line on C++. Don’t get me wrong, C++ *does* have problems! But they sure as heck are not that it’s slower (to run, at least!) or C++ has a worse programmer pool (which is a stupid argument even if it were true, just don’t use the bad programmers!). And, of course, the usual missing the point of C++ again, and thinking it’s still only “C with Classes”, circa 1988. I think you misread or didn’t read what Linus said. Boost and STL didn’t exist in 1988. I just wrote a huge rant about the abuses of C++, but we really don’t need more of that. Linus is blunt and rude about his opinions, but he does know what he’s talking about. Sometimes it’s even worth wading through the profanity to extract the meaning. Also: don’t oppress his Finnish culture. (that was a joke) I liked the FQA, it puts a very in-depth explanation of the failures of C++. Only if “failure” is defined as “ways in which it isn’t my favorite language.” I don’t know if he’s genuinely clueless about why C++ is what it is, why it was incredibly successful despite its legion “failures,” and why new projects are developed in it, or if he’s just pretending to make his arguments seem better. No one is going to read that essay and change their mind about C++. If you already dislike C++, the author is happy to reinforce your beliefs. If you appreciate C++, it’s a transparent attack with a poor grounding in reality and completely missing the poitn. One might as well identify the “failures” of the M1 Abrams: doesn’t fit in standard parking spots, tears up my driveway (and the lawn around it, since it doesn’t fit in my driveway), fuel inefficient, poor driver visibility, replacement parts are expensive, and the seats are uncomfortable. C++ is not the right answer for every project. It’s not the right answer for most projects. But it is a good solution for a non-trivial number of projects. While the author of that rant is busy ranting, people are getting work done in C++, choosing to use it despite knowing languages lacking these “failures,” and happy to have it as an option. I work in C#. I learned Java and C++, but have done basically zero real work with either. I still kind of miss C++, though C# is a better compromise than Java was. I do not consider myself an expert programmer of any stripe. (How much of that is truth, how much is Dunning-Kruger in action, and how much is false modesty I leave to the judgment of others.) I would still like to be able to declare things other than types at the namespace level, because a static class seems like a cumbersome solution to that problem. I would like the option of truly multiple inheritance, even if it seems like 90% of my peers don’t grok inheritance and polymorphism at all. I’d like to have private and protected inheritance, even if it’s only syntactic sugar for aggregation. I don’t want to go back to C++ libraries and platform, but, as a novice, I was always less familiar with the standard libraries than with the language. (And I sure as hell don’t miss manual memory management, though ISTR that more recent C++ standards include a garbage collector.) It’s kind of weird. One the one hand, I think that making programming more difficult actually does produce better programmers, and I think this is true even aside from the effect of filtering out programmers who just can’t hack the more difficult tools to start with. But. The other effect of making programming more difficult is making programming more difficult, and it still means making the process more error-prone and time-consuming. Most of the time, this trade-off just plain does not pay off. In that regard, Torvalds is in a weird, rarefied sort of environment. Given his reputation, he could probably find enough people of an arbitrary level of skill to work on a project of arbitrary size, even if he chose to use, say, BF (apologies; language name contains an F-bomb) as the language. I don’t think that decision works that way for most people in most environments, even if it does for Linus. Considering how crappy Git turned out, I wouldn’t put much weight in Linus’s words there. Git is as crappy as the people using it really. Git is very complicated, and it can be hard to understand how decentralized SCM systems are supposed to work. But it has some very nice benefits over traditional systems, as it allows for very agile development. No other SCM system I have worked with allowed me to abandon a feature, only to pick it right back up 50 commits down the line. Git? Crappy? Pistols at dawn, sir! But seriously, as Ian says, it’s as bad as the person using it. It’s a powerful tool that gives you more than enough rope to shoot yourself in the foot. It does help if you embrace a pattern like “git flow” or “github flow” to manage the complexity and put some guidelines on how it should be used. I disagree, I think git is great. But learning to use it right takes a long time. The steep learning curve sure does suck, and if you’re coming from a more traditional VCS like SVN, you’ll have a very frustrating time at first. I was first introduced to git roughly 5 years ago. I didn’t really become proficient until maybe a year ago, and having a day job that uses it helped a great deal with that. Once you obtain the power to rewrite history though (interactive rebasing), you never want to go back :D The fact is, C++ would get a lot less crap if it hadn’t been the language of choice for crappy community colleges to teach worthless AS-CS degrees in, for over a decade. We have theoretical C programmers teaching most of our practical C++ programmers, from a curriculum that never even mentions how to import a library, let alone integrate it properly. The hardest part of learning C++ was learning to forget all the BS I learned studying for my AS. After reading this, I feel absolutely obligated to link to Steve Yegge’s rant about Java’s full-OO design. Shamus probably knows it already (in fact, I’m surprised there was no link to it :p), but if you like poking fun at Java’s everything-is-an-object doctrine, this one is hilarious. Aside from that, I feel compelled to add that this does not constitute, from me, an attack against Java of any sort (don’t want to start a holy war, Emacs-vs-Vi style). I just link it for the laughs. I love this article. The parable of the horseshoe nail gets me every time! Ok, let’s get serious now though. Emacs or Vi? :P Hey now, no religious commentary I have never used Emacs, so clearly the only right answer is and forever will be vi. Except I’ve never technically used vi, just vim, so let’s go with that being the One True Editor, and if you disagree, you are clearly insane and I have the right to break into your house and steal all your stuff. Why is it better, you ask? Oh you. What a silly question to ask. Isn’t it obvious? The best editor is Notepad++ on Windows, and Kate on *nix. Except if you’re on the command line, then it’s Vim. “Except if you're on the command line, then it's Vim.” Yeah, about that… time and place motherf***** I kid, i feel like Vim actually is better but it’s so damn hard to use compared to Emacs. Is Vim usable for C++ in a command-line environment? A) Religion is supposed to be verboten here. B) Having used both (comparing vim to Emacs here; nobody uses vi any more), they both have roughly the same capabilities. The vim people where I work can do almost anything I can do with Emacs (no gdb mode for them!) and I can do everything they’ve done with vim. There’s no basis for arguing that one is objectively a better editor. C) Both can be used from command line or in fancy windowing systems. D) That said, Emacs is clearly better. Hey, now! I actively prefer nvi to vim, because when I learned vi in 1989, the I I had was nothing like vimand much like nvi. And, thus, vim breaks my hand-eye coordination. And that, when using vi, is stressful. Notepad++ can’t even draw menus right. I’m always amazed at developers who are still having trouble with things that were perfected in 1984– how is it even possible to have a program in 2013 that can’t draw menus right!? SublimeText is much better. Is that a joke? What do you mean “can’t draw menus right”? Honestly curious, I see no difference with N++’s menus. They look the same as every other menu in Win7. Honestly, I’ve been using Notepad++ for years now, but just recently I’ve switched over to using SublimeText 2 (because my new work computer is a Mac), and ST is pretty wonderful. It’s very like Npp; no strange key commands to get used to (that’s not meant as a bash against things like vim; I like vim, too), but with some nice features. Things I like: 1) Much better plugin/package system. (And from what I can tell, many more plugins to choose from) It probably helps that it’s built on python, so plugins are just python code. 2) Python console. Even if you don’t technically know python, you could probably make use of a python shell. (Though I haven’t looked much into this; but I love the idea of it) 3) Directory tree for opening files, creating files, renaming files, etc. 4) Single click a file to ‘preview’ a file, which is identical to editing it except that the previewed file doesn’t have a tab, and disappears when you change tabs. (It prevents unnecessary tab explosion that I find when I try to work on projects with a lot of files and I just want to reference single files) The best editor for you is whatever damned editor you want to use. It shouldn’t matter to anyone if it is spelled with two, five or any other number of letters. Me, I use emacs for large edits, vi for small-to-=medium edits and ed for tiny-to-small. I mostly do large edits, though. IE6 Though by no means do you have to write your Java to look that way. Ed, man! !man ed I was really hoping “horseshoe nail” referred to a nail bent into the shape of a horseshoe. It looks broken and useless, but you can actually use it to nail together complex geometries, since the nail will “curve” through the material. You have to do it on purpose though, and finding horseshoe shaped nails among your normal ones is bound to be a bit upsetting. Also, the whole parable is a bit misleading. If you’re going to loose the battle for want of a nail, there’s not nearly enough redundancy and robustness in your supply chain, command chain, or any other kind of chain. I read it not as a parable about how the little things are super important, as much as a parable about the importance of safety factors and well engineered infrastructures. The power and ease of use of Object Oriented Programming is not in an object heirarchy. But rather in the implementation of interface. An object can only have one parent but can have multiple interface. This is was the key concept that allowed to make effective use of OOP. Learning this was not easy because a) every damn book on OOP starts with inheritance and the Animal->Mammal->Dog examples b) C++ doesn’t make interfaces (virtual functions) stand out. They look almost like the regular inheritance setup. Last run not walk (or type very fast on Amazon.com) and get Design Patterns from Amazon.com. Design Patterns are to OOP what algorithms are to imperative programming. IT is a book about how to create and use a combination of objects to accomplish something. And get Refactoring, Improving Design of Existing Code. These two books are outstanding and more important they are not holistic “You got to change your programming” type of books. They are like a really good set of cookbooks that explain very well how to do certain things. The two in combination will help you with your code. Design Patterns how to get the most out of OOP, and refactoring tells how to get from where you are now to a different point without breaking shit along the way. I been using these on a complex CAD/CAM machine control program using VB6 for 10 years with great success. I been working as a programmer in Northwest PA for nearly 30 years and these two books are some of the most outstanding books on programming I ever owned and I still use today. Thanks for the recommendations. I may pick some of them up over Christmas break. I would have thought algorithms were to OOP what algorithms are to imperative programming. Where’s that like button again? ;-) I think the earlier discussion about intelligence of programmers was actually pretty close to the mark. OO allows for much better software but it also requires more intelligent developers to do it well (cf imperative programming). There seems to be an emerging consensus that Functional Programming is the next step up, FP can be used to make even better software than OO but with the bar for developer intelligence set even higher. Conversely if your developers aren’t smart enough you better just hope your projects are simple enough that it doesn’t matter what paradigm you use! I would add “stick-in-a-class and wrap accessors around anything that requires access from multiple threads”, that way you can stick suitable locking around the modification, so you don’t end up with things affecting the wrong variable. But, then, I don’t normally write code for games and when I do, the game engine is single-threaded and I tend to use Common Lisp instead of C++. Mostly, I write assorted scaffolding around server code in C++. Java’s main problem in this sense is that it overloads the word ‘class’ to mean ‘A set of possible values’, and ‘a namespace’, and ‘a compound data type’. In Java, not everything is an object, but there isn’t enough vocabulary to say ‘this thing is semantically a namespace, and this thing is semantically a representation of data’. A few more keywords would probably solve it(!) ;-) Technically the ‘set of possible values’ is the Enum. At work we use the “Spaghetti-Oriented” design Shamus described (I imagine OO looked like meatballs to the original coders). For my hobby projects, though, I’ve taken a rather esoteric approach. Instead of trying to model the real world as objects, I design the program’s systems (collision, movement, graphics, etc) as objects, and the world ‘objects’ as data structures that these system hold and share with whatever other systems need it. So, for example, instead of a SpaceMarine object with a position member and an Alien object that also has a position (possibly inherited from an Entity base class), I have a MovementComponent class with a list of positions and associated entity ids. The CollisionComponent class has the collision data for each of them, also associated to the corresponding id. And the graphics component has the model information for each, associated with the proper entity id. So instead of calling “spaceMarine.Update(); alien.Update();”, I’d call “movementComponent.Update();collisionComponent.Update();graphicsComponent.Update();”. The movement component has the information it needs to move things around. The collisionComponent has a reference to the movement data, so it can check for collisions and update the movement data if necessary (tight coupling between these two systems). The graphics component has a constant reference to the movement data so it can update the model matrices each frame, but it doesn’t modify the movement data (loose coupling), and knows nothing about the collision data (no coupling). So a component is defined by what information is needed to perform a certain operation, and is linked to whatever components hold associated information. The world the system models is just a collection of dumb data, and it’s the systems that operate on this data that are the programs’ objects. I’ve found this approach called “data-oriented”, though I might have taken liberties in my application. It seems more natural for me to think about things like this though. That’s a lot like what I ended up doing, except I still have the “SpaceMarine” and “Alien” classes. They contain components(Drawable, Audio, Collider, probably an Input component that will handle player input, AI, and netcode somewhere in the future) which they handle off to the various component managers(Draw manager, Audio manager, Collision manager), which are responsible for making sure all the Drawables get drawn, Audibles get audio’d and Colliders get checked for colliding. It’s probably a good thing that nobody else needs to look at my code… I maintained a CAD/CAM program for nearly 30 years and pulled it through a variety of languages and different OSes. When OOP first burst on the scene I looked into along with everybody else. Dutifully following along with the Animal->Mammal->Dog examples the books give. And while interesting it only seem to help with a small amount of problems. Then I found Design Patterns by the Gang of Four. Design Patterns are like algorithms for imperative language. The teach how to construct objects to accomplish a variety of useful general task. Similar to sorting algorithms or dealing with hash tables. For example one pattern they talk about is a command object. Another was a state object. Both of which was very useful for my CAD/CAM programming. With it I was able to change the design of my software to allow for a full undo/redo system. Using the command pattern to organize the overall design and the state pattern to save and restore what the command did in a compact form. One thing the Design Pattern enlightened about was that power of OOP is not in inheritance of behavior but rather in the implementation of interfaces. As I was using VB6 when I first read all this this was very helpful because OOP programming in VB6 only support interfaces. In contrast the use of inheritance in Design Patterns was very limited. Which mirrored my own experience in trying to use OOP. In my opinion the key to OOP is learning how to use interfaces. The nice thing is that a object can only have effectively have one parent, but it can implement any number of interfaces. Later when I did a simulation of the Mercury Space Casule in C++ as a hobby project. I found that C++ obscured interfaces in a major way. However it does support them. By now I bet you are thinking that it is too late for all this given the amount of time you put in. Well there is something to help with that. And that is the book Refactoring: Improving the design of existing code. The book is a cookbook of different procedures to use when you want to alter the design of your code in a safe and predictable. The author explains why each procedure works the way it does. The best part it works with any type of code in any langauge. For example if a subroutines gets too large and you want to pull a section out and make it a subroutine of its own. The book explains how to do it step by step so you don’t trash your code. And it has dozens of procedures addressing all type of design changes. I am experienced at converting a code base to a different language and OS. In my time I shifted it from a 1980s HP Workstation to a DOS PC, from DOS PC to Windows 3.1, from Windows 3.1 to Windows 32 bit (98/XP). At first I didn’t believe refactoring works as well as the author claimed. But then I tried because we had to radically alter some of our design to handle new types of machines and it does work. Way better than I thought it would. And when the IDE support refactor it like the closest thing to heaven in programming I can think of. I learned to write Object-Oriented code in Hardware Description Language. We have a Module here! The Module has input wires and output wires(typically including a clock signal and a reset signal). We feed inputs into the module, and get outputs from it. How do the outputs happen? I DON’T CARE, IT’S A BLACK BOX! I just care that it gives me the right outputs! So yeah… Interfaces. Something I understood, but now that you’ve mentioned it, I understand WHY I understood. I used to hate pos.SetX ( pos.GetX ( ) – (pos.GetY ( ) * pos.GetZ ( ) ); but I’m starting to come around to it now. The sort of situation I get is that something is occasionally setting X to -1000000 and I have no idea what’s doing it. If SetX is a function, I can at any time add some kind of sanity check with an assert or breakpoint to tell me exactly when the value is going out of sensible bounds and what triggered it. It’s must easier to do this if it’s a function right from the start. Or I might discover I need to set a ‘this object has moved so trigger collision detection’ marker for it, or some other thing I can’t easily anticipate… Yes but a decent language allows you to make a property exposing X and then implement it with either do direct variable access or a get method without the calling code needing to know anything about how the property is implemented. Gives you the best of both worlds and the flexibility to start with direct variable access and then add getters/setters as complexity grows. Delphi did this back in the 90s and there are plenty of other good examples. A decent language may expose properties properly, but you can still replicate it in C++ well enough when all you have is C++ and without the clunky “Get” and “Set” in names. You really are just stuck with (). That makes me think – how would one create a tool to create a c++ class much quicker? C++ has the problem of taking far too long for annoying admin tasks every time you want to make a new object. Maybe there’s already a tool out there… There are several. Generating boilerplate is a thoroughly solved problem. My editor does it for me. Most IDEs I’ve worked with will do the standard work for you. You tell them “Add Class to Project”, and they’ll open a window asking you the name of the class, locations for header and implementation files, and create the files with header guards, declarations for constructors and destructors (helpfully defined as virtual) and whatever inheritance you defined. That’s most of the boilerplate you’re likely to define as common to all classes. There isn’t much more that a program can do without knowing what you intend to do with the class. Use what you need: start with a stupid struct with public fields, add stuff as you need it, because you probably won’t. In particular, don’t bother with a whole new header and implementation file for each class, write the code where you need it to make it work first, then dump it all in the header when that becomes ugly, then move out method bodies when that becomes ugly. Don’t take pain you don’t need to. Class generators exist, but they can’t do terribly much for you, since there’s not that much actual boilerplate for a new class. Now, generating the comparison operators or the << formatting operator on existing types, *that* would be useful. The real question is, “Is there a way to program this without so much boilerplate?” The answer is usually, “Yes”, with the implied action “Move on to a higher-level language.” Can’t remember where I read it, but the number of errors produced is proportional to the number of characters/lines/things typed. * So, usually, you’ll want to use whichever language/library/foo lets you express yourself as concisely as possible. * Even when you’re using a tool to auto-generate your boilerplate, the size of your code will affect how quickly you can read through it, analyze it, debug it, etc. So even with tools, you want your code to be concise. Has “stop using programming language Y” or “use programming language Z” ever changed anyone’s mind ever in response to “how do I do X in programming language Y?” Even it is has, it’s still not an answer to the question. The boilerplate for creating a class is really very little. It’s just the header guard. It’s just boring to write #ifndef BLAH #define BLAH #endif //BLAH Then it’s just “class $ClassName {};” and optionally declaring the constructors, which you might not want. A couple thoughts on how other languages do it (because I like other languages): First, Python. In Python, you can make a class that looks like a struct: class Foo(object): # This is Python <3.0; Py3k doesn't need object there ….member # I can’t convince this blag software to properly format things. People can instantiate a Foo (as foo, for example) and get and set member with foo.member. But then, when member needs to update some other funky things (log messages, event notifications, etc.) you can do that without changing the interface to the class. (This isn’t a Python tutorial, so I’m not going into details, but it’s pretty easy.) It’s great. You don’t need to write getters and setters just because you might want them at some point in the nebulous future. Python’s philosophy on private members is a bit less restrictive than most languages: _member can be accessed directly, but probably shouldn’t and _function won’t be imported with “from module import *” and __member can be accessed directly but its name has been mangled so you have to know what it’s called if you want to be able to break things. Second: Erlang. Erlang uses processes to encapsulate state. If you want a space marine, you can spawn a space marine process that accepts and generates messages. OTP wraps this up in a nice interface, but the essence is just a process per object. The best thing about Erlang (with OTP) is that if you make a new version of your code, you can upgrade the running processes with zero downtime. This isn’t particularly useful in game clients, but it’s awesome for servers. Anyway, C++ does OOP brokenly. You can tell because it promises that your private members will never be modified by anything else, but doesn’t actually do anything to prevent some unrelated function from stomping all over your memory. Const too. You can say things are const, and sometimes they’ll be put in .text and actually be const, but usually you can just cast it away and modify the const stuff and nothing will crash. I don’t know much about Java, having never used it, but Steve Yegge wrote a hilarious post about the kingdom of nouns a while ago. I particularly like Python, because it let’s you use many different paradigms. OO? Check. Functional? Check. Etc? 99% of the time, check! Name a programming language. Statistically speaking, chances are you just named a multi-paradigm language (Wikipedia may contain language that sounds far more authorative than it is, but the broad strokes can also be found in a decent textbook that touches this topic). Because they kinda grew that way once there was a decent example of something that could do any single paradigm. If the language was developed in the late ’80s forward then you should really expect it to cover quite a broad range of paradigms (and the ‘fun’ is looking at how badly or well each language managed to get them all working together and avoiding duplicating functionality for each way of accessing it – or just straight up duplicating functionality if you franken-language your way there with actual duplication throughout your broad, fragmented std lib and base features). Python is an interesting example of a dynamic and dynamically typed language that takes hold of the scripting needs in a lot of places, while still being a programming language suitable for writing most programs you could want to (if performance wasn’t an issue, not a unique issue of Python) and you could actually build a consistent specification for it without dealing with a significant suicide issue for the documenters. I generally don’t like dynamically typed languages (not knowing what type something is at compile time means I cannot know what something is at time of writing and this unravels into a sea of concerns that making compile time guarantees on types fixes for me and allows me to get down there and reason on the type specifications for optimisation) but have been doing quite a lot of Python stuff in the last few years at work (because sometimes you follow the library rather than write a massive interface layer to translate data structures being passed back and forward to your lib in a different language, and because Python is a great choice for rapid prototyping new algorithm designs). Just add some is_instance guards. def foo(a_str, b_int): …if not is_instance(a_str, str) or not is_instance(b_int, int): …….raise TypeError(“You gave me the wrong type”) At least Python is strongly dynamically typed, so: “2” + “2” => “22” (and not 22, or 4, or ???) 2 + 2 => 4 “2” + 2 => Error and that’s guaranteed to happen. Unlike the weakly-typed languages. Coming from compile time typed languages, run time checks are frustrating. I prefer to turn as many bugs into compiler errors as possible. I gather it’s possible with dynamically typed languages. I’ve been told of there is at least one language (sadly blanking on which) whose compiler is smart enough to deduce things like “In this function, the parameters a and b are added together. Therefore, if someone passes values that can’t be added, or can’t be added together, the compiler will complain without ever running the code. (Don’t take the above as “never use Python.” Python is a rock solid language. I recommend everyone who programs consider it for new projects.) I think you’re describing type inference; this is a feature of a few functional languages, including Haskell and the ML family. Technically, though, compile-time type inference is considered static typing, though I actually really like it because I think, when done right, it combines the safety and performance benefits of static typing with the flexibility of dynamic typing. Type inference (of the form I think you’re describing, using var/val rather than a type in your source at places where what you want will become obvious – basically removing duplication of the type token when it isn’t needed) is something you should expect, going forward, at the IDE level even if programming languages don’t adopt it. Things like C# (in 2007) and C++11 have added it and Scala (and yep, a lot of functional first languages) always had it. There’s no real need for a lot of the type tokens in most languages and if you’re going to be strong then you definitely don’t need it and if you’re weak then you’re not really saving people without it (one is busy work that does some validation of the programmers understanding, the other is hidden by implicit type conversion so it isn’t even throwing up errors). But it takes more than no work and most languages were devised when the idea of parsers running on each token add to run grammar checks and even do advanced static code analysis as we write code was well into the magical future of Moore’s law. Alan’s post seems to be considering some static code analysis being run on a dynamically typed language to point out places where a clear contradiction can arise, rather than waiting for it to fall apart at run-time. If you’re running something like PyLint, Pyflakes, or PyChecker (I think all 3 do type inference passes; other DCA or SCA tools exist for other dynamically typed languages) then the analysis they do will give you some indication of clearly bad code. But the compiler isn’t required to have types and so some code will resist analysis. This is the freedom of dynamically typed, which I prefer to give up for guaranteed compile time type errors, and a limitation of code analysis tools. In my view statically typed languages used generic programming to get past the really nasty limitations that originally made dynamically typed languages so seductive. Yep, I’m aware of how to turn Python into an approximation of any other language I desire but using manually inserted run-time type checking into every bit of your code is a sure sign you’re using the wrong language for the job. I want compile time type checking to do as much as possible basically in every language I use. Even jumping around implicit casts in weakly typed C (once described to me as the minimum required type system to have a working pointer system and not a jot more) seems preferable to having to deal with all type concerns at run-time. It’s a bit like the original C++ compilers being C compilers with a C++ to C transformer step at the front (with some rejection logic for things that are not C++ – a critical point as these later become compiler errors that pure C compiled with a C compiler cannot reproduce). Technically it means that the first C++ users (before the C++ specs moved to the point where this is no longer possible) are just enjoying some syntactic sugar on C so you should just use C. Only that’s missing the point. A bit like the Turing complete bar: everyone jumps it so they’re all the same. Only they’re not and picking the right tool is important. I will occasionally check types when I feel I really need to in my Python code but generally try to follow Python guidelines to use duck typing at all points. I just feel like I’m working without a safety net and would be happier with static typing. It doesn’t help that most people think of dynamic typing as type inference and Scala and C# (to randomly pick two quite nice staticly typed languages) both show this can work just fine without giving up on knowing your types at compile time. But this is an “I like X” thing where I happen to sit in the static typing camp and I’m not sure another couple of decades of coding, even if I continue to work in a mix, is going to change that. Now mutable objects as default arguments being created at code load time rather than creating at each instantiation. That seems like Wat language design in Python. After a few months you get to accept why you end up there but if that isn’t a slightly weird exposure to the mutable/immutable split in the type system hitting the first class function, I don’t know what is. Maybe it is there as an important lesson everyone has to hit as they learn the language but sometimes you do wonder why it isn’t sugar for making a clean mutable each call and so acts like everyone else who isn’t a Python user expects. Contrary to popular belief, python does not actually support a functional paradigm very well. Actually I would say that it does not support it at all. First of all, it does not optimize tail recursion. Making it near useless for implementing any algorithm in a purely functional way. Secondly it has not have shorthand way for defining functions. The lambda keyword is a remnant of one of the first patches to the python source code. Guido looked into removing it, but there was not direct replacement for what little purpose it did serve. Thirdly, it does not support any pattern matching, meaning it is useless as a functional language compared to more modern and mature counterparts. At best the syntax is functionally inspired, with functions being first class citizens, and various comprehensions being the only noticeable functional features. That being said, I love python personally, I use it every day, at work, for my personal projects. It simplifies my work a great deal. But, knowing many languages, and having written a few compilers on my own. The language and the API is a real mess. The only feature that really deserves praise is how easy it is to use. C# has a really interesting solution to the getter setter problem. (Obligatory: I’m not trying to be an evangelist just discussing an interesting approach to the problem discussed) Basically C# has two different types of object variables, fields and properties. Fields, with a lower-case variable name, are basically standard object properties. So “private int health;” is pretty much what you’d expect. However, you can also declare properties, with capital letter variable names. These are accessed just like fields, i.e. “player.Health”, however, under the hood that’s actually a function call; as well as “player.Health = 10” is also a function call. C# will automatically implement a standard getter and setter for you (or just one, or neither if you so choose), or you can implement custom logic. So you might see: string Name {get; set;} //Automatically implement getter/setter private int health; int Health { get { return health; }; set { if(value < 0) die() health = value; //Value is a special variable for the value being assigned } } Anyways, my syntax is bad, but it's close enough to see the idea. I've only used C# for a few months, but I do find that I really like it. It takes the basic idea of Java but with much more flexibility and just better design over all. D does this as well(though not transparently. That may have more to do with Code::Blocks than D, thought), and in fact dynamic arrays have a built-in Property, “length,” which can be called as a right-hand value if you want to check the array’s length, or can be called as a left-hand value if you want to set the array length. Small side-effect is that you can’t do array.length++(which is how I figured out that it does this) One of the reasons I compare D to C# so often. I feel like it’s worth noting that the naming convention described above is just a convention. But, yes, properties and nifty, and auto-implemented properties are extra-nifty. There are some quirks, though, that prevent a property from behaving like a field of the same type. For instance, you cannot pass a property in place of an out or ref parameter of a given type. This will make sense, if you think about it: an int property is not a variable of type int, it is a pair of methods (one that takes an int and returns void, and one that takes nothing and returns an int) which are swapped between at compile-time. On the upside, declaring public fields as properties by convention helps a bit with future proofing, and solves some questions about behavior of fields that are const vs. static readonly (i. e. const fields may be inlined to dependent DLLs during compilation, but a static readonly won’t; this makes consts exposed outside your library relatively dangerous). Still, it’s a very handy bit of syntactic sugar to have in the language. One of C#’s language features that I really, really like. Yeah, I wish I had that feature in C++, le sigh. I know enough of programming to understand everything you wrote, but not enough to care about which way is “right” or how one “should” do something. So, in other words, I guess I am in the perfect state to enjoy this post. ^.^ The goal of good programming is to communicate to humans what the computer is doing. Computers don’t care if you write all your code in binary or Haskell. Programming languages are for the benefit of humans. So when evaluating software for goodness, you can use the “how long does it take me to understand this?” metric. If it’s a long time compared to other software that does similarly complex things, it’s not good. Of course, that’s not very useful advice for a newbie. To call out the point I believe Nathon implicitly stated: the “right” answer varies based on the problem you’re trying to solve at the moment. This is part of why multi-paradigm languages exist (see Shivoa’s comment). Different parts of a large project might use different paradigms. It’s also part of why there are so many programming languages, different problems map better to different languages, and why many projects include multiple languages. (If you’re running a Java program, I pretty much guarantee there is C++ helping. If you’re doing massive numerical crunching in Python (NumPy), Fortran is probably hiding under the hood. There is a saying. Always write your code as if the one to later maintain it is a manic psychopath who knows where you live. The extended version also says – that guy might be you. Whilst I agree it is sometimes annoying to have to use a lot of getX style methods (though in that case, why not make a function called doAlgorithm to do that from inside the object and use the result there?), I’ve had some bad, bad experiences at hunting through code to find where the object.x was reset, by another programmer in a different thread, and there are lots of other .x calls throughout the code… The ability to add a debug line to getX/setX and work out where in the code that call is actually located is a Godsend True. I really enjoy Python’s property implementation, where you can add getter-setter functions after the fact. Super handy, but of course it’s an interpreted language. OOP got sold back in the 90’s as a magic silver bullet that would solve software complexity forever. Shockingly, it didn’t turn out that way (presumably these people never read Fred Brooks) OOP is a *tool*, and like all tools it has strengths and weaknesses, problems it’s well-suited towards and problems where all it does is add needless complexity. Trying to impose it on every problem, large and small, causes as many problems as it solves. This is why Java drives me nuts. Its slavish devotion to Object Oriented purity has the effect of driving out other, equally useful tools. It’s like a toolbox full of hammers. What if I need to turn a screw? Java only requires that everything be declared inside a class, but it doesn’t enforce Object-orientation. You can, for example, have a program comprising a single mega-class. A C program disguised in Java. You can think of Java’s ‘class’ keyword as declaring either a data type or a namespace. It might help if these notions were separated, but maybe the language is too long in the tooth now and Java programmers don’t seem to mind the conflation. My primary gripe is the lack of functional programming facilities. Functions in Java are not first-class objects, which means no higher-order functions; Java has no anonymous functions, and to my knowledge doesn’t have full support for closures. This is with the caveat that the last version I used was Java 5; if any of these have been added to the language since, that’s great. The important thing is, none of these things are possible without abandoning Java’s “everything is an Object” orthodoxy. Well, Java 8 will add support for a lambda expression, but as far as I know this will just be syntactic sugar for anonymous inner classes. I actually don’t see the lack of functional constructs in Java as a disadvantage, or rather.. I wouldn’t see the addition of them as an advantage for Java. Java currently enshrines the theory of Object/Component Oriented programming and the only first class citizen are classes. I think this is very clean, personally. It’s true that Anonymous Functions, are not possible and that’s good for the same reason. However, you can achieve this behaviour by having an anonymous inner class which implements an interface (e.g. Callable, if you just want a functor). A limitation is that you may only close over final variables in an inner class. I think if you really want to mix Java with functional elements, a much better route is to pick a functional jvm language like Scala or Clojure. These languages give you the first class functional constructs, with the advantage of fantastic interop with the Java Class Library. My personal feeling is that Java should maintain it’s current position as a ‘class oriented’ language and not muddy the water by introducing things which are not a good fit. but maybe I’m just an old curmudgeon. :-) Well if you are using Java then the answer is obviously “Swing Harder”. ROFL. I want to throw in that many issues of OO that Shamus mentions are somewhat specific to the late 90’s style of OO languages such as C++ and Java. In actually modern languages (Scala, Eiffel), many of these problems are far easier. Nobody writes a vector.GetX() function in Scala. It’s just vector.x, as expected. It’s a bit more complex than that, but suffice to say, this issue is solved by now. The problem is that these newer languages are not that widely used yet, to put it mildly. That said, it’s not a secret that most games have very shallow inheritance structures, and not a strong object model. Not because the programmers suck at OO, but because games don’t translate well into OO. Everything interacts with everything, performance is super-important, but there are relatively few use cases compared to business software (how many tools does Photoshop have? How many types of guns are in Quake?). I also want to point to anther issue with OO, namely trying to map objects and relational databases. This (long) article explains it all, and is worth the read for any programmer. The short version: It’s absolutely impossible to perfectly map objects and relations, because they are not the same thing. Any attempt to do so will work nicely for 90% of the time, and then proceed to completely screw you over with a dirty, lightning powered flaming chainsaw in the rectum. That sounds like what you want is a static class*. With that, you would write something like Player::Upadate ();. This basically combines advantages of both approaches: the player data is nicely encapsulated (you can have private static fields), but you can’t have more than one player and you can also access the player from anywhere. * C++ doesn’t have any specific support for static classes, you just make your constructor private and don’t declare any instance members. I think the point was more along the lines of “I don’t need any of the features of a class, so why spend internal overhead on a class when a few arrays and some functions will do just as well?” Even in your example, you’re going out of your way to make the class harder to use in order to make it not behave like a class at all. Why use a class interface at all? I don’t think the features of a class are not needed here. What can still be useful: * Grouping all the related code in one place, with enforced consistent naming. * Having the ability to hide implementation details into private fields and accessing them only from a limited and knowns set of functions. And I’m not sure what kind of overhead are you talking about, but classes have pretty much no overhead in C++, and especially classes that you never instantiate.. Someone above talked about design patterns being the algorithms of OO programming and this is a perfect example. The pattern you’re looking for here is “Singelton”. Singleton allows you ensure that there is only one instance of a particular class running around. How does it work? You make the constructor private / inaccessible then create a static method that returns an instance of the object. The first time the static method is called you create a new object, return it, and create a static reference to that object. The second time and every time after you simply return a reference to the static reference you stored the first time. Singletons are great when you really need one, but they’re overused and a source of potential pitfalls. And a singleton object is probably still more awkward to deal with than the situation Shamus is describing with a mix of procedural/imperative and object-oriented coding. When do you actually need one instead of a static class though? I guess if you need some polymorphism for some reason? Other than that, I can’t think of anything. I think you may have misunderstood me: Singleton is a pattern, and I see no reason you couldn’t implement it as a static class. (My major concern re: pitfalls has to do with multithreading.) There are situations where it might be convenient to serialize singleton data to or from a shared source, such as a file or database. That sort of thing may not require or be compatible with wrapping in a static class. Most instances of “I know: I’ll solve it with a singleton!” I’ve seen either involved tracking a bunch of global state in C#, which doesn’t have global variables; or creating a singleton of a thing that doesn’t need to be a singleton (usually with a factory type). The former was the wrong solution to a non-problem, and the latter is a design error that is probably propagated by every almost example I’ve ever seen of a Factory implementation also being a Singleton. Singleton is a pattern that you use when you want static class, but you don’t want to use static class, because that’s not “object-oriented”. So, it doesn’t actually solve anything, it just makes your code more verbose. Yeah, I’ve read and heard about the Singleton “pattern” several times now, and every time it’s sounded like either nonsense or circumlocution. Every time it comes down to “We don’t like to call them “global variables” so we call them “Singletons” instead! Now it’s a design pattern instead of poor practice! The magic of terminology and obfuscation solves everything!” Just use global variables properly and call them global variables. Actually, static classes (and singletons) have one significant advantage over global variables: you can control access. With static class, you can have a private static field and allow access to it only indirectly, though some set of static methods. With normal global variables (or public static fields), you never know who is accessing it and whether they are doing it correctly. If someone is using a singleton just a simple global, they’re probably using it wrong. A singleton isn’t about “toss all your globals here.” The original Design Patterns specifies that it’s for when one has an object for which logically there should only ever be one instance of, and one wants to ensure no one erroneously instantiates a second one.” It accomplishes that job pretty well. Given that use case, it’s widely overused. Almost any circumstance in which I might want 1 of something, I can reasonably imagine wanting 2 or more. “There is only one player” stops being true as soon as you go multiplayer. “There is only one display” stops being true as soon as you go multi-screen. Even “there is only one event loop” becomes dubious assumption on a multi-core machine. On the (marginal) up side, there is a small advantage if someone is just using the singleton as a dumping group for globals. Globals suggest side-effecting code, and probably non-thread-safe code. If you need to add threading to such code, if all of the globals are in a singleton, it’s a lot easier to remove the singleton, take the object itself, and instantiate it once for each thread. Arguably not a big deal if one “Just use[s] global variables properly,” but if I’m handed someone else’s improper code, I’d rather the global variables were grouped into a singleton than scattered across the code like buckshot in a deer. +1 (I was thinking “Just use a singleton, just use a singleton…” all through that part, and as soon as I finished the post, I searched through the comments for “singleton” to make sure it was represented. :P) I think all programming should be approached that you may need to support it two years down the road so you better be able to understand it 2 years later when you are no longer in that headspace anymore. If you do that then the code will be able to stand up to other programmers. Also agree with the above that standardization amongst team is a must, but real world rarely happens. More like rough guidelines…oh well a rant for another time. I slowly gave up OO when working in python. I’m coding in go now, and I’m experimenting with immutable and pointerless structures, in a data-driven way. So far, I love it. Immutable means that I can parallelize everything without ever having to worry about synchronization. It means that I can also keep past versions of the world in memory so that I can replay it if something goes wrong. Not using pointers means that saving/loading the game state on disk is a one-liner. That comfort has a performance price, but I will value correctness above speed any day. The data-driven approach gives me some speed back anyway. I was thinking this article would end with “so I’ve done this whole project in imperative style, because all the downsides of imperative are alleviated when you’re the only person working on a project.” Don’t know about you, but I am perfectly capable of confusing myself when my projects starts to get large. Especially the parts I haven’t worked on for a bit tends to be forgotten. (and this is also the reason I try to be very generous with comments) I try to comment shit myself, but a lot of the time I just end up rewriting the code instead, which has the side effect of making it moire solid, lean and mean too; which I don’t mind :) There’s totally a good reason for the a.setX thing, although it’s not always necessary. Using getters and setters means it’s impossible to bypass the sanity checking code that stops things like having a negative age. This is, of course, only a problem if there are potential nonsense values and the program is structured so that might possibly happen, and the setter actually screens for such things. It’s much more important when you have multiple programmers. If you do not want the risk of a negative age then using unsigned is the solution as it can’t go negative. Signed and Unsigned exist for a reason. And that reason is people used to have total RAM measured in bytes, so you didn’t have space to ask for an int that could do both negatives and count all the way to 255 without taking up significant space. Sanity checking age makes a lot of sense when subtracting 1 from the age of 0 gives you the oldest age possible (UINT_MAX) and no errors in some languages (which cunningly defined away overflow errors with unsigned ints by saying they just wrap and this is the spec behaviour, nothing to see here) if you didn’t use signed ints. As an aside (as we’ve mentioned unsigned ints in C), signed ints have undefined behaviour if you ever fail to check for an overflow before executing that computation. This is potentially a rather exciting difference in the C spec for those two type groups, depending how much you believe your old professor and how graphic his embellishment of what the worst that undefined behaviour could mean. Now if there is undefined behavior related to this in the C spec then that is worrying indeed. But regardless, overflow is nasty, and if it happens it is the programmers fault, not the underlying language or storage method. Why is it the programmers fault? Because nothing should ever overflow or underflow in the first place. The way I code (and ensure) that my code behaves like is that if you have $FFFFFFFF and then add to that then the result should still $FFFFFFFF if that suddenly wraps around it’s a major bug/issue. Now if you do not use the whole range it’s easier as you can control things if the underlaying language wraps around or not. If signed and you use from 0 to 1000 then you could easily do a upper and lower check like (pseudocode) If (x>1000 then x=1000) or (x<0 then x=0) now if values never go negative naturally the second part could be (x999 … oldtime=timeGetTime() endif This will do the code inside the if block once per second, and you have to use (time-oldtime) as that is the only safe way (you end up with the difference so when it wraps (which it might every 49 something days on systems that is always on) your code will handle that fine.. You mention values up to 255 and memory in the past, but there are actually unsigned 32bit and unsigned 64bit CPU support as well? Now, I have heard statements that unsigned math can be slower than signed math, I’m yet to do a test myself or read up on any tests for that. Most of the time I never need to worry about signed vs unsigned. But when dealing with memory addresses or filepositions or handling of checksums (like CRC32) then I prefer to use unsigned. If I where to do a game and a monetary value where to be stored then I might use unsigned 32bit integer or 64bit integer, with or without a fixed point. (many games do this). If I where to do a financial program then signed would actually be a benefit as a negative is actually a valid result. If I where to do a game with damage calculation then I might use 32bit float. For a audio program I might use 32bit float (which can easily hold a 24bit integer value) or 64bit float is a lot of processing is to be done and highest precision is needed, float does have some minor rounding issues due to the way floats work. (and I know, there are 128bit+ features in newer CPUs but the gain is diminishing rapidly at a certain point) I advise reading the C specification, or more accurately I advise reading the K&R 2nd book and then maybe dropping in to the actual specification document (getting up to date with C99 or C11) from there as you need it. C is well specified as a language but there are quite a lot of things that are grammatical C and result in either compiler dependent execution or undefined behaviour (as defined by the spec, which should be considered the gold standard to hold compilers to). This is not a problem with the spec (or even that worrying – the range of non-compliant code that is similar to C, ie outside of the C standard, that a compiler will generate an executable for is far more concerning) but you do need to be aware of it before you consider yourself a competent coder in the language. There are also great resources like the CERT C secure coding standard that help explain how to code to avoid shooting yourself in the foot in C. In other words, one need to choose which version of C to code for. Using unsigned for such a thing only means that you now have another class of errors: Instead of the somewhat annoying “why do I have negative HP?” you now have the much more problematic underflow. As soon as subtraction is a thing you are likely to do, unsigned is wrong. Few people understand how to work with unsigneds (namely only use them when you are so close to the hardware that you care about individual bits), and that is why we have such horrible constructs as arrays that take DWORDs for indices and return them on GetCount(), only to die a horrible seg-fault death at the earliest chance. Actually, you are wrong, if all you care about is the individual bits (AND OR XOR NOT and similar) then it does not matter if it’s signed or unsigned as long as it’s consistent all the time, as soon as you move a value to from signed or unsigned storage the issue isn’t the language or the signed vs unsigned, the issue is the programmer being a moron. Programmers these days are so used to just casting something from one thing to another, and if something blows up they have no idea why. I searched up GetCount and segfault and the results I see are C++ specific, could this be because programmers just assumes that C++ waves a magic wand for them? The correct behavior (at least to me) is that the calculation: 0-1=0 The same way that the calculation 4294967295+1=4294967295 In the same way 2147483647+1=2147483647 and -2147483648-1=-2147483648 If the underlying language does not do that, then it is the responsibility of you as the programmer do be aware of this and code accordingly. If the language is speced properly and not undefined then unsigned or signed is not an issue. With the exception of things like timeGetTime(), things should not normally overflow/underflow/wrap around. Imagine if a gas pump at a gas station was allowed to wrap around or overflow. The result would be that the gas would overflow (pun intended) from the gas tank, and the gas station would owe YOU money instead (as the gas amount would be negative). “why do I have negative HP?” my answer is, because either the programmer of the game, or the programmer of the underlying language or the game engine screwed up. And as for GetCount and DWORD, luckily I’ve never had to deal with code that used that (I rarely use code by others without reviewing it anyway if it fits my needs). But if you have an array (I assume that is what you are talking about as you mention indices). Myself I use whatever number storage is big enough to hold the numbers I need to hold, combined that with always having control over what gets added/subtracted/multiplied/divided. I may be anal about coding like this, but to put it another way, I can’t recall the last time I had a division by zero, it’s really that long ago. I do recall the last time I had a wraparound bug though, and that was because I forgot to initialize the comparison value for a timeGetTime() check that was to be done later and occurred in the middle of some larger code rewrite/moving. My statement above of “If you do not want the risk of a negative age then using unsigned is the solution as it can't go negative. Signed and Unsigned exist for a reason.” still holds true. Now if programmers fail to maintain control over what is happening with their code and values (bounds checking and sanitizing user or 2nd or 3rd party interacting software/code, or loading stored/transmitted data), that is not the fault of unsigned or signed. Or if the underlying language does not handle unsigned and signed consistently or how people expect them to then that is a issue the programmer of the language or for the programmer that uses the language. Now, I code in a procedural language, and if I do C then I prefer to stick to C whenever possible if I do C based stuff. When it comes to #NET and java and managed stuff like that I have no idea how messed up/un-messed signed vs unsigned actually is as I never use those languages. When it comes to OOP then classing everything and mixing signed and unsigned and not documenting it is a huge blunder by whomever did that. I avoid New and (the implied) Destroy like the plague anyway. I prefer to allocate all memory/buffers I’ll for the duration of the program that I need at startup, and if temporary memory is needed (for processing a loaded image for example) then I allocate that memory and then free it when I no longer need it, but if possible I recycle that memory thus avoiding further allocation and de-allocation needs. And I never free any memory when I quit the program unless the Win32 API documentation states that this or that must be freed or unlocked first. All memory that “you” allocated is automatically freed. Instead of taking seconds or longer to quit the program can quit within a second and the system has the memory available ASAP. I’ve actually seen code/software that step through a list of heap allocated memory and free each entry. Stuff like that happens because the programmer do not understand the underlying code of the language or library or classes they use. So I’ll re-iterate, unsigned vs signed is not the issue, not any more than signed vs unsigned vs 32bit float vs 64bit float and so on is. The more things you define, the more things the compiler need to check. Checking for overflow to ensure consistent behavior on every operation has a price. Neither C nor C++ is going to accept that price. Thus, it’s undefined. So, most of your memory allocation is in one place, distant from the code using it? It seems like it would be easy to remove usage of some memory, but forget to remove the associated allocation. Why would you recycle it? All I can think of is optimization, and if you’re making this your default style, it sounds like premature optimization. Allocation and de-allocation is pretty cheap. Reusing the memory makes it harder to detect accidental aliasing; it will thwart pretty much all of the techniques for automatically detecting that. While there is a big advantage in a fast shutdown, there are several dangers. First, you’re going to make it very hard to use a memory leak detector. Also, if you’re using C++ and your coworkers are relying on destructors being called to handle final cleanup, it won’t be done. Sure, memory and sockets and some other things will get cleaned up, but temporary files, SOAP sessions, and can will be leaked. At most places, these habits will not make you friends with your co-workers. Just letting the program exit and not free the heap is actually MicroSoft’s own recommendation. Also you mention coworkers, luckily I have none. But even if I did, a project would have a agreed upon practice. And in the case of different languages used one could always compile to DLLs, using a modular approach to building a program. Shamus explains a lot of stuff better than both my Informatics Prof AND my OO Java tutor. I wish I could take classes with him, to be honest. Also, that hybrid style seems wonderful (at least when you code alone, I suppose when you’re in a team you really have to adhere to strict OO rules to make it easier). I would not be surprised that when Shamus gets too old to code (feels two eyes glaring), that he might end up doing some for design tutorials/design classes, theory classes of some sorts. Nothing more difficult for a programmer or technical guy to try and dumb down stuff so others that now less or very little can understand you, after all, sometimes we can’t even understand our own code at times. When you yourself stare at a piece of code you have written and go “OK! I understand what it does but I have no idea how I came up with the idea to do it this way, when did I write this code? 02:00 Sunday night? I must be going senile or something here…) It also does not help that a lot of things that are similar but a little different but has overlapping functiona,lity can be confusing to beginners you try to explain to either. Like structure vs object, or object functions vs procedures with a structure pointer, and so on. But I’m impressed with Shamus’ ability to explain things in a generally digestible way. Maybe having kids is part of the equation. Or maybe seeing how crappy the school system was first hand is part of it, or a combo of both. Or maybe, Shamus is just really talented at typing shit for other folks to read. :) Thanks for this post. I’m not a programmer, but as a scientist I hack around a bit with R to analyze my data. My formal programming experience starts and ends with a class on C++ I took in high school. Every so often when I stumble over epic internet arguments about Object Oriented programming or whatever, I’ve been puzzled about what everyone is arguing about and why I should ever care. With this post and the rest of your series, I’m realizing that all y’all professional programmers are dealing with orders of magnitude more complexity and interactions and ways for things to go wrong. For me, most of my data analysis scripts are simply ImportData, CleanUpData, TransformData, AnalyzeData, GraphData, etc. Really there’s very little room for something to go wrong that’s not a straightforward mistake on my part. So I suppose plain ol’ imperative programming is exactly the right approach for me. “space_marine.Damage (grenade_damage);” This is no different than doing this: Damage(*space_marine, grenade_damage); Here Damage() is a procedure/function, the first parameter is a pointer to the space_marine structure (or object if you roll that way, in this case they are almost synonymous), and second parameter is the damage. You can easily add a sanity check to the damage and to the npc/player/rock that is taking damage. I used to do a lot of functions that had a lot of parameters, or globals. But now I’m addicted to functions that take a pointer to a structure, and then none or more paramaters that do something to that structure, or based on that structure. I still do have “globals”, but my “globals” are all in a structure instead, and I have one single global variable that points to that structure instead. I also use Init and DeInit functions to allocate or populate a structure and then free or null it. Not unlike new and destroy in many OOP languages. Only that I do this in a procedural language, and no garbage collection (it’s all manual baby). Always choose wisely, sometimes a structure you just pass a pointer to may be all you actually need. Also if you set or get something using a object function then you get overhead, this can obviously be avoided by simply using unsigned and signed where appropriate (I mentioned this in another comment here). But OOP Get or Set stuff does not guarantee things will work as expected, some idiot may just decide to improve the Set function of a object and now shit is going haywire all over (maybe they changed from signed to unsigned or vice versa?) Procedural is also just as weak, if the procedure (or function as some call it from time to time) in some include is messed with or somebody changes a structure value from signed to unsigned or vice versa you get the same issue there. OOP is just a different way to code than Procedural, you can do the exact same stuff using either of these approaches (people did code before OOP, and OOP did not revolutionize anything practically speaking). What can fuck you up is that some bozo, some yoyo, some shmuck changes something about some piece of code that screwes up a lot of code that relies on that, or they fail to follow the internal guidelines for the project. Important note! Each project should have a set of guidelines to ensure consistency and less chance of bugs being introduced. So if you are 1+ on a project, start to write a damn manual documenting the functions, source comments are fine, but nothing beats a manual documenting stuff and you can search and reference it while you are writing/editing source code. (nothing worse than scrolling/looking through source to find the comment with the info you need). Wow – that was a brilliant articulation of the different paradigms – thank you! Sounds like you have adopted the pragmatic paradigm; using OO where it makes sense and limiting side effects where possible – make it as simple as possible but no simpler :p Anyway, nice article; as always. Enjoying the series immensely and looking forward to giving real cash moneys for the game when it comes out. Yeah, I’m a big fan of the pragmatic style as well. I’ve been told by professionals that my code is “messy” and “poorly structured” but then they comment on how quickly it runs, and how robust the output is. I’d guess the same is true of Shamus’ code. It’s easy to look down on informal code structure, but if it works at the end of the day as well as the beginning then I’d be more interested in learning than lambasting. I’m not prepared to comment on the clarity of the code Shamus produces, but “if it works at the end of the day as well as the beginning” is the wrong time frame. As a professional programmer, I’m much more interested in whether or not it works 6 months later, when weird features have been added by people who didn’t have time to fully understand how it worked to begin with (or wouldn’t have if it had been messy, hard to follow, and poorly documented). Thinking hard about structure is not always worth it. Sometimes your code gets run once and thrown away. “It runs faster” is only a good reason to have ugly things if you have profiled the equivalent but pretty code and decided that it’s too slow to do its job. That does not happen very often. The long and the short of it is that performance isn’t the whole story for most software projects. Maintenance cost far outweighs the cost of initial development for a great many ‘real’ projects. So, code structure matters, even if it’s not the first and most important thing to worry about. I often wonder why, if maintenance costs so much more than development, we don’t re-write more code from scratch. Yes, I realize inertia and sunk costs and such, but even so… Was that some very dry humor, or sincere? Can’t it be both? As if we’re going to re-write every architecture from scratch? Nonsense! And yet, we do it for toilet paper, plastic forks, keyboards, and airline production lines. The rules are generally the same, and patterns emerge, and lots of stuff gets re-used, but a lot of stuff gets re-built instead of maintained. I mean, at some point it’s going to be more cost effective to write working but hard-to-maintain code and then simply re-write the whole thing before it stops working. I don’t know where that threshold is exactly, but it exists. We do it with cars (car analogy!) so why not with software? Not saying anyone here thinks like this, but I get the impression that software engineers have no concept of wear, and lifespan. It’s like they think software is this untouchable perfect thing that will last forever. Its not, it wears out just like a bearing or a building. Eventually you need to design a new one. Certainly easy-to-maintain code is preferable, but it comes at a cost, and that cost is not always worth paying. Joel Spolsky explains far more eloquently than I can manage why rewriting from scratch is usually a mistake. I recommend “Things You Should Never Do, Part I” and “Netscape Goes Bonkers“. Good articles! So, it doesn’t matter if the code is ugly, as long as it works? I think that was the point I was trying to make at first. And yes, ideally one would write code that is easy to write, easy to maintain, works perfectly forever, and has no bugs. But, since we have to make trade-offs, I’m going to generally err on the side of “this code runs” instead of speculating on what kind of maintenance or feature creep is going to rear up in the future, distant or otherwise. That’s not the message I took from it. I got, “the code may be ugly, but it works, and that’s strictly better than throwing it away and starting from scratch.” I don’t see it as an endorsement of writing ugly code in the first place. A lot Spolsky’s articles are about doing things in a way that helps maintence. For example, his piece on Hungarian notation convinced me that it was a really good idea, and that I’d what I hated was erroneous Hungarian notation. (On that note: anyone who thinks Hungarian notation is stuff like “unsigned long ulCoordX”, read Spolsky’s article for how it was meant to be used, and why it can be useful.) Some software is like a disposable utensil, some software is a durable good. The way one addresses each is different. If your code is so great it never, ever needs to be touched again, great! Structure it however you want. If that’s not the case, a little care to readability, encapsulation, etc. might be worth the investment. One way to deal with the traditional problem of object oriented design is to turn things upside down a bit. Instead of expecting classes to do everything, classes are expected to expose events that “observers” can subscribe to and then do the magical things that a given subsystem expects, leaving the object oblivious to these actions. This isn’t a native C++ feature, but most frameworks (Qt, SDL, Windows, etc…) do provide them. What observers bring to the table is the fact that your space marine can simply raise a Walking event and the sound system can update the walking sounds as needed (staring, continuing, switching between sounds based on surface, cycling sound options to avoid obvious “looping”). Meanwhile the game-play system determines the “physical” results of the attempted move and the graphics system eventually gets notified of the updated location/orientation/status of the unit. The observer and the observed can then cooperate, the observed maintaining the state of the object while the observers maintain the state of the *impact* of that object on the game. Which isn’t saying it is a silver bullet… there is overhead in such systems. However, they are immensely flexible when the workload is divided well and the state objects provide a robust set of events to observe. I’ll stick to pure C for now. I am currently using the C 2011 standard. I am comfortable with pointers and the like. While I have experimented with C++, I found myself taking more time to solve problems that C++ produced where as with C, I got the job done, error free, usually the first time I coded it! I find C++ bloated. All my C code is commented, if you don’t know what I am doing when you look at my code from my comments, than you’re an idiot and should stick to BASIC programming. ;) I use structs to make “objects” with their own functions, which reside in their own C file. I am working on a game now, 100% C (2011) and have been surprised at how few errors I have had. When I started it I tried to do it in C++ and it was an excersize in frustration, and there was no WAY I was going to go online and ask questions in some forum, my experience with forums and getting answers is similar to some of the posts Shamus talked about with his “backing up the car 2 feet” analogy. :) I think it’s pretty obvious that if you’re programming in a language that you know well, you’re going to be more productive (and write code with less bugs etc.) than when you’re programming in a language that you don’t know yet. That’s an argument to stay with the language you know in the short term, but it doesn’t mean the new language is worse. And in the long term, I think it’s a good idea to actually learn and understand other languages, for two reasons: 1. You might find that the new language is actually better and start using it. 2. You might find that the new language has some interesting ideas, that might make your code in the old language better (e.g. emulating virtual functions in C after trying an object-oriented language, or using higher order functions in C++ or C# after trying a functional language). Specifically about C, when I programmed in it a bit recently, the thing I missed the most from C++ weren’t objects, it was generic collections. In the code I was writing, there were several linked lists of different types. Doing that using C++ templates (or C# generics) is trivial, even if the standard library didn’t already contain it. But I think that doing it cleanly in C is pretty much impossible. One more thing regarding forums: have you tried Stack Overflow? I believe it’s much better for asking about programming than>
https://www.shamusyoung.com/twentysidedtale/?p=21315
CC-MAIN-2019-30
refinedweb
20,856
68.91
Just created a new project trying out the QCAR Video Sample package. I get these errors in X-Code.. I've made sure there are no spaces,hyphens etc.. in my project name directory. #include "QCARUnityPlayer.h" #import "AppController.h" #import <CoreGraphics/CoreGraphics.h> #import <QuartzCore/QuartzCore.h> #import <UIKit/UIKit.h> #import <Availability.h> #import <OpenGLES/EAGL.h> #import <OpenGLES/EAGLDrawable.h> #import <OpenGLES/ES1/gl.h> #import <OpenGLES/ES1/glext.h> #import <OpenGLES/ES2/glext.h> #include <mach/mach_time.h> Any thoughts on this would really appreciated as i need to present this to a potental client tomorrow evening... Regards, Mick Hi Mick, Let me know how you are getting on as this problem sounds pretty weird. If you are still having problems you can PM me with a link to your project and I will try to look at it this week to see if I can reproduce. cheers, N
https://developer.vuforia.com/forum/ios/x-code-qcarunityplayerh-error
CC-MAIN-2020-29
refinedweb
153
64.37
23365/why-django-modeltranslation-too-many-feilds I want to translate the name field in the django application (1.11) using django-modeltranslation. I want to translate to en and fr, but in the admin panel I get 3 fields instead of two: name, name_en, name_fr. models.py class Country(models.Model): name = models.CharField(max_length=100) code = models.SlugField(max_length=20, default='') def __str__(self): return self.name admin.py class CountryAdmin(admin.ModelAdmin): list_display = ('name_en',) translation.py from events.models import Country class CountryTranslationOptions(TranslationOptions): fields = ('name',) translator.register(Country, CountryTranslationOptions) You can use the below link to refer Hello @kartik, If you still need to server ...READ MORE Hello @Alisha , Do print(func(x)) and find out what's ...READ MORE 950down voteaccepted It's because any iterable can be ...READ MORE This is because join is a "string" ...READ MORE To install Django, you can simply open ...READ MORE Try to install an older version i.e., ...READ MORE ALLOWED_HOSTS as in docs is quite self ...READ MORE Go to your project directory cd project cd project ALLOWED_HOSTS ...READ MORE Let me give some information on them: quit ...READ MORE Well, it sounds like openpyxl is not ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/23365/why-django-modeltranslation-too-many-feilds
CC-MAIN-2020-50
refinedweb
210
63.25
tag:blogger.com,1999:blog-8712770457197348465.post6232432799988112967..comments2015-06-30T00:20:33.772-07:00Comments on Javarevisited: Inner class and nested Static Class in Java with ExampleJavin Paul Thanks, does the sidebar with topics ar...@Anonymous Thanks, does the sidebar with topics are useful? there is also relevant articles at bottom. Javin Paul articles are very good for reference, special...your articles are very good for reference, specially for experienced professionals. only feature that is missing is easier navigation to relevant topics.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-76744164398990614692014-06-05T00:14:42.196-07:002014-06-05T00:14:42.196-07:00@Nithya : we don't need to create obj via oute...@Nithya : we don't need to create obj via outer class,we can even do,<br /> inner cl = new inner(); <br /> cl.goSureshbabu, Nice article. Can you please provide inform...Hi,<br /><br />Nice article. <br /><br />Can you please provide information about <br /><br />- what and how the nested classes can access members of the enclosing class.<br /><br />Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-64527762063765207542014-04-17T01:01:30.496-07:002014-04-17T01:01:30.496-07:00@Nithya : we need to create obj since go method is...@Nithya : we need to create obj since go method is not static .To access non static methods we need to create obj .If go method become static then no need to create obj access them by class nameAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-56766667735096137672013-04-25T23:16:39.528-07:002013-04-25T23:16:39.528-07:00public class Static_class { static class...public class Static_class {<br /> <br /> static class inner()<br /> {<br /> void go()<br /> {<br /> System.out.println("Hello");<br /> }<br /> }<br />public static void main(String s[])<br />{<br /> Static_class.inner cl=new Static_class.inner();<br /> cl.go();<br />}<br />}<br /><br />in this class i create obj for static innerNithya S article. The one question I never seem to fin...Nice article. The one question I never seem to find a good ansewr to is "why using nested static classes", and you answered it nicely and simply in the section "What is nested static class in Java". Mid-skilled Java programernoreply@blogger.com
http://javarevisited.blogspot.com/feeds/6232432799988112967/comments/default
CC-MAIN-2015-27
refinedweb
379
52.36
Introduction. What is Redis and why use it? Redis (REmote DIctionary Server), is an in-memory data structure store that can be utilized as a database, cache, or a message broker. Data is stored in Redis in the form of key-values where the keys are used to locate and extract the data stored on the Redis instance. Normal databases store data to disk, which brings in the extra cost, in terms of time and hardware resources. Redis avoids this by storing all the data in memory, which makes the data readily available and increases the speed of data access and manipulation, as compared to normal databases. This is the reason why Redis is known for its exceptional high-performance capability. Redis allows us to store data in multiple high-level data structures including strings, hashes, lists, sets, and sorted sets. This gives us more flexibility on the type and amount of information we can store on a Redis data store. Having been written in ANSI C, Redis is lightweight and without external dependencies. It is also quite friendly to developers since it supports most high-level languages such as Python, JavaScript, Java, C/C++, and PHP. When should you use Redis? The common use cases of Redis include: - Caching: Given its speed over traditional databases, in terms of read and write operations, Redis has become an ideal solution for temporarily storing data in a cache to accelerate data access in the future. - Message Queueing: With the capability of implementing the Publish/Subscribe messaging paradigm, Redis has become a message broker for message queueing systems. - Data storage: Redis can be used to store key-value data as a NoSQL database. Companies such as Twitter, Pinterest, Github, Snapchat, and StackOverflow all utilize Redis to store and make data highly available for their users. For instance, Twitter stores the most recent incoming tweets for a user on Redis to speed up the delivery of the tweets to client applications. Pinterest uses Redis to store a list of users and boards a user follows, a list of a user's followers, and a list of people who follow your boards, among other lists to enhance the experience on the platform. Installing Redis To further explore Redis, we need to download and install the Redis server using the instructions from the official webpage. Redis is also available as a Docker image on Docker Hub. It also ships with a Redis-CLI tool that we can use to interact with and manipulate data in our Redis server. Redis is also available for installation via Homebrew (for MacOS) and via the default apt repository for Debian Linux and its variants, such as Ubuntu. To install Redis on MacOS, simply run: $ brew install redis On Debian Linux: $ sudo apt-get install redis-server To verify our Redis installation, type the redis-cli command, then type ping on the prompt that comes up: $ redis-cli -v redis-cli 5.0.6 $ redis-cli 127.0.0.1:6379> ping PONG 127.0.0.1:6379> We can see that our Redis server is ready with the reply - PONG. Redis Commands Redis, through Redis-CLI, provides some handy commands that we can use to interact with the Redis server and manipulate the data stored there. By default, Redis servers run on the port 6379 and this will be visible on our prompt. The commands available within the Redis-CLI prompt include: SET: This command is used to set a key and its value, with additional optional parameters to specify the expiration of the key-value entry. Let's set a key hellowith the value of worldwith an expiry of 10 seconds: 127.0.0.1:6379> SET hello "world" EX 10 OK GET: This command is used to get the value associated with a key. In case the key-value entry has surpassed its expiration period, nilwill be returned: 127.0.0.1:6379> GET hello “world” # After expiry 127.0.0.1:6379> GET hello (nil) DELETE: This command deletes a key and the associated value: 127.0.0.1:6379> DEL hello (integer) 1 TTL: When a key is set with an expiry, this command can be used to view how much time is left: 127.0.0.1:6379> SET foo "bar" EX 100 # 100 is the number of seconds OK 127.0.0.1:6379> TTL foo (integer) 97 # Number of seconds remaining till expiry 127.0.0.1:6379> TTL foo (integer) 95 127.0.0.1:6379> TTL foo (integer) 93 PERSIST: If we change our mind about a key's expiry, we can use this command to remove the expiry period: 127.0.0.1:6379> PERSIST foo (integer) 1 127.0.0.1:6379> TTL foo (integer) -1 127.0.0.1:6379> GET foo "bar" RENAME: This command is used to rename the keys in our Redis server: 127.0.0.1:6379> RENAME foo foo2 OK 127.0.0.1:6379> GET foo (nil) 127.0.0.1:6379> GET foo2 "bar" FLUSHALL: This command is used to purge all the key-value entries we have set in our current session: 127.0.0.1:6379> RENAME foo foo2 OK 127.0.0.1:6379> GET foo (nil) 127.0.0.1:6379> GET foo2 (nil) 127.0.0.1:6379> GET hello (nil) More information on these and other Redis commands can be found on the official website. Redis with Django To demonstrate how to integrate Redis in a web application, we will build an API using Django and Django REST that can receive a key-value pair and store it in our Redis server. Our API will also be able to retrieve values for given keys, retrieve all key-value pairs stored and also delete a key-value entry. Let us start by creating a folder to house our project: $ mkdir redis_demo && cd $_ Then, let's create a virtual environment and activate it: $ virtualenv --python=python3 env --no-site-packages $ source env/bin/activate And finaly, let's install the needed libraries: $ pip install django djangorestframework redis Our application's API will receive requests and interact with our Redis server using the Redis-py library. Let's now create the app: # Create the project $ django-admin startproject django_redis_demo $ cd django_redis_demo # Create the app $ django-admin startapp api # Migrate $ python manage.py migrate To verify that our Django setup was successful, we start the server: $ python manage.py runserver When we navigate to http:127.0.0.1:8000, we are welcomed by: The next step is to add our api application and Django REST to our project by updating the INSTALLED_APPS list found in django_redis_demo/settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Add these two 'rest_framework', 'api', ] Redis-py needs a running instance of Redis to interact with. We will have to configure this in our django_redis_demo/settings.py by adding: REDIS_HOST = 'localhost' REDIS_PORT = 6379 With this setting, we can also use a Redis instance running inside a Docker container or a remote Redis instance, even though we might need to provide authentication details for that case. For now, we will use our local Redis instance that we set up. Next, we are going to create the route that will be used to access our API and link it to our main Django application. First, we will create an empty api/urls.py file, then create our path in the django_redis_demo/urls.py: # Modify this import from django.urls import path, include urlpatterns = [ ... # Add this entry path('api/', include('api.urls')), ] All requests coming in through the api/ endpoint will be now handled by our api application. What's missing now are the views that will handle the requests. Our views will be simple function-based views that will allow us to interact with the Redis server. First, let us create the URLs that we will interact with in our api/urls.py: from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from .views import manage_items, manage_item urlpatterns = { path('', manage_items, name="items"), path('<slug:key>', manage_item, name="single_item") } urlpatterns = format_suffix_patterns(urlpatterns) The first path will allow us to create entries and view all entries, while the second path will give us granular management of single entries. We will have two function-based views: manage_items() and manage_item() that will handle the requests and interact with our Redis instance. They will both reside in our api/views.py file. To better explain the code, we'll break it down into more concise chunks. If you want to see the full code, there's a link to the GitHub repo with the source code in the conclusion of this article. We'll start off by importing the needed libraries and connecting to our Redis instance: import json from django.conf import settings import redis from rest_framework.decorators import api_view from rest_framework import status from rest_framework.response import Response # Connect to our Redis instance redis_instance = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=0) Here, we create our connection object by passing the Redis host and port as earlier configured in our django_redis_demo/settings.py. Then, we create our first view manage_items() that will be used to retrieve all the items currently set in our running Redis instance. This view will also allow us to create new entries in our Redis instance by passing a JSON object: @api_view(['GET', 'POST']) def manage_items(request, *args, **kwargs): if request.method == 'GET': items = {} count = 0 for key in redis_instance.keys("*"): items[key.decode("utf-8")] = redis_instance.get(key) count += 1 response = { 'count': count, 'msg': f"Found {count} items.", 'items': items } return Response(response, status=200) elif request.method == 'POST': item = json.loads(request.body) key = list(item.keys())[0] value = item[key] redis_instance.set(key, value) response = { 'msg': f"{key} successfully set to {value}" } return Response(response, 201) Then, let's define manage_item(): @api_view(['GET', 'PUT', 'DELETE']) def manage_item(request, *args, **kwargs): if request.method == 'GET': if kwargs['key']: value = redis_instance.get(kwargs['key']) if value: response = { 'key': kwargs['key'], 'value': value, 'msg': 'success' } return Response(response, status=200) else: response = { 'key': kwargs['key'], 'value': None, 'msg': 'Not found' } return Response(response, status=404) elif request.method == 'PUT': if kwargs['key']: request_data = json.loads(request.body) new_value = request_data['new_value'] value = redis_instance.get(kwargs['key']) if value: redis_instance.set(kwargs['key'], new_value) response = { 'key': kwargs['key'], 'value': value, 'msg': f"Successfully updated {kwargs['key']}" } return Response(response, status=200) else: response = { 'key': kwargs['key'], 'value': None, 'msg': 'Not found' } return Response(response, status=404) elif request.method == 'DELETE': if kwargs['key']: result = redis_instance.delete(kwargs['key']) if result == 1: response = { 'msg': f"{kwargs['key']} successfully deleted" } return Response(response, status=404) else: response = { 'key': kwargs['key'], 'value': None, 'msg': 'Not found' } return Response(response, status=404) manage_item() gives us access to individual entries in our Redis instance. This view requires the caller to pass the key of the item we need in the URL. This key is then used to locate the value as stored in our instance. By using the PUT HTTP method and passing the new value of a key, we can update the value of the key. Through the DELETE method, we can delete a key-value pair from our Redis instance. To see our API in action, we will use Postman. But first, let us create an entry or two by using the redis-cli tool: $ redis-cli 127.0.0.1:6379> SET HELLO "WORLD" OK 127.0.0.1:6379> SET REDIS "DEMO" OK After setting the data, let us send a GET request to localhost:8000/api/items: Our API is able to fetch all the key-value pairs in our current Redis instance. Let us now send a POST request with the following payload to the same URL: { "mighty": "mug" } Let us send another GET request to the same endpoint: We can see that the key we created using our API is saved on our Redis instance. We can verify it's existence by using the CLI tool. Let us now test the second endpoint that returns the value of a single key by sending a GET request to: That went well. Let us now update the value associated to the HELLO key by sending the following JSON via a PUT request to the same endpoint: { "new_value": "stackabuse.com" } When we fetch the key HELLO again: Our value has been updated successfully. The final bit that is remaining is the deletion of keys, so let us go ahead and send a DELETE request to to delete the key we have just updated. When we try to access the same item after deleting it: We are informed that our key has been deleted. Our Django API has successfully interfaced with our Redis instance using the Redis-py library. Conclusion Redis is a powerful and fast data storage option, that if used in the right situation can bring a lot of benefits. It does not have a steep learning curve so it is easy to pick up and it also comes with a handy CLI tool to help us interact with it through simple and intuitive commands. We have been able to integrate our Django API with a locally running Redis instance seamlessly which is a testament to its ease of use with common high-level programming languages. The source code for the script in this project can be found here on GitHub.
https://stackabuse.com/working-with-redis-in-python-with-django/
CC-MAIN-2020-29
refinedweb
2,261
63.09
Installing Microsoft Visual Studio 2010 Service Pack 1 In Microsoft Visual Web Developer 2010 ExpressMar 11, 2011 Can I install Microsoft Visual Studio 2010 Service Pack 1 in Microsoft Visual Web Developer 2010 Express?View 1 Replies Can I install Microsoft Visual Studio 2010 Service Pack 1 in Microsoft Visual Web Developer 2010 Express?View 1 Replies In Microsoft Visual Web Developer 2010 Express, Edit->Quick Find mean item, the "Quick Find" item, everytime I have to select "Find In Files" again, how can I set "Find In Files" as default?View 3 Replies I have Download "VWD_RV_Addon_enu" which is reportviewer setup when I double click it displays Below information This add-on requires Microsoft Visual Web Developer 2008 Express Edition Service Pack 1. Upgrade to Service Pack 1 and try again. where can I get Service Pack 1.? I'm a new.View 2 Replies WebPI isn't able to install VWD 2010 Express on my system. I've previously un-installed the 2010 beta. Never had this problem before when upgrading VWD Express.View 8 Replies Can Microsoft Visual Studio 2010 Express use only 30 days? After I click Help ->About Microsoft Visual Studio 2010 Express menu, I find "Only 27 days remaining"!View 1 Replies My instructions for creating a new web service with VWD 2010 Express call for using the installed template, "AST.NET Web Service". But this template is not listed. I would like to create a simple web service in visual basic, place it in IIS 7 on my desktop, and then consume it probably using a proxy class. Is there another way to create a new web service in VWD 2010 Express? Microsoft Visual Web Developer 2008 Express Edition not possible to open Visual Studio? [Code].... I currently doing a website that require to have a report for higher management, but i cant seem to have the crystal report tool in my MS Visual Web Developer.View 2 Replies How to do sum 2 differences fields as a new column in Subtotal ? I know to do in Microsoft Access and that is easier.View 2 Replies We have developed apllication in Microsoft VS 2008 and when we opening this same application with Microsoft VS 2010. Then it's asking to convert. So can anybody tell me what it is converting exactly. Means it's open application in Microsoft VS 2010 and running properly also. But i am understanding whats happning while converting. have a 'Connection.cs' file in the App_Code folder of Microsoft Visual Web Developer 2010, but it alerts me of an error: The type or namespace name 'Connection' could not be found (are you missing a using directive or an assembly reference?) ('Connection' is the name of a class in the Connection.cs file) [Code]....". I'm totally new to ASP.NET ( as a VC++ 6.0 engineer ), I have just downloaded the express edition of 2010 web developer and cannot find for the life of me the correct project template to create an ASP.NET webservice.. in 2008 it appears there is an option for this .. however I cannot find it in 2010..View 3 Replies How do I display the Toolbox? I've looked under every menu item and just don't see it.View 1 RepliesWhen advanced properties and modified some of the information because the ControlID is a Text field and the Database Column is a BigInt.My select statement looks like this: [Code].... What I don't know is how to get the parameter into the select statement.I've tried: [Code].... I use Firefox to browse the web, but I'd like Force Visual Web Developer 2010 Express to exclusively use Internet Explorer when I run my web apps (by pressing F5). is there a way to set this?View? My existing system has Visual Studio 2008 and Visual Web Developer 2010 Express. But Microsoft web installer for Webmatrix has made Wematrix Launch ribbon menu pointing to Visual Studio 2008. How could I make Webmatrix point to Visual Web Express 2010. To make use of IntelliSense and the debugger, I have to manually launch Visual Web Developer 2010 Express.View 8 Replies What is the different between the vs 2010 Web Developer Express and the full version of 2010?With the vs 2010 Web Developer Express will I be able to use all types of databases (MSSQL, MySQL, Access, ect) and enitity frame work?View 2 Replies One thing I do like about visual studio is the autoindent feature in the code behind where you can essentially close off the bracket of a loop or method or class and it'll automatically indent everything to make it consistent looking.View 1 Replies I am using ASP.NET MVC and want to have Unit Test functionality integrated within Visual Web Developer 2010 Express (or Visual Studio LightSwitch). Is it possible and if so, what is the recommended/best way to get it?View 1 Replies Can i use web developer express 2010 to deploy applications or is it still in Beta?View 1 Replies
https://asp.net.bigresource.com/-installing-Microsoft-Visual-Studio-2010-Service-Pack-1-in-Microsoft-Visual-Web-Developer-2010-Express-585TFOmfP.html
CC-MAIN-2021-10
refinedweb
848
65.01
Bundling GlassFish v3 Prelude - XWiki and the GlassFish Embedded (Part 2) By alexismp on oct. 03, 2008 Update: things have changed quite bit since I wrote this for v3 Prelude (now v3 Final is the way to go). Please check this link for up-to-date info on GlassFish Embedded. In Part I, I covered a first technique to bundle the XWiki application with GlassFish v3 Prelude. The distribution and packaging discussed included a "traditional" auto-deployment of a web application (WAR) in a lightweight application server (GlassFish v3 Prelude). XWiki is a non-trivial application and I felt it would be a great test for the GlassFish Embedded API. This enables GlassFish to run in-process as explained in the rest of this entry. While the embedded API can be very useful for testing (it can now already be used with Maven and Grails for instance), the goal here is to produce a self-container Java SE application which contains GlassFish Embedded, the XWiki WAR archive and some glue code to start glassfish and deploy the applicationPutting the pieces together GlassFish Embedded does not use OSGi but rather a more traditional class-loader hierarchy so I had to work around a "classical" JAR precedence issue: • removed the log4j jar from the XWiki application and make it available as a library (appropriate Class-Path: entry in the manifest of the overall JAR). • used <class-loader in sun-web.xml to avoid further library conflicts (documented here) Using the GlassFish Embedded API is pretty straightforward : import org.glassfish.embed.App; import org.glassfish.embed.AppServer; public class XWikiOnGlassFish { public static void main(String[] args) throws IOException { AppServer glassfish = new AppServer(8080); App app = glassfish.deploy( new File("/path/to/xwiki-enterprise-web-1.5.2.war") ); } }Results The application weights 20 MB for the full GFv3 Prelude embedded (see other distributions here) + 4Ko "glue" application + 40MB XWiki. The startup time is as follows: with an additional 12 seconds to load the XWiki web app. The memory consumed (used heap as reported by VisualVM) is 15 MB right after the welcome page is displayed and 35 MB after exercising the application a bit. I'll leave the packaging of this Java SE application (see what the OpenSSO guys did) using Java Web Start as an exercice to the reader. More coverage of the GlassFish Embedded API (including the ScatteredWar API, and the Maven integration) can be found here. Note that a few API changes happened since that post.
https://blogs.oracle.com/alexismp/tags/api
CC-MAIN-2015-18
refinedweb
416
50.87
Creating a Python GUI using Tkinter Tkinter is the native Python GUI framework that comes bundled with the standard Python distribution. There are numerous other Python GUI frameworks. However, Tkinter is the only one that comes bundled by default. Tkinter has some advantages over other Python GUI frameworks. It is stable and offers cross-platform support. This enables developers to quickly develop python applications using Tkinter that will work on Windows, macOS, and Linux. Another benefit is that the visual elements created by Tkinter are rendered using the operating system’s native elements. This ensures that the application is rendered as though it belongs to the platform where it is running. Tkinter is not without its flaws. Python GUIs built using Tkinter appear outdated in comparison to other more modern GUIs. If you’re looking to build attractive applications with a modern look, then Tkinter may not be the best option for you. On the other hand, Tkinter is lightweight and simple to use. It requires no installation and is less of a headache to run as compared to other GUI frameworks. These properties make Tkinter a solid option for when a robust, cross-platform supporting application is required without worrying about modern aesthetics. Because of its low aesthetic appeal and easy of use, Tkinter is often used as a learning tool. In this tutorial, you will learn how to build a Python GUI using the Tkinter library. Table of Contents You can skip to a specific section of this Python GUI tutorial using the table of contents below: - Python GUI - A Basic Tkinter Window - Python GUI - Tkinter Widgets - Python GUI - Label in Tkinter - Python GUI - Entry in Tkinter - Python GUI - Text in Tkinter - Python GUI - Create Buttons in Tkinter - Python GUI - Working With Events - Final Thoughts By the end of this tutorial, you will have mastered Tkinter and will be able to efficiently use and position its widgets. You can test your skills by trying to build your own calculator using Tkinter. Let’s get down to it and start with creating an empty window. Python GUI - A Basic Tkinter Window Every Tkinter application starts with a window. More broadly, every graphical user interface starts with a blank window. Windows are containers that contain all of the GUI widgets. These widgets are also known as GUI elements and include buttons, text boxes, and labels. Creating a window is simple. Just create a Python file and copy the following code in it. The code is explained ahead and creates an empty Tkinter window. import tkinter as tk window = tk.Tk() window.mainloop() The first line of the code imports the tkinter module that comes integrated with the default version of Python installation. It is convention to import Tkinter under the alias tk. In the second line, we create an instance of tkinter and assigning it to the variable window. If you don’t include the window.mainloop() at the end of the Python script then nothing will appear. The mainloop() method starts the Tkinter event loop, which tells the application to listen for events like button clicks, key presses and closing of windows. Run the code and you’ll get an output that looks like this: Tkinters windows are styled differently on different operating systems. The above given output is generated when the Tkinter window is generated on Windows 10. It is important to note that you should not name the python file tkinter.py as this will clash with the Tkinter module that you are trying to import. You can read more about this issue here. Python GUI - Tkinter Widgets Creating an empty window is not very usefu. You need widgets to add some purpose to the window. Some of the main widgets supported by Tkiner are: - Entry: An input type that accepts a single line of text - Text: An input type that accepts multiple line of text - Button: A button input that has a label and a click event - Label: Used to display text in the window In the upcoming section, the functionality of each widget will be highlighted one by one. Note that these are just some of the main widgets of Tkinter. There are many more widgets that you can check out here, and some more advanced widgets here. Moving on, let’s see how a label works in Tkinter. Python GUI - Label in Tkinter Label is one of the important widgets of Tkinter. It is used for displaying static text on your Tkinter application. The label text is uneditable and is present for display purposes only. Adding a label is pretty simple. You can see an example of how to create a Tkinter label below: import tkinter as tk window = tk.Tk() lbl_label = tk.Label(text="Hello World!") lbl_label.pack() window.mainloop() Running this code will provide the following output: For reasons that I'll explain in a moment, this output is far from idea. Let's explain this code first. The variable lbl_label initializes a Tkinter label variable and is attached to the window by calling the pack() method. You can also change the background and text color. The height and the width of the label can be adjusted as well. To change the colors and configure the height and width, simply update the code as follows: lbl_label = tk.Label( text="Hello World!", background="green", foreground="red", width="10", height="10" ) Running the code will yield the following output: Fig 3: Configuring Tkinter Label Widget You may notice that the label box is not square despite the fact that the width and height have been set equal. This is because the length is measured by text units. The horizontal length is measured by the width of 0 (number zero) in the default system font and similarly, the vertical text unit length is determined by the height of the character 0. Next, let's explore how to accept user input in a Tkinter application. Python GUI - Entry Widgets in Tkinter The entry widget allows you to accept user input from your Tkinter application. The user input can be a name, an email address or any other information you'd like. You can create and configure an entry widget just like a label widget, as shown in the following code: import tkinter as tk window = tk.Tk() lbl_label = tk.Label( text="Hello World!", background="green", foreground="red", width="20", height="2" ) ent_entry = tk.Entry( bg="black", fg="white", width="20", ) lbl_label.pack() ent_entry.pack() window.mainloop() Running the code will yield the following output: You can read the input inserted by the user by using the get() method. A practical example of this method will be shown in the button section later in this Python GUI tutorial. Python GUI - Text in Tkinter The Tkinter entry widget is useful if you’re looking for a single line of input. If a response requires multiple lines then you can use the text widget of Tkinter. It supports multiple lines, where each line is separated by a newline character ‘\n’. You can create a text widget by adding the following code block in the code shown in the entry widget section: txt_text = tk.Text() txt_text.pack() Running the code after adding the code above will yield the following output: Python GUI - Create Buttons in Tkinter If you want your Tkinter application to serve any meaningful purpose, you will need to add buttons that perform some operation when they are clicked. Adding a button is pretty straightforward and similar to how we added the other widgets. You can add a simple button by adding the following code block: btn_main = tk.Button( master=window, text="Main Button" ) btn_main.pack() Running the code will yield the following output: Now that there’s a button, we can do some serious damage! The button generates an event that can be used for changing elements or performing other functionality. Python GUI - Working With Events For the purpose of this tutorial, functions will be kept simple. So, whenever the Main Button is clicked, whatever the user inputs in the entry widget will be pasted in the text and label widgets. The code is edited as follows to get achieve this functionality: import tkinter as tk def copyText(text): if(str(text)): textVar.set(text) txt_text.insert(tk.END, text) window = tk.Tk() textVar = tk.StringVar() textVar.set("Hello World!") lbl_label = tk.Label( textvariable=textVar, background="green", foreground="red", width="30", height="2" ) ent_entry = tk.Entry( bg="black", fg="white", width="30", ) txt_text = tk.Text() btn_main = tk.Button( master=window, text="Main Button", command = lambda: copyText(ent_entry.get()) ) lbl_label.pack() ent_entry.pack() txt_text.pack() btn_main.pack() window.mainloop() In this code, the copyText() method has been introduced. This method copies the text of the entry widget to the label and the text widgets. To change the text of the label, we introduced a stringVar and instead of setting the text of label, we set the textVariable equal to stringVar. Using the command statement, we set the button to call the copyText method whenever it is clicked. The entry widget’s text is passed to the method. In the copyText method, the first step is to check whether the entry widget is an empty string. Python makes it simple to do this as an empty string is considered a boolean false value in Python. After checking for the empty string, the value of the entry widget is copied to the stringVar and the text widget. The text has been inserted at the end of the text widget by setting its position as tk.END. It can be set to a particular index as well by replacing it with “1.0”, where ‘1’ is the line number and ‘0’ is the character. Executing the code will yield the following output: Final Thoughts Working with Python is fun and simple. It allows you to build cool applications pretty easily. Learning Tkinter allows you to build your first Python GUI. It’s simple, supports cross-platform compatibility and you can build many different applications with it. This tutorial is just a basic guide to Tkinter. There is much more available for you to learn about Tkinter. Learning about geometry managers should be your next step to improve your Tkinter skills. After working through this tutorial, you should have a basic understanding of Tkinter and how to use buttons to call functions, paving way for further exploration.
https://nickmccullum.com/python-gui-tkinter/
CC-MAIN-2021-04
refinedweb
1,735
55.95
63099/not-able-to-get-output-in-spark-streaming Hi everyone, I tried to count individual words using spark streaming. Here I am using Netcat for providing input using socket concept.But I am not able to get the output, though it is not showing any error. Can someone tell me the error? Thank You Seems like master and worker are not ...READ MORE Hi! I found 2 links on github where ...READ MORE You lose the files because by default, ...READ MORE you can access task information using TaskContext: import org.apache.spark.TaskContext sc.parallelize(Seq[Int](), ...READ MORE You can get the configuration details through ...READ MORE As parquet is a column based storage ...READ MORE Instead of spliting on '\n'. You should ...READ MORE Though Spark and Hadoop were the frameworks designed ...READ MORE Hi@akhtar, Dstreams are the basic abstraction that is ...READ MORE Hi@akhtar, Yes, Spark streaming uses checkpoint. Checkpoint is ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/63099/not-able-to-get-output-in-spark-streaming
CC-MAIN-2020-10
refinedweb
167
70.39
This: The above lists all the parts of this guide except for individual reader comments. A single long page with all of them excluding reader comments is available for printing (but has dysfunctional links and is not in correct html).). You . There are a few conventions which will make for a more usable, less confusing, web. As a server administrator, or webmaster as they are known (the term having been coined on this page, below) you should make sure this applies to your data. This Guide gives more ideas for all information providers. See especially: Your server administrator needs these things set up once per server:. You should put a "pass" line into your daemon rule file to map the document name "/" onto such a document. As well as a summary of what is available at your host, pointers to related hosts are a good idea. The welcome page for a server is often now called a "home" page because it is a good choice for a client to use as a home (default) page. The term "home" page means the default place to start your browser. Don't be confused by this, though. There are two separate concepts. The welcome page will be welcoming those new to your server who want an overview of what it contains. It will serve a similar purpose to your home page, but it differs in the audience it addresses. Often, it only confuses things to have to, so people within the organization use the welcome page as their home. This at least ensures that they are aware of the public view of the organization. I don't do this myself, as I have many personal things on my home page, which I don't want on the organization's welcome page nor my own "welcome" page, my Bio. A welcome page may have explanations about what your server is all about which would be a waste of space on a home page for your local users. So you may want to make a separate home page for local users. If you have a serious server then it may last longer than the machine on which it runs. Ask your internet domain name manager to make an alias for it so that you can refer to it, instead of as "mysun12.dom.edu" as "". This will mean that when you change machines, you move the alias, and people's links to your data will still work. In the future [3/94] clients come out of the box configured to look for a local "www" machine, to use its welcome page as "home" if no other default is specified. This means that anyone starting such a client within your domain will get a relevant place to start. You should make a mail alias "webmaster" on the server machine so that people who have problems with your server can mail you about it easily. This is similar to the "postmaster" alias for people who have mail problems with your machine. The server administrator (the one with the root password) in principle has the power to turn the thing on or off, and control what happens. However, it is wise to have clearly delegated responsibility for separate areas of documentation. Maybe the server administrator has no responsibility at all for the actual content of the data, in which case he or she should just keep the machine running properly. The web has spread from the grass roots, without a central authority, and this has worked very well. This has been due in part to the creativity of information providers, and the freedom they have to express their information as directly and vividly as they can. Readers appreciate the variety this gives. However, in a large web they also enjoy a certain consistency. If you are a person responsible for managing the information provided by your organization, you have to balance the advantages of a "house style" with the advantages of giving each group or author free rein. If you end up with decisions in this area, it is as well to write them down (not to mention put them on the web). What ownes. They why are there so many dangling links in the world? Part of it is just lack of forethought. Here are some reasons you hear out there: Do you really fel that the old URIs cannot be kept running? If so, yu chose them very badly. Think of your new ones so that you will be able to keep then running after the next redesign. That I can sympathise with - the W3C went though a period like that, when we had to carefully sift archival material for confidentiality before making the archives public. The solution is for betwene the URI of an object and where a file which represenst it actually is in a file system. Think of the URI space as an abtsract space, perfectly organized. Then, make a mapping onto whatever reality you actually use to. Then, tell your server. You can eaven write bits of your server. John doesn't maintain that file any more, Jane does. Whatever was that URI doing with John's name in it? It was in his directory? I see. There is a crzy notion that pages produced by scripts have to be located in a "cgibin" or "cgi" area. This is exposing the mecahnism of how you run your server. You change the meachanism (even keeping the content the same ) and whoops - all your URIs change. For example, take the The National Science foundation: NSF Online Documents the main page for starting to look for documents, is clearly not going to be something to trust to being there in a few years. "cgi-bin" and "oldbrowser" and ".pl" all point to bits of how-we-do-it-now. By contrsast, thenold 1998 document classification scheme is in progress. Though in 2098 the document numbers might look different, I can imagine this URI still be ing valid, and the NSF or whatever carries on the archive not being at all embarassed about it. This is the probably one of the worst spin-offs of the URN discussions. Some seem to think that because there is research about namespaces which will be less choses, or just a string you chose. This looks very like an HTTP URI. In other words, if you think your organization will be capable of craeting URNs which will last, then prove it by doing it now and using them for your HTTP URIs. There is nothing about HTTP which makes your links URI. It is your organization. Make yourself a databse of document URN to current file, and let the web server use that to actually retrieve files. If you have got to this point, then unless you have the time and money and contacts to get some software design done, then you might claim the next excuse: Now here is one I can sympathise with. I agree entirely. What you need to do is to have the web server look up a persistent URI in an instant and return the file, whereveer you current crazy filesystem has it stored away at the moment. You'de documeny in the URI space without changing the URI. Too bad. But we'll get there. At W3C we are playing with "Jigedit" functionality (jigsaw server latter which us good to start a URI with. If a document is in any way dated, even though it will be if interest for generations, then the date is a good starter. The only exception is a page which is deliberately a "latest" page for for example the whole organization or a large part of it. is the latest "Money daily" column in "Money" magazine. The main reason for not need ing the date in this URI noone is likely to want to link to that for link which will outlast the magazine - if you want to link to the content, you would link to it where it appears seperately im the archives as (Looks good. Assumes that "money" will mean the same thing thoughout the life of pathfinder.com. There is a duplication of "98" and an ".html" you don't need but otherwise this looks a strong URI). Everything! After the creation date, putting any information in the name is asking for trouble one way or another. So a better example from our site is simply a report of the minutes of a meesting of W3C chairpeople. Remember that this applies not only to the "path" part of a URI but to the server name. If you have seperate servers for some if your stuff, remember that that division will be impossible to change without destroying many many links. Some classic "look what software we are using today" domain names are "cgi.pathfinder.com", "secure", "lists.w3.org". They are made to make administartion ain't soap, will you want to be referred to as "soap.com" even when you have switched your product line to something else. (With apologies to whoever owns soap.com at the moment). Keeping URIs so that they will still be around in a 2, 20 or 200 years is clearly not as simple as it sounds. However, all over the Web, webmasters are making decisions which will make it really difficult for themselves in the future. Often, this is becasue thy are using tools whose task is seen as to present the best site in the moment, and noone ahs eveluated what will happen to the links when things change. The message here is, however, that many many things can change and your URIs can and should stay the same. They only can if you think about how you design them. If: Remember. Here. The: Here are some reasons for leaving it where it is: This section of the style guide deals with the layout of text within a "document", the unit of retrieval of information on the web. To be completed. You should try to: Make) Some information is definitive, some is hastily put together and incomplete. Both are useful to readers, so do not be shy to put information up which is incomplete or out of date -- it may be the best there is. However, do remember to state what the status is. When was it last updated? Is it. Of] The title of a document is specified by the TITLE element. The TITLE element should occur in the HEAD of the document. There may only be one title in any document. It should identify the content of the document in a fairly wide context. The title is not part of the text of the document, but is a property of the whole document.> The unwise..) This. The temptation is to strip out these instructions and leave a link like: There is now WWW accessto our large FTP archive which was previously only available by FTP, NFS and mail. This collection includes much public domain software and text whose copyright has expired.The web is read by people who don't need or, often, want to know about FTP and NFS - or even WWW! So the following is better: Our archive includes much public domain software and text whose copyright has expired.Keeping on the subject of discourse rather than the mechanisms and protocols keeps the text shorter, which means people are more likely to read it. Even when you are working within the web metaphor, use links, don't talk about them. For example You can read more about this in the tutorial which is linked to the home pageobviously would be be better as The tutorial has more about this.Another common one is The tutorial contains sections on mowing, sharpening the mower, and buying a mower.Give the reader a break, and let him or her jump straight there! The tutorial contains sections on mowing, sharpening the mower, and buying a mower..) (Part of the Style ... ) Thanks to my brother Michael for descibing "how and why" trees he uses in his team-building training. Acceptable Content Due Credit Acceptable content Acceptable language copyright or other intellectual property right, and material inciting to ... )© 1995 TimBL Thanks to my brother Michael for descibing "how and why" trees he uses in his team-building training.
http://www.w3.org/Provider/Style/All.html
CC-MAIN-2018-30
refinedweb
2,057
70.84
just write #include <stdlib.h> in your program hira write > at the end of line 1 B FOR FAZ????????????? plz tell me assignment file ma kis kis cheez ki snapshot aye gi koi btai assignment file main kia kia cheez upload karni hy. any one upload snapshot plzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz. i have done my assignment in window 7 it correct 100% with no error and i have also sumbit it... Thanks Allah... plz tell me kitny snapshot assignment ma paste karni ha ........ or kon kon si below are given 1: your written borlandc program 2: compile your program and take snapshot 3: run your program and give the required value and take snapshot 4: Load your program through CMD command and load LBA.exe file and give the reaquired value and take snapshot. 5: Load LBA.txt file in dos mode 6: then use debug command 7:-d 0000:3f00 and press enter and take snapsho 8: -a enter 9: -t enter that's it you have to take sanpshot every command and paste it MS Word and write bereief description... Shamoon assignment me ks ks k snap shota lagany hai plzz ye bta daen © 2020 Created by +M.Tariq Malik. Promote Us | Report an Issue | Privacy Policy | Terms of Service
https://vustudents.ning.com/group/cs609systemprogramming/forum/topics/disscus-solution-of-assignment-no-03-of-system-programming-cs609?commentId=3783342%3AComment%3A3940154&groupId=3783342%3AGroup%3A59533
CC-MAIN-2020-34
refinedweb
209
79.8
The Trouble with gcc’s –short-enums Flag GCC has a cool and relatively obscure optimization flag called short-enums. It is the kind of tweaky little optimization that I get excited about, but it has a dark side that bit me. What to love about short-enums Normally GCC compiles enums into a full register width value, like a 32-bit number. The default size of an enum can technically be different on different platforms, but in practice it will will be 32 bits most places. short-enums instructs GCC to use the smallest storage it can. So if your enum has all its values within 8 bits, say from 0-255 – which will be essentially all enums for most code – it will be stored in a single byte. It is the equivalent of adding attribute “packed” to all enum declarations. It is a tradeoff. Smaller storage will make your structures smaller. If you are trying to create tiny records for container classes, heaps and similar structures, it can be really appealing to cram your enums into 8-bits and fit the management of small data structures into 4 or 8 bytes. You balance this against the knowledge that on modern systems access to 8-bit addresses is slower than access to full register size addresses ( e.g. aligned 32 or 64 bit accesses on modern platforms are fastest ). With pipelining, in practice the 8-bit accesses are usually just as fast as 32, and if you have a ton of little structures the optimization is often worth it. The problem with short-enums If you use a third party library that has not been compiled with short-enums, but you include their headers, and those headers include structures that have enums, you can end up referencing structure elements at the wrong offset. This is especially the case with c libraries that usually expect you to reference structure members directly yourself (without accessors). This leads to much merriment as you try to figure out why a library that mostly seems to function correctly keeps passing you garbled structures. I got this problem when using GraphicsMagick, an image manipulation library. In their API, images are created into an Image struct: Image* image = BlobToImage( imageInfo, srcImage.getBuffer(), srcImage.getCursor(), &exception ); fprintf( stderr, "Image width: %d, height: %d\n", image->columns, image->rows ); It was surprising to me in this case that the image width and height had bad values, yet the structure works fine when passed to other GraphicsMagick functions. If I look at the definition of Image the problem is revealed: typedef struct _Image { ClassType storage_class; /* DirectClass (TrueColor) or PseudoClass (colormapped) */ ColorspaceType colorspace; /* Current image colorspace/model */ ... etc ... unsigned long columns, /* Number of image columns */ rows; /* Number of image rows */ ... more members ... } Image ClassType, and ColorspaceType among others are enums. The library will treat each one as if it 32-bit storage, but my code was treating them as if they have 8 and 16-bit storage. Adding the “short-enums” flag subtly changes the meaning of code in included header files. If your projects consist 100% of your own code, or you use third party libraries that you build yourself, short-enums is generally safe. Even if you use pre-built third party libraries, but those libraries don’t expect you to compute your own offsets into their data structures (e.g. they have accessors to all their structures) you should not have a problem. A Better Way to get the Same Effect Don’t use --short-enums. It is like using a sawed-off shotgun affecting more code than you intended. If you want short enums, add: __attribute__ ((__packed__)) to each enum that you think would benefit from a packed representation. Only in a few cases will it make a meaningful performance difference. 7 Responses You’re referring to the flag either as “short-enums” or “–short-enums”, but it probably should be “-fshort-enums” in both cases. The typography is making the double dashes a little hard to read. Traditional GCC – like you find on most linuxes accepts flags like “–short-enums” and “–no-short-enums”, as well as the “f” style flag you’re talking about: “-fshort-enums” and “-fno-short-enums”. GCC versions based on clang, like you find on Os X seem to only accept the “f” type flags for these options. The base name of the flag is “short-enums”, and then there are ways to call it with and without “no” and with “–” or “-f”, so to me it makes sense to refer to the feature by its base name. Packed produces bad layout if the structure has wholes. The best of both worlds seems to be to do this selectively when packing is actually worth it: enum myenum field:8; I think 2 things are mixed up here: data size and alignment. The packed attribute only affects alignment and I doubt whether every compiler will decide to make an enum 8-bits when it’s used. If an enum is 32-bit, the different alignment won’t make it any smaller. Alignment might affect the size of a struct that contains it, but that’s something different. A very good point that using short-enum “subtly changes the meaning of code in included header files” because of the potential difference in how storage space is recognized. If space is a valuable resource to you (i.e. embedded systems), there is kind of trick you can do to avoid enums. There is definitely an argument to made here (enums allow better debugging, ease of understanding, etc), but if you’re finding yourself in the need for short-enum, you may consider simply typedef-ing a smaller type (uint8_t) and #define-ing the options. Again, just a trick to save some space since the preproccessor will handle all those #defines, again, this does make debugging a little bit uglier. e.g. typedef uint8_t ColorType /* ColorType */ #define RED 0 #define BLUE 1 #define GREEN 2 Cool idea. Then you never have to worry about the size of the storage used changing. Replacing an enum with typedef and #define may work in some cases, but when referring to enum values through a namespace, that strategy unfortunately doesn’t work.
https://oroboro.com/short-enum/
CC-MAIN-2020-40
refinedweb
1,044
67.89
Support » Pololu P-Star User’s Guide » 10. Compiling a program with MPLAB X and MPASM This section explains how to get started programming the P-Star in assembly using MPLAB X and XC8. MPLAB X a free integrated development (IDE) from Microchip for programming their PIC microcontrollers. MPASM is an assembler that comes with MPLAB X. For most people, we recommend “developing P-Star apps with XC8”:Section 5.3, which allows a mixture of C and assembly code. This section is for advanced users who only want to use assembly. MPASM supports two types of code: absolute and relocatable. These instructions will show how to write absolute code, where the location of every instruction and variable is known ahead of time. The alternative is relocatable code, which allows multiple assembly files to be combined into one program using a linker. - Download and install the latest version of MPLAB X. - Find “MPLAB X IDE” in your Start Menu and run it. - From the File menu, select “New Project”. - On the first screen of the New Project wizard, select the “Microchip Embedded” category and then select “Standalone Project”. Click “Next”. - For the Device, type the name of the microcontroller on your P-Star, which is either “PIC18F25K50” or “PIC18F45K50”. Click “Next”. - On the “Select Tool” screen, you can select “PICkit 3” but this choice does not matter because we will not use MPLAB X to the load the program onto the board. - For the compiler, select MPASM. - For the Project Name, choose something like “p-star1”, and choose the folder you want it to be in. Click “Finish” to create the project. - In the “File” menu, select “Project Properties”. In the “MPASM (global options)” category, check the “Build in absolute mode” check box, then click “OK”. - Now we need to create the assembly source file. Locate the “Projects” pane. If the “Projects” pane is not visible, you can open it by opening the “Window” menu and selecting “Projects”. Left-click the “+” sign next to “Source Files” to expand it and verify that your project has no source files yet. Then right-click on “Source Files”, select “New”, and then select “pic_8b_simple.asm…”. If “pic_8b_simple.asm” is not visible in the menu, you can find it by selecting “Other…”, “Microchip Embedded”, and then “MPASM assembler”. - Choose a file name such as “main” and then click “Finish”. This should create a new file named “main.asm” and open it for editing. - Copy and paste the following code into main.asm, replacing all the code that was there by default: - To compile the code, open the “Run” menu and select “Build Main Project”. - The “Output” pane should show the build output from MPLAB X. One of the last lines of the output should say “Loading code from” and have the full path to the HEX file produced during compilation. #include <p18f25k50.inc> org 0x2000 goto start org 0x2020 ledRedOn: bcf TRISC, 6 return ledRedOff: bsf TRISC, 6 return start: bcf LATC, 6 ; Set up the red LED ; Enable Timer 0 as a 16-bit timer with 1:256 prescaler: ; since the instruction speed is 12 MHz, this overflows about ; every 1.4 seconds. movlw b'10000111' movwf T0CON mainLoop: movf TMR0L, W ; Trigger an update of TMR0H ; Blink the red LED with a period of 1.4 s. btfss TMR0H, 7 rcall ledRedOff btfsc TMR0H, 7 rcall ledRedOn goto mainLoop end If your P-Star has a PIC18F45K50, the code above will work as is, but you should change it to include p18f45k50.inc instead of p18f25k50.inc. Where to find more information For information about the instruction set, hardware peripherals, and registers on the PIC, see the PIC18F25K50/PIC18F45K50 datasheet. For information about MPLAB X, you can find useful resources under the “Help” menu and in the “docs” directory inside your MPLAB X installation. For information about MPASM, see its user’s guide, which is in the “mpasmx/docs” directory inside your MPLAB X installation. If you have questions, you can post in Microchip’s MPASM forum or the Pololu Robotics Forum.
https://www.pololu.com/docs/0J62/10
CC-MAIN-2020-24
refinedweb
680
72.66
* A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login JavaRanch » Java Forums » Java » Beginning Java Author problems with math methods Roxanne Billings Greenhorn Joined: Apr 01, 2011 Posts: 8 posted Apr 06, 2011 17:45:41 0 Just when I think I am starting to get this stuff . . . I get stuck again. (please help) I am writing a program that has a user enter their first name, last name, year of birth. Then I am trying to output their age, create a random amount of years in the future, and calculate their future age. I have most of the beginning working so far. . . but now I am stuck between creating the random array of int years (future years) and calculating that result with a primitive type int. Here is the code I have so far . . . /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package assignment7_1; import java.util.Scanner; /** * * */ public class Assignment7_1 { /** * */ public static void main(String[] args) { //Create Scanner Scanner input = new Scanner(System.in); //Have user enter a string System.out.print("Enter your first name: "); String firstName = input.nextLine(); //Have user enter a string System.out.print("Enter your last name: "); String lastName = input.nextLine(); //Have user enter year of birth System.out.print("Enter year of birth in four digit format: "); int birthYear = input.nextInt(); int verifyLength = verifyLength(birthYear); int[] newYear = new int[1]; for (int i = 0; i < newYear.length; i++){ newYear[i] = (int) (Math.random() * 50/1)+1; System.out.print(newYear[i] + "\n"); } randomAge(newYear[], birthYear); /**I KNOW THIS IS WRONG -- THIS IS WHERE I KNEW I WAS STUCK!!!*/ initials(firstName, lastName); String revLast = revLast(lastName); String revFirst = revFirst(firstName); System.out.println(revFirst + " " + revLast); } //verify four character year public static int verifyLength(int birthYear){ Integer chkYear = new Integer (birthYear); String strYear = chkYear.toString(); int p = birthYear; if (strYear.length() == 4) { p = birthYear; } else{ System.out.println("Invalid Year Entered"); } return p; } //reverse last name public static String revLast(String lastName){ StringBuilder stringbuilder = new StringBuilder(lastName); stringbuilder.reverse(); return stringbuilder.toString(); } //reverse last name public static String revFirst(String firstName){ StringBuilder stringbuilder = new StringBuilder(firstName); stringbuilder.reverse(); return stringbuilder.toString(); } //Create user's initials public static void initials(String firstName, String lastName){ char[] firstChar = firstName.toCharArray(); char[] lastChar = lastName.toCharArray(); char charF = firstChar[0]; char charL = lastChar[0]; System.out.println(charF + ". " + charL + "."); } //Method to calculate projected age public static void randomAge(int newYear, int birthYear){ // Add newYear to 1900; then subtract from birthYear int newYear1 = (newYear + 1900); int newAge = (newYear1 - birthYear); System.out.println(newAge); } Thank you in advance for any assistance you can provide me! RB Greg Brannon Bartender Joined: Oct 24, 2010 Posts: 561 posted Apr 06, 2011 18:07:41 1 Check for an answer on DIC. Always learning Java, currently using Eclipse on Fedora. Linux user#: 501795 fred rosenberger lowercase baba Bartender Joined: Oct 02, 2003 Posts: 11401 16 I like... posted Apr 07, 2011 06:55:07 0 What do you mean by "create a random amount of years in the future"? this could mean you're trying to find one date some random amount of time in the future, or you could be trying to find a random number of years, all of which are in the future. Being a good programmer means knowing, understanding, and being able to explain the problem clearly to everyone else. So, let's focus on one small part...what EXACTLY are you trying to create? There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors I agree. Here's the link: subject: problems with math methods Similar Threads I dont get the "get and set" method for my homework System.in.read giving a number when no entry has been made Why does cons remain equal to null? Can Somebody please help me with my code? Create a Name class to manage different name changes of a person. All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/533521/java/java/problems-math-methods
CC-MAIN-2014-42
refinedweb
692
66.94
Take Back Control Using modular JavaScript for front-end development Node Summit, 2018-07-25 Who is this guy? Laurie Voss COO & co-founder, npm Inc. @seldo What are we talking about? Part 1: Avoid Nasty Surprises Taking Back Control Part 2: Take Control of JavaScript Itself Taking Back Control JavaScript is enormously popular Top 5 languages on GitHub by number of pull requests opened npm is also popular Modular code is getting more popular 97% of the code in a modern web app comes from npm 85% of npm users do front-end development npm is a company that sells goods and services Your team will ship faster and your code will be more secure with npm Enterprise Part 1: Avoid Nasty Surprises npm is at version 6 Upgrade right now! npm install npm -g 1. npm locks by default 2. npm saves by default 3. npm ci will double the speed of your builds npm ci You can use anywhere you used to use npm install and it will be twice as fast 4. npm has 2FA: two-factor auth Secure your npm account in 30 seconds: npm Security A bunch of new features 5. npm Quick Audits Just run npm install! npm Quick Audit stats - 3.5 million scans per week - 51% vulnerable - 37% high - 11% critical Yikes! 6. npm audit Just run in your current project: npm audit Learn more: 7. npm audit fix Just run in your current project: npm audit fix or npm audit fix --force for the adventurous 8. npm.community Part 2: Take Control of JavaScript Itself Modular code is great Modular code is the solution to the problem of tiny human brains Links in a network increase quickly links = n(n-1)/2 Human brains cannot handle giant programs Modular code limits possible interactions Modular code fits into your tiny human brain Efficient developers >>> efficient code 2008: no modules in JavaScript 2009: all the modules in JavaScript CommonJS modules exports = function() { ... } var mod = require('filename') Define: Use: 2009: An explosion of server-side JavaScript - Node.js - SpiderApe - V8cgi - K7 - Narwhal - Jack 2009: all the package managers JavaScript in 2009 was a mess People just tried stuff out Server side modules today: pretty good The commit where npm was bundled with node: Programming language choice is determined by the libraries available Node.js and npm: a virtuous cycle Developers love libraries Developers will do a lot of work to avoid doing work Enter transpiling and bundling 2011: browserify Webpack and babel Webpack is taking over the web Babel is changing JavaScript 60% of npm users are building React apps Webpack + babel works great So obviously we need to change everything. Webpack + babel are kind of a pain Why are you like this, JavaScript? Bundling and transpiling is tricky to get right Bundling is a performance issue Code splitting is hard Static analysis is really hard breaks static analysis require() ES6 to the rescue with import() ES6 modules export function square(x) { return x * x; } import {square} from 'filename' Define: Use: But code splitting is still really hard Browser support for ES6 modules sucks <script type="module"></script> No support for module ID import './lib' vs import 'lib' Module IDs are easy in Node.js Module ID is essential to reusable code Without module ID you still need a transpiler Punting on Module ID is a huge problem Browser imports have performance issues HTTP 2 is not going to magically fix everything ES6 syntax is available already Old vs. new * for real-world applications ES6 modules: we're just not that into them What world do we want? A proposal: - Modular JavaScript - That works on browsers and servers - Doesn't require transpilation - Doesn't require bundling - Can be lazily loaded by browsers - Doesn't require tons of tooling - Compatible with npm npm compatibility is a hard requirement Because developers are addicted to libraries npm will evolve How do we build this? You already know how. It's time to step up by writing some really terrible software It's 2008 again We have fixed this before Standards bodies don't innovate Remember XHTML 2.0? Don't be afraid to try something weird It's only a website. This is your time to invent the next big thing You can be the next random person Thank you! @seldo These slides Talk to me Take Back Control By seldo
https://slides.com/seldo/take-back-control
CC-MAIN-2021-21
refinedweb
735
55.27
Opened 6 years ago Closed 6 years ago #7729 closed bug (fixed) GHC panics. Invalid core Description Following code snippet triggers panic: {-# LANGUAGE FlexibleContexts, TypeFamilies #-} module Monad where class Monad m => PrimMonad m where type PrimState m class MonadTrans t where lift :: Monad m => m a -> t m a class (PrimMonad (BasePrimMonad m), Monad m) => MonadPrim m where type BasePrimMonad m :: * -> * liftPrim :: BasePrimMonad m a -> m a newtype Rand m a = Rand { runRand :: Maybe (m ()) -> m a } instance (Monad m) => Monad (Rand m) where return = Rand . const . return (Rand rnd) >>= f = Rand $ \g -> (\x -> runRand (f x) g) =<< rnd g instance MonadTrans Rand where lift = Rand . const instance MonadPrim m => MonadPrim (Rand m) where type BasePrimMonad (Rand m) = BasePrimMonad m liftPrim = liftPrim . lift GHC 7.6.2 panics $ ghc-7.6.2 -c Monad.hs ghc: panic! (the 'impossible' happened) (GHC version 7.6.2 for x86_64-unknown-linux): cgLookupPanic (probably invalid Core; try -dcore-lint) $dMonadTrans{v ahe} [lid] static binds for: local binds for: main:Monad.lift{v ra} [gid[ClassOp]] main:Monad.liftPrim{v rc} [gid[ClassOp]] main:Monad.$p1PrimMonad{v rgv} [gid[ClassOp]] main:Monad.$p1MonadPrim{v rgA} [gid[ClassOp]] main:Monad.$p2MonadPrim{v rgB} [gid[ClassOp]] Please report this as a GHC bug: whereas 7.4.2 reports type error $ ghc-7.4.2 -c Monad.hs Monad.hs:28:14: Occurs check: cannot construct the infinite type: m0 = t0 m0 Expected type: BasePrimMonad (Rand m) a -> Rand m a Actual type: m0 a -> Rand m a In the expression: liftPrim . lift In an equation for `liftPrim': liftPrim = liftPrim . lift Change History (6) comment:1 Changed 6 years ago by comment:2 Changed 6 years ago by comment:3 Changed 6 years ago by Had a user bitten by this one today: {-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TypeFamilies #-} module Test where import Control.Lens newtype A a = A a deriving (Show) asA :: Iso' a (A a) asA = iso A $ \(A x) -> x f :: (Ord a, Eq a) => a -> [(a,b)] -> Maybe b f _ _ = Nothing ‗‗ type instance Index (A a) = a instance (Gettable f, Ord a) => Contains f (A a) where contains = containsLookup (\k m -> f k (m ^. from asA)) thing :: A a thing = view asA [] main = print $ thing ^. from asA It causes $ ghc --make Test.hs [1 of 1] Compiling A ( Test.hs, Test.o ) ghc: panic! (the 'impossible' happened) (GHC version 7.6.2 for x86_64-unknown-linux): cgLookupPanic (probably invalid Core; try -dcore-lint) $dMonadReader{v a2W4} [lid] static binds for: local binds for: Please report this as a GHC bug: on 7.4.1 I get localhost:wl-pprint-terminfo ekmett$ ghci ~/Cube.hs GHCi, version 7.4.1: :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. /Users/ekmett/Cube.hs:17:14: Occurs check: cannot construct the infinite type: a3 = [(a3, a2)] Expected type: Index (A a) -> p Bool (f Bool) -> A a -> f (A a) Actual type: a3 -> p Bool (f Bool) -> A a -> f (A a) In the return type of a call of `containsLookup' In the expression: containsLookup (\ k m -> f k (m ^. from asA)) This contains the result of -dcore-lint. comment:4 Changed 6 years ago by Haev you checked whether it's fixed in HEAD, as this ticket claims? Currently it's a bit of a guess that it's the same bug, isn't it? It's bad that 7.6 fails here. I hate the idea of the main extant compiler being broken; very un-keen on tracking it down given that the benefit will be for a matter of months only. Well, I suppose the next HP is likely to use 7.6. It's a balance with how painful it is. Keep saying if it is! I think I'll re-open anyway. Simon comment:5 Changed 6 years ago by For the record, I confirm that ekmett's program and the original ticket concerns exactly the same bug, fixed in HEAD. Both programs can be reduced to, which crashes 7.6 and gives occurs check in 7.7. I don't think this bug is worth hunting and releasing another 7.6.x - I would close it. comment:6 Changed 6 years ago by OK, thanks for checking! Simon Interesting. With HEAD we get If you change the offending line to then we get a different erro rmessage Although these errors look different, they are acutally pretty similar. GHC 7.6.2 fails to reject the program, but gives a Lint error if you use -docore-lint. I don't propose to try to fix this... too obscure. I'll add a regression test thought. Thank you for the example. Simon
https://trac.haskell.org/trac/ghc/ticket/7729
CC-MAIN-2019-35
refinedweb
792
66.84
Brian Shirai - Registered on: 12/19/2008 - Last connection: 10/06/2015 Issues - Assigned issues: 0 - Reported issues: 37 Projects - CommonRuby (Developer, 12/21/2012) - Ruby (Contributor, 07/10/2013) Activity 12/23/2014 - 08:47 PM Ruby trunk Bug #10638: Keyword Hash processing is inconsistent - Sorry, I had an old MRI version selected in chruby, this appears to work correctly on trunk. - 08:32 PM Ruby trunk Bug #10638 (Closed): Keyword Hash processing is inconsistent - An empty Hash passed to a method taking a keyword rest argument is not dup'd. A modification to the keyword rest Hash... 07/08/2014 - 09:55 PM Ruby trunk Bug #10016 (Closed): Destructuring block arguments with a Hashable last element - The following code: ~~~ruby # destructure_bug.rb def m x = Object.new def x.to_hash() {x: 9} end yiel... 06/03/2014 - 03:48 PM Ruby trunk Bug #9898 (Closed): Keyword argument oddities - Case 1: If a method takes a single argument, and the method is called with a keyword splat, the method receives the p... 05/06/2014 - 05:25 PM Ruby trunk Bug #9810 (Open): Numeric#step behavior with mixed Float, String arguments inconsistent with docu... - The Numeric#step documentation states: "If any of the arguments are floating point numbers, all are converted to f... 10/03/2013 - 02:26 AM Ruby trunk Feature #8976: file-scope freeze_string directive - > It would be a very bad idea to have a directive that completely changes the meaning of code from one file to anothe... 09/24/2013 - 01:07 PM Ruby trunk Bug #8945 (Closed): Unmarshaling an Array containing a Bignum from a tainted String returns a fro... - In 2.1, Symbol, Fixnum, Bignum, and Float (at least) have been changed to frozen by default. Consequently, calling #t... 02/27/2013 - 10:38 AM Ruby trunk Bug #7964: Writing an ASCII-8BIT String to a StringIO created from a UTF-8 String - Martin, what do you mean by: "However, the question is whether the resulting string should always be BINARY (exactly ... 02/26/2013 - 04:32 PM Ruby trunk Bug #7964 (Assigned): Writing an ASCII-8BIT String to a StringIO created from a UTF-8 String - =begin In the following script, an ASCII-8BIT String is written to a StringIO created with a UTF-8 String without er... 02/21/2013 - 03:17 AM Ruby trunk Bug #7200: Setting external encoding with BOM| - #set_encoding accepts ("bom|utf-16be:euc-jp") but rejects ("bom|utf-16be", "euc-jp"). This is inconsistent, confusing...
https://bugs.ruby-lang.org/users/293
CC-MAIN-2016-07
refinedweb
418
59.53
Overview of Design Patterns for Beginners Introduction. What are Design Patterns? A real world software system is supposed to solve a set of business problems. Most of the modern languages and tools use object oriented design to accomplish this task of solving business problems. Designing a software system is challenging because it not only needs to meet the identified requirements but also needs to be ready for future extensions and modifications. A software design problem may have more than one solution. However, the solution you pick should be the best in a given context. That is where design patterns come into the picture. There may be multiple routes that take you to the top but not all will do so in the same amount of time and effort. Some routes might be tough to walk but they might take you to the top in less time. Some other routes might be easy to walk but they may take too much time. Which one is the best route? There cannot be a single answer to this question. Depending on your physical strength, available time and external conditions, such as weather, you need to compromise on a route as the "best". In the preceding example, you were unaware of any of the routes leading you to the top. What if somebody gives you a detailed map along with all possible routes, along with pros and cons of each? Obviously, you will be in a much better position to begin your journey. Let's try to draw a parallel in terms of a software system designing. Suppose you have been given a software design problem to solve. As a developer you may attempt to solve it based on your own skills and experience. However, if you start the design from scratch you may end up spending too much time and effort. Additionally, you may not know whether your design is the best possible design in a given context. That is where design patterns come into picture. Simply put a design pattern is a proven solution to solve a design problem. A design pattern provides a template or blueprint for solving a software design problem at hand. Why are design patterns better than a "from scratch" solution? That's because thousands and thousands of developers all over the world have used them successfully to solve a design problem. Thus they are proven solutions to recurring design problems. Additionally, since design patterns are well documented you have all the information needed to pick the right one. A design pattern is usually expressed by the following pieces of information: - Name : A design pattern usually has a name that expresses its purpose in nutshell. This name is used in the documentation or communication within the development team. - Intent : Intent of a pattern states what that pattern does. Intent is usually a short statement(s) that captures the essence of the pattern being discussed. - Problem : This refers to a software design problem under consideration. A design problem depicts what is to be addressed under a given system environment. - Solution : A solution to the problem mentioned above. This includes the classes, interfaces, behaviors and their relationships involved while solving the problem. - Consequences : Tradeoffs of using a design pattern. As mentioned earlier there can be more than one solution to a given problem. Knowing consequences of each will help you evaluate each solution and pick the right one based on your needs. Note that the above list is just the minimum information needed to describe a pattern. In practice, a few more aspects may also be needed to be expressed. As an attempt to catalog popular design patterns Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides documented around 23 design patterns in their book titled "Design Patterns: Elements of Reusable Object-Oriented Software". These design patterns are the most popular and commonly used patterns today. These patterns are often termed as Gang of Four (GoF) patterns since they are documented by these four authors. What are the Benefits of Using Design Patterns? The discussion about design patterns should have given you some idea about their benefits. Let's quickly identify and summarize these benefits here: - Design patterns help you to solve common design problems through a proven approach. - Design patterns are well documented so that there is no ambiguity in the understanding. - Design pattern may help you reduce the overall development time because rather than finding a solution you are applying a well known solution. - Design patterns promote code reusability and loose coupling within the system. This helps you deal with future extensions and modifications with more ease than otherwise. - Design patterns promote clear communication between technical team members due to their well documented nature. Once the team understands what a particular design pattern means, its meaning remains unambiguous to all the team members. - Design patterns may reduce errors in the system since they are proven solutions to common problems. Classification of Design Patterns Now that you understand what design patterns are and what their benefits are, let's see how they are classified. The GoF design patterns are classified into three categories namely creational, structural and behavioral. - Creational Patterns : Creational design patterns separate the object creation logic from the rest of the system. Instead of you creating objects, creational patterns create them for you. The creational patterns include Abstract Factory, Builder, Factory Method, Prototype and Singleton. - Structural Patterns : Sometimes you need to build larger structures by using an existing set of classes. That's where Structural Patterns come into picture. Structural class patterns use inheritance to build a new structure. Structural object patterns use composition / aggregation to obtain a new functionality. Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy are Structural Patterns. - Behavioral Patterns : Behavioral patterns govern how objects communicate with each other. Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template method and Visitor are Behavioral Patterns. Example of a Design Pattern - Singleton Now that you know the purpose and benefits of design patterns, let's conclude this article by looking into a simple example of design patterns. In this example you will use Singleton design pattern. As mentioned earlier, Singleton is a creational design pattern. The intent of the Singleton design pattern is as follows: To ensure that only one instance of a class is created and to provide a global point of access to the object. The above intent tells us that Singleton is useful when you wish to create one and only one instance of a class in the system. Consider a case where you are building a class that represents some costly system resource. Since the resource is expensive you wish to ensure that the users of the class create only one instance of the class to avoid any wastage of the resources. Singleton pattern can be used to enforce such a functionality. Consider the following class written in C# that uses Singleton pattern. public class CostlyResource { private CostlyResource() { //nothing here } public DateTime LastRequestedOn { get; private set; } private static CostlyResource instance = null; public static CostlyResource GetInstance() { if(instance==null) { instance = new CostlyResource(); } instance.LastRequestedOn = DateTime.Now; return instance; } } The above code creates a class named CostlyResource. The constructor of the class is made private so that you cannot instantiate it from outside of the class. The CostlyResource class has just one public property, LastRequestedOn, that stores the DateTime at which the last request for the object instance was made. Then the code creates a static instance of CostlyResource class and sets it to null. This variable is static because it needs to be shared with multiple calls. It then creates a static method named GetInstance(). The GetInstance() method is responsible for creating an instance of CostlyResource and stores it in the instance variable. It also sets the LastRequestedOn property to the current DateTime value. Finally, instance is returned to the caller. The CostlyResource class can be used in some other part of the system like this: static void Main(string[] args) { CostlyResource obj1 = CostlyResource.GetInstance(); Console.WriteLine(obj1.LastRequestedOn); System.Threading.Thread.Sleep(2000); CostlyResource obj2 = CostlyResource.GetInstance(); Console.WriteLine(obj2.LastRequestedOn); if(Object.ReferenceEquals(obj1, obj2)) { Console.WriteLine("obj1 and obj2 are pointing to the same instance!"); } Console.ReadLine(); } The above code creates a variable of type CostlyInstance (obj1) and points it to the instance returned by GetInstance() static method. It then outputs the LastRequestedOn property on the Console. The code then halts the execution for a couple of seconds by calling the Sleep() method of Thread class. It then creates another variable of type CostlyInstance (obj2) and calls GetInstance() again to obtain the instance. To prove that object pointed to by obj1 and obj2 is one and the same the code uses ReferenceEquals() method of the Object class. The ReferenceEquals() method accepts the two instances to compare and returns true if they are pointing to the same object. If you run the above code you will get an output as shown below: Pointing to the Same Instance Summary Design patterns offer proven solutions to recurring design problems. GoF design patterns are widely used by developers and are classified into three categories - creational, structural and behavioral. This article presented a quick overview of design patterns. It also discussed Singleton design pattern along with its C# implementation.
https://www.developer.com/design/overview-of-design-patterns-for-beginners.html
CC-MAIN-2017-51
refinedweb
1,546
56.05
The current lowinterest- rate environment creates powerful wealth transfer opportunities. Each month, the IRS issues minimum interest rates that can be applied to intra-family loans so that the IRS does not treat the transaction as a gift. These interest rates are known as the “applicable federal rates” (AFRs). The minimum AFR that must be paid to avoid having the loan treated as a gift varies depending on the length of the loan. In addition, each month the IRS announces the minimum interest rate that can be used to measure the present value of annuities, income interests and remainder interests for estate and gift tax purposes (known as the Section 7520 rate, or hurdle rate). For August 2008, the Section 7520 rate is 4.2 percent. Estate planning professionals can use these low rates to shift wealth, free of transfer taxes, from one generation to the next. Since low rates will not last forever, you may want to consider the following “wealth-shifting” techniques that are designed to capitalize on the low-interestrate environment: Intra-Family Loan An effective, yet under-used, technique is the simple intra-family loan. Rather than making a gift of a particular asset to a child, a parent can loan assets to the child. If the child earns a rate of return on the borrowed assets that exceeds the AFR, the excess return (over the interest rate) is transferred to the child free of transfer taxes. For example, assume that a parent during August 2008 loans $1 million to a child for nine years in return for an interestonly $1 million promissory note bearing interest at 3.55 percent (the August 2008 AFR for midterm loans). If the child invests the $1 million in an asset that returns 10 percent annually, the asset, minus the annual $35,500 interest payment, will be worth $1,875,876 after nine years. Accordingly, upon termination of the note and repayment of the $1 million principal balance, the child would retain $875,876 free of transfer taxes. A drawback to this transaction is that the IRS treats the interest payments to the lender (i.e., the parent) as taxable income. If, however, the loan is made to a trust created for the benefit of the child, and the trust is structured for income tax purposes as a “grantor trust” with respect to the parent, the parent’s annual receipt of interest will not be treated as taxable income. A “grantor trust” is simply a trust that is ignored for income tax purposes, so that the trust assets are treated for income tax purposes as if they are still owned by the parent. Income and gains attributable to the trust’s assets are reported on the parent’s income tax return, which allows the trust to grow without the burden of paying income taxes. The parent’s income tax payment on assets that ultimately pass to the child is the equivalent of a tax-free gift to the child. Grantor Retained Annuity Trust A grantor retained annuity trust (GRAT) is an irrevocable trust that pays its creator (the grantor) an annual annuity for a fixed term of years. The annuity paid to the grantor is a percentage of the initial value of the GRAT’s assets and could have a present value approximately equal to the value of the property transferred into the trust. There is little or no gift associated with the transaction because the grantor’s retained interest in the GRAT is approximately equal to the property transferred to the GRAT. This type of GRAT is often called a “zeroed-out GRAT.” If the total annual return (income and/or appreciation) on the GRAT assets exceeds the Section 7520, or hurdle, rate, the excess will pass to the grantor’s children, free of transfer taxes, upon termination of the trust (if the grantor survives the term). For that reason, GRATs work particularly well in a low-interest-rate environment. The transfer tax benefits of a zeroed-out GRAT can be illustrated by the following example: Assume (i) a parent transfers $5 million to a GRAT with a fiveyear term, (ii) the GRAT assets will increase in value at a rate of 15 percent per year during the GRAT term, and (iii) the Section 7520 rate in effect at the creation of the GRAT is 4.2 percent. Based on these assumptions, the parent will receive an annual annuity payment of $1,129,459 from the GRAT during the five-year term. Because the GRAT annuity payments have a present value equal to the value of the property transferred, formation of the GRAT is not treated as a gift. The assets remaining in the GRAT at the end of five years will, based on these assumptions, equal $2,441,546 and be distributable to the children free of gift and estate tax. Installment Sale to a Grantor Trust Another strategy commonly recommended in a low-interest-rate environment is an installment sale to a grantor trust. This transaction is similar to the intrafamily loan to a grantor trust, but, instead of loaning assets to the trust, a parent sells an existing high-performing asset to a grantor trust held for the benefit of the parent’s descendants. As discussed, a grantor trust is “ignored” for income tax purposes; the trust’s assets are treated as if they are still owned by the grantor. This means that, if a parent sells assets to the grantor trust in return for a promissory note, no capital gain tax is triggered by the sale, and the annual interest paid by the trust to the parent is not taxable income to the parent. Although the trust is ignored for income tax purposes, it is respected for estate and gift tax purposes. Accordingly, the parent shifts the asset’s future appreciation to the trust (where it will ultimately pass to the grantor’s descendants) free of estate, gift and, if appropriately structured, generation-skipping transfer (GST) taxes. The following example illustrates the benefits of this transaction: A parent sells $5 million of assets to an existing grantor trust that is held for the benefit of the parent’s descendants in exchange for a five-year $5 million promissory note. The note requires interest to be paid annually at the August 2008 mid-term AFR of 3.55 percent and a balloon payment of principal to be paid at the end of the five-year term. For illustrative purposes it is assumed that the trust assets will grow at a rate of 15 percent per year during the trust term. As discussed, no gain or loss is recognized on the sale of $5 million of assets to the trust, and the annual interest payments of $177,500 ($5 million x 3.55%) will not be treated as taxable income to the parent. After the re-payment of the $5 million note, $3,860,013 will be left in the trust and will pass to the beneficiaries free of gift, estate and GST taxes. Charitable Lead Annuity Trust A charitable lead annuity trust (CLAT) is another technique that works particularly well in a lowinterest- rate environment. A CLAT should be considered by anyone who has significant charitable objectives. Like a GRAT, a CLAT pays a predetermined annuity amount to charity, with any remaining property passing to non-charitable remainder beneficiaries (typically the grantor’s children). Also like a GRAT, the annuity is typically structured as a zeroed-out CLAT, so that it has a present value approximately equal to the value of the property transferred into the trust. Thus, a CLAT is virtually identical to a GRAT, except that the annuity is paid to charity rather than to the grantor. As with a GRAT, a CLAT’s remainder beneficiaries are more likely to receive significant assets when interest rates are low. For example, assume (i) a parent transfers $10 million of assets to a CLAT with a 20-year term, (ii) the annuity payable annually to the charity is 7.228 percent of the initial fair market value of the trust assets; (iii) the discount rate for the CLAT is 3.8 percent (the June 2008 rate); and (iv) the total annual return on the assets transferred to the CLAT is nine percent. Based on these assumptions, the charity would receive an annual annuity of $722,846 from the CLAT for 20 years, and $19,063,205 would pass free of tax to the parent’s then-living children. Thus, parents can use a CLAT in a low-interest-rate environment to transfer significant wealth to their children and simultaneously accomplish their charitable objectives. Low Rates Will Not Last The current low-interest-rate environment is unlikely to last, due to inflationary pressures facing our economy. Accordingly, parents and other donors who want to take advantage of low interest rates should act quickly. If you would like more information on one of these estate planning techniques, please contact your Sonnenschein Trusts & Estates attorney at your earliest convenience.
https://www.lexology.com/library/detail.aspx?g=575a63e1-66dd-4425-a35d-812f28aa6236
CC-MAIN-2017-39
refinedweb
1,510
54.26
Steve Loughran <stevel@apache.org> writes: >> My issue comes from my build system architecture: >> - a main Ant project parse a XML configuration file which is a Ant build >> file >> itself, and where I would like to make available custom DataType in a >> specific antlib/namespace >> - a plugin is a Ant project which is able to do anything it wants. Like >> taskdef and typedef... >> The plugin project has been "forked" from the main Ant project. How can I >> (programmatically speaking) transfer taskdef/typedef from the plugin project >> to the main project ? > > you can't --that is what "forking" implies. you are operating within a new > environment. Ok I know it is not cleaned - regarded the Ant task development guidelines. I'm working on 'el4ant' (sourceforge) and I need some extract features in Ant for my build.xml generation from project description works smoothly. I have "misuse" Ant to parse my project description XML files and it is really convenient in fact ;) My question may be simpler: - How can I copy tasks and types from one Ant project to another ? It is simple to do that with properties. I suppose it is not impossible to do that with tasks/types. I just ask for help to avoid to "waste" time into Ant internals hacking... but I will do it in case of non response. Thank you for your help -- Yves Martin --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org For additional commands, e-mail: dev-help@ant.apache.org
http://mail-archives.eu.apache.org/mod_mbox/ant-dev/200509.mbox/%3Cf6fys6h00u.fsf@pcyma.elca.ch%3E
CC-MAIN-2020-10
refinedweb
248
74.69
Chapter 12. Exceptions Chapter 12. ExceptionsPrev Part I. Exam Objectives Next Chapter 12. ExceptionsIdentify correct and incorrect statements or examples about exception handling Hello - Struts Hello Hi Friends, Thakns for continue reply I want to going with connect database using oracle10g in struts please write the code...:// Thanks Amardeep Hello - Struts.1.8 Hello World Example Struts 2.1.8 Hello World Example  ... to develop simple Hello World example in Struts 2.8.1. You will also learn how... started with the Hello World tutorial using Struts 2.1.8: The web configuration Chapter 3. Develop clients that access the enterprise components supports J2EE level 1.2. The WebSphere v5 and v51 Application Client hello Java Error in Hello World Java Error in Hello World hello Java Hello World HELLO World program in Java hello java program 12 java program 12 Write a java program to verify whether the given number is palindrome or not by taking from input Buffer reader(console). import java.io.*; public class CheckPalindrome{ public static void main struts how to start struts? Hello Friend, Please visit the following links:... can easily learn the struts. Thanks Struts - Struts Struts Hello Experts, How can i comapare in jsp scriptlet in if conditions like... }//execute }//class struts-config.xml <struts..."/> </plug-in> </struts-config> validator Hello I like to make a registration form in struts inwhich.... Struts1/Struts2 For more information on struts visit to : pdf chapter pdf chapter As we all have seen a pdf file, in the pdf file there are too many chapter. Do you... the constructor of the Paragraph pass a String. Now make a Chapter and inside Developing JSP, Java and Configuration for Hello World Application and required configuration files for our Struts 2 Hello World application. Now... on the "Run Struts 2 Hello World Application" link on the tutorial...;Struts 2 Hello World Application!</title> </head> <body> hello .. still doesn't run - Java Beginners hello .. still doesn't run Iam still having a prblem in running...; String today="first"; order [ ] o=new order[12]; Bell [ ] B=new Bell[100...{ for(int i=0;i<12;i++) System.out.println ("\n"+i+" "+o[i].Oname+" "+o[i Labels in Struts 2.0 - Struts Labels in Struts 2.0 Hello, how to get the Label name from properties file Develop Hello World example using Spring 3.0 Framework Spring 3 Hello World Example  ..., create new project in Eclipse IDE and then write simple Hello World application... the example code in Eclipse IDE. Let's start developing loop code to print the Pyramid: 1 1234 12 123 123 12 1234 1 loop code to print the Pyramid: 1 1234 12 123 123 12 1234 1 Hi, I want to know how the code to print the pyramid below works. It uses nested for loops. Pyramid: 1 1234 12 123 123 12 1234 1 Doubts on Struts 1.2 - Struts Doubts on Struts 1.2 Hi, I am working in Struts 1.2. My requirement is to display data in a multiple selected box from database in a JSP page. Can... visit for more information. Chapter 11. Transactions using captcha with Struts - Struts using captcha with Struts Hello everybody: I'm developping a web application using Struts framework, and i would like to use captcha Hi friend,Java Captcha in Struts 2 Application : Struts Flow Struts Flow can u explain about struts flow with clear explaination Hello, Chapter 5. EJB transactions Specification (see Chapter 17) includes six defined transaction attributes Authentication - Struts Authentication Hello everybody, How to provide high level authentication in struts application Actions in Struts Actions in Struts Hello Sir, Thanks for the solutions you have sent me. i wanted examples on Struts DispatchAction,Forword Action ,Struts lookupDispatchAction,Struts mappingDispatchAction,Struts DynaActionform.please Developing Hello World application Hello World Example A Hello World Example given below which shows the basic flow of Struts 2.2.1. Let us illustrates how to write java class and configure...;html> <head> <title>RoseIndia.net Struts Tutorials</title> Chapter 8. Entity Beans Chapter 14. Security Management Chapter 1. EJB Overview Chapter 9. EJB-QL Eyeryone... Hello Eyeryone... how to download java material in roseindia.net website material please kindly help me... by visu... connection Thanks HelloWorld.jsp Struts 2 Hello World... static final String MESSAGE = "Struts 2 Hello World Tutorial!"; public Java - Struts Java hello friends, i am using struts, in that i am using tiles... in struts-config file i wrote the following action tag... doubt is when we are using struts tiles, is there no posibulity to use action class Chapter 13. Enterprise Bean Environment Chapter 5. Client View of an Entity exception - Struts exception Hi, While try to upload the example given by you in struts I am getting the exception javax.servlet.jsp.JspException: Cannot...: Exception in JSP: /FileUpload.jsp:10 7: 8: 9: 10: 11: 12: 13 Understanding Struts - Struts Understanding Struts Hello, Please I need your help on how I can understand Strut completely. I am working on a complex application which is built with Strut framework and I need to customize this application but I do Struts 2 hello world application using annotation Struts 2 hello world application using annotation Annotation...;)}) An annotation Based Hello World example is given below which takes user name as input and prints a message Hello plus user name. HelloWorldAction.java package struts2 - Struts struts2 hello, am trying to create a struts 2 application that allows you to upload and download files from your server, it has been challenging for me, can some one help Hi Friend, Please visit the following Error - Struts to test the examples Run Struts 2 Hello...Error Hi, I downloaded the roseindia first struts example... create the url for that action then "Struts Problem Report Struts has detected Hello world Hello world (First java program)  ... and can be run on any operating System. Writing Hello World program is very simple. To write the Hello world program you need simple text editor like note.  Chapter 2. Design, build and test web components Hi... - Struts Hi... Hello Friends, installation is successfully I am instaling jdk1.5 and not setting the classpth in enviroment variable please write the classpath and send classpath command Hi, you set path = C Hello World How to send message in struts on mobile - Struts How to send message in struts on mobile Hello Experts, How can i send messages on mobile i am working on strus application and i want to send message from jsp java - Struts java What is Java as a programming language? and why should i learn java over any other oop's? Hello,ActionServlet provides the "... interface.Please check at Hello World Program in JRuby HelloWorld.rb Hello World Date := Tue Sep 23 18:12:26 GMT+05:30 2008... Hello World Program in JRuby  ... JRuby "Hello World" Example. So go through this tutorial to find out Hi... - Struts Hi... Hello, I want to chat facility in roseindia java expert please tell me the process and when available experts please tell me Firstly you open the browser and type the following url in the address bar login application - Struts application using struts and database? Hello, Here is good example of Login and User Registration Application using Struts Hibernate and Spring. In this tutorial you will learn 1. Develop application using Struts 2. Write help - Struts execute(){ name = "Hello, " + name + "!"; return SUCCESS; } } but error Struts Video Tutorials to Struts 2 Framework and Creating Hello World application Struts 2 Tutorials - 4 - Developing Hello World Application View more...Struts Video Tutorials - Now you can learn the Struts programming easily. In this tutorial | 2.1.8 - Struts 2.1.8 Tutorial examples. Struts 2.1.8 Hello World In this section we will learn how to develop our first Hello World example using the latest Struts 2.8.1.... Struts 2.1.8 - Struts 2.1.8 Tutorial   Struts - JSP-Interview Questions Struts Tag bean:define What is Tag bean:define in struts? Hello,The Tag <bean:define> is from Struts 1. So, I think you must be working on the Struts 1 project.Well here is the description of <bean Hello World - Java Beginners Hello World Java Beginner - 1st day. Looked at the Hello World script and thought I would give it a try....I created the script in Notepad. Saved...){ System.out.println("Hello World!"); } } what am I doing wrong. Am I expecting Chapter 2. Client View of a Session Bean Chapter 4. Session Bean Life Cycle Chapter 7. CMP Entity Bean Life Cycle Chapter 10. Message-Driven Bean Component Contract J2ME Hello World Example J2ME Hello World Example This is the simple hello world application. In this example we are creating a form name "Hello World" and creating a string message " Hello - Java Beginners Hello Hello I have a two button update and delete I want to user click on update button then msg will be displayed in msg box Are u sure want to update If user click yes then all record will be updated
http://roseindia.net/tutorialhelp/comment/213
CC-MAIN-2014-41
refinedweb
1,510
58.18
Generating dynamic content with MediaWiki/2009/W37/5 Timeline for the day of the September 11 attacks currently redirects to here while this learning resource is being constructed. To convert a red link below to the Wikipedia article simply add w: as a prefix to the link. Clicking on a red link as it is creates a new local learning resource in the Wikiversity main namespace. Dynamic timeline[edit] This page was created on the 8 year anniversary of the September 11 attacks (USA) and shows how an interactive timeline can be constructed. All times are in New York Time (EDT or UTC - 4). Wikipedia[edit] The September 11 attacks, in addition to being a unique act of aggression, constituted a media event on a scale not seen since the advent of civilian global satellite links, round-the-clock television news organizations and the instant worldwide reaction and debate made possible by the Internet. As a result, most of the events listed below were known by a large portion of the planet's population as they occurred. Events[edit] Below is an hour-by-hour breakdown of the events based on the Timeline for the day of the September 11 attacks Wikipedia article. Generating dynamic content with MediaWiki can help to create "re-enactments" of important historical events for use on Portals and Featured pages that "unfold" as the events did in actual time. The events section on the Wikipedia article is 46 kilobytes long. We'll be breaking this big page into subpages so that dialup users, and those using mobile devices or old ancient browsers can edit and access pages without difficulties or delays. To do this, we'll use parser functions to create and access subpages to Timeline for the day of the September 11 attacks (currently a redirect to here): - Timeline for the day of the September 11 attacks/06/00 trough Timeline for the day of the September 11 attacks/23/30. - /06/00 has the first hour References[edit] Further reading[edit] - Bernstein, Richard B. (2003). Out of the Blue: A Narrative of September 11, 2001. Times Books. ISBN 0-8050-7410-4. - Thompson, Paul (2004). The Terror Timeline: Year by Year, Day by Day, Minute by Minute: A Comprehensive Chronicle of the Road to 9/11. HarperCollins. ISBN 0-06-078338-9. External links[edit] - "Interactive 911 Timeline" - Provided by TimeRime.com. - "Complete 911 Timeline" minute by minute - Provided by the Center for Cooperative Research. - Comprehensive Minute By Minute Timeline On 911 Mark R. Elsis - Washington Post, 27 January 2002 Details of discussions that took place between President Bush and his advisors on the night of September 11. - September 11: Chronology of terror: CNN timeline published September 12. - 911 Case Study: Pentagon Flight 77: 3d Computer Simulation about The Pentagon impact. - Video Archive of News Stations - Archive.org
http://en.wikiversity.org/wiki/Generating_dynamic_content_with_MediaWiki/2009/W37/5
CC-MAIN-2013-48
refinedweb
475
51.89
i post this question here because in weld forum i havent no feedback. i've developed a custom context that is similar to @viewScoped context. I have two controllers , say ActionA, ActionB, in order to implements a test wizard. @CustomScoped@Named("actionA")public class ActionA{ private String var1; @Produces @Named("var1")public String getVar1(){ return var1;} public void setVar1(String var1){this.var1 = var1;} } @CustomScoped @Named("actionB") public class ActionB{ private String var2; @Inject @Named("var1") String var1; public String getVar2(){ return var2; } public void setVar2(String var2){ this.var2 = var2; public void endWizard(){ System.out.println("var1 is: " + var1); Steps: 1) Go to ActionA, make var1 equals to "var1"; 2) Go to ActionB, make var2 equals to "var2"; 3) Invoke endWizard method of ActionB class and i can read into the consolle "var1 is: var1"; 4) Go back to ActionA and make var1 equals to "var1_second_change"; 5) Go forward to ActionB, invoke endWizard method of ActionB class and i read into the consolle "var1 is: var1", when i expect to read "var1 is: var1_second_change"; In my custom context, instead i can see that var1 field of instance of ActionA controller contains correct value (var1 in fact is equals to "var1_second_change" value). I cant understand why that newly value cant be updated Can anyone help me? P.S. Sorry my english is bad. Retrieving data ...
https://community.jboss.org/thread/199933
CC-MAIN-2014-10
refinedweb
225
56.49
What would you like to do? What is the algorithm of generating unique random numbers like in mobile recharge coupons? luhn algo Was this answer useful? Thanks for the feedback! How do you generate true random numbers? True random numbers need a number frame to give it space. Try perl. type in $randomnumber1=int(rand(200))+1; you can change the 200 to anything you like and it… will generate a random number between whatever your number is and one. How do you get Visual Basic to generate a random number? Or you can do Rnd*232 Where 232 is a number of your choice higher or lower number. I have used this in a Timer and works well. Valtros --------------------…---------------------------------------------------------------------------------------------- Use the random function. The example below will give a random number between 1-100 r = Random(1, 100) How do you generate random numbers in PHP? Use the function "rand()" or "mt_rand()". Both functions will generate a random number (as a return value, so be sure to make it point to a variable - see examples). Howe…ver, "rand()" is slower and uses a default PHP randomizing system. mt_rand() is four times as fast, and uses the Mersenne Twister randomizing format - which is much more random. Both functions have two optional parameters - a minimum integer and a maximum integer, respectively. By filling in these parameters, you will get a random number between the values you give (so, giving one and five will give you a random number that is no less than one, and no greater than five). These, again, are optional - and if left blank, the tiniest integer possible is no less than 0, and the largest integer possible is generated by the PHP function "getrandmax()" / "mt_getrandmax()" automatically. Examples, of which all are acceptable: ---- /* Examples using no parameters */ $randomNumber = rand(); $randomNumber = mt_rand(); /* Examples using parameters */ $randomNumber = rand(1, 5); $randomNumber = mt_rand(6, 10); ---- If your PHP build is version 4.2 or under, you will need to seed the random number generator with a value to base off of. "srand()" and "mt_srand()" (to be used with rand() and mt_rand() functions, respectively) can be used in this case. They both only have one optional parameter, which is any seed value - any number. If omitted, a random seed will be generated. More acceptable examples: ---- // Example using no parameters srand(); $randomNumber = rand(); // Example using the seed parameter srand(12345); $randomNumber = rand(); // Example using the "mt" random format functions (without parameters) mt_Rand(); $randomNumber = mt_rand(); // Example using the "mt" random format (with parameters) mt_rand(12345); $randomNumber = mt_rand(); ---- Are random number generators truly random? yes, because the number generated is from the computer's CPU database and is selected randomly therefore it must be a random number It depends on how the numbers are genera…ted. If they are based on things in the environment, like noise levels, then yes. If they are solely generated by computer functions, then no, they are pseudo-random numbers, which will be random enough for most purposes. How do you make a random number generator? Using c++ #include #include #include using namespace std; int main() { srand(time(0)) cout … What is Hardware random number generator? In computing, a hardware random number generator is an apparatus that generates random numbers from a physical process. The output of the pseudo-random number generator? Is a set of numbers that look random and will pass most tests of randomness. How does a random number generator work? Computer-based random number generators are usually not truly random. Many of these generators choose a result starting with the milliseconds clock on the machine the applicat…ion is used on. This can be used for video games, virtual dice rolling, and other situations where true randomness is not terribly important. Both false randomness and true randomness rely on algorithms to produce numbers that tell the system what result it should display. How do you generate random numbers in Excel? You can use the RAND function or the RANDBETWEEN function. How do you generate a random number in c? Pseudo-random numbers can be generated with function rand or random. What is a random number and how are generated? Random numbers that are generated by a computer are pseudo-random (not really random), but they will pass enough statistical tests for randomness to be useful in simulation ra…ndom processes. Java has random number generators in the standard libraries. See the related link if you need more information. Answered How do you get a random number generator on Microsoft Excel? "=rand()" in a cell gives a random number between 0 and 1. Every time the sheet is recalculated (F9 key) a new random number is generated. Answered In Technology How you can generate an random unique number in visual basic studio? You can use this function: Function Random(ByVal Lowerbound As Long, ByVal Upperbound As Long) Randomize() Random = Int(Rnd * Upperbound) + Lowerbound End Function An…d use it by using: whatever.Text = Random(1, 1000) This example gives a number between 1 and 1000. Answered In Uncategorized What does it mean to generate random numbers in Java? Generating random numbers in Java is somewhat of a misnomer because the numbers are actually semi-random.It means to use the program to obtain random integers to use in hypoth…etical situations such as statistics. Answered In Uncategorized How can random numbers be generated in Java? Random numbers can be generated in Java using the "random" class. One needs a single "random" object to generate a series of random numbers as a unit. Answered How do you generate serial numbers in algorithm? You need to store the last number used somewhere - for example, in a variable that doesn't disappear after closing the function. Then, every time the function "Serial Number" …is invoked, simply add one to this number, and return the new number.
http://www.answers.com/Q/What_is_the_algorithm_of_generating_unique_random_numbers_like_in_mobile_recharge_coupons
CC-MAIN-2017-34
refinedweb
976
55.74
I have Basic doubt about the class and instantiation details, though I am writing such code. In my windows forms application, I have two classes inside a namespace. Namespace=testnamespace class1 = myform, file=myform.h class2= mybutton, file=mybutton.h even though they are under the same namespace (=testnamespace), if I want to instantiate mybutton in myform, I need to #include "mybutton.h" in the top. Why do I need to include eventhough they belong to same namespace. I have around 15 classes, as of date, and I find it a hassle. Instead, is there any setup to uniformly call the other classes within same namespace? in myform.h, If I give private: testnamespace::mybutton* _mybutton; it does not accept until I include the *.h file. Please refer me to sample readme pages or related pages, that may help me understand the basic concepts. Thanks in advance, Well, Jil. namespace is a very simple thing which cansimplify the type name, for example, you don't need to type System.Windows.Forms.form every time if you import the System.Windows.Forms via using keyword. It's not a very big deal at all. A namespace can contain serval files. If you want to instantiate a class, the class defination is necessary.
http://www.windowsdevelop.com/windows-forms-general/basic-doubt-about-the-class-instantiation-details-54629.shtml
crawl-003
refinedweb
211
68.87
shm_unlink - remove a shared memory object (REALTIME) #include <sys/mman.h> int shm_unlink(const char * name); The shm_unlink() function removes the name of the shared memory object named by the string pointed to by name. If one or more references to the shared memory object exist when the object is unlinked, the name is removed before shm_unlink() returns, but the removal of the memory object contents is postponed until all open and map references to the shared memory object have been removed. Upon successful completion, a value of zero is returned. Otherwise, a value of -1 is returned and errno will be set to indicate the error. If -1 is returned, the named shared memory object will not be changed by this function call. The shm_unlink() function will fail if: - [EACCES] - Permission is denied to unlink the named shared memory object. - [ENAMETOOLONG] - The length of the name string exceeds {NAME_MAX} while _POSIX_NO_TRUNC is in effect. - [ENOENT] - The named shared memory object does not exist. - [ENOSYS] - The function shm_unlink() is not supported by this implementation. None. None. None. close(), mmap(), munmap(), shmat(), shmctl(), shmdt(), shm_open(), <sys/mman.h>. Derived from the POSIX Realtime Extension (1003.1b-1993/1003.1i-1995)
http://pubs.opengroup.org/onlinepubs/7990989775/xsh/shm_unlink.html
CC-MAIN-2015-40
refinedweb
199
63.9
MXML (Magic XML) And a small development company offering services creating application using Magic XML… Flex applications Starting today XXXXX offers its clients development of Flex web applications based on MXML (“Magic eXtensible Markup Language”) and ActionScript program language. If you are still wondering, MXML doesn’t officially stand for anything. However the sensible bet is that it was likely born out of the fact that Macromedia defined the XML namespace and therefore the “M” probably represents Macromedia. The moral of the story is, don’t believe everything you read on the net. Even if it is on Wikipedia (or this blog for that matter :p) One Comment I say adobe should embrace Magic XML! Sounds wicked! (…at least I’d finally have an excuse for wearing this cape and cone hat at work ;) )
https://blog.flashgen.com/2008/04/its-a-kinda-magic-xml/
CC-MAIN-2020-50
refinedweb
134
57.81
Client side validation for Number values Hi, Recently in my project , i needed to validate an input (whether it is a integer or not) on client side. I tried many codes but they are bit lengthy. Then I encountered the simplest way as given below, which worked. For any input value, it checks whether it is an Integer or not. function isInteger(a) { return (!(parseInt(a).toString() == 'NaN')) } It worked for me ans saves a lot of time. Hope it helps. Regards Vishal Sahu vishal@intelligrape.com Hi amit, Thanks for the suggestion.. i was unaware about isNAN() so i used this.. We also have isNaN() function defined in javascript which returns true if value passed is not a valid number. Thanks
https://www.tothenew.com/blog/client-side-validation-for-number-values/?replytocom=34901
CC-MAIN-2020-40
refinedweb
122
77.64
Type: Posts; User: Neerad Thanks Newnic, This works for whole Dilog box and not for the individual Static text items. All the text items gets changed here. I want to have different colors for differnt text items. Thanks buddy but this seems to be working for the Doc View programs, I am talking about the Dialog box programs. I am only able to change the font of static text on the dialog boxes. Please... I want to change the foreground and back ground color of 1) The Static Text I have put on the dialog box. 2) The text of the edit box on the dialog box. Please help me out! Thanx buddy, This methametics will some day kill me. I gotta start doing some maths again right from grade 5 onwards! Thanx a lot. Thanks a lot buddy, The problem was that i read the MSDN which explained in the following way search template<class FwdIt1, class FwdIt2> FwdIt1 search(FwdIt1 first1, FwdIt1 last1, ... Any body knows how is search template to be used which is declaed in algorithms?? Can any body tell me the significance of afx_msg written in fron of so many functions??? it is just #defined in afxwin.h as #ifndef afx_msg #define afx_msg #endif Actually COM Interface just does that. A COM dll is able to keep track of functions in different executables for notifying as and when required. So there must be a way without using interprocess... Dll does not poses any problem for the above code. You can always include the header file in dll and if not available just declare the functions in the dll itself. Since dll sits just within the... #include<stdio.h> class clssA { public: void fun_Of_clssA_2B_called_By_Ptr(); void (clssA::* retAddressOf_fun())(); Has anybody used this API????????/ GetCurrentProcess() The result is always the max that can fit into a unsigned integer. try using this. unsigned int uResult; uResult =... :mad: void CDlgOpenDlg::OnOK() { // TODO: Add extra validation here OPENFILENAME ofn; // common dialog box structure char szFile[260]; // buffer for file name HWND hwnd; ... If you wish that you can compile the code so that it produces a shared object under Linux/Unix environment and a dll under windows environment and would then run in their respecive environments. This... If you require that your supposedly called dll should be named as libSomething.so under Unix/Linux environment and Something.dll under windows and should be able to compile the same code under two... I wish to read an ini file whereupon i wish to write something like this. ValueModifier = "Sum F1 F2" When i have the above string "Sum F1 F2" read in some character array, i should be able to... Your solution really helped me thinking in new direction. But may be i wasn't very clear in putting up my requirements. I needed something like an & operator in Foxpro or a function like "CallByName"... It's about really making things flexible. U See if this were possible the way i want, I would be able to define the rules (applied to the incomming data) into the ini file and thus making things... I wonder if it is possible to call a function whose name is stored in a character variable. i.e. if Str1[4] holds "Sum" Then is it possible to call Sum by refering it through Str1? Inline Assembly,... End of file character to my knowledge is ^Z. Is there a way to delete from any given file? if it is ^Z or let's say any other character - Can placing the same character any where in between... How can a com client be written in VC++. i have already made a COM component which is used in VB. I want to use the same component in another VC++ application and let me have access the interfaces... Scan through the following code #include <stdio.h> char *retval() { char myval[100] = "100 retval"; return myval; } Thanks! Thanks a lot for the wonderful reply! I have understood now what was lacking... and sorry that i forgot to remove the wrong code in my solution. I shall verify a couple of things and shall... Your site address does not solve the problem at all. I need to know why cannot "Just" the Abstract class pointer in my example be used? instead of pointer to pointer to the class (in the solution). ... Hi, My problem is "Why" following is the code i am working on. class AbstractBase { public: virtual void funct() = 0; }; class Child : public AbstractBase { void funct()
http://forums.codeguru.com/search.php?s=ebba3a43bcb1f82b9fbd0b5c1ec38103&searchid=5098367
CC-MAIN-2014-41
refinedweb
755
75
CodePlexProject Hosting for Open Source Software I'm very new to Orchard and .Net for that matter. Please excuse me if this is one of those basic newbie questions I should have known the answer to by now. I'm receiving the following error when attempting to build a site based on the Minty theme (although I don't think it's related to the theme). Error: The type or namespace name 'Contrib' could not be found (are you missing a using directive or an assembly reference?) ...\App_Web_gnz0rcdh.0.cs 30 Line 30 in App_Web_gnz0rcdh.0.cs 30 public class _Page_Modules_Contrib_FileField_Views_DefinitionTemplates_FileFieldSettings_cshtml : Orchard.Mvc.ViewEngines.Razor.WebViewPage<Contrib.FileField.Settings.FileFieldSettings> It appears to me that reference should resolve correctly based on the project. Also, this is the standard plain-Jane out-of-the-box code without any logic modifications or additions. Any suggestions would be greatly appreciated. TIA! Most obvious thing: do you have the Contrib.FileField module installed? I believe so - again my .Net newbie status shines through brightly... The VS Solution Explorer shows Contrib.FileField under Modules. I have the 'site' open in WebMatrix and launched VS from there. Thanks for the response. LC. Try building in Visual Studio first (or run ClickToBuild.cmd in the root of Orchard source). Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://orchard.codeplex.com/discussions/278800
CC-MAIN-2016-44
refinedweb
248
61.93
Structure a Flask React Monorepo June 8, 2019 This is my project structure for a Flask server and React client residing in the same git repository. It's fairly similar to the many NodeJS, React monorepos out there where the server code will be in the server subdirectory and the client code will reside in the client subdirectory. First, let's start by creating the project directory and intialize the git repository: mkdir flask-react-monorepo cd flask-react-monorepo git init Let's create a virtual environment for the repo with venv and place it in the venv directory inside the project. We will want to add this to our .gitignore file also. Once we have our virtual environment set up, we'll need to let our system know to use it. python -m venv venv echo venv/ > .gitignore source venv/bin/activate Let's install our dependencies, first for Python, then keep a list of the dependencies in a file called requirements.txt. pip install Flask pip freeze > requirements.txt requirements.txt (your versions may vary) Click==7.0 Flask==1.0.3 itsdangerous==1.1.0 Jinja2==2.10.1 MarkupSafe==1.1.1 Werkzeug==0.15.4 The canonical way to structure flask apps have a Python package named whatever the actual app is supposed to be within a subdirectory. Check out the Flask tutorial here for more details. For now, let's call the Flask server server. It can easily be api or something else you prefer. mkdir server For our Flask setup to work, we will need to create a file named setup.py in the root of our project directory: setup.py from setuptools import setup setup( name='server', packages=['server'], include_package_data=True, install_requires=['flask'] ) Now, let's just set up a simple Flask app in the server Python package by having an __init__.py file in our server directory. server/__init__.py from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello, World!' Now comes for the fun part of integrating our JavaScript client. I'll simply use create-react-app for this, but you can pretty much replace this with any front end framework or CLI tools you like. From the project root: create-react-app client Now, we can go and type FLASK_APP=server flask run from the project root to run our development server and, from another terminal, run yarn start from the client directory to run the development client, but that's just 1 too many steps for me. To streamline the development process, I'll also use yarn in the project root and install the concurrently package. From the root directory: yarn init yarn add -D concurrently echo node_modules/ >> .gitignore Now, let's add some scripts to the package.json file yarn init generated. I want yarn client to run the client development server and yarn server to run the backend development server. I also want to call yarn start from the root to run both concurrently. { "name": "flask-react-monorepo", "version": "1.0.0", "main": "index.js", "author": "Warren Wong <me@warrenwong.org>", "license": "MIT", "devDependencies": { "concurrently": "^4.1.0" }, "scripts": { "start": "concurrently \"yarn client\" \"yarn server\"", "client": "cd client && yarn start", "server": "FLASK_APP=server flask run" } } If everything works out, your back end will be on port 5000 and your client will be on port 3000 by default.
https://warrenwong.org/posts/structure-a-flask-react-monorepo/
CC-MAIN-2022-33
refinedweb
566
64.91
01 May 2007 16:52 [Source: ICIS news] LONDON (ICIS news)--BP’s chief executive Lord Browne resigned on Monday after UK courts lifted a legal injunction preventing a newspaper group from publishing details of his private life. BP said his designated successor Tony Hayward had been appointed as the group’s new CEO with immediate effect. Browne resigned following a judge’s ruling that he had lied to the High Court about how he met his former partner Jeff Chevalier. “Concerning the court documents disclosed today, I wish to acknowledge that I did have a four-year relationship with Jeff Chevalier who has now chosen to tell his story to Associated Newspapers, publishers of the Daily Mail, Mail on Sunday and Evening Standard," he said in a BP press statement. "These allegations are full of misleading and erroneous claims. In particular, I deny categorically any allegations of improper conduct relating to BP,” he added. BP chairman Peter Sutherland said: “At John’s specific request, the board instigated a review of the evidence. That review concluded that the allegations of misuse of company assets and resources were unfounded or insubstantive.” Browne said he would step down with immediate effect because he did not want the focus on his private life to detract from the task of running BP. “For a chief executive who has made such an enormous contribution to this great company, it is a tragedy that he should be compelled by his sense of honour to resign in the painful circumstances,” said Mr Sutherland. Browne steered BP to new heights including the merger with Amoco and helped turn the group’s performance around. His last months as chief executive were marred, however, by the close public scrutiny of the group’s poor safety procedures which resulted in the tragic explosion and fire at its ?xml:namespace> Browne said the allegations made by Chevalier make misleading and erroneous claims. But the former BP CEO admitted that he had lied in initial witness statements about how he had met his former partner. “This account, prompted by my embarrassment and shock at the revelations, is a matter of deep regret. It was retracted and corrected. I have apologised unreservedly, and do so again today.” BP said Browne would lose an agreed entitlement and a bonus worth more than £3.5m (€5.1m/$7.0m). He would also forego inclusion in the long-term performance share plan for 2007-2009 with a maximum potential value of some £12m, it added. In January this year, Browne announced that he would step down at the end of J.
http://www.icis.com/Articles/2007/05/01/9025425/lord+browne+resigns+from+bp+over+court+hearing.html
CC-MAIN-2013-20
refinedweb
434
58.72
Creating Vue.js Transitions & Animations. I've prepared live demos on CodePen and GitHub repos to go along with this article. This post digs into Vue.js and the tools it offers with its transition system. It is assumed that you are already comfortable with the basics of Vue.js and CSS transitions. For the sake of brevity and clarity, we won't get into the "logic" used in the demo. Handling Vue.js Transitions & Animations Animations & transitions can bring your site to life and entice users to explore. Animations and transitions are an integral part of UX and UI design. They are, however, easy to get wrong. In complex situations like dealing with lists, they can be nearly impossible to reason about when relying on native JavaScript and CSS. Whenever I ask backend developers why they dislike front end so vehemently, their response is usually somewhere along the lines of "... animations". Even for those of us who are drawn to the field by an urge to create intricate micro-interactions and smooth page transitions, it's not easy work. We often need to rely on CSS for performance reasons, even while working in a mostly JavaScript environment, and that break in the environment can be difficult to manage. This is where frameworks like Vue.js step in, taking the guess-work and clumsy chains of setTimeout functions out of transitions. The Difference Between Transitions and Animations The terms transition and animation are often used interchangeably but are actually different things. - A transitionis a change in the style properties on an element to be transitioned in a single step. They are often handled purely through CSS. - An animationis more complex. They are usually multi-step and sometimes run continuously. Animations will often call on JavaScript to pick up where CSS' lack of logic drops off. It can be confusing, as adding a class could be the trigger for a transition or an animation. Still, it is an important distinction when stepping into the world of Vue because both have very different approaches and toolboxes. Here's an example of transitions in use on Spektrum's site: Using Transitions The simplest way to achieve transition effects on your page is through Vue's <transition> component. It makes things so simple, it almost feels like cheating. Vue will detect if any CSS animations or transitions are being used and will automatically toggle classes on the transitioned content, allowing for a perfectly timed transition system and complete control. First step is to identify our scope. We tell Vue to prepend the transition classes with modal, for example, by setting the component's name attribute. Then to trigger a transition all you need to do is toggle the content's visibility using the v-if or v-show attributes. Vue will add/remove the classes accordingly. There are two "directions" for transitions: enter (for an element going from hidden to visible) and leave (for an element going from visble to hidden). Vue then provides 3 "hooks" that represent different timeframes in the transition: .modal-enter-active/ .modal-leave-active: These will be present throughout the entire transition and should be used to apply your CSS transition declaration. You can also declare styles that need to be applied from beginning to end. .modal-enter/ .modal-leave: Use these classes to define how your element looks before it starts the transition. .modal-enter-to/ .modal-leave-to: You've probably already guessed, these determine the styles you wish to transition towards, the "complete" state. To visualize the whole process, take a look at this chart from Vue's documentation: How does this translate into code? Say we simply want to fade in and out, putting the pieces together would look like this: <button class="modal__open" @Help</button> <transition name="modal"> <section v- <button class="modal__close" @×</button> </section> </transition> .modal-enter-active, .modal-leave-active { transition: opacity 350ms } .modal-enter, .modal-leave-to { opacity: 0 } .modal-leave, .modal-enter-to { opacity: 1 } This is likely the most basic implementation you will come across. Keep in mind that this transition system can also handle content changes. For example, you could react to a change in Vue's dynamic <component>. <transition name="slide"> <component : </transition> .slide-enter { transform: translateX(100%) } .slide-enter-to { transform: translateX(0) } .slide-enter-active { position: absolute } .slide-leave { transform: translateX(0) } .slide-leave-to { transform: translateX(-100%) } .slide-enter-active, .slide-leave-active { transition: all 750ms ease-in-out } Whenever the selectedView changes, the old component will slide out to the left and the new one will enter from the right! Here's a demo that uses these concepts: See the Pen VueJS transition & transition-group demo by Nicolas Udy (@udyux) on CodePen. Transitions on Lists Things get interesting when we start dealing with lists. Be it some bullet points or a grid of blog posts, Vue gives you the <transition-group> component. It is worth noting that while the <transition> component doesn't actually render an element, <transition-group> does. The default behaviour is to use a <span> but you can override this by setting the tag attribute on the <transition-group>. The other gotcha is that all list items need to have a unique key attribute. Vue can then keep track of each item individually and optimize its performance. In our demo, we're looping over the list of companies, each of which has a unique ID. So we can set up our list like so: <transition-group <li class="company" v- <!-- ... --> </li> </transition-group> The most impressive feature of transition-group is how Vue handles changes in the list's order so seamlessly. For this, an additional transition class is available, .company-move (much like the active classes for entering and leaving), which will be applied to list items that are moving about but will remain visible. In the demo, I broke it down a bit more to show how to leverage different states to get a cleaner end result. Here's a simplified and uncluttered version of the styles: /* base */ .company { backface-visibility: hidden; z-index: 1; } /* moving */ .company-move { transition: all 600ms ease-in-out 50ms; } /* appearing */ .company-enter-active { transition: all 300ms ease-out; } /* disappearing */ .company-leave-active { transition: all 200ms ease-in; position: absolute; z-index: 0; } /* appear at / disappear to */ .company-enter, .company-leave-to { opacity: 0; } Using backface-visibility: hidden on an element, even in the absence of 3D transforms, will ensure silky 60fps transitions and avoid fuzzy text rendering during transformations by tricking the browser into leveraging hardware acceleration. In the above snippet, I've set the base style to z-index: 1. This assures that elements staying on page will always appear above elements that are leaving. I also apply a absolute positioning to items that are leaving to remove them from the natural flow, triggering the move transition on the rest of the items. That's all we need! The result is, frankly, almost magic. Using Animations The possibilities and approaches for animation in Vue are virtually endless, so I've chosen one of my favourite techniques to showcase how you could animate your data. We're going to use GSAP's TweenLite library to apply easing functions to our state's changes and let Vue's lightning fast reactivity reflect this on the DOM. Vue is just as comfortable working with inline SVG as it is with HTML. We'll be creating a line graph with 5 points, evenly spaced along the X-axis, whose Y-axis will represent a percentage. You can take a look here at the result. See the Pen SVG path animation with VueJS & TweenLite by Nicolas Udy (@udyux) on CodePen. Let's get started with our component's logic. new Vue({ el: '#app', // this is the data-set that will be animated data() { return { points: { a: -1, b: -1, c: -1, d: -1, e: -1 } } }, // this computed property builds an array of coordinates that // can be used as is in our path computed: { path() { return Object.keys(this.points) // we need to filter the array to remove any // properties TweenLite has added .filter(key => ~'abcde'.indexOf(key)) // calculate X coordinate for 5 points evenly spread // then reverse the data-point, a higher % should // move up but Y coordinates increase downwards .map((key, i) => [i * 100, 100 - this.points[key]]) } }, methods: { // our randomly generated destination values // could be replaced by an array.unshift process setPoint(key) { let duration = this.random(3, 5) let destination = this.random(0, 100) this.animatePoint({ key, duration, destination }) }, // start the tween on this given object key and call setPoint // once complete to start over again, passing back the key animatePoint({ key, duration, destination }) { TweenLite.to(this.points, duration, { [key]: destination, ease: Sine.easeInOut, onComplete: this.setPoint, onCompleteParams: [key] }) }, random(min, max) { return ((Math.random() * (max - min)) + min).toFixed(2) } }, // finally, trigger the whole process when ready mounted() { Object.keys(this.points).forEach(key => { this.setPoint(key) }) } }); Now for the template. <main id="app" class="chart"> <figure class="chart__content"> <svg xmlns="" viewBox="-20 -25 440 125"> <path class="chart__path" : <text v- {{ 100 - (y | 0) + '%' }} </text> </svg> </figure> </main> Notice how we bind our path computed property to the path element's d attribute. We do something similar with the text nodes that output the current value for that point. When TweenLite updates the data, Vue reacts instantly and keeps the DOM in sync. That's really all there is to it! Of course, additional styles were applied to make things pretty, which at this point you might realize is more work then the animation itself! Live demos (CodePen) & GitHub repo Go ahead, browse the live demos or analyze/re-use the code in our open source repo! - The vue-animate GitHub repo - The vue-transitions GitHub repo - The Vue.js transition & transition-group demo - The SVG path animation demo Conclusion I've always been a fan of animations and transitions on the web, but I'm also a stickler for performance. As a result, I'm always very cautious when it comes to relying on JavaScript. However, combining Vue's blazing fast and low-cost reactivity with its ability to manage pure CSS transitions, you would really have to go overboard to have performance issues. It's impressive that such a powerful framework can offer such a simple yet manageable API. The animation demo, including the styling, was built in only 45 minutes. And if you discount the time it took to set up the mock data used in the list-transition, it's achievable in under 2 hours. I don't even want to imagine the migraine-inducing process of building similar setups without Vue, much less how much time it would take! Now get out there and get creative! The use cases go far beyond what we have seen in this post: the only true limitation is your imagination. Don't forget to check out the transitions and animations section in Vue.js' documentation for more information and inspiration. This post originally appeared on Snipcart's blog. Got comments, questions? Add them below!
https://css-tricks.com/creating-vue-js-transitions-animations/
CC-MAIN-2019-22
refinedweb
1,852
56.96
12420/how-to-solve-syntaxerror-unexpected-eof-error-in-python I am trying to parse blockchain using python using the following code: from chainscan import iter_blocks for block in iter_blocks(): if block.height > 10: break for tx in block.txs: print('Hello, tx %s in block %s' % (tx, block)) I am getting this following error: File "<ipython-input-3-06037b89d550>", line 1 for block in iter_blocks(): ^ SyntaxError: unexpected EOF while parsing I have checked the code from my reference and there is no problem in the code but it is still not working. How to solve this? There is not a problem in the code but there is a problem in the indentation. Use the code with proper indentation like this: from chainscan import iter_blocks for block in iter_blocks(): if block.height > 10: break for tx in block.txs: print('Hello, tx %s in block %s' % (tx, block)) This should solve your error I am getting the same error for this code: name ='John' friend = 'Sharon' print('Hello %s, this is %s' % (name, friend) You are missing a parenthesis in your code. The proper code would be: print('Hello %s, this is %s' % (name, friend)) It seems like there is no required ...READ MORE Try compiling and migrating the contract: $ truffle ...READ MORE I also had the same error. I ...READ MORE OCI is open container initiative.. The error ...READ MORE You are facing this error because you ...READ MORE Summary: Both should provide similar reliability of ...READ MORE This will solve your problem import org.apache.commons.codec.binary.Hex; Transaction txn ...READ MORE First try restarting the system and then ...READ MORE I think the docker-compose tool is not ...READ MORE OR At least 1 upper-case and 1 lower-case letter Minimum 8 characters and Maximum 50 characters Already have an account? Sign in.
https://www.edureka.co/community/12420/how-to-solve-syntaxerror-unexpected-eof-error-in-python?show=12421
CC-MAIN-2022-27
refinedweb
308
73.47
I just wrote a command intended to go in the context menu. Is it possible to make the caption dynamic (not animated, just custom each time the menu is built for display)? This isn't exposed to Python yet, will add for the next dev build. Awesome, can't wait! I'd imagine this could be used for labeling the file MRU list too Tried it, it works great. There's a small issue with it when using it on the main menus on Windows though - the flyout menu width grows to fit the text, but never shrinks again. e.g. try this in a menu: import sublime, sublime_plugin foo = True class test(sublime_plugin.TextCommand): def description(self): global foo foo = not foo return "*" * 120 if foo else "i'm small" It works properly for context menus though. Thanks again! What about dynamic content for a menu? It would be great if we could supply a builder that would generate menu items when the menu is posted, similar to how the recent files list is generated, etc. thanks,-Judah The recent files menu isn't actually dynamically generated, some of the items are just hidden, and you can do the same thing from Python. The menu looks like { "command": "open_recent_file", "args": {"index": 0 } }, { "command": "open_recent_file", "args": {"index": 1 } }, { "command": "open_recent_file", "args": {"index": 2 } }, ... The open_recent_file command implements is_visible(self, index) (which plugins can also do), and uses this to give the appearance of a dynamic menu. Could the open_recent_file command be changed so it has a description(self) implementation that returns " - ", where N is the index + 1? Then change the menu file to have corresponding mnemonics? "alt+f,r," is a handy key combo
https://forum.sublimetext.com/t/dynamic-captions-for-menus/2106/3
CC-MAIN-2016-07
refinedweb
284
62.88
K. Kuzzle enables you to build modern web applications and complex IoT networks in no time. Learn how Kuzzle will accelerate your developments 👉 Kuzzle is production-proof, and can be deployed anywhere. With Kuzzle, it is possible to deploy applications that can serve tens of thousands of users with very good performances. The easiest way to start a Kuzzle application is to use Kourou: npx Then you need to run Kuzzle services, Elasticsearch and Redis: kourou app:start-services Finally you can run your application inside Docker with npm run dev:docker Kuzzle is now listening for requests on the port 7512! Your first Kuzzle application is inside the app.ts file. For example, you can add a new API Controller: import { Backend } from 'kuzzle'; const app = new Backend('playground'); app.controller.register('greeting', { actions: { sayHello: { handler: async request => `Hello, ${request.input.args.name}` } } }); app.start() .then(() => { app.log.info('Application started'); }) .catch(console.error); Now try to call your new API action by: npx kourou greeting:sayHello --arg name=Yagmur Learn how to Write an Application. Train yourself and your teams to use Kuzzle to maximize its potential and accelerate the development of your projects. Our teams will be able to meet your needs in terms of expertise and multi-technology support for IoT, mobile/web, backend/frontend, devops. 👉 Get a quote You can consult the public roadmap on Trello. Come and vote for the features you need! 👉 Kuzzle Public Roadmap You're welcome to contribute to Kuzzle! Feel free to report issues, ask for features or even make pull requests! Check our contributing documentation to know about our coding and pull requests rules Kuzzle is published under Apache 2 License.
https://awesomeopensource.com/project/kuzzleio/kuzzle
CC-MAIN-2022-05
refinedweb
282
54.02
I’m trying to connect to MySQL on localhost using PyMySQL: import pymysql conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost') but (both on Python 2.7 and Python 3.2) I get the error: socket.error: [Errno 111] Connection refused pymysql.err.OperationalError: (2003, “Can’t connect to MySQL server on ‘localhost’ (111)”) I’m sure mysqld is running because I can connect using mysql command or phpMyAdmin. Moreover, I can connect using MySQLdb on Python 2 with nearly the same code: import MySQLdb conn = MySQLdb.connect(db='base', user='root', passwd='pwd', host='localhost') It seems that the problem is on PyMySQL side rather than MySQL but I have no idea how to solve it.
https://howtofusion.com/about-python-pymysql-cant-connect-to-mysql-on-localhost.html
CC-MAIN-2022-40
refinedweb
120
58.79
Hi I am a beginner at C programming, and I am going through the K&R book page by page. Currently I'm stuck at exercise 1-13, where I'm supposed to make a program that counts the number of letters in each word in a sentence, and print the results on a horizontal histogram. In this code I'm supposed to use getchar() and arrays. When I run my code and type a sentence, I get an exact copy of that sentence printed out. For some reason, my array is not being printed out. Any help would be greatly appreciated. ======================================== #include <stdio.h> main() { int c, position, i; int length[10]; //array declared position = 0; for (i = 0; i < 10; ++i) //sets all the values in the array to zero length[i] = 0; while ((c = getchar()) != EOF){ if (c != ' ' || c != '\n' || c != '\t'){ //if getchar() does not read a space, tab, or newline (aka, reads a letter), print the character putchar(c); ++position; length[position - '0'] = '*'; //array counts letter by replacing an 0 with a *. } else { //if getchar() encounters a space, tab, or newline, print the array beside the previous word. printf(" "); for (i = 1; i < 11; ++i) printf("%d", length[i]); printf("\n"); for (i = 0; i < 10; ++i) //set all values in array to zero again length[i] = 0; position = 0; } } }
http://forums.devshed.com/programming-42/character-counting-histogram-wont-execute-945928.html
CC-MAIN-2014-35
refinedweb
225
77.37
JavaScript: The Good Parts - Roger Jordan - 3 years ago - Views: Transcription 1 2 3 JavaScript: The Good Parts 4 Other resources from O Reilly Related titles High Performance Web Sites JavaScript and DHTML Cookbook JavaScript: The Definitive Guide Learning JavaScript. 5 JavaScript: The Good Parts Douglas Crockford Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo 6 JavaScript: The Good Parts by Douglas Crockford Copyright 2008 Yahoo! (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) or Editor: Simon St.Laurent Production Editor: Sumita Mukherji Copyeditor: Genevieve d Entremont Proofreader: Sumita Mukherji Indexer: Julie Hawks Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: May 2008: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O Reilly logo are registered trademarks of O Reilly Media, Inc. JavaScript: The Good Parts, the image of a Plain Tiger butterfly, and related trade dress are trademarks of O Reilly Media, Inc. Java is a trademark, a durable and flexible lay-flat binding. ISBN: [M] [7/08] 7 For the Lads: Clement, Philbert, Seymore, Stern, and, lest we forget, C. Twildo. 8 9 Table of Contents Preface xi 1. Good Parts Why JavaScript? 2 Analyzing JavaScript 3 A Simple Testing Ground 4 2. Grammar Whitespace 5 Names 6 Numbers 7 Strings 8 Statements 10 Expressions 15 Literals 17 Functions Objects Object Literals 20 Retrieval 21 Update 22 Reference 22 Prototype 22 Reflection 23 Enumeration 24 Delete 24 Global Abatement 25 vii 10 4. Functions Function Objects 26 Function Literal 27 Invocation 27 Arguments 31 Return 31 Exceptions 32 Augmenting Types 32 Recursion 34 Scope 36 Closure 37 Callbacks 40 Module 40 Cascade 42 Curry 43 Memoization Inheritance Pseudoclassical 47 Object Specifiers 50 Prototypal 50 Functional 52 Parts Arrays Array Literals 58 Length 59 Delete 60 Enumeration 60 Confusion 61 Methods 62 Dimensions Regular Expressions An Example 66 Construction 70 Elements 72 viii Table of Contents 11 8. Methods Style Beautiful Features Appendix A. Awful Parts Appendix B. Bad Parts Appendix C. JSLint Appendix D. Syntax Diagrams Appendix E. JSON Index Table of Contents ix 12 13 Preface1 If we offend, it is with our good will That you should think, we come not to offend, But with good will. To show our simple skill, That is the true beginning of our end. William Shakespeare, A Midsummer Night s Dream This is a book about the JavaScript programming language. It is intended for programmers who, by happenstance or curiosity, are venturing into JavaScript for the first time. It is also intended for programmers who have been working with JavaScript at a novice level and are now ready for a more sophisticated relationship with the language. JavaScript is a surprisingly powerful language. Its unconventionality presents some challenges, but being a small language, it is easily mastered. My goal here is to help youto learn to think in JavaScript. I will show youthe components of the language and start you on the process of discovering the ways those components can be put together. This is not a reference book. It is not exhaustive about the language and its quirks. It doesn t contain everything you ll ever need to know. That stuff you can easily find online. Instead, this book just contains the things that are really important. This is not a book for beginners. Someday I hope to write a JavaScript: The First Parts book, but this is not that book. This is not a book about Ajax or web programming. The focus is exclusively on JavaScript, which is just one of the languages the web developer must master. This is not a book for dummies. This book is small, but it is dense. There is a lot of material packed into it. Don t be discouraged if it takes multiple readings to get it. Your efforts will be rewarded. xi 14 Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, filenames, and file extensions. Constant width Indicates computer coding in a broad sense. This includes commands, options, variables, attributes, keys, requests, functions, methods, types, classes, modules, properties, parameters, values, objects, events, event handlers, XML and XHTML tags, macros, and keywords. Constant width bold Indicates commands or other text that should be typed literally by the user. Using Code Examples This book is here to help youget your job done. In general, youmay use the code in this book in your programs and documentation. You do not need to contact us for permission.: JavaScript: The Good Parts by Douglas Crockford. Copyright 2008 Yahoo! Inc., If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at Safari Books Online When yousee a Safari xii Preface 15 How to Contact Us Please address comments and questions concerning this book to the publisher: O Reilly Media, Inc Gravenstein Highway North Sebastopol, CA (in the United States or Canada) (international or local) (fax) web site at: Acknowledgments I want to thank the reviewers who pointed out my many egregious errors. There are few things better in life than having really smart people point out your blunders. It is even better when they do it before you go public. Thank you, Steve Souders, Bill Scott, Julien Lecomte, Stoyan Stefanov, Eric Miraglia, and Elliotte Rusty Harold. I want to thank the people I worked with at Electric Communities and State Software who helped me discover that deep down there was goodness in this language, especially Chip Morningstar, Randy Farmer, John La, Mark Miller, Scott Shattuck, and Bill Edney. I want to thank Yahoo! Inc. for giving me time to work on this project and for being such a great place to work, and thanks to all members of the Ajax Strike Force, past and present. I also want to thank O Reilly Media, Inc., particularly Mary Treseler, Simon St.Laurent, and Sumita Mukherji for making things go so smoothly. Special thanks to Professor Lisa Drake for all those things she does. And I want to thank the guys in ECMA TC39 who are struggling to make ECMAScript a better language. Finally, thanks to Brendan Eich, the world s most misunderstood programming language designer, without whom this book would not have been necessary. Preface xiii 16 17 Chapter 1 CHAPTER 1 Good Parts1 setting the attractions of my good parts aside I have no other charms. William Shakespeare, The Merry Wives of Windsor nonexistence to global adoption in an alarmingly short period of time. It never had an interval in the lab when it could be tried out and polished. It went straight into Netscape Navigator 2 just as it was, and it was very rough. When Java applets failed, JavaScript became the Language of the Web by default. JavaScript s popularity is almost completely independent of its qualities as a programming language. 1 18. Why JavaScript?are good in some other language and youhave to program in an environment that only supports JavaScript, then youare. 2 Chapter 1: Good Parts 19 Analyzing JavaScript JavaScript is built on some very good ideas and a few very bad ones. The very good ideas include functions, loose typing, dynamic objects, and an expressive object literal notation. The bad ideas include a programming model based on global variables.. The fashion in most programming languages today demands strong typing. The theory is that strong typing allows a compiler to detect a large class of errors at compile time. The sooner we can detect and repair errors, the less they cost us. JavaScript is a loosely typed language, so JavaScript compilers are unable to detect type errors. This can be alarming to people who are coming to JavaScript from strongly typed languages. But it turns out that strong typing does not eliminate the need for careful testing. And I have found in my work that the sorts of errors that strong type checking finds are not the errors I worry about. On the other hand, I find loose typing to be liberating. I don t need to form complex class hierarchies. And I never have to cast or wrestle with the type system to get the behavior that I want. JavaScript has a very powerful object literal notation. Objects can be created simply by listing their components. This notation was the inspiration for JSON, the popular data interchange format. (There will be more about JSON in Appendix E.) A controversial feature in JavaScript is prototypal inheritance. JavaScript has a classfree. JavaScript is much maligned for its choice of key ideas. For the most part, though, those choices were good, if unusual. But there was one choice that was particularly bad: JavaScript depends on global variables for linkage. All of the top-level variables of all compilation units are tossed together in a common namespace called the global object. This is a bad thing because global variables are evil, and in JavaScript they are fundamental. Fortunately, as we will see, JavaScript also gives us the tools to mitigate this problem. In a few cases, we can t ignore the bad parts. There are some unavoidable awful parts, which will be called out as they occur. They will also be summarized in Appendix A. But we will succeed in avoiding most of the bad parts in this book, summarizing much of what was left out in Appendix B. If you want to learn more about the bad parts and how to use them badly, consult any other JavaScript book. Analyzing JavaScript 3 20 The standard that defines JavaScript (aka JScript) is the third edition of The ECMAScript Programming Language, which is available from The language described in this book is a proper subset of ECMAScript. This book does not describe the whole language because it leaves out the bad parts. The treatment here is not exhaustive. It avoids the edge cases. You should, too. There is danger and misery at the edges. Appendix C describes a programming tool called JSLint, a JavaScript parser that can analyze a JavaScript program and report on the bad parts that it contains. JSLint provides a degree of rigor that is generally lacking in JavaScript development. It can give you confidence that your programs contain only the good parts. JavaScript is a language of many contrasts. It contains many errors and sharp edges, so you might wonder, Why should I use JavaScript? There are two answers. The first is that youdon t have a choice. The Web has become an important platform for application development, and JavaScript is the only language that is found in all browsers. It is unfortunate that Java failed in that environment; if it hadn t, there could be a choice for people desiring a strongly typed classical language. But Java did fail and JavaScript is flourishing, so there is evidence that JavaScript did something right. The other answer is that, despite its deficiencies, JavaScript is really good. It is lightweight and expressive. And once youget the hang of it, functional programming is a lot of fun. But in order to use the language well, you must be well informed about its limitations. I will pound on those with some brutality. Don t let that discourage you. The good parts are good enough to compensate for the bad parts. A Simple Testing Ground If youhave a web browser and any text editor, youhave everything youneed to run JavaScript programs. First, make an HTML file with a name like program.html: <html><body><pre><script src="program.js"> </script></pre></body></html> Then, make a file in the same directory with a name like program.js: document.writeln('hello, world!'); Next, open your HTML file in your browser to see the result. Throughout the book, a method method is used to define new methods. This is its definition: Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; ; It will be explained in Chapter 4. 4 Chapter 1: Good Parts 21 Chapter 2 CHAPTER 2 Grammar2 I know it well: I read it in the grammar long ago. William Shakespeare, The Tragedy of Titus Andronicus This chapter introduces the grammar of the good parts of JavaScript, presenting a quick overview of how the language is structured. We will represent the grammar with railroad diagrams. The rules for interpreting these diagrams are simple: You start on the left edge and follow the tracks to the right edge. As you go, you will encounter literals in ovals, and rules or descriptions in rectangles. Any sequence that can be made by following the tracks is legal. Any sequence that cannot be made by following the tracks is not legal. Railroad diagrams with one bar at each end allow whitespace to be inserted between any pair of tokens. Railroad diagrams with two bars at each end do not. The grammar of the good parts presented in this chapter is significantly simpler than the grammar of the whole language. Whitespace Whitespace can take the form of formatting characters or comments. Whitespace is usually insignificant, but it is occasionally necessary to use whitespace to separate sequences of characters that would otherwise be combined into a single token. For example, in: var that = this; the space between var and that cannot be removed, but the other spaces can be removed. 5 22 whitespace / / any character except line end space tab line end * any character except * and / / * / JavaScript offers two forms of comments, block comments formed with /* */ and line-ending comments starting with //. Comments should be used liberally to improve the readability of your programs. Take care that the comments always accurately describe the code. Obsolete comments are worse than no comments. The /* */ form of block comments came from a language called PL/I. PL/I chose those strange pairs as the symbols for comments because they were unlikely to occur in that language s programs, except perhaps in string literals. In JavaScript, those pairs can also occur in regular expression literals, so block comments are not safe for commenting out blocks of code. For example: /* */ var rm_a = /a*/.match(s); causes a syntax error. So, it is recommended that /* */ comments be avoided and // comments be used instead. In this book, // will be used exclusively. Names A name is a letter optionally followed by one or more letters, digits, or underbars. A name cannot be one of these reserved words: abstract boolean break byte case catch char class const continue debugger default delete do double 6 Chapter 2: Grammar 23 else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var volatile void while with name letter digit _ Most of the reserved words in this list are not used in the language. The list does not include some words that should have been reserved but were not, such as undefined, NaN, and Infinity. It is not permitted to name a variable or parameter with a reserved word. Worse, it is not permitted to use a reserved word as the name of an object property in an object literal or following a dot in a refinement. Names are used for statements, variables, parameters, property names, operators, and labels. Numbers number literal integer fraction exponent JavaScript. Numbers 7 24 integer any digit except 0 0 digit fraction. digit exponent e + digit E - represents all values greater than e+308. Numbers have methods (see Chapter 8). JavaScript has a Math object that contains a set of methods that act on numbers. For example, the Math.floor(number) method can be used to convert a number into an integer. Strings. 8 Chapter 2: Grammar 25 string literal " any Unicode character except " and \ and control character " escaped character ' any Unicode character except ' and \ and control character escaped character ' escaped character \ " ' \ / b f n r t u double quote single quote backslash slash backspace formfeed new line carriage return tab 4 hexadecimal digits. Strings 9 26 Two strings containing exactly the same characters in the same order are considered to be the same string. So: 'c' + 'a' + 't' === 'cat' is true. Strings have methods (see Chapter 8): 'cat'.touppercase( ) === 'CAT' Statements var statements var name = expression ;, A compilation unit contains a set of executable statements. In web browsers, each <script> tag delivers a compilation unit that is compiled and immediately executed. Lacking a linker, JavaScript throws them all together in a common global namespace. There is more on global variables in Appendix A. When used inside of a function, the var statement defines the function s private variables. The switch, while, for, and do statements are allowed to have an optional label prefix that interacts with the break statement. Statements tend to be executed in order from top to bottom. The sequence of execution can be altered by the conditional statements (if and switch), by the looping statements (while, for, and do), by the disruptive statements (break, return, and throw), and by function invocation. A block is a set of statements wrapped in curly braces. Unlike many other languages, blocks in JavaScript do not create a new scope, so variables should be defined at the top of the function, not in blocks. The if statement changes the flow of the program based on the value of the expression. The then block is executed if the expression is truthy; otherwise, the optional else branch is taken. 10 Chapter 2: Grammar 27 statements expression statement ; label name : disruptive statement try statement if statement switch statement while statement for statement do statement disruptive statement break statement return statement throw statement block { statements if statement then if ( expression ) block else block Here are the falsy values: false null Statements 11 28 undefined The empty string '' The number 0 The number NaN All other values are truthy, including true, the string 'false', and all objects. switch statement switch ( expression ) { case clause disruptive statement default : statements The switch statement performs a multiway branch. It compares the expression for equality with all of the specified cases. The expression can produce a number or a string. When an exact match is found, the statements of the matching case clause are executed. If there is no match, the optional default statements are executed. case clause case expression : statements A case clause contains one or more case expressions. The case expressions need not be constants. The statement following a clause should be a disruptive statement to prevent fall through into the next case. The break statement can be used to exit from a switch. while statement while ( expression ) block The while statement performs a simple loop. If the expression is falsy, then the loop will break. While the expression is truthy, the block will be executed. The for statement is a more complicated looping statement. It comes in two forms. The conventional form is controlled by three optional clauses: the initialization, the condition, and the increment. First, the initialization is done, which typically initializes the loop variable. Then, the condition is evaluated. Typically, this tests the loop variable against a completion criterion. If the condition is omitted, then a condition of true is assumed. If the condition is falsy, the loop breaks. Otherwise, the block is executed, then the increment executes, and then the loop repeats with the condition. 12 Chapter 2: Grammar JavaScript: The Good Parts by Douglas Crockford 1 JavaScript: The Good Parts by Douglas Crockford Publisher: O'Reilly Pub Date: May 2, 2008 Print ISBN-13: 978-0-596-51774-8 Pages: 170 Table of Contents Index Overview Most programming languages contain , Pemrograman Dasar. Basic Elements Of Java Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle: JavaScript: Control Statements I 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University (revised October 8, 2004) 1 Introduction The PCAT language (Pascal Clone Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors School of Informatics, University of Edinburgh CS1Ah Lecture Note 5 Java Expressions Many Java statements can contain expressions, which are program phrases that tell how to compute a data value. Expressions can involve arithmetic calculation and method Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle A First Book of C++ Chapter 2 Data Types, Declarations, and Displays A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- switch Multiple-Selection Statement switch Multiple-Selection Statement (This feature is rarely useful, although it s perfect for programming the iterative song The Twelve Days of Christmas!) If no match occurs, the default case is executed, Course: Introduction to Java Using Eclipse Training Course: Introduction to Java Using Eclipse Training Course Length: Duration: 5 days Course Code: WA1278 DESCRIPTION: This course introduces the Java programming language and how to develop Java applications Java (12 Weeks) Introduction to Java Programming Language Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short HTML5/CSS3/JavaScript Programming HTML5/CSS3/JavaScript Programming Description: Prerequisites: Audience: Length: This class is designed for students that have experience with basic HTML concepts that wish to learn about HTML Version 5, University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python Introduction Welcome to our Python sessions. University of Hull Department of Computer Science Wrestling with Python Week 01 Playing with Python Vsn. 1.0 Rob Miles 2013 Please follow the instructions carefully. Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables CMSC 131 - Lecture Outlines - set... Concepts and terminology in the Simula Programming Language Concepts and terminology in the Simula Programming Language An introduction for new readers of Simula literature Stein Krogdahl Department of Informatics University of Oslo, Norway April 2010 Introduction 6.170 Tutorial 3 - Ruby Basics 6.170 Tutorial 3 - Ruby Basics Prerequisites 1. Have Ruby installed on your computer a. If you use Mac/Linux, Ruby should already be preinstalled on your machine. b. If you have a Windows Machine, you Chapter 2 Introduction to Java programming Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break C Compiler Targeting the Java Virtual Machine C Compiler Targeting the Java Virtual Machine Jack Pien Senior Honors Thesis (Advisor: Javed A. Aslam) Dartmouth College Computer Science Technical Report PCS-TR98-334 May 30, 1998 Abstract One of the 09336863931 : provid.ir provid.ir 09336863931 : NET Architecture Core CSharp o Variable o Variable Scope o Type Inference o Namespaces o Preprocessor Directives Statements and Flow of Execution o If Statement o Switch Statement Programming in Access VBA PART I Programming in Access VBA In this part, you will learn all about how Visual Basic for Applications (VBA) works for Access 2010. A number of new VBA features have been incorporated into the 2010 Introduction to Java A First Look Introduction to Java A First Look Java is a second or third generation object language Integrates many of best features Smalltalk C++ Like Smalltalk Everything is an object Interpreted or just in time 1 Introduction. 2 An Interpreter. 2.1 Handling Source Code 1 Introduction The purpose of this assignment is to write an interpreter for a small subset of the Lisp programming language. The interpreter should be able to perform simple arithmetic and comparisons Programming for MSc Part I Herbert Martin Dietze University of Buckingham herbert@the-little-red-haired-girl.org July 24, 2001 Abstract The course introduces the C programming language and fundamental software development techniques. Lecture 1 Notes: Introduction Introduction to C++ January 4, 2011 Massachusetts Institute of Technology 6.096 Lecture 1 Notes: Introduction 1 Compiled Languages and C++ 1.1 Why Use a Language Like C++? At its core, a computer is just C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with the basic components of a C++ The Basics of C Programming. Marshall Brain The Basics of C Programming Marshall Brain Last updated: October 30, 2013 Contents 1 C programming 1 What is C?................................. 2 The simplest C program, I........................ 2 Spacing WEB MANAGEMENT CT211. Fall 2012 PACKET II Fall 2012 CT211 WEB MANAGEMENT PACKET II This packet includes the mandatory assignments for each Chapter that is covered in the required course textbooks. All assignments must be completed on the date Introduction to Python WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language Java Programming Fundamentals Lecture 1 Part I Java Programming Fundamentals Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Introduction to Java We start by making a few Encoding Text with a Small Alphabet Chapter 2 Encoding Text with a Small Alphabet Given the nature of the Internet, we can break the process of understanding how information is transmitted into two components. First, we have to figure out Hypercosm. Studio. Hypercosm Studio Hypercosm Studio Guide 3 Revision: November 2005 Copyright 2005 Hypercosm LLC All rights reserved. Hypercosm, OMAR, Hypercosm 3D Player, and Hypercosm Studio are trademarks WIRIS quizzes web services Getting started with PHP and Java WIRIS quizzes web services Getting started with PHP and Java Document Release: 1.3 2011 march, Maths for More Summary This document provides client examples for PHP and Java. Contents WIRIS. Custom Javascript In Planning A Hyperion White Paper Custom Javascript In Planning Creative ways to provide custom Web forms This paper describes several of the methods that can be used to tailor Hyperion Planning Web forms. Hyperion Introduction to Web Services Department of Computer Science Imperial College London CERN School of Computing (icsc), 2005 Geneva, Switzerland 1 Fundamental Concepts Architectures & escience example 2 Distributed Computing Technologies Going Above and Beyond Whitepaper Going Above and Beyond Using Advanced Techniques to Create Customized HTML Templates August 3, 2010 Copyright 2010 L-Soft international, Inc. Information in this document is subject to change AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall [Refer Slide Time: 05:10] Principles of Programming Languages Prof: S. Arun Kumar Department of Computer Science and Engineering Indian Institute of Technology Delhi Lecture no 7 Lecture Title: Syntactic Classes Welcome to lecture Want to read more? It s also available at your favorite book retailer, including the ibookstore, the Android Marketplace, and Amazon.com. Want to read more? You can buy this book at oreilly.com in print and ebook format. Buy 2 books, get the 3rd FREE! Use discount code: OPC10 All orders over $29.95 qualify for free shipping within the US. C programming. Intro to syntax & basic operations C programming Intro to syntax & basic operations Example 1: simple calculation with I/O Program, line by line Line 1: preprocessor directive; used to incorporate code from existing library not) 2. Names, Scopes, and Bindings 2. Names, Scopes, and Bindings Binding, Lifetime, Static Scope, Encapsulation and Modules, Dynamic Scope Copyright 2010 by John S. Mallozzi Names Variables Bindings Binding time Language design issues Logic Instructions and Assignments Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story. Visualizing Software Projects in JavaScript Visualizing Software Projects in JavaScript Tim Disney Abstract Visualization techniques have been used to help programmers deepen their understanding of large software projects. However the existing visualization CS 1133, LAB 2: FUNCTIONS AND TESTING CS 1133, LAB 2: FUNCTIONS AND TESTING First Name: Last Name: NetID: The purpose of this lab is to help you to better understand functions: Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named CS 111 Classes I 1. Software Organization View to this point: CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects Java Review (Essentials of Java for Hadoop) Java Review (Essentials of Java for Hadoop) Have You Joined Our LinkedIn Group? What is Java? Java JRE - Java is not just a programming language but it is a complete platform for object oriented programming. 6.087 Lecture 3 January 13, 2010 6.087 Lecture 3 January 13, 2010 Review Blocks and Compound Statements Control Flow Conditional Statements Loops Functions Modular Programming Variable Scope Static Variables Register Variables 1 Review:
http://docplayer.net/284846-Javascript-the-good-parts.html
CC-MAIN-2018-39
refinedweb
5,079
53.71
Archive Things to do on your next game jam I just wrapped up a game jam at the Art Institue over the past weekend (screenshots pending). We didn’t get much in the way of innovative gameplay implemented, mainly just expanding the behaviors that Gamini has. Ideally these game jams should be more about totally radical ideas. You have 3 days at most so you’re not making a “real” game, so why not go nuts on the design. Something that, to me, seems like a gam-jam kind of project and pretty interesting is The Unfinished Swan by Ian Dallas. They have a really cool video on the site that’s definately worth your time. Gemini dev update #2 So much has changed since my last update. First off, we’ve created a system for managers to be plugged into the basic game state. The three core managers are game object, update and render. The default versions of these three get auto-added to a game state unless you specify your own to use. Why might this be useful or interesting you ask? Well consider the problem of one behavior we were working on. CollidableWhenMoving hooks into a game object’s move method using on_after_move. The behavior then needs to check the object that just moved against anything it might have collided with. There’s a basic behavior (BoundingBoxCollidable) that does the actual coordinate checking, but CollidableWhenMoving still needs to get a list of other game objects to check against. Previously, the behavior was keeping an internal list of objects it had been added to. This sort of worked, except that it used class level variables which really breaks down if you want to be able to pause, swap to another state for a while and then come back. Also, other collision’ish behaviors would have to maintain their own lists of game objects and there was no way to share those lists so CollidableWhenMoving could only collide with other CollidableWhenMoving objects. Oh, and it was also an ugly hack. So the answer was clear, we needed a way for behaviors to generically get information. This evolved into the idea of a state having some number of managers that could provide that information. So now after the movement of a game object, CollidableWhenMoving can query the GameObjectManager registered on the state and ask it for an appropriate list of objects to check against. Another big improvement was the idea that behaviors should be able to be used as interfaces. So kind_of? was enhanced to check against behaviors as well. Also a new behavior class method: depends_on_kind_of was added to allow a behavior to express the need for another behavior witout having to specify the type. Unlike depends_on, the depends_on_kind_of method does not require or add any dependant behaviors, it simply sets up a instantiation check that will raise an exception if there is not a sub-class of the declared behavior on the object. This allows you to depend on some kind of algorithm object, even though you don’t care which one. The keymap concept has been enhanced to give you some fairly nice syntax for setting up input processing. Here’s the keymap file for the example pong-like game. map KEY_HELD, :source_value => Input::KEY_Q, :destination_type => :p1_paddle_movement, :destination_value => :up map KEY_HELD, :source_value => Input::KEY_A, :destination_type => :p1_paddle_movement, :destination_value => :down map KEY_HELD, :source_value => Input::KEY_O, :destination_type => :p2_paddle_movement, :destination_value => :up map KEY_HELD, :source_value => Input::KEY_L, :destination_type => :p2_paddle_movement, :destination_value => :down The destination_type and destination_value are totally arbitrary and should be customized to make sense for each particular game. Other supported input map types are key_pressed, key_released, mouse_moved and mouse_button_pressed/released. Finally, we’ve split out the example game into the examples directory. It’s now an actual game with animating sprites, scores and two player controls.? Gemini dev update #1 Some of my previous posts regarding Gemini seemed to have garnered some attention thanks to someone posting one of them to DZone (thanks whoever that was). So, since there’s no official home page with nice docs and tutorials and such I decided I would just keep a more public journal of the development progress of Gemini until those things are actually warranted. So, to bring people up to speed on this Gemini thing. It’s a JRuby game engine that sits on top of the Java based Slick library which itself uses OpenGL via LWJGL (that enough layers for ya?). Gemini’s secret sauce is the idea that your game logic should not be in a big monolithic while loop. Of course your game needs the basic game loop ingredients of checking for input, updating the game state and redrawing the scene but is a big while loop really the best place for all that? So we started with the idea of game objects as the basic “thing” that exists in the world. Game objects in reality are really just empty containers for you to attach behaviors to, without any behaviors they aren’t really much of a “thing”. So, game objects via behaviors become the centerpoint of the game development effort. To that end game objects support the idea of adding and removing behaviors and behaviors understand the idea of dependencies. With that in place, you can create a game object that has a sprite, can move around and collide with other things and has callbacks for all its events in just a few lines. class Ball < Gemini::GameObject has_behavior :UpdatesAtConsistantRate has_behavior :BoundingBoxCollidable has_behavior :Sprite end [/sourcecode] Now, this doesn't tell the Ball object, what sprite to use, what to do on updates, what sorts of things to collide with, etc. Behaviors add methods to the game object they are attached to; methods that we can use in the load method to set up all our properties. [sourcecode lang='ruby'] # the x= and y= methods are added by BoundingBoxCollidable which depends on # Movable2D which depends on Spatial which provides the x= and y= (phew!) def load collides_with_tags :wall preferred_collision_check BoundingBoxCollidable::TAGS self.image = "ball.png" self.updates_per_second = 30 self.x = rand(640 - width) self.y = rand(480 - height) @vector = [rand(5) - 3, rand(5) - 3] end [/sourcecode] Those self.= calls are there to force the method to be invoked instead of creating and assigning to a local variable. So with that done, the only pieces left to get a bunch of balls bouncing around on the screen is to say what happens on each updated (the tick method gets called by the UpdatesAtConsistantRate behavior) and to say what happens when the ball runs into a wall (defined by anything with a :wall tag). [sourcecode lang='ruby'] # The on_ callback system is instance level and thus would be added to the load method on_collided do |event, continue| vector[0] = -1 if x > (640 – width) vector[0] = 1 if x < 0 vector[1] = -1 if y > (480 – height) vector[1] = 1 if y < 0 end # The move method was added by BoundingBoxCollidable which depends on Movable2D def tick move(x + @vector[0], y + @vector[1]) end [/sourcecode] So, plenty of hard coded stuff that we plan to swap out for a relational positioning system (0 = left side of screen, 1 = right side of screen) and the collision handler could probably be a bit prettier but it's a start. So where is Gemini today? Well, certainly not in a position to make an actual game with. There's infrastructure for our concepts of behaviors and game objects, there's an internal message queue which allows game objects to communicate asynchronously and in a totally decoupled manner (it's also going to be used for stuff like input handling). The next two components to start hacking on are the input system and a basic GUI system which my associate Logan Barnett will be heading up. Beyond that there are lots of places to hit up for performance improvements including but no limited to moving various parts over into Java based libs. Certainly something computationally heavy like a physics engine would be a great candidate for Java, and thankfully there are several to choose from (plus all the C based ones that have simply been wrapped in Java). So the future is bright, we can already move a good number of sprites around doing collision detection with zero optimizations and the behavior based system appears to have long legs in terms of allowing us to implement everything from keyboard input to playing sounds to moving as part of a cutscene as part of a behavior. 50% performance boost, for free? Wouldn’t it be nice to live in a world where you can wake up one day and have some project of yours just magically run 50% faster? Well my friends, JRuby is a world of mystery and amazement. In the past few days the JRuby team has been working feverishly on their Java integration rewrite. Along the way Charles Nutter managed to clean up the number of layers a Ruby call had to go through to get to Java. The net result: my test case for Gemini that I posted about earlier when from a frame rate of 27 fps to 40 fps. None of my actual code changed, I just swapped out the jruby.jar for a newer build. Swapping them back takes me back down to the 27 fps range. So, mana does fall from heaven occasionally, at least in JRuby land. Java game library + JRuby + awesome DSL = Gemini I’ve been working with JRuby to build high level systems on top of powerful Java libraries for about 2 years now. My most successful endeavor has been Monkeybars, a libarary for making Swing a lot easier to use. My other project has been in the game development arena. The project name is Gemini, and although it’s not nearly as advanced as Monkeybars, I was able to get to a significant point over the weekend. Yes, here in all its glory, the simple “crapton of sprites bouncing back and forth demo”. Now you’re probably saying, big deal, I can do that in like 40 lines of code in <insert favorite programming language/framework> and no doubt you would be correct. What’s interesting about the way Gemini does things is in how it gives you an extremely flexible way of compositing together your game objects and your application as a whole. The code to get this going using Gemini is pretty straightforward. We have a game state that is loaded by Gemini when it starts up. That game state then instantiates 1000 of our game objects and they proceed to load their images and care for their own logic of bouncing around on the screen. Here’s the code in main.rb that kicks off the app: require 'gemini' Gemini::Main.new("Test game", 640, 480) And here is the state that is loaded by default when Gemini runs: main_state.rb class MainState < Gemini::BaseState def load @sprites = [] 1000.times {@sprites << Duke.new} end def update(delta) @sprites.each { |sprite| sprite.update(delta) } end def render(graphics) @sprites.each { |sprite| sprite.draw } end end [/sourcecode] Finally we have the Duke class that was instantiated in the MainGame class: [sourcecode lang='ruby'] class Duke < Gemini::GameObject has_behavior :Movable2D has_behavior :Sprite has_behavior :UpdatesAtConsistantRate def load self.image = "duke.png" self.updates_per_second = 30 @direction = :right self.x = rand(640 - image.width) self.y = rand(480 - image.height) end def tick if x > (640 – image.width) || x < 0 @direction = @direction == :right ? :left : :right end self.x = x + (@direction == :right ? 1 : -1) end end [/sourcecode] Apart from some hackish ternary ifs in the Duke class I think the whole thing is pretty darn readable, especially considering all that it is doing. As you can see, everything is extremely declarative including those has_behavior calls in the Duke class. Those nifty bits of metaprogramming bring in all the crunchy goodness of the class and make the x, y, image and updates_per_second methods appear. Movable2D gives us a move method and also pulls in the Positional2D behavior that provides the x and y methods. UpdatesAtConsistantRate gives us an update method that calls tick at the rate specified by updates_per_second. Finally the Sprite behavior gives us the image method and the draw method that gets called in the MainGame class. Most of this is bare bones at the moment. What if you don't have the UpdatesAtConsistantRate? When update is called you asplode. Same for Sprite / render. So clearly a more flexible game state is needed, probably involving the game object behaviors auto-registering themselves with the game state to be called during an update/render cycle. But as a whole I'm quite happy with the way Gemini is starting to shape up. Next on the agenda is getting keyboard mapping hooked into the RecievesKeyboardEvents behavior so you can control duke, then we'll have what could pass for a real game.
https://dkoontz.wordpress.com/tag/gemini/
CC-MAIN-2017-17
refinedweb
2,156
61.06
0 I'm currently taking Java I and I have to write a program that reads 5 integers and determines and prints the largest and smallest numbers without using an array. I have to only use the if statements. I can't figure out how to make the if statement apply to 5 variables and manipulate all of them. I'm using the Deitel 8th edition How to Program book. I can't figure out how to make the if statement compare all five. This is due today and I have tried contacting my teacher and a classmate and neither have responded. Here is what I have so far: import java.util.Scanner; public class LargestAndSmallestIntegers { public static void main(String[] args) { Scanner input = new Scanner( System.in); //set variables int num1; int num2; int num3; int num4; int num5; System.out.println(" Enter first ineger: " ); //prompt num1 = input.nextInt(); System.out.println(" Enter second integer: " ); //prompt num2 = input.nextInt(); System.out.println(" Enter third integer: " ); //prompt num3 = input.nextInt(); System.out.println(" Enter fourth integer: " ); //prompt num4 = input.nextInt(); System.out.println(" Enter fifth integer: " ); //prompt num5 = input.nextInt(); if (num1 > num2) System.out.printf("%d", num1); } } Edited 3 Years Ago by happygeek: fixed formatting
https://www.daniweb.com/programming/software-development/threads/256043/need-help-with-java-simple-largest-smallest-number-program
CC-MAIN-2017-04
refinedweb
206
60.01
Pool of instances vs new() Tony Smith Ranch Hand Joined: Mar 15, 2005 Posts: 77 posted Oct 16, 2006 15:40:00 0 A question has come up and I'd like some input. We're developing a web app, we get up to perhaps 5 hits/second. The work is done by routines which create a lightweight pojo, populate it from the web page, send it off (think pre-Cambrian RPC), and produce a populated pojo. There are many of these pojos and a typical web action could cause perhaps 5 sets of requests and responses to be created. So that's perhaps 50 new object creations/sec. One developer is a total Luddite and prefers low-tech easy solutions. He's comfortable with making new input and output pojos as they are needed and letting the garbage collector do what comes naturally. That would be me The other developer wants to be as efficient as possible and is talking about creating a cache of pojos and reuse them to reduce work on the garbage collector. Now the pros and cons of the first approach are clear. It's easy and requires no additional code. It is easier to test . It has possibly garbage collection issues as its "con." The pros and cons of the second approach aren't as clear. The pros are possible efficiency. The cons are more numerous: 1) Now you need to write some caching code. That's more to break and test. 2) The caching code needs to be synchronized. A little contention can remove any efficiencies gained, I'd think. 3) There are perhaps a thousand pojos so you need 1000 caches. You can make a class which can cache any of them. But at some point you have to create a new instance of the desired class. The developer is proposing that we do this using reflection by specifying the full package-and-class as a String and creating an instance in the caching class. Something like: MyPojoInterface pojo12 = poolObject.getInstance("com.this.that.Pojo12"); The String serves two purposes - it could be a hashkey index for the pool, and it also allows the pool class to instanciate it if we need a new instance. That may work but to me it is quite stinky. If we passed Pojo12.class at least we wouldn't be pretending that we have loose coupling. 4) After you're done you have to remember to release your pojos back to the cache. So that's more code and testing . We're talking C-language-like memory leaks here. Opinions please. I don't want to be a total ogre about it but I haven't had a garbage collection issues in years. Jim Yingst Wanderer Sheriff Joined: Jan 30, 2000 Posts: 18671 posted Oct 16, 2006 16:30:00 0 I pretty much agree with you. Generally the coding and maintenance hassles of object caching outweigh gains, unless the objects are sufficiently "heavyweight". The classic example of a heavyweight object being a Connection, since it takes considerably more time to create than a typical POJO. Threads are also often worth pooling. Other objects might be - usually if they have links to external resources beyond the data fields of the object itself. I.e., if it's more than just a POJO. (Depending how you define POJO; it's a bit subjective.) At the very least, I'd develop the simpler (cacheless) solution first , and see how well it performs. A simple way to see how much time is consumed by GC is by invoking the JVM with java -verbose:gc. How to do this in a web server depends on the web server, I guess, but somewhere there's a JVM being invoked to kick it off, usually in the startup script. Just tweak the script to include the -verbose:gc option, and see what the output looks like. (Should go to standard out, wherever that's routed to.) My gut feeling is, creating and GCing 50 POJOs / second doesn't sound like a very big deal Modern garbage collectors are often pretty fast (especcially compared to the earliest releases) and presuming they're going to be slow is often a mistake. To add to your list of potential problems with caching, there's the possibility that you may accidentally bleed state from one request to another, if you fail to properly clear out the data in the POJO when it's returned to the cache. Typically you need a clear() method or something similar to reset the fields. Which is just another thing to maintain - you may add a field to the POJO, but forget to add it to the clear() method. Alternately if you construct a new object, it's much more likely that the fields were properly initialized to whatever their defaults should be. In the event you can't convince your coworker not to waste time on this, you may benefit from introducing some sort of factories (possibly abstract) to obtain POJO instances from, which can hide whether the instances are new or cached. A simple implementation: public class FooHome { public Foo getFoo() { return new Foo(); } public void release(Foo f) { /* do nothing */ } } You can use things like this to create your POJOs, and the other developer will know that they may replace this implementation with a more complex cache, but maybe not right away. And if they do so anyway, putting in a more complex implementation, you can easily revert to a simpler solution later, either temporarily or permanently. This can be a useful way of checking to see if the cache solution is really providing any benefits, or not. And if not, maybe you can use this to help convince the other developer to stop wasting more time. Or to convince your mutual boss that she should find you a more productive co-worker. [ October 16, 2006: Message edited by: Jim Yingst ] "I'm not back." - Bill Harding, Twister Ilja Preuss author Sheriff Joined: Jul 11, 2001 Posts: 14112 posted Oct 17, 2006 03:06:00 0 Just want to strengthen Jim's point: modern garbage collectors are *very* efficient in collecting short lived objects. It's what they are optimized Tony Smith Ranch Hand Joined: Mar 15, 2005 Posts: 77 posted Oct 17, 2006 06:17:00 0 Thank you for the responses. When I say pojo, I mean an object that has a lightweight constructor, has no remarkable memory requirements, and has no links to external resources such as db connections or threads. In this case, the pojos are subclasses of a baseclass but the same rules apply to the base class. So far then, we don't see a reason to pool/cache pojos. (revision - Upon consideration, the reference to 1000 classes in the first post was an exageration, we really have around 400 matched pairs of pojos. It hardly matters, but hey...) Now, the "problem" with the factory solution above is that I have something like 400 (matching) pojo pairs, a builder and debuilder. If I add a factory in that fashion, I need 400 factories if they are explicit, and 1 if they aren't. But if they aren't explicit I have to deal with the co-worker wanting to pass the package-and-class as a String... (aside - the pojos are all generated by a java utility that consumes a DDL-ish file. I could just as easily generate the factory classes at the same time. So it would be no "additional" code once the code generator was enhanced...) That, however, seems to be a different issue. Issue #1 is that there seems to be no real lift in caching my pojos. [ October 17, 2006: Message edited by: Tony Smith ] [ October 17, 2006: Message edited by: Tony Smith ] William Brogden Author and all-around good cowpoke Rancher Joined: Mar 22, 2000 Posts: 12674 5 posted Oct 17, 2006 07:05:00 0 For a laugh, google for "premature optimization evil" Trying to come up with spiffy fixes for problems that may not exist is a recipe for yet another project that is late and full of bugs. Bill Jim Yingst Wanderer Sheriff Joined: Jan 30, 2000 Posts: 18671 posted Oct 17, 2006 11:15:00 0 The problems with the factory solution seem to be largely addressed by the fact you're using code generation here. And the individual factories can be kept simple by putting much of hte functionality in an abstract bast class. (Or use composition rather than inheritance, maybe.) This isn't a road I'd really want to go down, but my point is that if you are unable to dissuade your co-worker from a caching solution, try to guide that solution in a form that makes it easy to switch between a caching solution and a non-cacheing solution. These factories I'm talking about would be part of the caching solution - quite possibly they'd be the caches themselves. But from the outside, we don't need to know whether they use caching or not. Anyway, yeah, we all seem to agree that using caching seems pretty silly at this point. The factory stuff is just a possible compromise if you can't dissuade your co-worker. I would also note that there's one other use case where caching might make sense - that's if you have a large number of POJOs with identical contents, and you can make the POJOs immutable. Then you may get significant benefits from sharing those immutable objects among all clients who need a POJO with the same content. Like the String pool, for example. At this point there seems to be no particular reason to think this is the case for you, so it's, again, premature optimization. But it might come up later... [ October 17, 2006: Message edited by: Jim Yingst ] Tony Smith Ranch Hand Joined: Mar 15, 2005 Posts: 77 posted Oct 17, 2006 13:28:00 0 Thanks for the suggestions, again. I feel a lot better. The truth of the matter is that the co-worker is actually my consultant and will do what I say. I sought the reality check here since I didn't want to be a totally close-minded ogre. The consultants we have are pretty decent and knowledgable people and not wisely dismissed out-of-hand. The pool is nixed since he can't give an example of where it is beneficial while the cons are considerable. He's pretty adamant, however, that the pojo creation should be limited to one place. I'd personally hammer the instanciation directly into the code. He was uncomfortable with it, so what I offered was similar to the suggestion above: 1) ReqPojo x = AFactoryThing.get(ReqPojo.class); Which is explicit, which I like, but the creation (or recycling) of the instance of ReqPojo is controlled in AFactoryThing.get(). The get() method would simply return a new instance of the class passed in until the time comes when it becomes insufficient, if ever. 2) ReqPojo x = ReqPojo.getInstance(); Where the static getInstance() method invokes a method in the super class, passing ReqPojo.class as an argument. This removes the AFactoryThing while allowing it to be easily inserted into the super class later. [ October 17, 2006: Message edited by: Tony Smith ] Don't get me started about those stupid light bulbs . subject: Pool of instances vs new() Similar Threads Using Unreferenced vs a daemon thread lock question (regarding client ID Object Caching? Moving bean logic to regular java classes String objects creation All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/381215/java/java/Pool-instances
CC-MAIN-2014-15
refinedweb
1,955
69.92
Hi, I am compiling the following simple program on g++ under cygwin: insertThe compilation is fine, but I get a seg fault on the line *p = 0 at run-time and I have no idea why.The compilation is fine, but I get a seg fault on the line *p = 0 at run-time and I have no idea why.Code:#include<stdlib.h> using namespace std; int main() { int *p; *p = 0; } GDB gives: Starting program: /home/David/basic.out Program received signal SIGSEGV, Segmentation fault. 0x0040107d in main () at basicTest.c:8 8 *p = 1; Any help would be greatly appreciated. Thanks, Dave.
http://cboard.cprogramming.com/cplusplus-programming/85978-seg-fault-trivial-pointer-assignment.html
CC-MAIN-2016-18
refinedweb
105
64.2
My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move every moment. Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing root.mainloop() move() <b1-motion> Use the after method on the Tk object: from tkinter import * root = Tk() def task(): print("hello") root.after(2000, task) # reschedule event in 2 seconds root.after(2000, task) root.mainloop() Here's the declaration and documentation for the after method: def after(self, ms, func=None, *args): """Call function once after given time. MS specifies the time in milliseconds. FUNC gives the function which shall be called. Additional parameters are given as parameters to the function call. Return identifier to cancel scheduling with after_cancel."""
https://codedump.io/share/t4nvdgXcZ2IR/1/how-do-you-run-your-own-code-alongside-tkinter39s-event-loop
CC-MAIN-2017-34
refinedweb
156
66.84
dask.distributedCluster Dask is a parallel processing library that provides various APIs for performing parallel processing in a different way on different types of data structures. We has already discussed about dask APIs like dask.bag, dask.delayed, dask.distributed, etc in separate tutorials. We have also covered a basic introduction of all APIs in our dask.bag tutorial. As a part of this tutorial, we are going further and introducing other important topics like global variables, locks, and publish/subscribe patterns which are commonly used in parallel processing. This kind of primitives lets work coordination happen between workers and clients. Dask provides each of these coordination primitives which lets us handle shared data without it getting corrupted when shared between various processes. We'll be discussing each one with various examples below. Below is a list of classes available in dask.distributed the package which we'll be discussing as a part of this tutorial: We'll be going through each of these classes and explain each with examples. We'll start by creating dask.distributed the cluster which will hold a list of workers for running tasks in parallel. dask.distributedCluster ¶ We can create a dask cluster on a local machine by creating a client object as described below. It'll create consisting of workers the same as a number of cores on a computer. Please refer to our tutorial on dask.distribtued if you want to know different ways to create clusters. We'll be using this client object to submit tasks to the worker in clusters. from dask.distributed import Client client = Client() client We generally declare constant variables as global variables in python which can be accessed by any part of an application. We might need global variables in parallel processing applications as well. Dask provides us with a way to keep global variables using Variable class from dask.distributed. We'll be explaining below its the usage with examples. It provides get() and set() which lets us get and set values of global variable. from dask.distributed import Variable Below we have declared global variable y which can be accessed by any method running in parallel on dask workers. We have defined a method named slow_pow() which raises the number passed to it to the power of value set in the global variable. We loop through 1-10 and call slow_pow() to get the power of 5 for each number in parallel. global_var = Variable(name="y") global_var.set(5) import time def slow_pow(x): time.sleep(1) y = global_var.get() return x**y %%time futures = [] for i in range(1,11): future = client.submit(slow_pow, i) futures.append(future) [f.result() for f in futures] CPU times: user 312 ms, sys: 53.7 ms, total: 366 ms Wall time: 3.13 s [1, 32, 243, 1024, 3125, 7776, 16807, 32768, 59049, 100000] Below we have designed another example demonstrating usage of the global variables. Here we first scatter the value of numpy array using scatter() method which distributes values to all workers and has got reference future to it. We have set this reference future as a global variable that can be evaluated on all workers to get the value of an array. import numpy as np arr = np.arange(1,11) future = client.scatter(arr, broadcast=False) global_var = Variable(name="array") global_var.set(future) %%time def slow_add(x): time.sleep(1) future = global_var.get() return x + future.result()[x-1] futures = [] for i in range(1,11): future = client.submit(slow_add, i) futures.append(future) [f.result() for f in futures] CPU times: user 473 ms, sys: 91.5 ms, total: 565 ms Wall time: 3.43 s [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] Queues are another data structure available in dask which can be used to share data between workers or workers and clients. We can create a queue by using the Queue class of dask.distributed module. It let us declare the name of the queue as well as specify the maximum size of the queue. If we don't specify max size then it let us grow the queue as long as we want. We can use a queue to pass any kind of data like int, float, dict, list, etc. Queues are managed by schedulers hence everything passed between workers or clients 7 workers will route through the scheduler. Queues are not ideal for moving a long amount of data. It’s well suited for a small amount of data or futures (futures can point to a large amounts of data). from dask.distributed import Queue Below we have declared queue which we'll be using to collect error messages when the function fails. We have created a function named slow_pow() which accepts two arguments x and y. It raises x to the power of y and returns the result. If it fails then we capture the error and put error details into the queue. We then execute function 10 times from 1-10 passing it index as x and y as 5 if an index is even else string 5 if an index is odd. We then loop through futures and when we can't get results we retrieve error detail from the queue. queue = Queue(name="Exceptions") def slow_pow(x, y): try: time.sleep(1) return x ** y except Exception as e: queue.put("{} ** {} Failed : {}".format(x,y, str(e))) return None futures = [] for i in range(1,11): f = client.submit(slow_pow, i, 5 if i%2==0 else "5") futures.append(f) for f in futures: res = f.result() if not res: print(queue.get()) else: print(res) 9 ** 5 Failed : unsupported operand type(s) for ** or pow(): 'int' and 'str' 32 7 ** 5 Failed : unsupported operand type(s) for ** or pow(): 'int' and 'str' 1024 5 ** 5 Failed : unsupported operand type(s) for ** or pow(): 'int' and 'str' 7776 3 ** 5 Failed : unsupported operand type(s) for ** or pow(): 'int' and 'str' 32768 1 ** 5 Failed : unsupported operand type(s) for ** or pow(): 'int' and 'str' 100000 Locks are very useful primitive when you are working with shared data. Dask provides a lock future that works exactly like threading.Lock. We can declare lock using Lock class of dask.distributed module. We can restrict access to a particular part of code to only one worker at a time which can prevent concurrent updates. We'll explain the usage of the lock below with examples. from dask.distributed import Lock Below we have created an example where we try to access the global variable in a method which runs on workers. We then try to modify the value of that global variable as well. We have divided it into 2 sections where we run code without lock primitive and with lock primitive to show a difference. Below we have declared a method named update_i() which accesses the global variable and sets its value. We have then called this method 10 times on different workers. We want that each one gets the last updated value. But when we print results we can see that all of them are printing the same which was not expected. variable = Variable(name="shared_data") variable.set(1) def update_i(): variable.set(variable.get() + 1) return variable.get() futures = [] for i in range(1,11): f = client.submit(update_i) futures.append(f) client.gather(futures) [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] As a part of this section, we have first declared a lock. We then passed this lock to method update_i(). We have covered section where we update the global variable in lock using context manager. This will make sure that only one worker can access this part of the code at one time. This will make all other workers wait while the previous work is done. We then execute the same code as last time and can notice that it returns values that are incremented by 1 from previous values even though they are not in sequence. lock = Lock(name="PreventConcurentUpdates") variable.set(1) def update_i(lock): with lock: variable.set(variable.get() + 1) return variable.get() futures = [] for i in range(1,11): f = client.submit(update_i, lock) futures.append(f) client.gather(futures) [11, 3, 2, 5, 4, 10, 6, 9, 8, 7] Below we have explained another example where we try to access queue data without lock and with lock. We can see that without lock all of the workers seem to return same data. But when we wrap code into lock context manager then only one worker can access data at a time hence properly takes one value from the queue. We can see that with lock, all of the outputs are different as all were able to access queue one by one. queue = Queue(name="shared_data") for i in range(1, 11): queue.put(i) def get_queue_data(): return queue.get() futures = [] for i in range(1,11): f = client.submit(get_queue_data) futures.append(f) client.gather(futures) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] queue = Queue(name="shared_data") for i in range(1, 11): queue.put(i) def get_queue_data(lock): with lock: return queue.get() futures = [] for i in range(1,11): f = client.submit(get_queue_data, lock) futures.append(f) client.gather(futures) [3, 4, 2, 9, 10, 1, 6, 5, 7, 8] Dask provides implementation of publish-subscribe pattern. We can declare publish and subscribe to objects using Pub and Sub class of dask.distributed. We can create a topic by setting the topic name as a string to published and create subscribers with the same topic name. The subscriber will be subscribed to the publisher with that topic name. We can declare as many subscribers as we want and link them to the publisher with a particular topic name. Publishers and subscribers find each other using the scheduler but do not use it for passing data between them. They can pass data between each other once they find each other using the scheduler. Publisher subscriber is ideal to use when you want workers to communicate with each other and don't want data to be passed through scheduler which can be slow as well as a bottleneck. from dask.distributed import Sub, Pub Below we have declared publisher with the topic name ClientIdTopic and have declared two subscribers to this topic. We also have declared a method named publish_to_topic() which will publish to the topic by with that worker’s id passed to it as an argument. We then try to retrieve data published by calling subscribers. We can call either get() or next() method on subscriber to get data. pub = Pub(name="ClientIdTopic") sub1 = Sub(name="ClientIdTopic") sub2 = Sub(name="ClientIdTopic") def publish_to_topic(x): time.sleep(1) pub.put("Worker ID : %d"%x) futures = [] for i in range(1,11): f = publish_to_topic(i) futures.append(f) for i in range(10): print(sub1.get()) Worker ID : 1 Worker ID : 2 Worker ID : 3 Worker ID : 4 Worker ID : 5 Worker ID : 6 Worker ID : 7 Worker ID : 8 Worker ID : 9 Worker ID : 10 sub2.get() 'Worker ID : 1' sub2.next() 'Worker ID : 2' Please make a note that if you call get() or next() methods on subscriber but there is not data published to topic then it'll stop execution of any further statement after it waiting for publisher to publish anything to topic so that it can get that value and return. This ends our small tutorials on coordination primitives in dask.distributed API. Please feel free to let us know your views in the comments section.
https://coderzcolumn.com/tutorials/python/dask-global-variables-queues-locks-and-publish-subscribe
CC-MAIN-2021-04
refinedweb
1,947
65.42
#include "rgbd.hpp" Object that can compute the normals in an image. It is an object as it can cache data for speed efficiency The implemented methods are either: Fast and Accurate Computation of Surface Normals from Range Imagesby H. Badino, D. Huber, Y. Park and T. Kanade Gradient Response Maps for Real-Time Detection of Texture-Less Objectsby S. Hinterstoisser, C. Cagniart, S. Ilic, P. Sturm, N. Navab, P. Fua, and V. Lepetit Constructor Initializes some data that is cached for later computation If that function is not called, it will be called the first time normals are computed Given a set of 3d points in a depth image, compute the normals at each point.
https://docs.opencv.org/3.1.0/d1/d5b/classcv_1_1rgbd_1_1RgbdNormals.html
CC-MAIN-2020-05
refinedweb
116
60.85
TL;DR: I made a USB keypad that's good for gaming and typing entirely with one hand. So, remember back in February when I said that keyboard hacking seems like fun? Well, I finished this GameChord thing back in July after about 5 months of occasional work. But, I've been too busy drinking booze and playing video games to get my butt in a chair and write about it. Let's see if I can fix that now... The design I started doodling with key layouts and came up with this. Only 18 switches, but enough for gaming. At the time, I was putting a lot of hours into Elite Dangerous, so this felt promising as a spaceship control pad. Over on builder.swillkb.com, I plonked in the JSON from Keyboard Layout Editor and came up with some SVG files that printed up nicely. That gave me a paper mockup of a mounting plate for key switches. I had some clear keycaps, so I dropped them onto the paper to get a sense for how it would feel under my hand. Of course, cats happen - so those keycaps didn't stay put for very long. But, that's okay. Nothing wandered off too far, and I got what I needed from the mess on my desk. Making the case Back when I first started thinking about building a keyboard, I assumed I'd send off whatever design files I came up with to a place like Ponoko and get the mounting plate made for me. Prices at those places were just a bit higher than I liked, though. I also suspected things wouldn't work with my first attempt. I wanted to be able to iterate without it taking days or weeks to learn from my mistakes and refine. That's when I remembered i3Detroit was just down the road. I'd been meaning to get over there for a couple of years: Among other things, the space has nice laser cutters that I really wish I'd used back when I butchered some plastic to make a terrible PC monitor case. A month or so later, I'd gotten through the new member onboarding process and a few training sessions with the laser cutter. I had some acrylic sheets still on hand, so I gave my design a shot: Pretty sure I had the power too high and the speed too low for the run in this video. But, the result was not too bad for a first attempt. I had a few dozen Cherry MX Clear switches to play with, so I snapped them into the plate and put on the keycaps I'd used in the paper mockup earlier: Still lots of work ahead, but I was feeling pretty accomplished after taking this little glamour shot. I even took it into an i3Detroit member meeting for show & tell. Re-making the case At this point, I'd already heard the term "kerf". Like a saw blade, the laser has a width that destroys material while cutting. You want that on the inside edge of something like a key switch mounting hole, in order to keep the dimensions correct. Unlike a blade, the laser is a cylindrical beam that passes through a lens to form something like an hourglass. So, the kerf's shape depends on the lens focal length and the conical section that intersects with the material. Well, I didn't account for the kerf well enough in my first plate. All the key switches were wobbly. Some would just fall out if I flipped the thing over. Time for some of those iterations I figured I'd have to end up doing. I know the saying is "measure twice, cut once" - but in this case it was easier to measure by cutting! I tried mounting holes with a sampling of kerf widths until I found one that matched the key switch tolerances. Not so snug that it cracked the plate, but not so loose that it wiggled or fell out. Once I found a good laser focus and figured out the kerf, I attacked another sheet of acrylic with the laser to produce another iteration of the case. Two changes you might notice: I added slots to glue in some socket headers, so I could unplug or replace the Teensy without soldering. I also found some relegendable keycaps on Massdrop - they have little removable covers that take 14mm paper squares. I figured that would come in handy for crazy key layouts I might come up with. Wiring up the key matrix I haven't learned how to design circuit boards yet, so I figured I'd just handwire this like I saw in the video. Only 18 switches, so how bad could it be? Turns out, it's rather annoying. Interesting exercise with my terrible old Radio Shack soldering iron. I think I'd much rather get over that PCB fabrication hurdle for when I try scaling this up to a 60% keyboard like my HHKB. The technique here involves first building up rows of diodes across the right-hand pin of every key switch. The diodes serve to prevent ghosting when multiple keys are pressed. Then, I stripped sections of wires to run as columns down the left-hand pin of the switches. The remaining insulation ensures the column wires don't short against the row diodes. Wiring up the Teensy This matrix gives me 4 rows (counting the thumb switches) and 5 columns - or 9 I/O pins to scan 18 switches. Except for magical PD6 - which is hardwired to an onboard LED - just about every pin is fair game on the Teensy for rows or columns. So, I tried to pick a set that would be easiest to route wires. Since this case is transparent, I wanted to keep things visually interesting with different colored wires and a neat shape to the runs. Of course, I botched things a bit and marred the acrylic by splashing solder and slipping with the iron a few times. But, maybe no one will really notice. If I had to do this over again - and I still hadn't learned how to make a PCB - I'd probably try using something thinner like 30AWG repair wire. That seems like it would thread through the spaces much better, which would be even more important for a board with many more switches. Programming the Teensy I based the GameChord firmware on the great tmk firmware that seems popular on mech keyboard forums. Building the matrix was easy: The firmware scans through rows (DF0, DF1, DF4, and DF5) by pulling each low in turn. The columns (DB4, DB5, DB6, DF7, and DF6) are set as "active low" pins - which means keys pressed in the current scan row get connected to ground and read as signals. So, I wrote the functions to manipulate & read the appropriate row & column pins, respectively. It was almost too easy: Holy crap. My attempt at setting up firmware for my newly wired DIY keypad worked first time. How does this happen.— Les Orchard (@lmorchard) June 25, 2016 From there, I built a dead simple key map with just enough keys to play Overwatch: #include "keymap_common.h" const uint8_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { KEYMAP( ESC, 1, 2, 3, T, \ TAB, Q, W, E, R, \ LSFT, A, S, D, F, \ NO, NO, LCTL, SPC, C), }; const uint16_t PROGMEM fn_actions[] = {}; I got it all working and had myself a nice evening of pushing carts and taking objectives. Going crazy with chording I had all these relegendable keycaps and this crazy flexible tmk firmware - so I decided to try implementing a complex and fully impractical keymap based on chords with the thumb keys. Given two thumb keys in combination, I can get 4 layers out of the other 15 keys - for a total of 60 keys. The firmware also lets me distinguish between keys held or just tapped, which gives me a few more layers or modifier keys. Long story short, I can get most of the functionality of a regular keyboard out of just one hand. All I have to do is just get used to putting my left hand through some very awkward and uncomfortable contortions until I get up to full typing speed! As I've written before, I do really like odd input devices. But, this got old fast. This isn't so much a practical peripheral as a thing I did because I could. It gave me an excuse to explore the firmware more and to use Inkscape to design some legends for my nifty keycaps. Showing it off And just to wrap things up, this happened: I even have a project out in the @i3Detroit tent at #MakerFaireDetroit ! pic.twitter.com/v0goD3DCBk— Les Orchard (@lmorchard) July 30, 2016 This was the first summer I went to Maker Faire Detroit as a Maker. I helped for a bit at the i3Detroit tent, mainly just standing and smiling at the front table as folks walked in. But, I had my little keyboard out there on a table, with a project card and everything. It and I were only there for a handful of hours, but it's pretty satisfying to have actually gotten this thing done!
https://blog.lmorchard.com/2016/08/29/gamechord/
CC-MAIN-2021-21
refinedweb
1,554
78.08
This tutorial is designed to help you get a WFS running with your own Geographic data. Install the default demo Before installing your own data, ensure you can get the default mapbuilder demo working. Refer to which explains how to install mapbuilder and geoserver. Create your own data Refer to geoserver documentation for how to set up your own WFS data. Copy the wfs-t demo Edit index2.html and convert "config.xml" to "config2.xml" Create a template.xml The template.xml is used to populate a default FeatureCollection. The FeatureCollection will be used to populate the WFS Insert Transation. Use template_roads.xml or template_cities.xml as an example. One effective method of creating your template file is to look at the GML returned by a GetFeature request on your WFS layer. For example, if I am trying to edit "topp:roads", point your web browser to and follow the structure of the GML feature member exactly but remove all attributes and coordinates specific to that feature. It is important that you update the xml namespaces to be the same as your WFS. Ie, make sure you change the xmlns: attribute, and replace all the "topp:" strings with your namespace. In your template, this usually involves adding the namespace(s) to your gml:featureMember. An example template.xml for a point layer might look like: Update featureCollection in config file In config2.xml, check the FeatureCollection namespace to make sure the namespace(s) for your WFS are included. Update EditLine/EditPoint attributes in config file In config2.xml, update defaultModelUrl to reference your new template.xml file. Update featureXpath. featureXpath is an Xpath reference to the GML coordinates in your template.xml which need to be updated. For example. if you were using the template.xml show above, your featureXPath for the EditPoint widget would look like: Again, make sure that you use the XML namespaces in the Xpath reference (ie. "topp:the_geom" instead of just "the_geom")
http://docs.codehaus.org/display/MAP/WFS+Tutorial
CC-MAIN-2014-41
refinedweb
328
60.31
Law & Order Helped Me Understand BFS (Breadth-First Search) TL;DR — Give your brain a break, and you’ll find the answer. When I started learning Computer Science Fundamentals (CS Fun) there were a lot of things I didn’t understand. Heck, there are a lot of things I still don’t understand, but back then (I’m speaking, just a few months ago) I felt like I was never going to pick any of it up. At Ada Developers Academy, like with most short term training programs in tech, everything went really quickly. One day we were learning about how to manipulate arrays, and the next it seemed like we were talking about how to build Linked Lists and Directed Graphs! One of the many data structures we covered in our CS Fun class was the concept of a Binary Tree. It, like most Tree data structures, is normally drawn to look like an upside-down tree, and its defining feature is that each “leaf" node or record has at most 2 children nodes/records. Once we were told what it was, we were to learn how to traverse it and search or data in it. In other words, how to get from node to the next node, and look for information. This is where Breadth-first Search comes into play. Breadth-First Search says, “I’m going to traverse the tree from the top down, stopping at all nodes on each level to see if they contain the data I’m looking for.” For some reason, my brain could not wrap itself around this concept. I could hear my inner dialogue begin to say, “So, you’re telling me that I’m going to use another data structure called a queue to store nodes, and then read those nodes’ data to find out what the next nodes are and if they have the data I need? Huh?” My head literally hurt trying to work this out. After a number of tries of only getting as far as, “I know I need a queue to enqueue and dequeue node objects”, I let my brain take a break. It was time to watch a show. My guilty pleasure show of choice at the time was Law & Order: SVU. Now, I admit, that show did kind of stress me out as well, but somehow I was hooked on it. As I watched episode after episode I discovered that in a number of episodes they would find a suspect they thought might know the person they were looking for. When they found this person they would throw them in jail. Now, because this was a t.v. show they typically could only interview/interrogate one person at a time, usually, in the order they picked them up. A light bulb went off in my head! I finally understood BFS! The first suspect they found was like the head node of the Binary Tree. The officers threw that first suspect in jail (queued them on the queue) in order to remove them later (dequeue) and find out what they know and who they know. If the suspect isn’t the criminal, then the suspect's known associates are thrown into jail, and then interrogated the same way that the first one was. This continues until the criminal (target node) is found or the case is cold (there are no more nodes to search in the queue). The brain works in mysterious ways. Now it’s possible that this analogy didn’t work for you, and that’s okay. Everyone’s brain works a little different. Give yourself a break, and you just might have your “ah, ha” moment. Everyone’s “ah, ha” moments look a little different and come in all shapes and sizes. If this analogy worked for you and you’d like to see this coded in Ruby, you can see my code below. If the analogy didn’t work for you, but you’d still like to see my breadth-first search coded in Ruby, you can see my code below. (Please be kind in your feedback if you have any. Thank you.) Otherwise, thanks for sticking with me and let me show you the way my brain made it through the code. Best of luck to all of us learning CS Fun! class Node # what a criminal knowsattr_accessor :value, :left_node, :right_node def initialize(value) @value = value @left_node = null @right_node = null endend# This node ^^ knows no one because both its children are nullclass Queue # The jail class for new jail creationdef initialize @queue = Array.new end def enqueue(item) @queue << item end def dequeue @queue.shift end def empty? @queue.empty? endenddef breadth_first_search (first_suspect_node, target_value) new_node_jail = Queue.new new_node_jail.enqueue(first_suspect_node) while !new_node_jail.empty suspect_node = queue.deq if suspect_node.value == target_value return suspect_node # you've found your criminal end # if the suspect_node has nodes that it knows, enqueue them new_node_jail.enqueue(suspect_node.left) if suspect_node.left new_node_jail.enqueue(suspect_node.right) if suspect_node.right end return "No criminal found" end
https://medium.com/@OhKPond/law-order-helped-me-understand-bfs-breadth-first-search-1fd11a58171e?source=rss-120b1313ae7b------2
CC-MAIN-2022-40
refinedweb
839
71.65
My current program takes user input for an expression tree, example *2x and outputs * 0 0 2 0 0 x 0 0 *2x is stored in a string. the 2nd and 3rd columns represent a left-child right-child array. When one of the following operands are input "+ - * / " the zeros need to be changed to the locations of their child's. Like in this example 2 would be the left child of * and x would be the right child so the output should look like * 1 2 2 0 0 x 0 0 The only way I have thought to do this is to use a switch statement to look for the operands but I don't know how to call on the index that it's child is in. This is my code: Code:#include <iostream> #include <iomanip> using namespace std; int main() { char s[50]; cout << "Input the prefix expression.\n"; cin >> s; cout << "\nThe expression tree is:"; int row = strlen(s); int col = 2; char a[10][10]; int i, j, c; int pos; for (j = 0; j < row; j++) { a[j][0] = s[j]; for(i = 1; i <= col; i++) { a[j][i] = '0'; switch (s[j]) { case '+': case '-': case '*': case '/': a[j][i] =; break; } } } for (j = 0; j < row; j++) { cout << "\n"; for(i = 0; i <= col; i++) { cout << a[j][i] << setw(2); } }
https://cboard.cprogramming.com/cplusplus-programming/120889-2-dimensional-array.html
CC-MAIN-2017-47
refinedweb
229
70.6
Download presentation Presentation is loading. Please wait. Published byJocelin Collins Modified about 1 year ago 1 Git Branching What is a branch? 2 Review: Distributed - Snapshots Files are stored by SHA-1 hash rather than filename Stored in git database in compressed format Must “checkout” from database into working directory to edit In this example, files A, B and C are tracked 3 Example commit, 3 files 4 After 3 commits 5 Default branch is master master moves forward automatically when you commit git push origin master … now you know what master means 6 Add a branch cmd: git branch testing Why is creating a branch in git cheap and quick? Because it’s just creating a 40-character SHA-1 checksum of the commit it points to 7 But you’re still on master HEAD = pointer to current branch NOTE: concept of HEAD is different from CVS 8 Use checkout to change cmd: git checkout testing 9 Make changes on that branch edit test.rb (e.g., vim test.rb) cmd: git commit –a –m ‘made a change’ 10 Switch back to master cmd: git checkout master NOTE: This also reverts files in your working directory (e.g., c:\mycode) back to master. So edit to test.rb no longer in your working directory (but you haven’t lost it, as long as you committed before switching – remember it will be in your local database. But don’t delete.git!) 11 Change master branch edit test.rb again cmd: git commit –a –m ‘made other changes’ 12 Example Steps (for future reference) Create Java Project Create class TheBrancher, including main git init git add src/* git commit -m "Initial load" Updated source with a "leaf" variable public class TheBrancher { private String theLeaf; public void updateLeaf(String newLeaf) { theLeaf = newLeaf; } public void showLeaf() { System.out.println(theLeaf); } public static void main(String[] args) { TheBrancher brancher = new TheBrancher(); brancher.updateLeaf("Turning yellow for fall"); brancher.showLeaf(); } 13 Example, continued git commit -am "added a leaf" git log –graph –decorate --oneline # create a branch git branch needTree # see the branch git branch # switch to new branch git checkout needTree private String theTree; public void makeATree() { theTree = "Aspen"; public String toString() { return "TheBrancher [theLeaf=" + theLeaf + ", theTree=" + theTree + "]"; } # and in main brancher.makeATree(); System.out.println(brancher); git commit -am "Added a tree" git status # go back to master git checkout master # what happened in Eclipse? 14 Getting it back together At this point, no changes have been made on master Can easily “merge” the two branches git checkout master git branch –no-merged git merge needTree Done with FAST FORWARD option (just moves a pointer) 15 Basic Merging No conflicts 16 Need to switch to an urgent fix git checkout master git checkout –b hotfix vim index.html git commit –a –m ‘fixed broken code’ NOTE: git won’t let you switch to master if you have uncommitted changes that conflict with the code you’re checking out. So you should have a clean slate before you switch (stash and amend can deal with this – later topics) git checkout -b creates branch AND checks out 17 Now merge hotfix and master git checkout master git merge hotfix This will be a “fast forward” merge – because branch was directly upstream, git just moves pointer forward. 18 A little cleanup, then return to issue 53 git branch –d hotfix git checkout iss53 vim index.html git commit –a –m ‘finished footer’ Be careful with branch –d. OK in this example, just a duplicate pointer. May not always be the case. Note that work done on hotfix is not part of iss53 branch. 19 Basic merge $ git checkout master $ git merge iss53 Merge made by recursive. README | files changed, 1 insertions(+), 0 deletions(-) git identifies the best common ancestor to use for merge 20 Basic Merge result master now includes hotfix and iss53 Remove iss53 if you want: git branch –d iss53 21 Remote Branches Supplemental Material 22 Remote Branches All the branching we’ve done so far has been local Remote repositories (e.g., github) also have branches 23 Understanding remote branches Git server – it’s not always github! right now, only have master clone files from server into your working directory. Remote branch – on server – [remote]/[branch] clone names your remote origin by default Local branch – [branch] 24 Branches diverging You’ve made changes. Someone else pushed changes. master on remote NOT the same as your master! BUT, both are master (we’re not dealing with local branches yet) 25 Synchronize your work note: fetch doesn’t merge! Need to: git fetch origin git merge origin/master (handle conflicts if any, note that branch name is origin/master) git push You can also do: git pull origin master (does fetch and merge) 26 Tracking Branch A tracking branch is a local branch that has a direct relation to a remote branch If you’re on a tracking branch and type git push, Git knows which server and branch to push to git pull on a tracking branch fetches remote references and merges clone automatically creates a master branch that tracks origin/master. So git push and git pull work right out of the box. You can add other tracking branches: git checkout --track 27 Forking If you want to contribute to a project but don’t have push access, you can do a fork… create your own copy. Main project can pull in those changes later by adding them as remotes and merging in the code from the fork. 28 Configuration It’s a good idea to set up your.gitignore file A global file (.gitignore_global) can also be very useful for ignoring files in every git repositories on your computer. Local per-repository rules can be added to the.git/info/exclude file in your repository Example for Java: *.class # Package Files # *.jar *.war *.ear Be sure to read! : 29 More useful info checkout-and-reset These three commands have entirely different purposes. They are not even remotely similar. git revert This command creates a new commit that undoes the changes from a previous commit. This command adds new history to the project (it doesn't modify existing history). git checkout This command checks-out content from the repository and puts it in your work tree. It can also have other effects, depending on how the command was invoked. For instance, it can also change which branch you are currently working on. This command doesn't make any changes to the history. git reset This command is a little more complicated. It actually does a couple of different things depending on how it is invoked. It modifies the index (the so-called "staging area"). Or it changes what commit a branch head is currently pointing at. This command may alter history (by changing the commit that a branch references). 30 Continued… Using these commands If a commit has been made somewhere in the project's history, and you later decide that the commit is wrong and should not have been done, then git revert is the tool for the job. It will undo the changes introduced by the bad commit, recording the "undo" in the history. If you have modified a file in your working tree, but haven't committed the change, then you can use git checkout to checkout a fresh-from-repository copy of the file. If you have made a commit, but haven't shared it with anyone else and you decide you don't want it, then you can use git reset to rewrite the history so that it looks as though you never made that commit. These are just some of the possible usage scenarios. There are other commands that can be useful in some situations, and the above three commands have other uses as well. Similar presentations © 2017 SlidePlayer.com Inc.
http://slideplayer.com/slide/4370517/
CC-MAIN-2017-09
refinedweb
1,314
67.89
Caption button won't appearJacquesGenevieve Jan 24, 2013 10:27 AM Hi! I added a FLVPlayback and FLVPlaybackCaptioning on my scene. Each instance are named respectively "display" and "caption". The skin I use is SkinUnderPlaySeekCaption.swf The showCaptions parameter into the FLVPlaybackCaptioning is set to "true". When I publish the file, the play button and the seekbar are there, but not the caption button. Why is it not showing? How can I force it to show? Thank you for your help. Here's the code, in case you might need it : import fl.video.*; import fl.controls.ProgressBarMode; var flvControl:FLVPlayback = display; var flvCaption:FLVPlaybackCaptioning = caption; var flvSource:String = "videos/P01_Intro.flv";(); } pb.mode = ProgressBarMode.MANUAL; pb.indeterminate = false; flvControl.addEventListener(VideoProgressEvent.PROGRESS, progressHandler); flvControl.addEventListener(VideoEvent.READY, readyHandler); flvControl.source = flvSource; 1. Re: Caption button won't appearkglad Jan 24, 2013 11:25 AM (in response to JacquesGenevieve)1 person found this helpful the source for flvControl should be a timed text xml file, not an flv. check the help files for how to create that file. 2. Re: Caption button won't appearJacquesGenevieve Jan 24, 2013 11:30 AM (in response to kglad) It is a xml? caption.source = "intro.xml"; The .flv is the video...? Everything works fine. The subtitles appears on the video. It's just the button that won't appear. So basically, I have no choice, for now, to keep the subtitles always on or off. 3. Re: Caption button won't appearkglad Jan 24, 2013 12:19 PM (in response to JacquesGenevieve)1 person found this helpful correct, it is an xml. actually, an xml with a specific (timed text) format: from the flash help files: var xml:XML = <> and the caption button needs to be created and coded by you or, use a skin with a caption button like the skin you said you used, SkinUnderPlaySeekCaption.swf 4. Re: Caption button won't appearJacquesGenevieve Jan 24, 2013 12:55 PM (in response to kglad) Yup. That's what I have too. The subtitles are working quite fine. It's the button on the skin that won't appear. I tried adding the code manually, instead of using the component inspector. For a while I kept the old FLVPlayback on the stage as I was programming the new one. I published and : the button was there on my new instance! (But wasn't functionnal.) Then I flushed the first one from the stage, keeping the one that worked, re-published : it disappeared again! 5. Re: Caption button won't appearkglad Jan 24, 2013 1:04 PM (in response to JacquesGenevieve) upload your files to a server and post a link. or, attach a screenshot showing your caption.swf skin with video playing. 6. Re: Caption button won't appearJacquesGenevieve Jan 24, 2013 1:19 PM (in response to kglad) 7. Re: Caption button won't appearkglad Jan 24, 2013 2:15 PM (in response to JacquesGenevieve) i don't see that but i don't have a french flash pro version so, who knows. anyway, drag a caption button from the component panel, place it where that skin's button should be visible and assign an instance name (eg, cap_btn). then use: caption.captionButton=cap_btn; 8. Re: Caption button won't appearjacquesge Jan 25, 2013 11:48 AM (in response to kglad)1 person found this helpful Yesss! That solved the problem! Thank you! I still don't know why the button wouldn't show in the first place (since the play button and the seekbar are visible without having to add them individually on the stage). But the good news is that : now it works! I did have to add a little function to toggle the visibility : obviously. I'll write it down, in case it might be useful to anyone in the future. --- cap_btn.addEventListener(MouseEvent.CLICK,onCaptionChange); function onCaptionChange(e:*):void { if (caption.showCaptions){ caption.showCaptions = false; } else { caption.showCaptions = true; } } 9. Re: Caption button won't appearkglad Jan 25, 2013 12:15 PM (in response to jacquesge) that's interesting because you should not need that, either. but, at least, you got it working. 10. Re: Caption button won't appearjacquesge Jan 25, 2013 12:22 PM (in response to kglad) Really? Indeed it's strange, because I tried it before adding this function and the button did appear, but I couldn't toggle the visibility of the text. It worked only when I added the function... It seems I'm not the first one who had this problem : 11. Re: Caption button won't appearkglad Jan 25, 2013 1:03 PM (in response to jacquesge) what cs version are you using and what swf version are you publishing for? 12. Re: Caption button won't appearjacquesge Jan 25, 2013 1:06 PM (in response to kglad) CS4 and 10.
https://forums.adobe.com/thread/1141085
CC-MAIN-2017-22
refinedweb
811
67.15