text
stringlengths 20
1.01M
| url
stringlengths 14
1.25k
| dump
stringlengths 9
15
⌀ | lang
stringclasses 4
values | source
stringclasses 4
values |
|---|---|---|---|---|
Why does JRules show incorrect results when performing certain arithmetic operations on decimal numbers? For example, if I add 1.09 to 0.9, the result is 1.990000000000003.
Answer by odmfp (10435) | Feb 11, 2015 at 02:57 AM
Cause
Decimal numbers are generally encoded in computer programs. Therefore, they cannot be represented precisely with a fixed size set of bits, whether it is 32, 64 bits or more.
Answer
The lack of accuracy of the computer based representation of a number is not a limitation of JRules. This lack of accuracy generally lies in the way that decimals are represented internally in software programs.
The following sample Java class illustrates this limitation:
public class Main { public static void main(String[] args){ double p = 1.09; System.out.print(p + 0.9); } }
This class typically outputs a value such as: 1.990000000000002
To get a better precision, you can specify the rounding that should be used. You can use classes such as java.math.BigDecimal for a better control over the mathematical accuracy of computations.
This is also applicable to ODM and Business Rules service for Bluemix.
18 people are following this question.
Issue with HTDS signature : double wrapped complex BO type parameters 1 Answer
Printing Boolean attribute 1 Answer
Active property and runtime rule selection 1 Answer
Improving response time when editing a large decision table 1 Answer
Decision Warehouse query does not return any data for ruleset executions 1 Answer
|
https://developer.ibm.com/answers/questions/174813/the-results-of-arithmetic-operations-show-unexpect.html?smartspace=hybrid-cloud-core
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
No, this is not a known issue.
Please raise a ticket on the JIRA issue tracker for this.
The more information about the bug, the faster it is likely to be resolved. (Adding a patch
or a pull request with unit tests is ideal.)
Remko
(Shameless plug) Every java main() method deserves
> On May 30, 2018, at 8:36, Husby, Joseph P. <Joseph.P.Husby@leidos.com> wrote:
>
> Hello log4j group,
>
> I think we've found a bug... When using JsonLayout for our appender in 2.11.0, an object
that has "{}" in its toString will result in a recursive output. Here is a simple code example
and resulting output to illustrate the problem:
>
> import org.apache.logging.log4j.LogManager;
> import org.apache.logging.log4j.Logger;
>
> public class Test {
>
> public static final Logger log = LogManager.getLogger(Test.class);
>
> public static void main(final String[] args) {
> log.info("Testing: {}", new TestObj());
> }
>
> static class TestObj {
> @Override
> public String toString() {
> return "This is my toString {} with curly braces";
> }
> }
> }
>
> This produces the following output:
>
> [
> {
> "thread" : "main",
> "level" : "INFO",
> "loggerName" : "Test",
> "message" : "Testing: This is my toString This is my toString {} with curly braces
with curly braces",
> "endOfBatch" : false,
> "loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
> "instant" : {
> "epochSecond" : 1527636365,
> "nanoOfSecond" : 40000000
> },
> "contextMap" : { },
> "threadId" : 1,
> "threadPriority" : 5
> }
> ]
>
> Note how TestObj's toString is inserted in place of its "{}", resulting in it (sort-of)
being logged twice. Is this a known issue?
>
> Thanks!
> Joseph Husby
>
---------------------------------------------------------------------
To unsubscribe, e-mail: log4j-user-unsubscribe@logging.apache.org
For additional commands, e-mail: log4j-user-help@logging.apache.org
|
http://mail-archives.us.apache.org/mod_mbox/logging-log4j-user/201805.mbox/%3C208A9621-4FCA-49A0-9608-F128961589FF@gmail.com%3E
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Archive
Retrieving web pages with foreign characters
When you make a request to a web page using code such as:
HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(requestURI);
HttpWebResponse httpresponse = (HttpWebResponse)httprequest.GetResponse();
Stream responsestream = httpresponse.GetResponseStream();
StreamReader httpstream = new StreamReader(responsestream);
string bodytext = httpstream.ReadToEnd();
You may find that certain characters may be missing from the string returned, such as the copyright © character, or foreign characters, such as é (e acute). In order to get around this you need to use Latin encoding (ISO 8859) in the StreamReader thus:
StreamReader httpstream =
new StreamReader(responsestream, Encoding.GetEncoding("iso8859-1"));
… had me stumped for ages!
Indexed views SQL Server 2005
In an attempt to speed up queries coming from my 11 million row table "Companies", I decided to dabble in a bit of indexed views, which are now available in sql 2005.
Here’s a transscript of how I got on (warts and all)
Microsoft Windows [Version 5.2.3790]
(C) Copyright 1985-2003 Microsoft Corp.
C:Documents and SettingsAdministrator>sqlcmd
1>
Sqlcmd: Warning: Last operation was terminated by the user by pressing Ctrl-C.
C:Documents and SettingsAdministrator>sqlcmd -S.SQLEXPRESS -E
1> use dinfo
2> create view VCompanies with schemabinding as
3> select * from’.
Sqlcmd: Error : Microsoft OLE DB Provider for SQL Server : One or more errors oc
curred during processing of command..
1> use dinfo
2> go
Changed database context to ‘dinfo’.
1> create view VCompanies with schemabinding as
2> select * from companies
3> go
Msg 1054, Level 15, State 6, Server OPENMERCHANTACCSQLEXPRESS, Procedure VCompa
nies, Line 2
Syntax ‘*’ is not allowed in schema-bound objects.
1> create view VCompanies with schemabinding as
2> select id,name,address,city,PostCode,Telephone from companies
3> go
Msg 4512, Level 16, State 3, Server OPENMERCHANTACCSQLEXPRESS, Procedure VCompa
nies, Line 2
Cannot schema bind view ‘VCompanies’ because name ‘companies’ is invalid for sch
ema binding. Names must be in two-part format and an object cannot reference its
elf.
1> select id,name,address,city,PostCode,Telephone from dinfo..companies
2> create view VCompanies with schemabinding as
3> select id,name,address,city,PostCode,Telephone from dinfo.’.
1> create view VCompanies with schemabinding as
2> select id,name,address,city,PostCode,Telephone from dinfo..companies
3> go
Msg 4512, Level 16, State 3, Server OPENMERCHANTACCSQLEXPRESS, Procedure VCompa
nies, Line 2
Cannot schema bind view ‘VCompanies’ because name ‘dinfo..companies’ is invalid
for schema binding. Names must be in two-part format and an object cannot refere
nce itself.
1> create view VCompanies with schemabinding as
2> select id,name,address,city,PostCode,Telephone from dbo.companies
3> go
1> CREATE UNIQUE CLUSTERED INDEX VDiscountInd ON Vdiscount1 (ProductID)
2> go
Msg 1088, Level 16, State 12, Server OPENMERCHANTACCSQLEXPRESS, Line 1
Cannot find the object ‘Vdiscount1’, because it does not exist or you do not hav
e permission.’.
Sqlcmd: Error : Microsoft OLE DB Provider for SQL Server : One or more errors oc
curred during processing of command..
1> SET ANSI_NULLS ON
2> SET ANSI_PADDING ON
3> SET ANSI_WARNINGS ON
4> SET CONCAT_NULL_YIELDS_NULL ON
5> SET NUMERIC_ROUNDABORT OFF
6> SET QUOTED_IDENTIFIER ON
7> SET ARITHABORT ON
8>
9> go’.
1> drop view vcompanies
2> go
1> create view VCompanies with schemabinding as
2> select id,name,address,city,PostCode,Telephone from dbo.companies
3> go
1> create unique clustered index idxVcompanies on VCompanies (name,address,city,
postcode,telephone)
2> go..
Warning! The maximum key length is 900 bytes. The index ‘idxVcompanies’ has maxi
mum length of 1275 bytes. For some combination of large values, the insert/updat
e operation will fail.
Msg 1105, Level 17, State 2, Server OPENMERCHANTACCSQLEXPRESS, Line 1
Could not allocate space for object ‘SORT temporary run storage: 49609231545139
2′ in database ‘dinfo’ because the ‘PRIMARY’ filegroup is full. Create disk spac
e by deleting unneeded files, dropping objects in the filegroup, adding addition
al files to the filegroup, or setting autogrowth on for existing files in the fi
legroup.
The statement has been terminated.
Sqlcmd: Error : Microsoft OLE DB Provider for SQL Server : One or more errors oc
curred during processing of command..
alter database dinfo
ADD FILE
(
NAME = dinfot2,
FILENAME = ‘C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDatadinfo2.ndf’,
SIZE = 5MB,
MAXSIZE = UNLIMITED,
FILEGROWTH = 5MB
)
GO
… and re-ran the Create index statement..
Recursive fallback not allowed for character u003F. Parameter name: chars
I just got this error on my website. The site has ASP.NET 2.0 beta 1 installed, It threw a wierd exception, which looked as if the Global.asax was corrupt, I deleted the file on the server, then got this error:
Recursive fallback not allowed for character u003F. Parameter name: chars: chars
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: Recursive fallback not allowed for character u003F. Parameter name: chars] System.Text.EncoderFallbackBuffer.ThrowLastCharRecursive(Int32 charRecursive) +127 System.Text.EncoderFallbackBuffer.InternalFallback(Char ch, Char*& chars) +259 System.Text.SBCSCodePageEncoding.GetByteCount(Char* chars, Int32 count, EncoderNLS encoder) +1632932 System.Text.EncodingNLS.GetByteCount(Char[] chars, Int32 index, Int32 count) +95 System.Text.Encoding.GetBytes(Char[] chars, Int32 index, Int32 count) +26 System.Text.Encoding.GetBytes(String s) +35 System.Diagnostics.EnvironmentBlock.ToByteArray(StringDictionary sd, Boolean unicode) +442 System.CodeDom.Compiler.Executor.ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine) +902 System.CodeDom.Compiler.Executor.ExecWaitWithCapture(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine) +65 System.CodeDom.Compiler.CodeCompiler.Compile(CompilerParameters options, String compilerDirectory, String compilerExe, String arguments, String& outputFile, Int32& nativeReturnValue, String trueArgs) +443 System.CodeDom.Compiler.CodeCompiler.FromFileBatch(CompilerParameters options, String[] fileNames) +532 System.CodeDom.Compiler.CodeCompiler.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, String[] fileNames) +230 System.Web.Compilation.AssemblyBuilder.Compile() +522 System.Web.Compilation.BuildProvidersCompiler.PerformBuild() +228 System.Web.Compilation.BuildManager.CompileWebFile(String virtualPath) +234 System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(String virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +580 System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, String virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +234 System.Web.UI.PageHandlerFactory.GetHandler(HttpContext context, String requestType, String virtualPath, String path) +73 System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, String path, String pathTranslated, Boolean useAppConfig) +702 System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +131 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +162
Any Ideas any body?
(Follow up: I restarted the server, and it resolved itself…)
Shrinking!
Traditional storage mediums
A brief history of Hard Drive Technology
In 1950, Engineering Research Associates of Minneapolis, USA, built the first commercial magnetic drum storage unit for the U.S. Navy, the ‘ERA hard disk drive, the predecessor of all current hard disk drives. The 3340 had two spindles each with a capacity of 30 MBytes, and the term "30/30 Winchester" was thus coined.
In 1980, Seagate Technology introduced the first hard disk drive for microcomputers, the ST506. It was a full height (twice as high as most current 5 1/4" drives) 5 1/4" drive, with a stepper motor, and held 5 Mbytes. My first hard disk" hard disks Encyclopaedia," followed in 1985. The 3 1/2" IDE drive started it’s existence as a drive on a plug-in expansion board, or "hard card." The hard card included the drive on the controller which, in turn, evolved into Integrated Device Electronics (IDE) hard disk drive, where the controller became incorporated into the printed circuit on the bottom of the hard disk drive. Quantum made the first hard card in 1985.
In 1986 the first 3 /12" hard disks with voice coil actuators were introduced by Conner in volume, but half (1.6") and full height 5 1/4" drives persisted for several years. In 1988 Conner introduced the first one inch high 3 1/2" hard disk drives. In the same year PrairieTek shipped the first 2 1/2" hard disks.
In 1997 Seagate introduced the first 7,200 RPM, Ultra ATA hard disk drive for desktop computers..
The right and wrong way to clone an object in C#
The Wrong way…
Flight[] flights = new Flight[0];
BinaryFormatter myBinary = new BinaryFormatter();
MemoryStream flightStream = (MemoryStream)dtSearched.Rows[i]["Flights"];
flightStream.Seek(0, SeekOrigin.Begin);
flights = (Flight[])myBinary.Deserialize(flightStream);
The right way…
public class A : ICloneable {
int x;
public object Clone() {
return MemberwiseClone();
}
}
Literature.
|
https://blog.dotnetframework.org/2005/03/
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Timeline …
-
10/01/09:
- 17:17 Ticket #2380 (Refactor template plugin options loading in view.load_engines) closed by
- fixed: Yes, corrected that already in my working copy. I have applied it now in …
- 17:08 TicketQueries edited by
- (diff)
- 16:53 TicketQueries edited by
- Updated to show links for current milestones (diff)
- 16:32 TicketQueries edited by
- (diff)
- 16:14 Ticket #2346 (Visit expires even though the user had accessed before expiry time) closed by
- fixed: Ok, I've mentioned it in the changelog and in the …
- 15:04 Ticket #2381 (TG 1.1 quickstart template does not use "now" passed by controller) closed by
- fixed: Fixed in r6754.
- 14:24 Ticket #2248 (tg.url() behaves differently than pylons.url()) closed by
- fixed: Im closing this ticket because I believe this is fixed. Please feel free …
- 14:22 Ticket #2253 (Parent-child relationship with admin to docs) closed by
- fixed: I believe this is well covered in multiple places with moviedemo.
- 14:16 Ticket #2373 (@expose('json') won't return lists) closed by
- fixed: I believe this is fixed with the TJ->SJ fixes. Im closing. Feel free to …
- 14:12 Ticket #2212 ([patch] Eliminate TurboJson and use plain simplejson.) closed by
- fixed
- 14:11 Ticket #2298 (Documentation error: python setup.py development) closed by
- fixed
- 14:11 Ticket #2263 (Custom Content Type document needs to be fixed.) closed by
- fixed
- 14:08 Ticket #2117 (Document/test call_on_startup/shudown hooks) closed by
- fixed
- 13:56 Ticket #2377 (Dispatcher regression in TG2.1:) closed by
- wontfix: I have determined the problem has to do with the way luke has his own …
- 10:28 Ticket #2382 (Quickstarted TG 1.1 project with SO and identity throws OperationalError) created by
- Quickstarted a TG 1.1rc1 project with SQLObject (0.11.2, but the same …
- 09:42 Ticket #2381 (TG 1.1 quickstart template does not use "now" passed by controller) created by
- The TG 1.0 quickstart templates displayed the current time using the "now" …
09/30/09:
- 11:33 Ticket #2380 (Refactor template plugin options loading in view.load_engines) created by
- Currently, we only pass a fixed set of options, which is defined in …
09/28/09:
- 23:08 Ticket #1282 (MoinMoin Header) closed by
- fixed: Fixed together with #1442.
- 22:57 Ticket #1442 (Wiki banner hides text when viewed with IE7) closed by
- fixed: Finally (hopefully) fixed this and made text in the wiki look a bit nicer …
- 10:33 Ticket #2379 (Document using HTTP Basic authentication in TG 1.1/1.5) created by
- See r6665 for the implementation and #2036 for how support for this came …
- 04:47 Ticket #2158 (Do not override the response content-type if it has already been modified.) closed by
- fixed: I'm closing this in favor of the more general #2378 mainly because, TG is …
- 04:44 Ticket #2378 (General content_type ticket.) created by
- This is a catchall titcket for #2158 and #2280 as each solution breaks it …
09/27/09:
- 15:03 Ticket #2376 (Impossible to pass empty strings/dicts/lists/zero-based values as default ...) closed by
- fixed: Fixed with r6736 in all 1.x branches and tests added.
- 12:33 Ticket #2377 (Dispatcher regression in TG2.1:) created by
- I'm experiencing some dispatcher regression in TurboGears 2.1dev when …
- 11:06 Ticket #2376 (Impossible to pass empty strings/dicts/lists/zero-based values as default ...) created by
- For example i want to pass 0 as default value (int, not a string): […] …
- 08:44 Ticket #1963 (Pages of quickstarted TG 1.1 app do not validate) reopened by
- It seems like setting genshi.default_doctype to default to html wasn't …
- 04:44 Ticket #2326 ("Using Jinja" docs typo) closed by
- fixed
09/26/09:
- 23:43 Ticket #2291 (Missing index method raises unrecoverable 404 instead of calling the ...) closed by
- fixed: This is currently working with tgtip.
09/25/09:
- 13:36 Ticket #2375 (Identity/Visit unit tests error because of missing table tg_visit) closed by
- fixed: There was some initialization being done at import time in …
- 08:11 Ticket #2375 (Identity/Visit unit tests error because of missing table tg_visit) created by
- When I run nosetests or python setup.py test for TG 1.1rc1 and …
09/24/09:
- 12:22 Ticket #2374 (Replace TG 1.0 favicon with a prettier one) created by
- The default favicon in the quickstart templates still hails from pre 1.0 …
09/23/09:
- 21:15 Ticket #2364 (Document protection of static files via the identity framework in TG1) closed by
- fixed
- 19:57 Ticket #2373 (@expose('json') won't return lists) created by
- When you return a list in a method that is @expose('json'), you instead …
- 13:30 Ticket #1205 (/login redirect fails with SecureResource) closed by
- duplicate
- 07:53 Ticket #2372 (IE7 (and IE6) fails in tgext.admin with tw.dojo) created by
- IE7 (and in some cases IE6) shows "IE cannot display this webpage" when …
- 02:53 Ticket #1504 (Pagination doesn't always work with prod.cfg) closed by
- duplicate: I think this is a duplicate of #1889 and is fixed in TG 1.0.7.
- 00:21 TicketQueries edited by
- (diff)
09/22/09:
- 23:42 Ticket #1305 (Display the record instead of an id in CatWalk ForeignKey) closed by
- duplicate: Duplicate to #681.
- 23:36 Ticket #1392 (Implement "tg-admin serve") closed by
- wontfix: apparently nobody was interested in implementing this and with the …
- 23:23 Ticket #57 (Investigate Django's cache system) closed by
- wontfix
- 23:19 Ticket #96 (Before deleting an object check if it have relations to be deleted ...) closed by
- wontfix: Cruft ticket. CatWalk is unmaintained, we won't add new features to it. …
- 23:17 Ticket #843 (Pagination for the widget browser) closed by
- wontfix: Cruft ticket. Frankly, I don't see much need for this. IMHO widget authors …
- 23:12 Ticket #206 (Support setting IdentityProvider per controller) closed by
- wontfix: Apparently nobody sees a need for this. Closing as "wontfix".
- 23:10 Ticket #605 (Defaults for dicts) closed by
- wontfix: Cruft ticket. Nobody seems to have missed this feature (whatever it was …
- 23:07 Ticket #558 (Teaching sqlobject inheritance to CatWalk) closed by
- wontfix: Cruft ticket. though I can still reproduce the described problem, CatWalk …
- 22:56 Ticket #551 (CatWalk: UnicodeCols set to None get changed to string "[Object ...) closed by
- worksforme: I can not reproduce this anymore with TG 1.1rc1 or TG 1.0 svn r6685.
- 22:15 Ticket #318 (Catwalk doesn't accept "None" in DateTime columns) closed by
- worksforme: I can not reproduce this anymore with TG 1.1rc or TG 1.0 SVN r6685.
- 22:09 Ticket #681 (use alternateID for dropdown (when available)) closed by
- fixed: This is supported in current version of CatWalk (don't know since when). …
- 21:56 Ticket #634 (LdapIdentityProvider) closed by
- wontfix: There is a recipe at …
- 21:51 Ticket #858 (so_to_dict function to support joins) closed by
- wontfix: Cruft ticket. Anyway, I don't think this belongs into the scope of …
- 21:42 Ticket #865 (Log page generation times) closed by
- wontfix: Cruft ticket. Since nobody has bothered to work on this, closing ticket as …
- 21:40 Ticket #855 (Catwalk back button does not work) closed by
- wontfix: CatWalk is an Ajax application. The browser back/forward buttons do not …
- 21:38 Ticket #906 (Migrate TurboTunes tutorial) closed by
- wontfix: Seems that nobody is willing to do this. The attached project still works …
- 21:30 Ticket #933 (provide feedback on Ajax calls in admi18n) closed by
- invalid: The description of this ticket is too vague to reproduce the problem. I …
- 21:25 Ticket #1111 (Catwalk doesnt work with DateCol() and TimeCol()) closed by
- wontfix: Cruft ticket. CatWalk is not maintained and will not grow new features. …
- 21:20 Ticket #142 (Add Caching document) closed by
- wontfix: Well, it seems clear that nobody is to willing to take this on. Closing …
- 21:17 Ticket #1008 (Catwalk doesn't import all models specified in sqlobject.txt) closed by
- wontfix: Cruf ticket. CatWalk is not maintained and will not grow new features. …
- 21:09 Ticket #1073 (No way to discover available quickstart templates) closed by
- wontfix: Document usage of paster create --list-templates in quickstart …
- 21:03 Ticket #1184 (CalendarDatePicker returns a datetime, not a date) closed by
- wontfix: Cruft ticket. The DateTimeConverter? in turbogears.validators is limited, …
- 20:44 Ticket #1888 (top_level_dir (in config) don't resolve correctly in namespace packages) closed by
- fixed: This is a duplicate of #12 and has been fixed in r6168.
- 20:27 Ticket #2317 (tg-admin throws exception on Python 2.4 due to wrong import) closed by
- fixed
- 20:26 Ticket #1860 (Integration of the Dejavu ORM in TurboGears) closed by
- wontfix: Since there has been no further feedback on this for several months, I'm …
- 20:00 Ticket #2339 (replace admin from catwalk to rum) closed by
- invalid: I agree. Anyway tickets for projects not hosted here should not be …
- 19:57 Ticket #2340 (port CustomQuery to Tg2) closed by
- invalid: These are both interesting ideas but nothing which belongs in the core of …
- 19:52 Ticket #2349 (Jsonifcation of valid XML data fails) closed by
- invalid: TGWS is not hosted by the TurboGears project. Please report the issue …
- 19:50 Ticket #2352 (Provide widget instance to callable default value) closed by
- wontfix: Look at partial functions in … …
Note: See TracTimeline for information about the timeline view.
|
http://trac.turbogears.org/timeline?from=2009-10-17&daysback=30&authors=
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
In my code below, I am defining two functions.
main
cube
main
cube
main
>>> def main():
number = int(input('Enter a number: '))
cubed_number = cube(number)
print("The number cubed is: ", cubed_number)
>>> def cube(number):
return number * number * number
>>>
cube
main
NameError
>>> main()
Enter a number: 5
The number cubed is: 125
>>>
cube
NameError
NameError
>>> class Main:
cubed_number()
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
class Main:
File "<pyshell#27>", line 2, in Main
cubed_number()
NameError: name 'cubed_number' is not defined
>>>
To understand what is happening, one must understand the distinction Python makes between defining a function, and executing a function.
When Python encounters a function definition, it compiles the function into a code object.
A code object is an internal structure Python uses to hold the bytecode associated with a specific executable block of code. It also holds other information Python needs to execute the bytecode such as constants and local variable names. The documentation gives a much more more extensive overview of what code objects are.
The code object is then used to construct a function object. The function object's code object is then used to execute the function when it is later called. Python would not execute the function, it would only compile the function into an object that could be used later for execution. The only time Python executes a function, is when the function is called.
Here is the relevant part from the documentation which mentions this:.
Because of this distinction, Python cannot verify a name is actually defined until the function is called. Thus, you are allowed to use currently non-existent names in the function body. As long as the name is defined when the function is called, Python will not raise an error.
Here is an example. We define a function
func that adds two variables together;
a and
b:
>>> def func(): ... return a + b
As you can see Python raised no error. This is because it simply compiled
func. It did not attempt to execute the function, so it does not see that
a and
b are not defined.
We can disassemble
func's code object, and see what the bytecode looks like using the
dis module. This will tell us more about what Python is doing:
>>> from dis import dis >>> dis(func) 2 0 LOAD_GLOBAL 0 (a) 2 LOAD_GLOBAL 1 (b) 4 BINARY_ADD 6 RETURN_VALUE
Python encoded two
LOAD_GLOBAL instructions in the byte-code. The arguments to the instructions are the variable names
a and
b respectively.
This shows that Python did see that we were attempting to reference two variables when compiling our function and created bytecode instructions to do so. But it does not attempt to actually execute the instructions, until the function is called.
Let's see what happens when we attempt to execute the bytecode for
func by calling it:
>>> func() Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> func() File "<pyshell#14>", line 2, in func return a + b NameError: name 'a' is not defined
As you can see, Python raised a
NameError. This is because it attempted to execute the two
LOAD_GLOBAL instructions, but discovered that the names where undefined in the global scope.
Now let's see what happens if we defined two variables
a and
b before calling
func:
>>> a = 1 >>> b = 2 >>> >>> func() 3
The reason the above worked, is because when Python was executing
func's byte-code, it was able to find the global variables
a and
b, and used those to execute the function.
The same applies to the example is the question. When
main was compiled, Python "saw" we were trying to call a variable named
cube and generated an instruction to get the value of
cube. But it did not attempt to find a callable object named
cube until the instructions were executed. And by the time
main's byte-code was executed(eg.
main was called), a function named
cube was defined, so Python did not raise an error.
If we try to call main before cube is defined however, we'll get a name error for the same reasons in the above example:
>>> def main(): ... number = int(input('Enter a number: ')) ... cubed_number = cube(number) ... print("The number cubed is: ", cubed_number) ... >>> main() Enter a number: 23 Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> main() File "<pyshell#22>", line 3, in main cubed_number = cube(number) NameError: name 'cube' is not defined
Python handles class definitions a bit differently from function definitions.
When Python encounters a class definition, it creates a code object for the class as with the function. However, Python also allows classes to have namespaces that are executed during the class definition. Python does not wait to execute the classes namespace because any variables defined should belong to the class. Thus, any names used inside of a classes name-space must be defined for usage during class-definition time.
The documentation for class definitions touches on this:.
However, this does not apply to methods. Python treats undefined names in methods as with functions, and allows you to use them when defining the method:
>>> class Class: ... def method(self): ... return var ... >>> var = 10 >>> cls = Class() >>> cls.method() 10
|
https://codedump.io/share/ADBtRb7YTW8A/1/why-can-i-use-a-variable-in-a-function-before-it-is-defined-in-python
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Another angle, with Big Bang, what happens to companies that have purchased an application container? Are they going to pay for an upgrade that includes just a namespace change?
Where Iâve had trouble upgrading application servers in the past has centered around the JSF UI stuff. For some old applications, EE upgrades have generally required an upgrade to the third party JSF component libraries. UI code tends to be a bit more fragile and the UI frameworks may not upgrade nicely (been my experience). Server-side code I havenât run into too many issues.
Iâd like to see the reference implementation (GlassFish) tackle the name spacing first. How hard will it be for GlassFish to support both EE 8 and EE 9 (assuming 9 has a different namespace)? To me this debate has been somewhat abstract. The impact of the refactoring is going to depend upon application complexity. Some organizations are deploying multiple applications to containers (which by different groups on different schedules) which communicate via RMI etc.
Separately, I think the Java ecosystem is going through a bit of upheaval at the moment with getting code running on post Java 8. With Java 9, the technical debt bill came due. Do we want to throw a namespace challenge into the mix at the moment when companies are grappling with transitioning to Java 11?
ÂJust curious, why arenât the individual specs making the decision on when they jump to the new namespace?
-Ryan
> On May 10, 2019, at 3:38 PM, domi <dbuechner93@xxxxxxxxx> wrote:
>
> I totaly agree with you guys.
>
> another point why i prefer the BIG-BANG transition is that after that step you can say IT'S DONE and build jakarta ee on a "carefree base".
>
> Dominic
>
> Am 10.05.19 um 18:54 schrieb Mark Struberg:
>> And even worse: we would break backward compat with every Jakarta EE release :(
>>
>> LieGrue,
>> strub
>>
>>> Am 10.05.2019 um 14:33 schrieb David Blevins <dblevins@xxxxxxxxxxxxx>:
>>>
>>>> On May 10, 2019, at 8:55 PM, Richard Monson-Haefel <rmonson@xxxxxxxxxxxxx> wrote:
>>>>
>>>> In the github proposal for Incremental, it says over and over again that the result would be mixed namespaces. But the Big Bang never says that yet it does say "Any packages not moved from javax to jakarta could be included in Jakarta EE, but would be forever frozen and never move to the jakarta namespace." Âwhich is exactly the same thing, right?
>>> Here's where they're the same:
>>>
>>> ÂJakarta EE 9 comes out and it is some mix of javax and jakarta. You must learn the mix.
>>>
>>> Here's where they're different:
>>>
>>> ÂBig Bang: Jakarta EE 10 comes out. You already learned the mix, you're good.
>>>
>>> ÂIncremental: Jakarta EE 10 comes out. Forget the old mix, learn the new one. Also update your source code again.
>>>
>>>
>>> And worse case...
>>>
>>> ÂBig Bang: Jakarta EE 11 comes out. You already learned the mix, you're good.
>>>
>>> ÂIncremental: Jakarta EE 11 comes out. Forget the old mix, learn the new one. Hope you have any chance of keeping it straight. Hope your boss doesn't get mad when you tell her you have to migrate source again to use a new feature.
>>>
>>>
>>> -David
>>>
>>> _______________________________________________
>>>
|
https://www.eclipse.org/lists/jakartaee-platform-dev/msg00216.html
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
>
to test out my json save function i built my game i clicked my savegame button and it saved my data when i clicked my load button it changed my players coordinates to the coordinates of the player when i saved my game. However when i exited my game and tried to load it didnt save the map or my position heres my saving script: using System; using UnityEngine; using System.IO; public class savemanager : MonoBehaviour { public string worldfile; public GameObject worldmap; public string json; public string fromjson; public int recoveredint; public savedata copy; public maploader mapreference; public void Start() { loadgame(); } public void savegame() {
savedata data = new savedata { map = worldmap, mapalreadygenerated = true, playerz = GameObject.FindWithTag("Player").transform.position.z, playerx = GameObject.FindWithTag("Player").transform.position.x };
worldfile = Path.Combine(Application.persistentDataPath, data.map.name);
json = JsonUtility.ToJson(data);
if (File.Exists(worldfile))
{
File.Delete(worldfile);
}
File.WriteAllText(worldfile, json);
Debug.Log("data saved to" + worldfile);
fromjson = File.ReadAllText(worldfile);
copy = JsonUtility.FromJson<savedata>(fromjson);
}
public void loadgame()
{
fromjson = File.ReadAllText(worldfile);
copy = JsonUtility.FromJson<savedata>(fromjson);
mapreference.savedworld = copy.map;
GameObject.FindWithTag("Player").transform.position = new Vector3(copy.playerx, 0, copy.playerz);
}
}
and heres the script of the data i want to save:
using System; using UnityEngine;
[Serializable] public class savedata {
public GameObject map;
public int[] slotitems;
public float[] slotamounts;
public float playerx;
public float playerz;
public bool mapalreadygenerated;
Answer by Cobra_03
·
Aug 13, 2018 at 02:39 PM
When you re-start your game, worldfile will be a declared variable but it will not have a value. You only assign a value to it in save game.
thanks i gave worldfile a value in my load function and it worked
Answer by Yemnefer
·
Aug 11, 2018 at 02:10 AM
go to "%userprofile%\AppData\LocalLow\<>companyname\<>productname\" and find the file that you saved, if it's not there, you're not saving it. also debug that Path.Combine and see if the path.
Best Saving Practices using Firebase
0
Answers
Parse different types of objects from Json
1
Answer
How to save progress like high scores and money on android onto the device and online
1
Answer
check SQLite database record
1
Answer
Fail to load data from json to list of list.
1
Answer
|
https://answers.unity.com/questions/1540906/my-json-saves-but-doesnt-load-after-i-exit-my-game.html
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Xamarin.Essentials: Geocoding
The Geocoding class provides APIs to geocode a placemark to a positional coordinates and reverse geocode coordinates to a placemark.
To start using this API, read the getting started guide for Xamarin.Essentials to ensure the library is properly installed and set up in your projects.
To access the Geocoding functionality the following platform specific setup is required.
Using Geocoding
Add a reference to Xamarin.Essentials in your class:
using Xamarin.Essentials;
Getting location coordinates for an address:
try { var address = "Microsoft Building 25 Redmond WA USA"; var locations = await Geocoding.GetLocationsAsync(address); var location = locations?.FirstOrDefault(); if (location != null) { Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}"); } } catch (FeatureNotSupportedException fnsEx) { // Feature not supported on device } catch (Exception ex) { // Handle exception that may have occurred in geocoding }
The altitude isn't always available. If it is not available, the
Altitude property might be
null or the value might be zero. If the altitude is available, the value is in meters above sea level.
Using Reverse Geocoding
Reverse geocoding is the process of getting placemarks for an existing set of coordinates:
try { var lat = 47.673988; var lon = -122.121513; var placemarks = await Geocoding.GetPlacemarksAsync(lat, lon); var placemark = placemarks?.FirstOrDefault(); if (placemark != null) { var geocodeAddress = $"AdminArea: {placemark.AdminArea}\n" + $"CountryCode: {placemark.CountryCode}\n" + $"CountryName: {placemark.CountryName}\n" + $"FeatureName: {placemark.FeatureName}\n" + $"Locality: {placemark.Locality}\n" + $"PostalCode: {placemark.PostalCode}\n" + $"SubAdminArea: {placemark.SubAdminArea}\n" + $"SubLocality: {placemark.SubLocality}\n" + $"SubThoroughfare: {placemark.SubThoroughfare}\n" + $"Thoroughfare: {placemark.Thoroughfare}\n"; Console.WriteLine(geocodeAddress); } } catch (FeatureNotSupportedException fnsEx) { // Feature not supported on device } catch (Exception ex) { // Handle exception that may have occurred in geocoding }
Distance between Two Locations
The
Location and
LocationExtensions classes define methods to calculate the distance between two locations. See the article Xamarin.Essentials: Geolocation for an example.
API
Related Video
Find more Xamarin videos on Channel 9 and YouTube.
Feedback
Send feedback about:
|
https://docs.microsoft.com/en-us/xamarin/essentials/geocoding?context=xamarin/xamarin-forms
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
The
product function is one of several handy combinatoric iterators included in the
itertools module. Combinatoric iterators are related to an area of mathematics called enumerative combinatorics, which is concerned with the number of ways a given pattern can be formed.
product gives us a way to quickly calculate the cartesian product of two or more collections. An example of the cartesian product can be found below:
product also frequently serves as an alternative approach to having multiple
for clauses inside list comprehensions.
In a previous post, we provided code for a list comprehension that would calculate all the possible roll combinations for two six-sided dice.
roll_combinations = [(d1, d2) for d1 in range(1, 7) for d2 in range(1, 7)]
We can do very much the same thing using the
product function.
from itertools import product dice_combinations = product(range(1, 7), repeat=2)
So what's going on here?
The
product function accepts any number of iterables as positional arguments, and has an optional keyword only parameter called
repeat.
When we provide two or more iterables as arguments, the
product function will find all the ways we can match an element from one of these iterables to an item in every other iterable. For example, we might have a pair of lists like so:
list_1 = ["a", "b", "c"] list_2 = [1, 2, 3]
When we pass these lists to the product function, we get the following:
cartesian_product = product(list_1, list_2) # ('a', 1) ('a', 2) ('a', 3) ('b', 1) ('b', 2) ('b', 3) ('c', 1) ('c', 2) ('c', 3)
If we were to add a third iterable, every one of these tuples would be matched up to an item in this third iterable. For example, if we had a third list containing
"x",
"y", and
"z", we would get output like this:
# ('a', 1, 'x') ('a', 1, 'y') ('a', 1, 'z') ('a', 2, 'x') ... etc.
The
repeat parameter is most useful for when we want to use the same iterable multiple times. We can see an example of this in our code for finding roll combinations. We can easily add more and more dice by increasing the value of
repeat.
If we set a
repeat value of
2 or more when we have multiple iterables,
product will duplicate all of the iterables for the purposes of finding the cartesian product. The following functions are identical in terms of functionality:
c_product_1 = product(["a", "b", "c"], [1, 2, 3], repeat=2) c_product_2 = product(["a", "b", "c"], [1, 2, 3], ["a", "b", "c"], [1, 2, 3])
That just about wraps up our introduction to the
itertools
product function. I hope you learnt something new, and I encourage you to play around with the things we've covered here to really understand how it all works.
We release new snippet posts every Monday, and something a little more substantial on Thursdays, but just in case you forget, you might want to follow us on Twitter to keep up to date with all our content. Next Monday we'll be covering some other cool
itertools functions, so make sure to check back next week!
We'd also love to hear about cool tips and tricks you think we should write about, so get in touch!
|
https://blog.tecladocode.com/python-snippet-8-itertools-part-1-product/
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Toggle navigation
About
Products
WPC Decking
Wall Panel
Privacy Fence
PVC Synthetic Boat Decking
PVC Fence
Outdoor Furniture
Market
Gallery
Durable Composite deck For Sale
Product List
kerala pvc panel ceiling image
australia wood panel
veranda horizontal rail kit
composite decking forms chat line
composite decking johannesburg
snap together tiles on grass
composite decking bc canada
how to finish the edges of composite materials
best product for uv protection of plastic
plastic grates for stone decking
best boat flooring material mexico
2x4 vinyl boards for fence
home depot pour and floor composite decking
interlocking plastic wall panels for shower
composite decking for raised beds
plastic tongue groove panels in hong kong
4x8 exterior composite siding
shadow box fence picket calculator
buy replacement wooden slats for garden bench
gypsum ceiling trading in namibia
composite 2x4 boards
tongue and groove mahogany composite decking
suppliers of garden edging singapore
wpc indoor panel
products made from wood plastic composite
houses with faux balcony exteriors
roll up beach deck pathway
pre cast boundary wall kerala kannur
cheapest fencing and pvc gates
cutting off porch planks craftsman
commercial grade polycarbonate exterior walls
wpc wall cladding cape town
2x6x14 tongue and groove
waterproofing over plywood subfloor
pvc decking weight
pine wood board and batten siding construction
installing deck around inground pool
how to prepare and paint composite wood siding
composite truck bed boards
moore wood defender composite deck
panel mdf interior door egypt
plastic garden fence panels suppliers
four point bending test of wood based composites
boat uk to spain
brown exterior composite wood stair treads
thin plastic decking to cover old decking boards
weight of pavers by foot
3 foot high wood fencing
synthetic wood tongue groove flooring
cheap patio floor without pavers around pool
reclaimed battleship lumber
structural foam and plastic composite
horizontal wood fence chicago
outdoor floor that look like wood
pvc self supportive wall panels
used railroad ties for sale california
fire proof fencing panels
lanai for 24 foot above ground pool
deck mount outboard bracket
wpc pergola manufacturer in dubai
wpc board in riyadh
patio decks decks houston
flowers wooden fence murals tutorial
lightweight wood for rooftops
cambridge pre packaged pavilion kits for sale
outdoor floor installation
extruded polystyrene foam composites panels for sale
exterior waterproof underlayment board
tongue and groove paneling wickes
composite company in bangalore
deck and balcony tiles cedar installations
floor plan maker
blue stain pine paneling 4 x 8 sheets
furniture projects using composite
high density plastic flooring outdoor
clear vinyl curtains for patio south africa
outdoor deck floating floor laminate
libya tiles importers
wpc board future in india
prefinished wood plank ceiling for outdoor patio
street composite dustbin singapore
kitchen waterproof flooring
decks and porches high fire resistance material
outdoor garden fibre flooring
trespa grooved worktops prices
wpc composite decking price singapore
plastic roof tiles for sheds
decorative screen panels outside
tongue and groove paneling bathroom
cheapest composite decking in sweden
can you attach deck to vinyl fencing
12x20 deck kit
buy tongue and groove pvc fence in uae
price of wood fences in india
static bending floor sample problem statement
what are the disadvantages of pvc ceiling
anti termite plastic wall panel
pictures of shiplap timber cladding south africa
maple flooring mildew resistant
outside flooring to put on grass
plastic wood outdoor flooring mexico
plastic wood tiles south africa
free project natural fiber
1 4 inch wood wall paneling
plastic tiles for shed
what stain to use on wood around a swimming pool
wood plastic composite business in india
two tiered deck around above ground pool
get inexpensive interlocking patio tiles
pvc pipe deck cover metal
balcony railing pictures
china laminate flooring manufacturer
white cracked ice plastic wall panel in cargo van
make garden bench out of decking ideas
cheap composite decking products brisbane
laminate flooring importer list
patio railing in south africa
panels aluminium fencing supplies ireland
lowes free standing fence panels
4x8 composite wood exterior cladding
redwood tongue and groove fence
solid organs vs solid organs
basket weave composite privacy fencing
best ceiling in zimbabwe
price for composite fencing malaysia
outdoor stairway iron designs in nigeria
lightweight stone for exterior deck flooring
3 mm hardboard sheet
pvc wood trim board price
wooden fence dubai sales
modern interior wall paneling
tongue and groove recycled plastic lumber best price
2 inch composite decking
corner bench seating
composite trailer flooring
insulated wood fence design
neo composite deck tiles review
wood fence panels delivered
outdoor pavilion construction plans
roll out vinyl decking
2x4 hollow polymer
jenis jenis pagar
wooden pallet supplier in qatar
flame requirements for decorative wall boards
disadvantages of timber floor
can composite decking be attached directly to concrete
fence rental near me
calculate wood ceiling non combustible
innovative composite design may replace aluminum chassis
can you use nails and screws in composite doors uk
saman deck stain
4 feet by 6 feet exterior composite flooring
composite wood versus gorilla decking
how much does a composite table cost
plans for pool decks for above ground pools
84 lumber pressure treated
composite split cedar fencing
aluminum honeycomb decking material
light weight panels for yacht interiors
pvc foam board floor advertising graphics
cheap pvc tiles in kenya
how to build a craftsman porch railing
pvc sheet shutter fence kenya moore
exterior plastic wood wall panels
spanish design of wall wood panelling
estimate for composite privacy fence
ultra modern boundary wall designs
best sealer for new mahogany deck
scrap wood collectors in malaysia
composite decking for outdoor factory in malaysia
translucent deck floor
wholesale wpc outdoor decking uk
plastic composite board for shuttering india
styrofoam insulated panels suppliers in manila
garages with decks on top in uk
pergola bill of materials
ship lightweight material
wpc fence panel
patio deck floor options
pvc ceiling advantages and disadvantages
how to remove cigarette burns from composite decking
2 ft tall garden fence
white pvc deck boards size
insulated building panels supplier
polyurethane on front porch decking
laser cut metal fence uk
outdoor patio flooring materials
vinyl picket fence panels uk
fake lumber trailer decking
interlocking deck tiles
advantages of non load bearing walls
vertical grain fir flooring for sale
fence industry standard
3 4 bench wooden slats for fences
outdoor projects out of recycled wood fences
can i shim my sagging composite deck boards
using biscuits on the miter joint of composite decking
cost of pvc mold in nigeria
2x4 composite lumber white
recycled content wood panel board
adding height to aluminum fence
daybed made from deck
sun fence shades with clips on fence post
wpc plastic wood board manufacturer malaysia
plastic composite sheet products
wood stairs and railing philippines
designing for composite climate
8 foot tall fence panels for sale
build countertop from 2x4
outdoor wall composite flooring
outdoor prefab deck stairs
fibreglass pools for sale
the best building materials for tropical climates
cheap fence panels for decking
dock decking idaho
cost box of vinyl siding
non splintering wood fence supplier
where to find wpc decking in cyprus
how much for a trex deck around a pool
jig saw blade to cut pvc board
how to paint synthetic molding
recycled exterior patio tiles
max spacing for diagonal trex decking
1 x 6 pressure treated tongue and groove boards
convert fence to solid
vinyl 2x4 boards
used railroad ties for sale in california
advantages of pharma doors panels
rooftop fence cost
max spacing between vinyl deck posts posts tagged
decking concrete pads uk
composite wood decking tiles
vinyl ceiling wood look
bacolod outdoor decking
custom cut pvc decking
porous composite decking
advantage of ribbed slab over solid slab
hunter green composite railing
plastic decking for dog run
wpc versus untreated wood durability
cellular pvc fence vs wpc fence
outdoor decking materials wood decking
composite railroad ties for landscaping
8 foot chain link fence prices in kenya
composite deck building materials nigeria
tongue and groove decking plastic wood
how much would labor be on a deck replacement
what materials are in a train carriage
how much is
breathable floor covering
18 foot round pool deck
premade deck panels
vinyl covered luan panel
2 stair tread overhang length
indoor vinyl tiles abu dhabi
wpc decking distributor in australia
decorative wood outdoor wall panels impact resistant foam
composite wood furring strips
modular wooden flooring brisbane
buy wholesale composite fence panels
spruce fence 6x8
boardwalk decking tiles uk
how to make a slanted backrest
plastic veneer for decking
plastic paneling hot tub siding
cheap decking west midlands
affordable patio covers houston
feed lot panel deck railing
manufactured home deck plans
outdoor park benches made of composite material
thai sun wood composite
natural composite deck for pontoons
swimming terrace flooring
pool materials suppliers in trinidad and tobago
pvc carpets prices kenya
print wood texture on plastic
cheap sheets for decking
polycarbonate fence panel
bargain outlet decking
wood plastic polyethylene lumber deck packages
1x6 tongue and groove treated planks flooring
composite decking rotherham
outdoor wood wall board in australia
pool deck flooring singapore
composite lumber wall penal 2x6
flexible outdoor flooring you can cut to shapes
cheap price wood plastic dustbin
3 rail wood fence with wire
deck over living space suppliers
woodlands pavilion seating for handicapped
wood plank flooring quezon city philippines
cons of cheap pine boards for walls
custom decks over basements for rent
simpson fence post brackets
non distorting outdoor decking importers
most durable fence coating
using tongue and groove flooring as a wall cladding
how much does it cost to cover my deck with roof
build on upstairs patios
picket fence malaysia in uk
garage wall panels in uk
pvc composite deck cleaner that is safe
composite wood truck bed floor
green decking wpc moldova
outer facade of pillars with plywood
material roof terrace covering idea
refinishing acrylic impregnated flooring
waterproofing decks over living spaces
can you use trex to build a retaining wall
outdoor fence panel fixing for thanksgiving
outdoor plastic wall roof panels
decking timber prices auckland
copper clad laminate spain
solar reflective index timber decking
pvc skirting south africa
composite decking growth in europe
price per linear foot for fence installation
pvc roof membrane with textured surface
manufacturer shadow box fence panels georgia
sears floor model refrigerator
floor cushions india
4x4 bench outdoor designs
pvc panel ceiling boards kenya
what is sanitary dustbin
solid fencing options
plastic laminate advantages and disadvantages
recycle plastic company in usa
how to keep deck boards from warping
composite wood rainscreen siding
vinyl picket fence panel
21 foot round pool how much fencing
how to make my laminate steps more safe
interior wall design supplier in qatar
acacia wood flooring best quality 2018
interlocking plastic deck tiles for cement
decking pvc decking reviews kitchen
outdoor floor decking in johor
composite decking for pontoon boats price
how to fence on top of a concrete curb in yard
trex indoor style slanted groove porch board
wood plastic composite manufacturer in tamilnadu
transparent 2mm pvc sheet
waterproof 2x4 boards
outdoor grass for floor singapore
outdoor deck boxes for sale
wood plastic composite in nigeria
how to clean composite plastic and wood patio furniture
phase change floor buy
special wooden cladding for houses
properties of a good dustbin
style selections vs choice deck
composite wood block flooring
floor sheathing trinidad and tobago
durable wood flooring supplier in new zealand
plastic slatted floor price in sri lanka sale
composite decking market
28 ft above ground swimming pool with deck
pvc wpc board germany
lowes composite composite decking price per square foot
vinyl or plastic ceiling panels pretoria
laying wooden flooring how to organise the staggering
disadvantages of plastic tiles
philippine house design with rooftop images vancouver
pressure treated bender plywood
vinyl fence manufacturers from china
white pvc fence slats
timber decking supplier qatar
pergola shade covers
hampton bay replacement wood slats
prefab steps for patio doors
marble philippines
roof deck beach homes
fake wall panels sri lanka
does lowes carry stick on reclaimed wood
vinyl deck posts with cable railing
composite exterior deck skirting board
4 x 8 sheets of plastic composite
gothic images of the grim reaper
resin outdoor privacy screen taupe
anti slip strips for decking ireland
football field fencing cost
windows design pictures in sri lanka
plywood floor panel wood texture illustrator
4 x 8 pvc sheets mexico
2x6 composite decking board cost
camouflage paneling for walls
how to make a deck pervious
tongue and groove aluminum boards
pvc ceiling in angola
composite sheeting material
wpc product project photos gallery | pictures | images
composite decking las vegas
modular housing in cape town
waterproofing for wood fence
difference between iron wood and wpc floor tiles
cast iron baluster posts
slats for park benches nz
decking import solutions
pvc groove philippines
how to touch up composite decking
deck floor plans 24ft x 12ft
cost to install wood siding on a house canada
where to buy round rail for fencing in nj
finger jointed porch flooring
manufacturer of plastic bag in sri lanka
how to make fibreglass anti slip
diy tile cost vs bamboo deck flooring
composite decking driftwood
untreated landscape timbers
attaching wood posts to concrete without brackets
pvc deck planks be all one length
bamboo decking co nz
railroad ties for sale in san fernando valley
can composite decking be used safely indoors
1x6 or 2x6 for fence
picnic table replacement slats
vinyl fence panels san diego
how to clean polywood outdoor furniture
aircraft nonskid walkway material
making a seat out of composite decking
marine interior paneling
how to make a pedal car out pvc pipe
boat floor covering material
swimming pool fencing sydney
bamboo roofing for pergolas
anchoring post to concrete slab
how to build steps for a pool with a platform
how to attach fence to concrete retaining wall
composite deck bench plans
foam rubber swim mats
sheets pvc united kingdom
high density fiberboard india
bamboo flooring cost in kerala
wooden barge building
composite deck railing systems home garden grills
porcelain decking sold in canada
fence posts metal
deck floor products
outdoor eco plastic wall panels
cheap outdoor patio flooring ideas
wall finishes for swimming pool environment
12 inch wide composite decking
cost to install wood ceiling paneling in denver
best panel width for stability of a fence
build a floating deck over pavers
how much cheaper is wood decking compared to pvc
diy outdoor pergola designs
treated plywood on boat lift over water
composite deck railing gates
composite decking on concrete stoop designs
gray composite flooring on sale
wpc garden deck with compression molding composites
gazebos at pricesmart
exterior wall plastic panels new zealand
outside floor tiles in india
bench slats in german
sloped floor built room out of a porch
best material for deck post
composite pvc sheet tanzania
most water resistant exterior tongue and groove deck
stairs out of composite decking installation
how to install wood plastic floor
stair railing parts defined
pvc deck rail post questions
playground covering ideas
metal curtain rail brackets
wpc material advantage and disadvantage
outdoor sheet wood
usa grown rot resistant woods for decking
pool wooden deck how to install
4x8 sheets plastic panels
2x6 white composite lumber
hollow plastic decking boards australia
how finish ends composite deck
laminate flooring price per square meter kenya
kerala style wood paneling
plastic boat deck lids
24 ft pool deck
ornamental fence brackets
pvc deck boards against house
exterior screen wall panels
balusters definition of socialism
landmark westside pavilion cinemas showtimes
above ground pool deck plans 24ft round patio
decorative exterior gable trim
how to build a snap it vinyl lattice gate
hardware to mount two boards at 45 degrees
trex decking distributors in denver
resistant material for ramps
brackets to fasten wood to concrete
deck flooring different from porch flooring
panels for houseboat walls
cost of building a precast concrete wall in zimbabwe
composite decking used as flower bed edging
review of ikea floor decking
staircase baluster calculator for decks
designs for fences in nigeria
hollow pots in suspended floor construction
berkeley forge bench repair kit
contemporary building facades design reviews
travertine tiles texture
composite and vinyl deck plans crown
cost of composite decking for porch
pvc spec sheet
boat dock plastic decking
concrete step covering outside
lightweight tile for balcony
how to build a triangle pergola
compare wood fence boards advantages
ceiling boards kroonstad
wood plastic composites wpc new zealand
sustainable outdoor floor material
hardboard wall panel indonesia
replacement carpet for pool deck
price of dura cladding
wpc lattices malaysia
wind friendly fence panels
how much does it cost to make plastic per square inch
wood timber cantilever knee brace
what slope are steel outside stair stringers
pergola wood kits gauteng
composite wood decking wpc problems with
plastic wooden decking in mexico
how to make my vinyl fence gate wider
how much to replace decking on a dock
convert sq ft price to linear foot price
average cost to install ceiling planks
how to build a 12x20 pavillion
urine stains wooden deck
wood plastic composite manufacturers in delhi
is there a fence contractors in manila
discount composite deck tiles
privacy fence screen sails
hard plastic panel singapore
free wooden garbage box plans
2 x 6 composite board covers
plans for a curved mason outdoor bench
how many linear fee are wood fence panels
south africa decking planks
diy curtains back patio
deck install wall attachment
plywood dock ramp
how to reduce static on outdoor deck
how to build deck with angle benches
1x6 roof decking properties
putting a wood deck over a concrete patio
1x3 tongue and groove decking
hog wire deck railing images
what color planters on red deck
cost of tongue and groove boards
best deal on composite decking
hard plastic deck flooring lumber
what weight will ilea decking take
using composite decking for fencing
outdoor wood for deck philippines
metal outdoor pub table and chairs
retractable pergola roof diy
can regular bits be used to cut composite wood
decking master waterproof vinyl decking
4x4x10 composite post
turn key vinyl extruding facilities
composite geodesic high rise
how to attach a bench to my fence post
plastic wooden deck for garden in cyprus
wedding fabric portland or
decks with fake wood
outdoor wooden tiles over concrete
price of lumber per linear foot
exterior wood panel over cement board sheathing
12x16 deck kit
4 thick plastic or vinyl decking
material to fill in gap in decks
adding floor joists
wooden wall panels south africa
covered patios pictures
veranda premium composite railing
sellers of durable chain link fence kenya
l shaped deck bench framing
how to make a fence out of pvc pipe
convex composite fencing
pvc decking screws industries
outdoor floor decking tiles italy
trex friendly mats
cebu philippines fence wall material
plastic post and rail fencing n ireland
plastic wood strips
platform on a slope
exterior wood tile india
8x8 pressure treated post lowes
plastic fencing in brentwood essex
vinyl plank flooring on freezing porch
bamboo wood planks philippines
name of pvc fence suppliers
demerits of aluminium composite panel
veranda armour guard 16ft brazilian walnut
prefabricated composite wall cape town
removable decorative fence panels
composite wooden decking in united kingdom
red cedar replacement swing slats
scranton craftsman railing
wood plastic composite wall cladding uk
matrix plastic decor screen ebay
18mm construction grade film faced plywood
weather resistant laminate flooring for outside use
pine deck railing for sale in philippines
evergreen decking colors
treating mildew in bamboo decking
can composite be stained
outdoor planters las vegas
solid plastic soft flooring
pvc laminate trailer flooring
high quality laminated foam board deck
cheap outdoor flooring in india
best room tile carpet to buy in ghana
simple house design in philippines with rooftop
australian composite decking reviews consumer reports
framing lumber composite price
where to buy encore deck stain
best deck boat reviews
how to attach 6x6 post to deck
who makes aluminum interlocking floors
what is the cost to paint 100 feet iron fence
no dig fencing for residential homes
fabricators of pop ceiling in sri lanka
can you make six foot fence taller
how much to charge for labor per foot wooden fence
rubber edge molding for inground pools
grooved plywood australia
cladding design solutions in south africa
carbide wear composite plate
best new deck sealer
qualified pvc for interior decoration
reclaimed boat decking
lattice fence cost
trespa panel price check
split rail fencing at 84 lumber
outdoor shed qatar for sale
is it safe to burn composite decking
how long does landscape composite bender board last
heated exterior deck mats
best slip resistant stairs singapore
pvc foam board australia
soundproof flooring suppliers
wall around deck
melbourne cheapest decking a roof
patio deck surface pad
easy diy corner benches
waterproof building foam board
plans for basic porch steps hand railing
wood flooring importer in singapore
wpc pergolas images with canvas
rich kerala staircase railing wood
composite patio decking fixing for chili
anti swell wpc decking floor in dubai
solid vinyl deck skirting question
faux log cabin walls
pvc fence panel installation
cost of trex deck vs concrete
uses advantages and disadvantages of composite wall
cedar decking pros and cons
where can i purchase alcoa oasis decking
carpeting that can be used for composite decking
how to remove wall tile adhesives
low voltage lighting for vinyl deck posts keeping
starboard to replace boat deck
what wood withstands weather
marine plywood for decking
pressure treated lumber at 84 lumber
how to build a rooftop deck on a pitched roof
24 foot diameter round pool deck plans
composite decking 6 inch wide with 3 inch grooves night
concrete boat dock decking cracking
is composite decking fire retardent
pvc waterproof decking costs
nosing outdoor floor materials in uk
prefab wooden porch steps for outside
square concrete patio landscaping ideas cheap
composite vs pvc decking under shingles
2x4 cover sleeve
twin wall polycarbonate ontario canada
how waterproof wood laminate furniture
how much a square metre for decking
interstate visions cedar grain vinyl fence
build a pergola on an existing deck
green decking wide planks swimming pool
decking composite in guangzhou
wood plastic composite deck in czech
plastic deck railing flower boxes
free 12x12 pool deck plans
coosa board boat decking installation
new side panels for hot tub uk
wood look composite material
how durable is wood floor paint
plastic cover for balcony
wood plastic beams suppliers in qatar
bendy board plywood price
paint for decking joists
dynamic composites railway ties
labour cost for 30 hours for decking
veranda decking recall
how to build a bench with composite lumber
slotted garage wall panels
composites ireland for sale in hong kong
how to build a deck over a driveway
8 foot vinyl fencing with lattice
wood plastic composite demand india
decks ladies sale
pvc youngs modulus
how much to install 200 ft of wood fence
where can hollow pot floor be used
plastic fencing products ireland
how to waterproof a 2nd floor deck prior to tiling
wolf decking rating reviews
cheap ways to get a pavilion in my backyard
4 ft x 8 ft pressure treated fence panel
never needs painting wpc exterior decks
8 ft high composite privacy fence panels
pvc gates northern ireland
materials needed to build a 16x16 deck floor
trinidad and tobago outdoor deck
pvc structure composite panels
clear see through curtains for porch
plastic pool deck supplier
hollow pvc bead board
how to make a wood railing for outside
cheap decking in the west midlands
blue decking material
rugs that can be used on fiberon decking
stair railing for a concrete stoop
white mdf sheets wholesale
plastic supplier manila philippines
tile board paneling water resistant
my beach house grey composite boards look brown
recycled compressed plastic outdoor furniture
vinyl fence panel on concrete patio
european federation of the plywood industry
ceramic tiles price list in saudi arabia
plastic fence is good to make a backyard fence
fiberon vs style selections
calculator chain price malaysia
wood plastic composite best decking material suppliers
trespa fencing what is it
split mosaic tiles uk
advantages of pvc wall panels
lowe s railroad ties price
how to build a deck on a slope with pictures
why is hollow pot used as floor slab
advantages of wood benches
price of quarter inch medium density foam sheet in kenya
white pvc ceiling belgium
pvc youngs modulus elastic modulus
plastic wooden fencing supplies berkshire
northern ireland outdoor flooring alterative decking
modern window grills design for srilankan homes
vinyl siding india
ground level deck using composite
laminates and wall suppliers in philippines
wolf pvc decking reviews of windows
trex elevations cost per square foot
termite proofing flooring
pavilion mall binan laguna
commercial fence installation orlando
cheap solution for outdoor flooring
process of manufacturing wood
core plastic wood board germany
artificial decking south africa
traditional deck chairs for sale uk
environmentally friendly outdoor deck for sale nigeria
water resistant wood plastic composite material
trex adirondack glider
wolf pvc decking prices garage
decking with fire rating
pvc board planks
wooden prefab gazebo for sale philippines
best flooring materials for terrace
good energy pontoon vinyl flooring
wood plastic dustbin price in malaysia
plastic laminated plywood sheets
synthetic decking production in uk do not wash
pictures of tile wood flooring
snap on deck board covers
synthetic grass distributor in netherland
composite wood trellis in uk
creative ways to cover concrete stairs
wolf pvc decking price kitchen
anti termite composite wood fence
home depot tongue and groove decking
vinyl fence vs wood
where to purchase composite flooring in united states
boat decking ideas
horizontal composite fences miami
used railroad ties portland oregon
how to add privacy screen to existing composite deck
cheapest wood fence options nonskid
outdoor tile vs composite material for balcony
is trex suitable for ground contact
porch board overhang
images of house with wall outside tiles in nigeria
cheapest ceramic floor tile in ghana
boat floor options other than wood
rooftop terrace surface materials
non slip strips for decks
how do you attach lattice panels to carport
how to clean paint off pvc deck boards under deck
best fade resistant composite decking
wood deck materials available in philippines boat
pvc gates for decks at home
how to build removable panels
best pvc decking material no maintenance
wilson fisher fire pit del rio
2x4 treated deck wholesale
6x6 deck guard post attachment to deck
outdoor floor tiles easy install sprinkler
black covering under deck
pvc interiors disadvantages
fence panels to hide garbage cans
stone pool deck repair
spruce vs pine lumber for fences
outdoor wall panels wood sydney
how heavy is a composite decking board
is polywood and trex the same
wood chips blow into my pool
veranda regency decking
composite fencing sales
trex per foot pricing
portable fence kenya
composite bridge deck railing example
partial brick and pvc post cladding covering
composite siding used as fencing
douglas pvc gypsum board ceiling
fence made out of wooden pallets
singapore recycle plastic lumber bench
outdoor landscape decking designs
engineered beams for sale
ghana plastic wood company and prices
how to repair plastic picnic table top
how to waterproof wooden exterior walls of a house
canadian wall cladding
composite bench plans
green heart wood for sale in uk
plastic wood products pricing south africa
farm gate on a slope in qatar
lattice fence in trinidad
best value for composite decking
wpc deck flooring prices supplier
evergreen composite decking color samples
anti fogging additives wood materials
ground reflectance factor of wooden decking
mobile home deck roof plans
4x8 waterproof decking material
composite deck prices in kenya in nairobi
sleeve for 2x4 home depot
composite horizontal fence boards
wear and tear on laminate flooring
impact of pvc tongue and groove for construction
cost of stockade fence per foot
composite privacy fence panels cost
common wpc panels wholesale
laminate floor philippines
trex vs wood pacific northwest area
floating deck using cinder blocks
non slip surface for cows in trailer
bench plans using pressure treated 2x4 dimensions
where do i get plastic pool coping edge
open interior staircase railings
tongue and groove pvc deck boards too close
a cantilevered balcony cost
an existing pvc fence
timber suppliers crete greece
free standing balconies
deck lumber from recycled plastic colorado
make a picnic table with composite decking
installing pvc deck railing systems
outdoor translucent panels
open fire pit in pavilion
pvc decking texas
install vinyl flooring in bathroom
plastic balcony railing
how to make waterproof outdoor deck dampproof
how to remove black tree sap from pvc deck
building backyard kids playground
how to higher existing fence
timber composite explanation
kazakhstan plywood
anti slip stair treads for composite decking
pvc skirting board germany
multi colored the fence specialist
harbor freight planer deck boards
3d interior wall panels egypt
vinyl exterior cladding kenya
plastic cladding for exterior walls
park benches for sale near me
blocks decking in cameroon
plastic lattice with wood posts
farm fencing green composite flex
pallet furniture business plan sample
how to make an outdoor table with vinyl decking
american floor mats promo
how to build a gate from composite decking
treated deck boards with grooves on bottom
decking namibia
9 foot fence boards
how to build vegetable garden fences
how to cover a deck to keep underside dry
wooden surround for above ground pools deck with pergola
molding design in sri lanka
advantages and disadvantages of laminate ceiling
teak wood shower floor in uae
horse fence cost calculator
north carolina outdoor handrail codes residential
vinyl sleeve for existing 2x4 lumber
best fence material
wood garden border fence
external cladding panels prefinished
pvc decking and railing in south africa
vinyl fence panel seconds for sale
wood plastic application wall panel disadvantages
wpc deck in indonesia
composite scaffolding plank
reciprocal saw blades for composite decking
how long will pvc wood last outdoors
wet boards for bathrooms
best material for porch railings
marine grade vinyl flooring bamboo
wpc security cabin price in india
cheapest pvc composite decking
backyard plastic wood panels
cheap interior floor covering
plastic molding manufacturing china
stan dawes fencing prices
building outdoor cabinets with composite decking
fencing specialists dublin
timber homes south africa
prices of wood by cubic foot
wood plastic composite supplier in singapore
how to install chain link fence next to retaining wall
outdoor wooden floor decorations high flame separation
dock pvc deck materials cedar
sleeper frame for decking
under composite decking
restaurant banquette bench seating
pictures of laminate laying against the hallway trilogy
european composite decking in hong kong
how much can side of stair tread overhang side
direction of laminate wood flooring
garden gates and fencing abu dhabi
wall concreting pics in kerala
exterior wall covering products supplier
deck over partial slab
composite playground fence components
precio del pool per linear foot
composite outdoor dining furniture
lowes wood fences panels
choice deck lowes
warna cat besi tempa
pvc wall panel manufacturing process
consumer reports and trex
temporary exterior flooring
calculate decking boards
composite fence post extensions
malaysian wooden boats
how to build a gate wood fence in a slope angle
2ft x 8ft vinyl fence
ideas for pool decks on above ground pools
labor cost for vinyl railing in german
plants that used as fence in backyard
deck stair nosing
pool deck flooring mats
pontoon railing material
how to conceal an ugly garden wall
buy composite decking for above ground pool
4x6 foot fence panels
pvc desk plans garage
exterior cladding similar to wood panels uae
mesh fence on a brick wall
best source for pontoon decking
cellular pvc decking price transfer
labor cost to install lattice
how to attach deck rails without brackets
labor cost to install plank decking roof
how much will meter house wall panel cost
split rail composite fencing
floor supplies wholesale
composite material for outdoor dust bins
weatherproof floor boxes for decks
what is courtyard fencing by kingsford
garden walls fences and hedges
wood composite board in uk
how to fence a verandah
deck timber post extenders
floor installation cost
outdoor wall covering veneer laminates
wpc boards india supplier
pvc deck cleaner in power
building a polymer deck furniture
vinyl flooring manufacturers in belgium
free wood park bench plans
plastic exterior stone veneer panels
low maintenance composite wood wall panel with cheap price
chalet bungalow pvc cladding
composite wood look panels for outdoor porch ceiling
diy interlocking decking singapore
pvc plastic ceiling board malta
tongue and groove pattern stock pine board
deck benches with brackets
how many boards are in a fence panel
6x8 privacy wood fence panels for sale
waterproof deck manufacturers
plastic garden mesh malta
pvc deck boards christmas
non combustible wood composite floor
outdoor privacy screens for decks cost plus world imports
what to use on lanai ceiling in florida
job in wpc board in india
build a paver bench and columns with lights
can i add to the height of my existing aluminum fence
where tongue and groove could be mostly used
wpc composite decking sealer
best non wood for decking
cost of synthetic teak for boats
parenchymatous injury and hollow injury
airstream with plastic plywood panels
rectangular above ground pool decks building plans
plastic wood board canada sale price
composite chain cost wiki
pvc coping cape town
best floor covering to cover concrete
plastic wood boxes target
wood plastic composite casual tables and benches
seaboard composite 4 x 8 sheets
terrace flooring pvc
ubs dealing with rhino boards and ceiling boards
gorilla deck boards cost
alteratives to plywood
composite wood posts for craftsman homes
vinyl deck railing kits video
how to make bench seating from composite decking
does cedar fencing shrink
pvc foam formulation
outdoors insulation panels
laying plastic deck tiles specs
rustic loft railing
roof top patio hose bib
thermal expansion of vinyl flooring
kerala style window frames
laminated floor for outdoor in dubai
black pvc deck railing lighting
ramp running lengthwise with deck
pvc tile manufactures in kenya
composite bead board flooring for van trailers
second story patio flooring ideas
neo tile urban groove light grey porcelain tile
composite plastic shed sales
corrugated transparent roofing for decks
lowes metal railing
how to build louvered screen wall
natural fibre polymer composite problem statement
deck kits cheap
wood look cement pavers for sale
plastic wall cladding south africa
lowes deck install cost in german
actual dimensions of 5 4 deck boards
vinyl deck posts and railing materials
deck platforms down steep slope
horizontal wood slat screen wall
outdoor pool shower supplier singapore
cheap recycled plastic sheet
privacy fence black aluminum in malaysia
home garden plastic deck materials online
how far will 2x6 treated deck boards span
exterior wall tiles ghana
temporary outdoor fencing for children
outdoor flooring around pool
pvc fence profile malaysia
sample project on plastic roads
wood plastic composite floor panel technical difficulties
4 ft wood fence panels
exterior wood deck suppliers uae
wpc decking poland
fireproof plastic decking
2 x4 or 2x8 on deck
wood vs synthetic surfboard
outdoor composite wall board suppliers
pvc deck overlay
no wood knots wood flooring supplier
labor louvered fence panels labor cost
outdoor wooden floor equipment uae nursery
teak cost per square meter
laminate flooring sri lanka
exterior grade vinyl flooring
best ideal tile for balcony
how many fence panels linear feet
build gate with composite material
wood fencing supplier in kenya
5 4 metre decking boards ireland
composite pre built decks
which company in ghana deals in cladding stone
outside floors enclosures
anchoring vinyl fence to cement pad
pvc deck flooring span
retaining wall with deck boards
decking over concrete front porch
how do you make wooden steps for above ground pool entry
standoff for deck ledger
84 lumber vinyl deck railing
2 x 12 prime lumber in hong kong
12 inch terrace board edging
use wood fencing panel suppliers perth wa
using composite decking for shed siding
composite wood storage sheds
how to paint wood composite furniture
wood skirting board distributor in ireland
lino flooring dublin woodie
home made decks cleaner for composite decks
non slip waterproofing for wood decking
materials for exterior dubai
reusing decking when expanding decking
pvc teak and holly in canada
manufacturer of wpc in philippines
prices per one tile in ghana
ultra design composite decking
liquid applied plastic floor covering
non combustible floor in german
main advantages of wood wool slabs
how to drill a hole in concrete to set fence post
wood composite plank facade cladding
pvc sheet for deck skirting knitted
engineered wpc outdoor flooring for sale
noise reduction fencing and made in usa
can i use composite decking boards for raised beds
replacement wood cast iron bench
wood plastic composite board floor specifications meaning
wood deck panels in houston
stone wall cladding price in kerala
how long does a wood deck last
10x10 pergola shade canopy
composite square perforated deck panels
can you put nature stone over decking
home depot pvc 2x4
average cost of putting up a fence
pine stockade fence board manufacturing
show raised composite decking patio
disadvantage of sandwich panel wall
palo china flooring for sale philippines
trex decking scratch removal
building a wood railing for concrete steps
wooden veranda designs eco friendly
shaw flooring waterproof snap together
quick ways to cover balcony
plastic poles in namibia
board shipping boxes at target
bargain outlet garden decking kits
outdoor tiles philippines
indoor outdoor decorative wall panel
what is the difference between flat slab and solid slab
deck boards butted or staggered
remove scratches from composite porch
parkland heritage victorian gazebo cover
americas most trusted under deck drainage
non flammable plants for exterior vertical garden
adding to wood fence for more privacy
recovering cement porch floors
10 ft yard composite fence supplier
lowes composite tile decking
outdoor deck carpet installation
2018 pre built decks
composite decking suppliers in west yorkshire
artificial external flooring paintable
tongue and groove pvc deck boards width
pvc garden fencing ireland
deck and above ground pool designs
veneer ceiling tiles
what is the best composite decking in the market
hollow core pvc patio decking
pop ceiling design germany
plastic decking for a balcony
what is the best wooden deck tiles uk
wpc decking price malaysia
hollow core slab suppliers of wood
42 inch aluminum rail price per ft installed
pvc deck rail post jobs
pictures of ecological terrace fences to allow privacy
timber edge to swimming pool
composite deck installation
pine furniture board wickes
coosa composite decking
pool patio designs photos
cheap decking options malaysia
plastic wood for jetties walkways with stepping
wpc flooring manufacturer germany
plastic raised decking
patio tiles made in usa
pallet fence plans
marine treated timber joists
plexi glass for a deck
composite stone for outdoor use
how to build a vinyl lattice gate
systems furniture panel station
fencing calculator south africa
interlocking polypropylene fake stones for exterior
faux teak and holly vinyl flooring
2x10x8 composite
wholesale composite fence anti temperature
wood plastic composite roofing lebanon
building composite gates with wpc
material cut list for 16x16 deck
pvc deck plank pricing quote
dull gray deck boards
pvc deck flooring estimator
can pvc wall panels be used in a hallway
disadvantage of composite panel system
composite boards dealers in kenya
porcelain deck tile grids
what kind of nails for smart siding
aluminum tongue and groove planks
how to install steel deck in philippines
build modern composite fence in hong kong
eco composite material weather proof
pvc privacy fence northern ireland
roof top deck hours
fiberon decking liquidation
how to install concrete window moulding philippines
outdoor deck composite flooring china
privacy fencing ideas using lattice
mdf board supplier in cebu
plywood used for waterproofing walls
6 panel 42 x 96 mahogany wood slab doors
garden fence panels healthy
deck and patio railing designs
wood pergola cost
ghana iron rod price
white no toxic solid composite fence
stick down floor covering for kitchens
temporary flooring ideas for portable gazebos
wood supplier philippines
teak and holly linoleum floor
plastic tiles that look like decking
does composite decks come in railing for decks
what is the best fence to put atop a wood retaining wall
solid pvc deck flooring quote
plastic timber india
good quaility 4x4x10 fence post
how to make furniture from railroad ties
pvc decking vs composite one
diy wooden deck over concrete slab porch
what cement is used with composite veranda decking
waterproof wall cladding sale in india
discontinued trex decking
fire retardant redwood stain
tanget plastic dealers
board distributors denmark
deck bench seat back slope
properly install railing joists spans
outdoor storage bench with inclined backrest
12x16 pool deck plans
ground clearance bellow wooden fence
composite and vinyl deck plans for liberty
indoor child care fencing
top rated composite fences uk
sierra hard top gazebo replacement roof panels
uses of wooden plastic composite panel
engineered tongue and groove porch flooring
composite deck post wrap
wood handrails for outdoor steps home depot
horizontal fencing slats
composite decking clearance install
composite wood floor and decor
what does composite cladding look like
composite lumber posts hawaii
how to make a bench with pavers fiji islands
protection in transparent pvc for balcony
pvc youngs modulus of elasticity
deck protectors for gas grills
horse box floor board
decking manufacturers in us
park bench supplier in germany
cost of 420 square foot deck
soft boat flooring material
installing laminate flooring
outdoor pavilion plans designs free with fire place
wind break privacy panels for a deck
lowes fence panels cedar composite
average cost of wood mezzanine floor canada
4ft by 8ft by 1 8 in clear or white out door panels
build planter box from composite material
what type on planters can be used on pvc decking
how to estimate an outdoor deck
composite boat flooring manufacturer
2x8x12 composite board
lightweight composite siding
waterproof wall panel materials
laminated roof decking
plastic wood composite decking joists
wpc garden hollow decking vs solid
composite outdoor decking tiles
45 degree wood railing
rooftop deck caribbean house plans
outdoor wood decking in johor bahru
composite deck skirting
unique deck baluster designs
thin plastic board
israel plastic pricing
temporary outdoor patio flooring
what company has a 1x6 tongue and groove composite
laminate front decking images
composite wood fencing horse wholesalers
artificial casing malaysia
breathable exterior plywood for subfloor used as flooring
laying garden decking floor non fading
waterproof decking boards
synthetic wood price malaysia
deck post spacing chart
ceiling boards pvc prices in south africa builders
plastic plywood home depot
middle groove pvc wall panel in hallways
fence planning calculator
decking panels manufacturer in uae
what primer to use for composite door frame
plastic pots suppliers philippines
how to build the back rest of a bench with wood
poly deck for pontoon boat floors
patio ideas for children
cedar pickets lowes
plastic fence posts suppliers
outdoor plastic carpet in south africa
exterior wall cladding for houses in malaysia
outdoor lanai ceiling contractors
plywood aquarium sealant
how much and where in lagos can i buy vinyl floor tile
making of tiles from sawdust and used pure water sachets
best wood for boat decking
plastic picket fence suppliers in cape town
cedar pros cons
ecological projects wood plastic composite products
veranda deck cleaner
pool decks vinyl or composite
where to find laminate flooring in port harcourt
building a series of decks on sloped ground
reconstituted wooden boarding
outdoor floor joist seal before decking
composite panels for boat decking
gray grooved capped composite decking board application
ikea decking review
waterproof synthetic wood flooring
wood plastic composite floors exterior wall panels
build a seat on existing decking
wood outdoor decks cost india
plastic wood deck in los angeles county inmate
better homes and gardens laying tile in bathroom
can i drive a car on composite decking
composite panels for boat floors replacement
faux wood ceiling planks
what material to use for outdoor handrails
horizonal panel fencing cost
walls and pvc ceiling panel
balcony floor material
import wholesale wpc decking dealer
cost of timber bridge per metre
wood composite supplier in johor
how to build a pvc fence with benches
8 foot high stockade fence
alternatives to marine plywood decking
composite shiplap boards
horizontal bar aluminum fence panels
deck tech southern california
modern fence walls in ghana
how to build deck railing out of hog panels
trex origins decking for sale
standard picnic table boards for weddings
concrete fence post extender
strong light weight fence
decorative garden fencing wood plastic composite fencing
cheap carpet tile in ghana
wind fence design
cheap outdoor flooring solutions fireproof
decking kits sale s a
tongue and groove porch flooring for sale
composite plywood 4 x 8 panels
roofing manufacturer philippines
disadvantages of contour crafting
second hands slabs in cape town
advantage interior wood wall
wood texture melamine mdf sheets
plywood sheets sizes denmark
how to build wood hand rail for steps
veranda composite fence boards
pvc deck furniture 2 chairs and a table for three
wood polymer lumbers flooring
glue for foam floor in a truck camper
roof decking polystyrene lumber floor liquidators
compare pvc and vinyl railing
compound wall construction cost in kerala
raw pvc deck post flower
wholesale composite plantation floor
clear fiberglass for top of pergola privacy
freedom emblem custom length clip instructions fence
rice husk wpc machine doors boards
how to attach a pergola post to top of deck
cheap price polymer panels
glue down vinyl decking products
steel deck cebu prices
cheap diy outdoor floor tiles singapore
waterproof outdoor covers for deck furniture
weather resistant decorative wall panel wholesale
slippery wood walkway
trek deck las vegas
buy composite lumber delaware
small above ground pool deck plans
floor decks in portugal praia
clading work villa in kerala
replacement bench slats in uk
harga plastic kitar
wood shades 4x8 wpc fence panels
deck linear foot
how to use composite decking wooden joists and rafters
framing patio covers calculations for nurses
buy silicone rubber in philippines
free 24ft round wook splash deck blueprints free
wpc decking in northern ireland
swimming pool flooring materials suppliers
2018 review of deck material
timber free from insect anti
ceiling tiles price in bangladesh
interlocking deck tiles versa tile
adding a gate to an existing wood fence
pvc wall fitting drawbacks
wood plastic composite supplier in brazil
spun fiberglass patio furniture
faux timber cladding in australia
free deck plans for a bestway 18 foot pool
how do you finish the deck with grooved edging
plastic patio enclosures
decking price sheet
synthetic wood for wall panels in bangalore
waterproof mezzanine floor design
pvc wall cladding systems in sri lanka
6x6 timber retaining wall
marine plywood supplier jurong singapore
where to buy laminated board in doha
wood deck pergola designs
floor paint colours
supplier for dura composite decking in ireland
materials for replacing boat plywood
lower melting point in composites
outdoor steps wooden balcony
house fence design photos in accra ghana
garden fence made out of crates
non skid coating for plastic composite
wood waterproofing materials
pvc wallboard middlebury in
how to attach handrail to concrete wall
staggering deck boards on 40 deck
wood panels for decorative fence supplier
trellis suppliers co louth
wooden deck swimming pools water resistant
deck floor stockists materials dampproof
timber decking around swimming pools
50x50 modern house plan
black privacy fence composite wood fence supply
composite railing cost calculator
insulated wall panel manufacturers johannesburg
how to make lattice for carport
synthetic decking for boats australia
prefab fence in philippines
disadvantages of plastic design method
cheaper interlock stone wood or composite deck
advantage of deck screws
where can i but 2x4x8 composite lumber
eric chrisman pvc
lanai roof systems
waterproof untreated lumber
pvc wooden balcony railing suppliers list
putting a railing on an existing deck
ready made composite platform decks
composite wood decking manufacturer in india
bio wood flooring for swimming pool
difference between treated wood and untreated wood
similarity and difference between ribbed and solid slab
dimensions can custom teak boat flooring
wall cladding tiles price in kerala
how thich are houseboat walls
pvc decking material white marsh
custom interior panels malaysia
recycle plastic lumber mauritius
parkland heritage bench replace wood in uk
evergreen composite decking
trex decking joist space requirements
extruded wood effect threshold
durable paint for plastic
plastic impregnated wood flooring
outside waterproof concrete flooring
wood floor to existing decking thresholds
sanding composite deck edge
interlocking vinyl plank floor installed outdoors
vinyl privacy fence calculator
pvc walling for sale in philippines
composite climate of delhi and its sun path
home window designs in sri lanka
4x8 plastic 3 4 for boat floors replacing
tongue groove treated lumber
can vinyl flooring be used on an outside deck
structural composite floor decking
continental fence panels west midlands
pvc foam board railing extrusion process
lightweight concrete floors over plywood
ceiling board suppliers in durban
cost of installed composite privacy fence texas
do it yourself pool deck painting
recycled plastic lumber 2x4 home depot
wooden fence qatar
where to buy 3d wall panels toronto
manufacturer decorative wall panels for mobile homes
outdoor deck tiles ireland
composite ceiling boards in german
outdoor non slip vinyl flooring
prefabricated timber exterior stairs
level 6x6 area of lawn
free standing picket fence
composite timber decking malaysia
cellular pvc decking problems in the community
how long will pittsburgh ultra advanced sealant last
attaching 4x4 to concrete patio
trex deck gates composite in finland
how to install bamboo flooring 90 degree turn
home legend engineered flooring
decorative outdoor wood railing cost
pvc decking vs composite video
interlocking 24 x 24 deck tiles
reconstituted timber decking long life span
harmonized tariff schedule vinyl decking
stone material in composite climate
pvc fence panels semi transparent
free deck railing designs
us distributor nord compensati plywood
cement board interior walls
anti slip decking strips wickes
used railroad ties portland
copper impregnated decking
poland wood plastic composite
grouting fence post
how to make round trash bin with wood
indoor football perimeter rebound boards
recycled wood composites floor plans
replacement plastic bench boards
external fire retardant plastic cladding for ceiling
lightweight timber decking panels
doors for sale in kenya
wire mesh panels for deck railing
pvc dock boards you use in coding
can termites eat composite wood
laminate floor sealer for waterproofing
decking tile connector uk
thick wood or plastic ceiling in south africa
paintable wood plastic composite products
synthetic wood to cover old wood
what is best composite decking in 2018
manufacture process of pvc window frames
paraffin deck oil
wood wall panel sale in malaysia
composite railing 10 ft
wpc swimming pool decking ideas
pros and cons of wood shipping containers
make corner bench out of decking
exterior wall panels wood fireproof door
picket fence cost per foot installed
wooden sliding doors srilanka
lightweight pavers for balconies uk
pros and cons of tongue and groove for house siding
lifecycle wood bridge decks
square deck around a round pool
84 lumber fence posts price
install laminate in 90 degree
compressed foam board
conservatory vinyl pvc board strength
angle for bench backrest
composite decking prices ireland
exterior wood wall clading material in mumbai
fence company tulsa
color guard railing systems pricing
how to install plastic backsplash panels
replacement cushions for range garden furniture
bali gazebo construction plans
difference type of flash doors in kenya and their prices
megastar pvc panels
armadillo composite decking reviews
building a wooden flower boxes
sound absorbing outdoor floor materials
installing vinyl deck posts light
best modern wall cladding systems uk
fence wall metal design ghana
laminate flooring importer in cape town
how to build a goat gate deck rail
wpc outdoor decking floor materials
waterproof exterior wall cladding
clear plastic fence panels
4 ft x 8 ft wood fence panels
light weight boat decking
wood plastic composite decking wpc decking
pergola kits in india
best deck paint reviews
wooden benches out of decking plans
plastic wood decking material squares
8ft x 8ft privacy fence panel
pintu geser di kuala terengganu
amish composite deck furniture
how to anchor a plastic shed to wood deck
swimming pool deck ideas above ground
paint for manmade wood
wood plastic composite pavilion
subway tiles for shower
can you paint polywood plastic furniture
build composite fencing wpc
building veranda stairs with composite material
reclaimed wood fence panels for sale
how to build rustic log fence
did you put plantation shutters on your screen porch
sun proof deck stain reviews
pool tiles safety depth marking tiles
black plastic fence panels
outdoor rubber tile diy pool
waterproof vinyl plank floor
wood composite decking hk
waterproof interior wall cladding
pvc composite decking home depot
outdoor wood deck stairs
show images of decking made into patio sets
composite rice flooring
how to build a cap rail on a privacy fence
i need to replace my deck railing by myself
fences plastic for sloping ground uk
tiles color in philippines
balcony roof covering in india
wpc plastic wall panel advantages and disadvantages
does trex decking scratch with pets
using a piece of vinyl flooring for a dance floor
battleship gray decking
how to install tongue and groove trex deck boards
building a 12x12 flat deck for swimming pool
pvc deck post sleeves rolled
how to waterproof an upper level wood deck
how to hide screw holes in composite decking
home made plastic lumber
12mm x 150mm engineered wood flooring
circular saw blades for hard composite material
water resistant wooden composite decking
trex composite decking unit weight
show synthetic landscaping timbers
plastic paving moulds in kenya
how to cover up unsightly paving slabs
buy composite wall cladding online dictionary
deck panels at lowes
wpc composite garden panels lowes
marine foam sheets for deck
2x6x8 actual dimensions
timber wood deck patio balcony
privacy fence installers cincinnati
natural wooden plastic composite floor in uk
best outdoor decking material
deck skirting materials
composite beam timber
how to attach a post to a wall
decks made out of vinyl pre assembled
caravan decking kits for sale
cost of fiberglass pilings
how to easily install a wpc fence panel
home garden metal railing for decks
composite decking prices lumber liquidators
cost of dura cladding
best decking material around pool
wooden decking that is cantilevered
deck restoration paint reviews
composite plastic timber suppliers in oman
best wood size for deck
marine plywood prices france
a back rest for a bitch for a wooden bench
exterior wood laminate rail bench
outdoor decking flooring in uk
wooden handrails for garden steps
composite deck railing cost per foot
redo boat floor with pvc
replacing concrete steps with wood
about composite decking suppliers in muscat
best laminate flooring
composite boards 3 inch
composite pergola in turkey
how to install composite panel siding
retail price of wpc in calicut
wpc noise barrier wall panel
wood plastic composite import project settings
spacing on deck boards
composite decking europe made vehicles
patio furniture manufacturers composite material
fiberon vs trex mildew resistance
vinyl railing in malaysia
integral veranda decking
artificial composite roof shingles
composite plastic building products
matrix decor screen panels
wood plastic composite aero space
wood for underwater use
cheap decking for sale in spain
composite pergola how to build
radiata pine primed finger joint edge center bead panel
composite panel manufacturers uae
facia soffit made in china
paintable pvc deck railing
wood fencing pickets in phoenix
pre fab stairways that can be raised lowered
anisotropic strength of wood
pipe rail costs per foot cost
pvc deck boards fading of signal
waterproof balcony flooring porch roof
gazebos kits home patio
plastic material that looks like timber
price of wooden flooring uganda
pre built structures using composite panels
wpc fencing cost per foot
panels for outdoor floors
plastic grille material for walkways jetties
active yards vinyl fence review
freestanding ground deck plans
pang waterproof sa tiles ng terrace
boat deck effect wood floor
outdoor plastic runner for ramp
future market of wpc in india
vinyl deck railing kits playing
white trex deck
how many composite boards needed for 260 feet to metres
balcony outdoor deck and stair kits
high density composite panel
how much should a replacement deck cost
installing picket fence panels
solid internal wood plastic decks pretoria
waterproof membrane for outdoor carpet
building wooden steps for manufactured home
wood plastic composite pallet in europe
home depot 4x8 sheets ceiling and wall panels
structural insulated panels in manila
how to calculate the length for fence posts
balcony design with wall
wood fiber composite manufactures india
composite shed base foundation how to
composite marine decking material 4x8
contemporary house plans with roof top decks design
wpc decking floor importers european countries
composite tongue and groove 1 x 6
garden fencing panels in hong kong
exterior wall panel
torrefied timber cladding
what sheet material could i use for a decking floor
picket fences in nigeria for sale
84 lumber vinyl fencing kits
deck material
deck floor for backyard patio
plastic wood fence panels hungary
pre made decks at lowes
weatherproof wood deck philippines
laminate simulated simulated wood boat floor
composite trailer decking
best size lumber for retaining wall
trex picnic table instructions
malaysia wood plastic boat builder
waterproof ceiling bathroom company south africa
cheaper deck or patio
pvc deck post skirt wrap
outdoor wood flooring panels
concrete fencing posts in kenya
where to buy mantis deck clip system
man made board timber or artificial
brazilian teak flooring at lowes
sturdy rigid lightweight inexpensive panels
porch boards tongue calculator
composite floor deck price per square foot
eco decking tiles terrace installation of laminate
small platform deck on a slope
what primer to use for composite woods
how to build a bench with a back and arm rests
gluts wooden and plastic
crystal white railing
make simple wooden outdoor bench
prices of vinyl flooring in cebu bionic
advantages and disadvantages of tilt up concrete
waterproof laminate flooring for sale in spain
pvc panel decorative germany
flexible under deck sheeting
treated lumber for swimming pool floors
buy wood floor in hong kong
installing board on metal risers
balcony decking singapore prices
how to clean a composite pergola
timber joists wholesale
wood plastic garden plank decking floor in singapore
composite wood for stair risers
cost to repaint wrought iron
building horse ranch fencing materials
4x8 vinyl ceiling panels at home depot
composites cubic foot
plastic flooring sri lanka
using pvc decking indoors
pvc t g decking kenya
deck plans for 33 round pool
how to cover a plywood deck
raised wall panels malaysia
fire pit mat for composite deck
used sandwich panel for sale in philippines
wooden decking windows set new designs in sri lanka
sealing outdoor deck floor
inexpensive patio flooring sale south africa
outside wall panels solid malaysia
building a boat from recycled material
redwood instead of marine plywood for transom
no toxic outdoor wpc flooring systems
does lattice come in 12 foot lengths
plastic flooring for patio outside table covers
attractive wood plastic composite suppliers in german
build furniture out of flooring
what are the merit and demerit of composite walls
pool covers for composite decking
kitchen mosaic tile designs
artificial plank cladding in uk story
types of wood fences in fiji islands
black deck composite distributors wanted
composite flooring barefoot friendly
what to use to fill knots in outside deck
9mm plywood board italy
6 x 8 french gothic wood panels
ventilated wood plastic composite solid decking
pvc flooring importer
1 x 4 tongue and groove pvc decking
how to weatherproof walls with slates
diy pool deck coating
composite panels johore malaysia
build outdoor bench with storage
wood paneling alternative
fencing installation cost uk
privacy fence panel price
wooden outdoor floor tiles australia
2 x 4 composite lumber prices
first floor outside balcony
outdoor wooden bench replacement slats
what can i use for a deck floor for a boat
best deck wood materials for ground contact
plastic pallets philippines
deck support around a 24 foot round pool
composite deck outdoor furniture nosing
8ft tall composite fencing
cheap wooden benches uk
how much for a 500 sq foot deck
what is wood plastic product
building an outdoor shower using privacy fence
secure balcony floor slats
parkland plastic panel suppliers
pine tongue and groove flooring costs
clear plastic covered deck panels
furniture plastic wood composite board
plastic 4x8 railing caps
how to make wood deck
engineered decking products rating
composite deck panels around pool
concrete covering exterior
melamine mdf in egypt
deck price per square foot calculator
bamboo decking in colder climates
how to stagger wood planks
outdoor deck panels colour stables
roofing options for cedar pavilion
how to build a area under a wood deck
plastic cladding on timber frame
garage deck flooring tiles
plastic wood effect fence panel
marine grade exterior vinyl glue planks
cellular pvc decking manufacturers marketing
branded plywood waterproof name
cost to remove treated deck boards
composite anti slip decking 3 5 wide
use sleepers as a decking base
pvc deck railing house
sports flooring qatar
outdoor bead board
utility trailer decking ideas
best way to fix an old deck boards solutions
outer boundary designs indian style
contemporary wood panel exterior
plastic labels for wood products
bamboo board supplier in dubai
decking for decking stairs
bathroom shower tiles grey
composite decking visualizer
wood plastic composite deck tile dealers in bangalore
reused composite decking
decks for rectangular bungalows
composite decking install in uk
wood pool surrounds flooring
how to build comfortable bench
motorized sun shades for patios and decks
vinyl wall cladding india
how to cover an ugly garden wall cheaply and quickly
waterproof molding for kitchen floor
cost of cambridge sherwood pavers
exterior flooring wholesalers spain
how to attach bamboo to a pergola
4x8 composite deck sheeting weathering
temporary white pvc fencing in uk in europe
wood decking for pergola flooring
building a house in costa rica
wrought railing vs wood railing
2 x 6 x 20 composite lumber price
composite decking price per square meter
patio pergola pictures
picket composite white
can i put bamboo flooring on an outdoor ceiling
easiest way to build a deck on uneven ground
recycled planks cape town
ikea outside wood tiles in german
environment friendly composite decking in philippines
matrix decor screens
decking solid wpc timber composite doors
new zealand wood panels wall panel dampproof
patio materials cost comparison
fencing contractor in mauritius
built a bench using 2x4
lanka window frames new potos
artificial composite wood polymer panel
plastic wall cladding in mumbai
price of composite decking
chain link fence price in malaysia
recycled synthetic deck material products international
install trex directly over plywood
thailand chiang mai decorative wall panels for patio
tongue and groove siding square foot installation price
plastic deck skirting wraps
lightweight composite floor for enclosed
build a deck on concrete slab
laminate flooring for stairs philippines
clearance grey vinyl fence panels
300 sq yards house design
pvc exterior doors namibia
sauna flooring materials
cheap way to cover up concrete steps
non toxic fencing materials
outdoor plastic wood flooring price
composite wood flooring in basement
plywood prices in kenya
redwood bender board for landscaping
pvc decking builders
vinyl coated on the wall like wood malaysia
trex fencing reviews
outdoor waterproofed rubber flooring for decks
laminate flooring manufacturer singapore
marine composite materials price
how do you make a fence
pvc deck board spacing wedge
anti slip decking treatment
solutions to heighten fence without getting new fence
chipboard panels germany supplier
advantages and disadvantages of pvc ceiling over others
10mm pvc sheet south africa
clorox composite deck cleaner
cost calculator for chain link fence in tamil nadu
waterproof slip proof decking system
plastic wood for decks by the box
price of ceiling siding in kenya
cheap ways to finish steps
plastic laminate exterior cladding
what is a porch on a second floor called
ultra deck rustic solid reviews
installing garden deck on sloping ground
heavy duty resin plastic panels
the tile shop locations in illinois
porch ceiling vinyl board
what material is better for exterior step railing
12x12 wood deck cost
how to cap a wood picket fence
ceiling manufacturers in sweden
cost of wood shades composite fencing installed india
outdoor table top material
exterior composite bead board
paraffin wood treatment
porch post material options
how to build an outdoor wood wall
renew deck coating reviews
evolve decking prices in uk
warehouse fencing singapore
composite fences dubai company
exterior wood walls
wood fence for sale near me
how many pickets in 100ft board and board
wood hand railing installation
bamboo decking reviews
decorative porch underpinning
two foot high vinyl fencing
video to construct composite deck
wall cladding for sale in ghana
how to build a fence that lets the wind through
bench for composite boards supplier
brandenburg louvered vinyl pergola
poultry fence made in usa
removable wood deck tiles for flat roof
wooden deck tiles houston
artificial outdoor wood floors in saudi arabia
non combustible wood plastic composite
4 composite boards 8x8 white
painting composite frames
multi colored recycled pvc fence
can old stockade fencing be used for interior flooring
how much does a section of stockade fence cost installed
decorative ceiling kampala
rubber mowing strips under fences
pressure threaded plywood 4x10 sheet
how to build a fence panels from landscape timbers
composite marine floor panels
retaining wall using pallets
definition of abrasion resistance wood
outdoor decking floor manufacturer in germany
second hand slabs for sale in western cape
decked out cost to do deck
natural brown garden decking rope
ultra tuff rubberized anti slip for a wood deck
fence post installation instructions
style selections railing
14 wide composite boards
can you refinish decking
waterproofing untreated pine
sealing earth stones hardboard panel to be waterproof
wpc decking install design space
materials to be used in tropical climate construction
8 foot tall vinyl fence panels
wen molded composite doors importers
plastic wood sun shade
swim platform non skid covering
fake brick wall tiles singapore hotels
decorative panels for outside mobile home
pvc fencing netting kenya
uses of recycled wpc roofing sheets deck railing
disadvantages of suspended timber floor
price and were buy interlocking plastic mold in nigeria
composite decking wholesale maryland
second floor patio floor choices
decking transition strip detail
decking boards as garden edging
pvc ceiling
how many boards are need to side a house in 2000 sq ft
exterior wood plank wall covering for sale
price of wood privacy fence
pvc decking material prices milk
wood plastic composite fence
plastic floor in philippines
installing wolf pvc decking
ideas to make a 2ft tall and 4ft wide white fence
guardian building products composite decking issues
composite deck vs composite siding
build garden flower box decking
portable composite deck flooring
disadvantages of wood in furniture manufacturing
pvc decking prices uk kids
how to cover wood fence with vinyl
weather grey composite decking
interlocking deck boards
outdoor landscape screening composite
where cam i buy plastic joists
wood deck over a wood deck deck
square edge verses grooved edge for decking
4x4 deck post anchors
where to buy faux wood and bricks in singapore
outdoor deck material options uk
euro fence composite
fence picket panel deck
trespa panel cost per square foot
movable pool floor singapore
small unique house with rooftop deck
synthetic pool deck suppliers in sri lank
how to stagger vinyl plank floor
customer reviews on composite decking in south africa
composite decking border
length of over hang on a step deck allowed
pvc deck covering material texture
timber patio decking weight
decking flooring waterproof
composite sheet decoration done in building
best pvc decking reviews ultrasonic pest
decorative acrylic panels ontario canada
balau wood manufacturer malaysia
wood plank supplier singapore
replace concrete steps with wood steps
pvc deck railing kits to make
chain fences prices in nigeria
engineered composite deck materials
vinyl flooring and porch rails reviews
palladio decking agents
bench seating cushion foam
veranda in vinyl white rail gate kit
cost effective option for patio
artificial decking in thailand
second hand electric fencing posts inverness
wood composite decking for sale in uk
pvc decking lowes payment
timber based composite
outdoor rubber deck tiles uk
what does cladding look like
pvc deck railing prices of oil
mounting a plastic wood core board on a wall
traditional vinyl vs wpc
floor tile layout application
best saw to cut composite boards
aluminum boat flooring material
bathroom pvc ceiling morocco
discount wood fence panels prices soundproof
insulation board netherlands
how to attach bamboo fencing on top of pergola
composite deck boards for sale toronto
buy composite decking online
how to install prefabricated fence video
composite materials for privacy fence
cheapest place to get decking
laminated wood flooring in berlin
birch solid wood floor trinidad and tobago
loose lay vinyl planks kenya
glulam price per foot in german
styles of pool decks of faux wood
composite deck railing systems prices effective
composite decking for inside a house
pvc pool decks refinishing
socio economics of sheet composite materials
like wood system in sri lanka
steel definition for kids
composite decking milton keynes
actual dimensions of 2x6 radial edge decking
cons of texture over paneling
stretch film ceiling price south africa
skim coat concrete block wall
lowe s decorative wallboard for bathrooms
build your own composite wall panels
tiles texture white gold
wind proof fence panels
fast floor pvc tiles 10
wood ceiling tiles egypt
pvc decking chalking it up meaning
hollow pot decking
price of eco friendly deck
price western cedar cladding northern ireland
composite above ground pool decking kits
hollow composite columns
attractive wood plastic composite material south africa
gazebo supplier in malacca malaysia
pergola ideas melbourne
ghana best fence design
edging on the bottom of gates
pvc deck board covers concrete
whats an inexpensive way to resurface a concrete patio
aluminum composite panel mexico
makeover and enhance a rooftop deck ideas
bulk wholesale china imports
curved plastic bench
cost calculator to install vinyl railing
installing laminate floor threshold
veranda linden 6x8 ft pre assemble parts
pvc materials supplier company
price fir composite patio solid floor insulation
height of pvc panelling sheet
how much does plastic lumber cost to make
manufacturing process flow of pvc plastic factory
anti slip composite stairs malaysia
composite decking as siding contractors
chain link fencing cost calculator
wet environments how to build a pvc fence
build a bench using recycled plastic
modular decking australia
concrete shuttering board for construction
how to make a waterproof cabinet out of wood
labor cost to install ceramic tile per square foot kenya
how to install reed fencing on balcony
build caravan decking
green in color composite decking
laying interlock deck tile on dirt
why wpc vinyl is non flammable
mdf board 18mm switzerland
advantages of wood composite board
lowes vinyl lattice panels 4x8
composite wood plastic park benches malibu
composite fence producers poland
2x3 composite lumber
how to put faux wood deck in
anti corrosive wood fence supplier
what a board fence would look like
how to make a gate in a fence panel
does composite decking expand and contract
molding for trex decking
customer reviews on veranda decking
pvc gates for decks restaurant
deck moves now space between deck and pool
how to build wood retaining walls with tongue and groove
poly wood lumber distributor
bathroom plastic tiles in singapore
composite slats for shower floor
plastic beams for ceiling
4x4 lumber landscape edging
veranda white balusters anti skid
attach fence panels with nails or screws
supplier of vinyl or pvc fencing in donegal ireland
composite dock plates hollow deck anchor
cost for deck per square foot canada 2018
wood plastic composite market demand curves
easy install fence south africa
wood handrails home patio
pvc railing for decks such marine
800 sq ft composite deck cost
laying of claypot on a decking
how to add height to an existing aluminum fence
cost to build transcend deck with vinyl railing
mobile home with lattice
wooden pergola uk
4x8 pvc panels mounted adhesive
wholesale click lock flooring
bottom caps for vinyl deck posts installing
lattice top privacy vinyl fence panel
pergola price in india
non slip plastic wood decks costa rica
grey composite fencing
how increase height of chain fence
recycled fence slats
wind break blinds for static caravan decking outdoor
bend a board edging uk
wood to use for park bench
cost per foot hardy plank fence
composite furring strip
framing a hog panel fence
wpc decking price plastic wood products america
extrusion composite material
plastic floor tiles for patios
clad using decking
disadvantage of plastic tile
building a gazebo on a deck
natural look wood cladding
how to make a dance floor cheap vinyl
plastic fence panels ireland
lawn diy deck furniture with plastic composite
how to build a raised deck on a concrete slab
pvc foam board importers mumbai
wood decking install
coefficient of linear expansion of plastic cladding
composite slats garden bench malaysia
outdoor planter box singapore
how to build a louvered privacy screen
ipe decking problems
plastic lace verandah brackets
fire proof timber flooring outdoor
wholesale thru flow dock panels
lowes fence install cost
pergolas kit wooden boats
raising a vinyl fence
pictures of brown metal railing for concrete steps
composite decking closeout sales
composite deck floor material dealer
supplier pool deck indonesia
tempera painting advantages and disadvantages
simple deck plans lowes
tongue and groove planking for fences
ideas or images of mirror clading walls
consumer complaints about deck sealers
how strong and durable plastic paver moulds
balcony roof transparent
building a playground border with landscape timber
cheap pool decks above ground semi buried
can composite lumber be put on a concrete patio
budget pavillion for deck
wood exterior wall panels
electric fence energizer price at malaysia
outdoor steps to uneven ground
composite chaise lounge
pvc fence that looks like stone
plywood distributor email manila
wolf amber wood decking price
how to remove nailed deck boards for reuse
remove replace deck boards per square feet
philippines composite bamboo fence
how much do 2x6 x10 lumber cost at home hardware
non slip composite decking kits uk
commercial grade aluminium honeycomb toronto on
composite plate stock for boats
types of fence panel
marine exterior stair tread
buy carpets in ghana
home depot porch flooring
span tongue and groove floor
15 ft deck and fence privacy screen
backyard patio ideas cheap
best pontoon boat surface
latitudes decking railing costa rica
tile shops minneapolis
reviews rubber wood decking
pvc deck boards home garden appliance
composite ranch fence
wall tiles design for outside house in nigeria
preassembled 8ft deck railing
sunburst deck panels in uk
6 inch composite post sleeves
can you put tile on a wooden screened in porch
how to replace wood on cast iron bench
how to use lattice on chain link fence
drying out fence pickets
4 x 8 sheets vinyl siding
working with composite lumber safely
fence supplies los angeles
star on pvc floors kenya
bracing composite lumber that twists
plastic wood spacers for lifting deck joists 2x6
freedom lattice panels
singapore outdoor patio decking uv resistant
timber deck boards weight
wall panel pricing
patio dividers
building laminate product cost
durable coating for outdoor wooden steps
wooden fencing panels cape town
composite wood deck sealer
who makes the best vinyl floor tiles
red wood decking review
building a deck on a slope in california
spray foam insulation sheet in pakistan
deck flooring without gap
installing pvc deck boards grain
amish built composite deck furniture
cheap stair railing design ideas
how to build a large deck over grass
pvc free foam sheet fence extruders
cheap composite decking swansea
wood fence to hide concrete wall
plastic pallets market in saudi arabia
best glue for composite material
temporary floors for outdoor wedding from plywood
composite wood pergola dubai
timbers decking price zambia
pvc decking reviews power
modular durable plastic formwork for construction
interlock composite decking
railing painted prices america
foam filled composite door review
cons and pros of pvc piling on walls
magic decking pvc decking cover cost
anti slip coating wood wheelchair ramps
pvc exterior wall cladding sheets price
stone deck cost
labor price to install wpc decking
clear non skid coat for composite decking
are rubber interlocking garden tiles design
pvc deck post lights down driveway
how to install wpc floor
waterproof composite board
synthetic boat deck pvc boat deck
wood plastic composite formulation
wood pool decking boards suppliers philippines
wood panels for decking sold in portland or
wpc building panel cambodia
how do you construct hollow pot upper floor
plastic planks covering wood decks
wood plastic composite outdoor deck importers of ukraine
heated outdoor deck
wood plastic composite turkey
composite decking solid or hollow wholesale distributors
vinyl flooring manufactuer in belgium
board for truck bed
home depot 2x6x12 price
wood cladding in ireland
make your own bench out of composite decking
staircase tile design in sri lanka
polyethylene 2x6 lumber
landscape turtle planter box cost
houseboat wooden paneling in iran
how to cut furniture board
6 wide concrete deck planking model
deck water diversion systems
composite fence install houston
porch restoration synthetic ice
treated wood fence panels 8 feet
deck design ideas and plans
laminate flooring for terrace balcony instalation
adding a peaked roof over a travel trailer
pvc white decking in ireland
pergolas supplier uae
pvc glass panel door egypt
photos of above ground round pool decks
easy to install patio floor zambia
malaysia outdoor wooden decking tiles
composite anti fungal board pvc fence
best flooring material for balcony or terrace
composite wood plastic decking kenya
pvc deck expansion
wood panels disadvantages
build observation deck
concrete footing for a pergola
dampproof outdoor floor materials
price of double deck in philippines product
black wooden privacy fence
putting up wooden privacy fence panels
price of plastic stalled floor for goat farm shed
how long will composite decking last
masterpiece patio decking reviews
the cost of pvc wood work per sq feet
cost to build exterior wood stairs
decking suppliers aberdeen scotland
long life flower boxes
panel fencing with decorative cutouts
diy exterior handrails design
styro boxes supplier philippines
price to paint handrail
photos of fence in nigeria
composite deck suppliers dallas fort worth
indoor sill walkway timber
lightweight pavers deck
how do i mount a 4x4 post to the floor
plastic floor pvc and wood fire rated
deck calculator lowes
plastic wood products slats
composite decking supplier bangor northern ireland
27 foot pool deck framing plans
cedar decking slippery
cellular pvc decking pros of leasing
composite walls and application
non slip waterproof decking
material safety datasheet of wpc
decking material descriptions
working with plastic lumber
waterproof decking for a balcony perspective richard
8 ft trex deck board
anti slip coating for composite decking
architecture box by plastic wood
composite decking wide plank
sprinter wall panels
white pvc fence panels ireland stockists
sheet vinyl flooring suppliers
composite laminate price
plastic lumber in france
free standing pvc railing portico
different ways to attach deck rail post
hollow deck boards anti corrosive antifreeze
cheap railing options for deck
residential handrail code requirements
composites distribution in thailand
wood shades park bench composite boards
wood railroad ties landscaping
synthetic marine decking for decking boats
18mm waterproof plywood board
mildew resistant composite decking
composite cladding for concrete steps
does dog pee stain composite decks
fencing wire sales in lusaka zambia
supply taichung pvc board
composite wood flooring indonesia power
new discoveries in wood flooring polymers
plastic wood in saint lucia
buy eco deck malaysia
removing adhesive sticker from composite decking
interlocking waterproof roof decking
wet wall bathroom monaco
bio composite product
bending wpc composite railing in qatar
lowes material pricing
white fence parts wholesale uk wholesalers
vinyl flooring tiles in karachi
agri waste composites
using gas table on pvc decking
how to make a cobblestone fence
wooden fence panels price singapore
utility cheap pressed wood siding
average cost composite decking
2x6 tongue and groove for a garage floor
2x6 pvc fence and wood lumber plastic decking
waterproof coating for wood deck slip resistant
floors used in ethiopia
what is agriculture composite
metal siding panels vietnam
plastic doors price uk
metal verandas skegness
clear plastic winter panels for porch walls
composite wood decking uae supplier
recycle wood decking for park thailand
how much does trex decking weight per square foot
plasticized wood panels
wood look vinyl privacy fence
synthetic boat deck
fixing scratch on composite wood
composite decking manufacturers spain
plastic wood manufacturer in malaysia
average cost of redwood fencing per foot
plastic plinths for fencing
price of aluminium sheet per square foot
style selections decking at lowes
exterior pvc floor tiles
exterior composite deck material looks like wood
maximum overhang for trex decking
convert chain link to plastic
2 composite rubber for dance floor
gap between composite fencing
entryway storage bench cushion
square meters to lineal meters
plastic pergola home china
wear wpc decking in vietnam
kodiak cedar products
wooden fence price economical long life
do they make universal tub surrounds
cheap patio floor without pavers
best low maintenance decking material
garden bench slat kit
installing deck boards on a diagonal with a border
plastic furring products
redwood hot tubs orange county
thailand stair hand rail
style solutions decking material
biggest wood plastic laminate factory
wooden dustbin singapore
pvc and paper composite
engineered wood flooring outdoor
insurance house replacement cost calculator
composite decking material for condo balcony screen
pvc board manufacturer south africa
resistance moisture wood wall panel decor
waterproof pergola canopy uk
composite wood plastic made in thailand
thin waterproof sheeting for floor
park bench replacement kit
teak and holly flooring prices
rubber extrusions profiles
wood board for sale malaysia
plastic outdoor carpet for decks
pvc gypsum board ceiling decoration
composite fence panel post hardware
wood deck polymer coating
harga panel dak beton murah 2018
pvc wood planks supplier in philippines
anti termite cheap flooring backyard
flat roof deck tiles
where to buy wood composite decking in malaysia
baltic birch plywood uk
horizontal louvered privacy
non absorbent wood fence design
business project work class 12 on products furniture
inexpensive patio roof diy deck railing
fence boards for sale winnipeg
sealers for wpc deck
how much is labour for fixing pvc ceiling
how to attach vinyl lattice to vinyl fence
flagstone garden walkway designs
pvc deck materials usage
pvc covering for deck boards rotting
plastic fence posts solid
natural looking composite decking
acacia wood interlocking deck tiles
wood grain vinyl picket fencing uk
plastic 4x8 sheets flooring material
fairway pvc deck railing replacement brackets sports
2 story house with roof deck
plastic trim boards uk
removable outdoor floor tiles
masonite decking cost sound
wood plastic composite product gallery
solid wood decking product
build a temporary wall from foam blocks
pergola plans materials list
pop up gazebos uae
diy composite privacy fence
tractor supply wooden fence posts
deck knee brace bracket
baluster for 5 8 round baluster
what to do for faded recycled plastic park bench
solid composite balusters supplier
tongue and groove composite wood fence
outdoor plywood deck waterproof plywood
pvc extruded pergola materials wholesalers
plastic marine panel in malaysia
revitalize pittsburgh resurfacer reviews
how to install gatehouse vinyl fence video
best materials for roof deck
magic deck pvc deck covering cost
waterproof cladding for outside sheds
can composite decking be glued to concrete
lightweight rigid composite boat floor panels
neoprene plastic wood sheet argentina
framing in outside doors with composite boards
buy plywood diy deck singapore
synthetic teak wood boat deck floor for sale in dubai
white upvc wood grain picket fence
decorative railing attachment to wood exterior french
cheap outdoor patio rugs
pool deck above or below top rail
kerala fibre wood composite cladding
decking be painted with anti skid product development
expansion joints for trex decking
modular precast concrete fence philippines
do it yourself outdoor flooring singapore
free deck plans for above ground
faux cement stairs
pvc 2x4 studs
feasibility study of chair furniture
attach a stockade fence to a chain link fence
pvc bench trunking
can you paint composite railing
conversion brackets fence
pergolas triangle how to build
capped composite decking problems
rubberized teak and holly flooring
cheap decking material
how to replace a damaged composite deck board
best floors balcony ireland
painting bathroom tile countertop
ideas to raise a block wall for privacy
cost of treated western red cedar
wood stairs and railings
pangu wall panels
wpc floor tiles plastic in philippines
boat floor replacement composite
plastic wood products for gazebos
outdoor floor tile singapore
composite decking lacquer peeling
recycled tire wood look flooring
pvc gates for decks of playing
where to buy long wooden planks in singapore
wrought wood railing wall mount brackets
cost of tearing a deck down
recycled plastic 6 x 6 10 timbers for sale
is it easy to put groove composite deck
floors 90 degree turn in hallway
water resistant bead board
new deck materials
wooden fencing panels singapore
lowes seven trust decking prices
cheap deck materials colorado
installing wpc ceiling
composite wood decking grand designs
white balusters stairs
laminated exterior panel wood
spare slats for teak seats
corrugated plastic board three layer
lowes handrails for outside stairs
best wood for gazebo floor
floor construction on balcony covered porch
timber decking around a swim pool
water seal plywood
composite sliding driveway gates
trex transcend decking weight
lowes exterior wood alternative
patio fence ideas
wood above ground pool deck kit
composite garden boxes
recycled plastic lumber prices austin texas
prefab tiny house kits usa
rice hull ash laminate wood bonded particle board
wet environments composite wood floor
lowes deck kits
plastic exterior decking system
interlocking waterproof decking in german
wolf pvc decking colors with names
low voltage lighting for vinyl deck posts everyone
brush on paint vinyl decking
cheap easy paneling ideas
commericial display russia
composite decking home depot
sizes of wood available in philippines
what is most durable cladding material among the plastic
cellular pvc decking pros buying
textured pvc decking sheet
weyerhaeuser fiber decking
changing wooden deck to pvc
deck installation costs
no toxic kids outdoor flooring
wood composite panel interior wall stockists
composite decking hollow core
can a pop up canopy be secured to a deck
plantation shutters dallas lowest price
trex spacing for stairs
arched metal pergola kits
composite decking joint spacer for waterproofing
how to insulate an open wood deck
pvc fence on the balcony
recycled plastic fencing posts in kenya
4x8 plywood substitute
wood plastic composite production line europe
facades sizes and price in south africa
bargain outlet complaints composite decking shrinking
modular basement walls
how to install composite flower bed
composite decking brands reviews
suitable substrates for plastic laminate
plywood boards for floor kenya
decking wall panel and fencing accessories
composite deck tiles over wood
patio woodgrain tile floor covering
the difference between soild flat and ribbed slab
alstone hybrid board price
wpc portable outdoor flooring supplier
tile flooring stores dallas tx
ecological products solid wood composite floor
use plastic decking board on my basement floor
build a wood fence horizontal composite
pvc foam board in indian
pvc deck railing canada breaking
outdoor furniture wholesalers usa
modern composite patio floor furniture for living
labour cost fit decking
decking on a sloping concrete
making a patio bench from wood
non flammable wood panel walls
bending plywood in italy
where can i buy the decking for my wooden paddleboard
composite pvc decking tiles under fireplace
waterproof panels india
bending strength and tensile strength
composite decking around pool slippery
pvc wire fencing panels egypt
cheap patio grating in uk people
wpc deck boards span
qualities of a dustbin
outdoor wooden flooring usa
repurpose fence posts still in ground
trim strips for pool steps
front porch deck material on concrete
actual length of decking boards
build composite deck
pvc ceiling production line made in germany
can composite decking be painted or stained
plastic wood grain fencing materials
floor matting for pigs philippines prices
hog wire deck railing from tractor supply
non slip floor screened in porch
german siding for sale
proper installation of teak flooring on top of grass
plastic pvc deck cover wood
cheap alternative to cedar decking
composite park bench manufacturers
deck pvc covering retaining
where to buy wood planks for walls in singapore
laminate wood decking planks to use on yard
sale on wood fencing in massachusetts
water proof plywood sheet 18 mm
plans to build a wood pergola
install ultra deck fence
ratio of wood in wpc
plastic pergola kits
armadillo decking installation specs
stair treads non slip
how to repair barrette privacy fence panels
horse fencing composite materials
furniture supplier in philippines
pvc fence materials supplier in uk
plastic floor boards south africa
best roof for balcony
center console foam core floor panels
prefabricated outdoor staircases gatineau ottawa
build a villa complex gazebo deck flooring
recycled plastic composite lumber manufacturers
pvc ceiling boards manufacturers in cape town
12mm wood vinyl paneling
diy fence out of pallets
wpc manufacturer in uae
decking pavers for roof
timber decking philippines supplier
alternative decking ideas
material to use to make shutters for exterior
blocking deck joist for strength
pvc deck furniture images
stair railing kits
nosing outdoor wooden decking in singapore
construction of hollow pot in suspended floor
decking of planter singapore condo
pvc exterior trim australia
composite deck wholesale
pre fab outdoor toilets pavillions
deck skirting brown pvc brick
4mm pvc sheet
paintable composite decking systems
wholesale decking materials
how many sq ft is a 10x15 porch
faux wood planks uk
what do i charge for tongue and groove ceiling
cost of redwood fence installed by my foot
russian birch plywood egypt
composite fence panels for decking
elastomeric and balcony surfaces
composite hollow wood for raised garden beds
slippery composite outdoor deck steps
foamboard buy in nigeria
harga pasang keramik lantai malaysia
corral panels oklahoma
5 4 decking board width
plastic wood cladding exterior malaysia
rattan wicker sofa in trinidad tobago
canvas decks made in usa
deck from composite wood models
garden furniture outdoor sri lanka
discontinued deck railing for sale
cladding available in philippines
plastic decking board suppliers in scotland
bendable composite landscaping edging
vinyl deck railing direct
veranda costal cedar groove edge decking
400 sq ft pvc deck price
composite decking on historic homes
wood grain plastic pergola material
decking with built in drain
wpc panel price
water pooling on composite deck
home garden plastic deck materials generally become warmer
garden lawn edging singapore
pvc fence designs pictures
interlocking wood decking in malaysia
trex decking weight per square foot
formulation wpc board
steel fence posts and rails
12mm laminate flooring
horizontal slats fence designs uk
waterproof deck topper
cost of wood plastic composite house
supplier merbau decking malaysia
trespa panels price
prices for 2x6 composite decking boards
pvc deck railing lowes insulation
plastic wood for fences
lightweight covering for outdoors decks
pvc laminated ceiling panel cebu philippines
24ft pool deck plans
self adhesive wall panels
lanai flooring sarasota
how to build a surround for a lazy spa monaco
covering an outside concrete wall with a wooden fence
outdoor wood sheets in uk
plastic resin squares for outdoors
insulated metal panel belarus
curtain designers in dar es salaam
buy tongue and groove mdf ceiling planks
cedar tongue and groove boards for deck
composite tongue and groove panel orlando
lanai over a wood deck
box deck on a slope
putting a deck on a flat fence
trex decking unit weight
can you put outdoor flooring on grass
baltimore maryland fence recycled
lineal foot cost to paint wrought iron fence
ceiling tiles manufacturers in johannesburg south africa
best pontoon flooring price
pvc interlocking tile in dubai
best plastic for marine applications
thermally modified poplar decking
timber decking price for balcony singapore
pvc composite decking installation guide
using trex decking for bed of a pickup
outdoor wood flooring georgia
composite barrel manufacture
veranda deck post installation
trex decking install cold weather
aluminum composite panel fabricator association africa
cheap outdoor patio flooring options
recycling plastic fencing george
do composite decks not rotating
mold inhibitor timber roof
multi colored modern fence solutions
inexpensive outdoor patio flooring
wood plastic composite extruder for sale in south africa
tongue groove treated lumber
sanding composite deck edge
evergreen composite decking
dimensions can custom teak boat flooring
pvc wooden balcony railing suppliers list
disadvantages of plastic design method
50x50 modern house plan
how to attach handrail to concrete wall
lower melting point in composites
6x6 timber retaining wall
free deck plans for a bestway 18 foot pool
ceiling tiles price in bangladesh
framing patio covers calculations for nurses
floor decks in portugal praia
cheap diy outdoor floor tiles singapore
clear fiberglass for top of pergola privacy
wood polymer lumbers flooring
second hands slabs in cape town
wind fence design
how to build deck railing out of hog panels
how to build a pvc fence with benches
what material to use for outdoor handrails
build a seat on existing decking
reconstituted wooden boarding
plastic picket fence suppliers in cape town
outdoor plastic carpet in south africa
what primer to use for composite door frame
synthetic wood price malaysia
what company has a 1x6 tongue and groove composite
rooftop deck caribbean house plans
lightweight composite siding
average cost of wood mezzanine floor canada
park bench supplier in germany
composite lumber posts hawaii
engineered tongue and groove porch flooring
12x16 pool deck plans
discontinued trex decking
plastic timber india
temporary flooring ideas for portable gazebos
6 panel 42 x 96 mahogany wood slab doors
roof top deck hours
porcelain deck tile grids
material cut list for 16x16 deck
fencing calculator south africa
patio tiles made in usa
pine furniture board wickes
wpc decking price malaysia
deck and above ground pool designs
lowes composite tile decking
remove scratches from composite porch
plastic poles in namibia
disadvantage of sandwich panel wall
10x10 pergola shade canopy
noise reduction fencing and made in usa
liquid applied plastic floor covering
non slip waterproofing for wood decking
use wood fencing panel suppliers perth wa
retaining wall with deck boards
wood fencing supplier in kenya
outdoor wooden floor equipment uae nursery
fireproof plastic decking
outdoor flooring around pool
outdoor pool shower supplier singapore
wood look cement pavers for sale
neo tile urban groove light grey porcelain tile
kerala style window frames
does cedar fencing shrink
terrace flooring pvc
plastic wood board canada sale price
where tongue and groove could be mostly used
pvc deck boards christmas
pvc plastic ceiling board malta
vinyl flooring manufacturers in belgium
how to fence a verandah
split rail composite fencing
mesh fence on a brick wall
pool deck flooring mats
malaysian wooden boats
choice deck lowes
wall concreting pics in kerala
under composite decking
timber homes south africa
cheapest pvc composite decking
composite scaffolding plank
best fence material
wooden surround for above ground pools deck with pergola
american floor mats promo
plastic cladding for exterior walls
kazakhstan plywood
install vinyl flooring in bathroom
free standing balconies
bench plans using pressure treated 2x4 dimensions
cost of stockade fence per foot
mobile home deck roof plans
farm gate on a slope in qatar
ghana plastic wood company and prices
partial brick and pvc post cladding covering
is polywood and trex the same
black covering under deck
pvc gates for decks at home
boat floor options other than wood
how to add privacy screen to existing composite deck
anti termite composite wood fence
synthetic decking production in uk do not wash
decking with fire rating
core plastic wood board germany
wolf pvc decking reviews of windows
pvc youngs modulus elastic modulus
advantages of pvc wall panels
ceramic tiles price list in saudi arabia
white mdf sheets wholesale
plastic pool deck supplier
never needs painting wpc exterior decks
how much to install 200 ft of wood fence
slotted garage wall panels
wood plastic beams suppliers in qatar
plastic deck railing flower boxes
how waterproof wood laminate furniture
pvc waterproof decking costs
marine plywood for decking
cedar decking pros and cons
composite patio decking fixing for chili
patio deck surface pad
how long does landscape composite bender board last
qualified pvc for interior decoration
can you make six foot fence taller
where to buy encore deck stain
pvc laminate trailer flooring
weather resistant laminate flooring for outside use
removable decorative fence panels
plastic fencing in brentwood essex
trex friendly mats
veranda premium composite railing
exterior wood panel over cement board sheathing
composite geodesic high rise
outdoor wood for deck philippines
hog wire deck railing images
deck install wall attachment
hard plastic panel singapore
average cost to install ceiling planks
what slope are steel outside stair stringers
hardboard wall panel indonesia
concrete step covering outside
1
2
3
4
5
6
7
8
|
https://www.certificadoenred.es/composite-deck/
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
.
Step 1: How It Works:
- Red for Anger
- Yellow for Happy
- Pink for Love
- White for Fear
- Green for Envy
- Orange for Surprise
- Blue for Sadness
- "wow"
- "can't believe"
- "unbelievable"
- "O_o".
- You could put it on your desk to get an early warning of something big happening somewhere in the world
- A literal 'mood...
Materials
- Arduino Duemilanove
- Wifly Shield
- Breakaway headers
- 9v battery
- 9v to Barrel Jack Adapter
- 5mm RGB LED
- 3x resistors (2x100 ohm,1x180 ohm)
- Wire
- Small printed circuit board
- USB Cable A to B to connect Arduino to computer
- Rosin-core solder
- Source code
- 1 x (5" x 5" x 0.25") - the top
- 4 * (4.75" x 4.75" x 0.25") - the 4 walls
- 1 x (4.5" x 4.5" x 0.25") - the base
- 1 x (4.5" x 4.5" x 0.125") - the mirror with a 6mm hole drilled in the middle
- 4 x (4.25 x 1" x 0.25") - the 4 inside walls
- Acrylic solvent cement
- Sand paper (to help diffuse the light)
- Soldering iron
- A computer
- Arduino development environment
- A wireless network (802.11b/g)
- Pliers
- Wire stripper
Step
Step 5: Choosing Good Search Terms
Twitter allows you to search for recent tweets that contain particular words or phrases.
You can search for tweets that contain any of a list of phrases by using the "+OR+" conjunction.
For example, here is a search request that might find tweets that express Fear:
GET /search.json?q="i'm+so+scared"+OR+"i'm+really+scared"+OR+"i'm+terrified"+OR+"i'm+really+afraid"+OR+"so+scared+i"&rpp=30&result_type=recent
I spent a long time finding good search phrases.
The search phrases needed to produce tweets that:
- very often express the desired emotion.
- very rarely express the opposite emotion or no emotion.
Many search phrases that I thought would work, turned out to not work that well when I searched with them.
Smileys have been used with some success to extract whether the sentence is positive or negative, but I didn't find them useful for extracting anything more.
The trouble with smileys is that a smile can mean so many things ;D
It is often used, it seems, as a kind of qualifier for the whole sentence; since people have to compress their thoughts into 140 characters, the meaning can become ambiguous.
The smiley often then acts as a qualifier that:
- 'this is a friendly comment'
- 'don't take this the wrong way'
- 'i am saying hello/goodbye with a smile'
- 'this is almost a joke'
- 'I know I'm being cheeky'
- 'I don't really mean this'
"so scared" or "really scared" is better than just "scared" which returns bad results: for example, "not scared".
Phrases in the first person seemed to produce better results.
Some search phrases give tweets that suggest the author feels the emotion: for example, "i really hate...", often sounds like they really are full of hate or angry, whereas other phrases containing the word "hate" give tweets that do not seem to express much emotion, like "why do you hate..."
Hyperbole is your best friend, ever:
Using phrases with hyperbole produced good results. Tweets with "I'm terrified" or "I'm petrified" in them were generally more fearful sounding than "I'm scared"
Regardless, the approach is still naive, but statistically, from my tests, it does seem to work well.
While testing the code, I did at one point get the horribly ominous "Flashing White" that signifies the world is feeling intense fear, but since I was still testing it all, I did not hide under the table straight away, but instead, threw caution to the winds, and went on to Twitter to see what people were suddenly so fearful about.
The recent tweets containing the Fear search string (see top of page) were largely relating to a large thunderstorm that had just started somewhere near Florida.
If you're interested, here are some of those tweets:
So... it works! ...Well, it needs the numbers tweaking to ignore the world's "tantrums", the short-lived fits of emotional outburst, and be more concerned with larger changes that signify bigger news.So... it works! ...Well, it needs the numbers tweaking to ignore the world's "tantrums", the short-lived fits of emotional outburst, and be more concerned with larger changes that signify bigger news.
- "Ahhh Thunder I'm so scared of Thunder !!!!! Help some 1"
- "I'm so scared of lightning now. Like I just ran home praying "
- "On our way to Narcosses at @Disney world's Grand Floridian hotel and there's a tropical storm right now. I'm terrified! ..."
- "I'm in my bathroom til the rain stops. I'm terrified of lightning and thunder..."
- "I'm terrified of thunder storms *hides in corner*"
- "I'm terrified of Thunder :("
- "If only I was wit my becky during this thunderstorm cause I'm really scared cause of a bad experience"
Step 6: Download the Code
The four libraries need to be copied into the Arduino library directory and then they can be imported as shown.
WorldMood/WorldMood.pde (see below) should be opened in the Arduino development environment.
You then need to correct the "[your network]" and "[your network password]" fields. eg.
#define network ("mynetwork")
#define password ("mypassword")
Then the sketch (and libraries) should be compiled and uploaded to the Arduino board.
see arduino.cc/en/Hacking/LibraryTutorial
The next 5 programming steps just give an overview of each of the components and include the most noteworthy parts of the source code...
**** Update ****};
See here for more info:
***** End Update ****
Step 7: Programming Step 1: SPI UART
The featured components of the shield are:
- a Roving Network's RN-131G wireless module
- SC16IS750 SPI-to-UART chip.
The Universal asynchronous receiver/transmitter (or UART) is a type of asynchronous receiver/transmitter, a piece of computer hardware that translates data between parallel and serial forms.
- The PC communicates over UART with the Arduino through pins RX and TX
- The Arduino communicates over SPI with the SPI-UART chip on the WiFly shield (SC16IS750 SPI-to-UART chip) though pins 10-13 (CS, MOSI, MISO, SCLK respectively)
- The RN-131G wireless module accesses network and send/receive serial data over UART.
The code below is based on a number of sources, but primarily from this tutorial over at sparkfun:
WiFly Wireless Talking SpeakJet Server
Step 8: Programming Step 2: Connecting to a Wireless Network
Step 9: Programming Step 3: Searching Twitter With TCP/IP Port 80
for example:
"Open 80"
will open a Http connection to.
Twitter actually requires more of the Http protocol than google.
For example, the "Host" field is often required in case there's more than one
domain name mapped to the server's IP address so it can tell which
website you actually want.
Twitter also requires a final linefeed and carriage return ("\r\n")
"Host: server\r\n"
"\r\n"
I use search.json rather than search.atom to give results in non-html format, and more easily parsed. (see apiwiki.twitter.com/Twitter-API-Documentation)
Step 10: Programming Step 4: RGB LED
*** update ***
If you find the colours look wrong, try removing the "255 -" from the analogWrite calls.
Thanks to shobley for finding this.
More info at
*** end update ***
Step 11: Programming 5: Computing the World Mood
The important thing is to carefully normalize and smooth the data, and to adjust the thresholds to give the right level of responsiveness and alarm. (i.e. it should flash when a headline news story
happens and not when a TV show starts, GMT)
Emotion, mood, and temperament
Firstly, the "world's emotion" is calculated by searching twitter for tweets with each of the 7 mood types (love, joy, surprise, anger, fear, envy, sad) .
A measure of "tweets per minute" is used to calculate the current emotion. A higher number of tweets per minute suggests more people are currently feeling that emotion.
Emotions are volatile, so these short-lived emotional states are smoothed over time by using a "fast exponential moving average"
(see en.wikipedia.org/wiki/Moving_average#Exponential_moving_average)
This gives us ratios for the different moods.
Each mood ratio is then compared to a base line, a "slow exponential moving average", that I call the "world temperament".
The mood that has deviated furthest from its baseline temperament value is considered to be the current world mood.
The deviation is measured as a percentage, so, for example, if fear changes from accounting for 5% of tweets to 10% then this is more significant than joy changing from 40% to 45% (They are both a +5% in additive terms, but fear increased by 100% in multiplicative terms.)
Finally, the world temperament values are tweaked slightly in light of this new result. This gives the system a self adjusting property so that the world temperament can very slowly change over time.
These values in WorldMood.pde are used to adjust how sensitive the system is to information.
- Do you want it to pick up when people are happy about a sport result or scared about the weather?
- Or would you prefer to only track big events like natural disasters or terrorist attacks?
#define emotionSmoothingFactor (0.1f)
#define moodSmoothingFactor (0.05f)
#define moderateMoodThreshold (2.0f)
#define extremeMoodThreshold (4.0f)
Step 12: Building the Box
Build an acrylic box ala this Instructable:
Step 13: Enjoy!
- Making it multilingual and not just English speaking places.
- Perhaps just associating with a keyword, for example every tweet must contain the word "Obama", then you could gauge public opinion on just that subject.
- Location specific. Perhaps you just care about your town or country. Twitter allows you to use the geocoding to do this.
- Make it tweet what the world mood is so as to complete the circle
- Ability to connect to it from a computer to see what keywords people are so emotive about.
I am very interested to hear any comments, corrections or questions. Please do contact me, if you so wish.
118 Discussions
6 years ago on Introduction
The world has changed a bit since this program was first posted. I finally have my mood light working, but it wasn't always easy..
Reply 4 years ago on Introduction
Excellent update/summary interesting that the tweets per second needs to be adjusted, i wonder if it would work on other social media platforms?
thanks for putting the time in to update.
Reply 6 years ago on Introduction
Yes, Arduino, Twitter and the World's Mood have changed a lot since May 2010. I"m afraid this is not an active project of mine, and I rely on great comments like this to keep this 'ible current.
Reply 5 years ago on Introduction.
Reply 5 years ago on Introduction
Also, as of today, the project no longer works.
Twitter has changed its API and now the query returns errors.
Reply 5 years ago on Introduction
Is there a way i can still make it ?
would be a great help if you can sugest a way to do this ?
Reply 5 years ago on Introduction
Unfortunately, no. I've not been able to get it to interface with the new API.
Question 1 year ago
hi mate, how much would be the budget for this project
i'm prepping for a national Arduino competition so a rapid reply would be much appreciated :)
love from malaysia
Question 1 year ago on Step 2
may i ask if how the arduino detects the moods on the twitter ? since it's my first to encounter this kind of project
2 years ago
I love this, and would love this next to my bed! One thing though. To keep cost down, how hard would it be to program the Arduino to read the information straight from the computer via USB connection
2 years ago
Sir do you have any codes for the modern twitter mood light?
3 years ago
Really Cool Instructable. I featured this Instructable in one of my collections:
3 years ago
Please keep us updated, good luck!
3 years ago
Can this still be made or has there been updates to Twitter that will make this accomplishable? Should we use the last change you made ?
4 years ago on Introduction
Is there anyone out there who has an idea of making code for aduinos? I'm having a hard time doing my project. I have no idea of what code to use. My project is about a gh-718c mini PIR motion sensor detecting my arm or hand. If the motion sensor detects that my hand is low, the light or LED will dim, and if it detects my hand on a high position, the LED will bright up. Please please. Help please. Thanks for the reply!
Reply 4 years ago on Introduction
By the way, I'm using an arduino uno. Thankyou. Please reply.
Reply 3 years ago
You'll have more luck with a raspberry pi
3 years ago
You're awesome, thanks for doing this!
6 years ago on Step 13
I am not even sure where to start with this comment! Bottom line, I got this running on newer hardware with a newer IDE.
Reply 5 years ago on Step 13
Hey! I tried going to the dropbox link you gave, but the file is missing. Do you still have it up somewhere? Thanks in advance!
|
https://www.instructables.com/id/Twitter-Mood-Light-The-Worlds-Mood-in-a-Box/
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
ExpressionToCodeLib 1.5.0.
See the version list below for details.
Install-Package ExpressionToCodeLib -Version 1.5.0
dotnet add package ExpressionToCodeLib --version 1.5.0
<PackageReference Include="ExpressionToCodeLib" Version="1.5.0" />
paket add ExpressionToCodeLib --version 1.5.0
Release Notes
Added experimental API in the Unstable_v2_Api namespace; jagged arrays with varying rank now work correctly; in some simple cases explicit generic type arguments are generated when necessary (issue #13); arrays of delegates now work.
Dependencies
This package has no dependencies.
|
https://www.nuget.org/packages/ExpressionToCodeLib/1.5.0
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Java’s generics have undoubtedly made life easier in some cases by enforcing type safety on collections. One collection that frequently does not benefit from them is maps used in a heterogeneous way – that is, a java.util.Map (or equivalent) that contains several non-compatible values. Assuming the keys are of the same type, it’s still not possible to type the value of the map as anything other than a java.lang.Object – exactly what it would have been prior to generics.
Looking through the Jetbrains documentation on its API for IntelliJ plugin development, it’s interesting to note their workaround for enforcing type safety in a map containing heterogeneous values:
- DataKey<T> – the access point to the map
- DataContext – an interface that can be used to wrap a map
This approach externalises the type-safety of the map’s content by shifting the casts to DataKey.
The interesting part of DataKey, from this viewpoint, is
@Nullable public T getData(@NotNull DataContext dataContext) { return (T) dataContext.getData(myName); }
Read access is via the key, and not directly on the map itself, e.g. for a key
DataKey<Foo> FOO = DataKey.create("foo")
a type-safe call without a cast can be made on the wrapped via:
Foo foo = MyKeys.FOO.getData(dataContext);
The map-based implementations of DataContext just does a regular lookup with the key provided by DataKey:
public class MyDataContext implements DataContext { private final Map<String, ?> data = new HashMap<String, ?>(); @Nullable Object getData(@NonNls String dataId) { return data.get(dataId); } }
and the returned object is cast to the correct type on the way out of DataKey. Simple and elegant.
It’s worth noting that both DataKey and DataContext are read-only in function – there’s a getData(), but no setData(). It’s easy enough to extend the concept to make sure that what goes into the map is of the same type as what comes out by adding a couple of extra methods, one on DataKey:
public void setData(DataContext dataContext, T value) { dataContext.setData(getName(), value); }
and another on DataContext:
public void setData(String key, Object value) { data.put(key, value); }
I’ve seen a lot of code where keys to access values from maps have been declared as static final Strings. Using DataKey, you could replace these declarations with DataKeys that specify the key to access the value and the type of the value itself, so
public static final String USER = "user"; ... User user = (User)map.get(USER);
would become
public static final DataKey<User> USER = DataKey.create("user"); ... User user = USER.getData(dataContext);
2 thoughts on “Storing multiple object types in Java maps with type safety”
This could be especially useful in Android where you can’t use generics.
Although, this would also mean that, instead of defining a DataKey using generics, you’d have to create a different subclass of DataKey for each type. I thought about passing the type into the DataKey’s constructor, but that wouldn’t help with the return type of getData. It’ll also require a little bit of reworking for the setter, but could totally be worth it.
Sorry, I was a little off in my last comment. It seems you CAN use generics in Android. My confusion was from Bundle and a few other things in the Android SDK that force you to do the casting. It’s been a while since I’ve worked with Android, and I hadn’t needed to use generics while I was working with it.
So yeah, you can pretty much use your design as-is.
|
https://www.objectify.be/wordpress/2010/04/21/storing-multiple-object-types-in-java-maps-with-type-safety/
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
CodePlexProject Hosting for Open Source Software
I would like to render a part that will supply my pages with general functionality such as rendering resources @Script.Include, @Style.Include and general background widgets like Popup windows etc. that all pages and widgets can use. How would I go
about including this part with all pages when my module is enabled?
Parts are always welded onto content items. So if you have a template that you want rendered on
every page, you don't want a part. Instead you can just generate a shape from an IShapeFactory which you treat as dynamic. So you call Shape.MyShapeName() and a file called MyShapeName.cshtml will be rendered. You could do this from a Filter and then
add that shape into WorkContext.Layout.
Hi randompete, can you supply or point me to an example if this please?
See Orchard.Framework\UI\Navigation\MenuFilter.cs; that's how the default menu gets rendered.
Also in Orchard.Widgets there is a filter that actually renders all the layers / widgets and puts them in the layout.
Thank you randompete, managed to get this working through a filter over the weekend and it now saves a tremendous amount of code in all the views as I am now able to render the Telerik MVC scripts and themes as part of a filter in my module. I
no longer have to add onto individual views anymore. Another side benefit I only realized after the fact is that all these controls are now available on the admin side as well so I am able to use the window and grid control's there as well. Only downside
is that scripts and views are rendered to all pages which can probably be managed through exlsion onthe filter but for now it works for me as all my pages use the Telerik MVC bits. I managed to also include a setting in my module where I store the active
theme so that it is easy to switch. Below is what I did in the filter and the widget view for anyone who is interested:
public class LayoutFilter : FilterProvider, IResultFilter
{
private readonly IWorkContextAccessor _workContextAccessor;
private readonly dynamic _shapeFactory;
public LayoutFilter(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory)
{
_workContextAccessor = workContextAccessor;
_shapeFactory = shapeFactory;
}
public void OnResultExecuting(ResultExecutingContext filterContext)
{
var workContext = _workContextAccessor.GetContext();
// should only run on a full view rendering result
if (filterContext.Result is ViewResult)
{
var viewWorkContext = _workContextAccessor.GetContext(filterContext);
var applicationSettings = viewWorkContext.CurrentSite.As<ApplicationSettingsPart>();
var telerikStyle = "Default";
if (applicationSettings != null)
telerikStyle = applicationSettings.TelerikStyle;
dynamic widgets = _shapeFactory.Parts_TelerikWidgets().TelerikStyle(telerikStyle);
workContext.Layout.Content.Add(widgets);
}
}
}
@using Telerik.Web.Mvc.UI
@using (Script.Head()){
Style.Require("TelerikCommon");
Style.Require(Model.TelerikStyle);
}
@(Html.Telerik().Window()
.Name("PopupWindow")
.Title("PopUp")
.Content("<iframe id='puwIFrame' frameborder='0' src='/Loading' style='border: 0; width: 98%; height: 97%;' title='Notes' scrolling='no'>This page requires frames in order to show content</iframe>")
.Modal(true)
.Draggable(true)
.Visible(false)
)
@using (Script.Foot()) {
Script.Require("jQuery");
Script.Require("jQueryCascadeExt");
Script.Require("jQueryTemplating");
@(Html.Telerik().ScriptRegistrar().DefaultGroup(group => group.DefaultPath("~/Modules/Orchard.Phambili/Scripts")).jQuery(false))
}
Filters are pretty powerful :)
Regarding it rendering to every single page, I'm wondering if it's possible to hijack the Layers rules engine in some generic way to control application of filters? Could be an interesting module...
@Pete: I guess hijacking Layers rule engine won't be necessary. Orchard has scipting engine built-in - Widgets module is just making use of it. The idea of filter layering in the same way the widgets are is awesome! It wouldn't introduce a big performance
impact though, as the script output can be cached.
Garpo
where did you add the telerik reference for the part.cshtml?
i always get an CS0246: The type or namespace name 'Telerik' could not be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 1: @using Telerik.Web.Mvc.UI
Line 2: @using (Script.Head()){
Line 3: Style.Require("TelerikCommon");
if i add it via filter
okay got it, it need to be added to orchard.Web
i tried to get rid of any references "outside the custom module"
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.
|
http://orchard.codeplex.com/discussions/259475
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Getting Started
WinShared is both a starting framework and sample code for Unity ports to Windows.
The repository itself is a Unity project with useful plugins, scripts, tools and a sample game. The repository contains Windows Solutions which enhance and extend the base solutions outputted from Unity specifically for Windows.
You can view an overview of the architecture here:
/statusIcon) CI
/statusIcon) Release
Prerequisites
- Visual Studio 2015 with latest updates
- Nuget Package Manager
- Unity 5.2.2p4 or later (commit 0362f4e564f515047690331610d9975609a69e7a is the last one that supports Unity 5.0)
Using WinShared on an existing porting project
Skip this step if you just want to take a look at WinShared.
Follow the steps in this section To initialize an existing Unity project you may be working on using WinShared.
This will include al the functionality of WinShared and related plugins as detailed in this read me, making your porting efforts hopefully a lot easier.
To do this, you will execeute the Init.ps1 PowerShell script, located in root of this repo.
Note: Please ignore this section if you have already installed via Unity Asset Store.
You will need to provide following parameters:
- TargetRepoPath - full path to root folder of new repository (for example:
C:\Code\SomeProject\)
- UnityProjectTargetDir - subdirectory under TargetRepoPath that contains Unity project (can be empty, if it is in the root of repo, for example:
Unityfor Unity project to be in
C:\Code\SomeProject\Unity)
- ProjectName - name of new project (ensure same as ProductName in PlayerSettings). Script will rename Windows projects, namespaces and solutions to match this name.
- IncludeExamples : optional. Boolean to indicate whether to include the example scene and game from Marker Metro to demonstrate WinIntegration features. Defaults to false.
This script will always copy the following files and folders to your target project:
- .gitignore - Up to date git ignore for Unity projects (you should manually merge this if there is an existing one)
- /BuildScripts/* - helper build scripts
- /Assets/Plugins/* - plugin binaries and scripts
- /Assets/MarkerMetro/Editor/* - helper editor scripts, including Tools > MarkerMetro menu options
- /WindowsSolutionUniversal - boilerplate windows 8.1 Universal solution folder, enhanced version of what Unity outputs
If 'IncludeExamples' is true the following will be copied across:
- /Assets/MarkerMetro/Example/* - see FaceFlip.unity, a small optional game scene with WinIntegration test points (recommended to see WinIntegration features in action)
- /Assets/StreamingAssets/MarkerMetro/* - supporting example video for WinIntegration tests
Guidance
Provided here is guidance for working with WinShared (and projects based on WinShared) which you should read and understand but are not directly related to setting up a new project.
Windows Solution Build Output
The WindowsSolutionUniversal folder contains the Windows Store and Windows Phone apps (Windows 8.1 and Windows Phone 8.1 Universal). The Windows10Solution folder contains the Windows 10 app.
Building to Windows
You must build out from Unity for the Windows Solutions to work. You can do this using the Tools > MarkerMetro > Build menu or specify the path manually via a standard File > Build Settings build.
Ensure that you build out to the correct output folders as follows:
- Windows 8.1 Universal > /WindowsSolutionUniversal
- Windows 10 Universal > /Windows10Solution
Game Settings
Some game settings need to be provided via the application side such as music, sound and notifications enabled status via the Windows 8 charms bar.
For example in the [Windows Store Settings Charm Control] () you will see code similar to the following:
musicSwitch.IsOn = GameController.Instance.GameSettings.MusicEnabled;
The GameController class is an intermediary class between the Application and Unity. Make sure that you initialize the Game Settings on the game side with a class which implements [IGameSettings] ()
GameController.Instance.Init(IGameSettings gameSettings);
Within the example game in WinShared this is done with the main GameMaster.cs class in the Awake method, [see here] ().
Application Configuration
Application configuration is provided via the /Config/AppConfig.cs class. You are able to turn various features on and off as well as supplying facebook and exception logging api keys for example.
Note that this class implemented IGameConfig and is supplied to Unity game side as part of app initialization within [MainPage.xaml.cs] (). This way you can have configuration which works across both the app and game.
MarkerMetro.Unity.WinShared.GameController.Instance.Init(AppConfig.Instance);
Managing Exception Logging
See WinIntegration Exception Logging for more on exception logging.
You can replace RaygunExceptionLogger with an alternative implementation of IExceptionLogger for your crash reporting needs. Ensure that your projects have a reference to the crash reporting solution you are using and wire up your IExceptionLogger implementation to that solution. Lastly, modify AppConfig.cs to assign your api key as required.
If you are not using exception logging at all you can remove Raygun as follows:
- Remove Raygun Nuget packages from the solution. Right click the solution and select "Manage Nuget Packages for Solution" and uncheck Raygun.
- Remove the RaygunExceptionLogger.cs class
- Change the ExceptionLogger.Initialize line in App.xaml.cs to ExceptionLogger.Initialize(null);
- modify AppConfig.cs to set the ExceptionLoggingEnabled property to return false to completely disable exception logging.
QA and Master configurations
The Windows Solutions have QA and Master solution configurations. QA has been copied from Master to provide a production ready configuration that can support testing.
At this point the differences are:
- Store Integration - QA uses simulated IAP, Master will attempt to use real production store APIs.
- Exception Logging - QA enables ability to crash test via Windows settings charm, but will be off by default. Master will hide this capability but ensure Exception Logging is on by default (if a key has been supplied)
- GameController.Instance.GameConfig.CurrentBuildConfig in Unity will return Debug/QA/Master configuraiton at runtime (based on app solution configuration) which can be useful to apply environment specific login within the game side.
Marker Metro Tools Menu
Tools > MarkerMetro provides some useful features for Unity developers porting to Windows.
Build Menu
Alows you to quickly build to Windows Universal.
Plugins Menu
This repository includes a stable version of all dependent Marker Metro plugins. You can easily update to later versions, as well as use and debug local versions of WinLegacy and WinIntegration.
Plugins > Update allows you to update the Marker Metro plugins (WinIntegration and WinLegacy) to the latest version. By default this option gets latest stable versions via the main public NuGet field, but you can also configure to use local solution folders if you are using your own fork for example.
Building the plugins locally allows you also to easily debug a particular Windows Store or Windows Phone plugin project as follows:
- Add the platform specific plugin project to your Windows solution (e.g. MarkerMetro.Unity.WinIntegrationMetro)
- Tools > Marker Metro > Plugins > Configure ( ensure Plugin Source is Local, and Build Local is Debug)
- Tools > Marker Metro > Plugins > Update
- Tools > Marker Metro > Build >
- Set breakpoints in your platform specific plugin project and then F5 on your app
Memory Optimization Menu
There is a memory optimization script that optimize texture settings to lower memory usage, which is useful specially for Windows Phone.
You can use the menu item Tools > Marker Metro > Memory Optimization > Optimize Texture Settings to run it.
It will locate all texture assets in the project and optimize their settings. You can also update an exclude list of files that you don't want to change using MemoryOptimizerExcludeList.csv. Simply enter the paths of the files you want the script to ignore (e.g.
Assets/Resources/ignoreme.jpg).
The script lowers the maximum size that a texture can have, the default is to use half of the resolution that is currently being used but it can be configured to be more aggressive. Note that if you run the script multiple times it will lower the resolution even more, but if that's your intention you should play around with the
TextureResizingFactor variable in the script. The script also forces the textures to use DXT compression, which is the best option for Windows.
Texture settings are stored in their corresponding meta files, therefore this script only changes a texture's meta files. Since Windows 8.1 and Windows Phone 8.1 use the same textures for a Universal build, we cannot change these settings for Windows Phone only. Therefore, you will need to essentially run a secnd low memory build after running this script specifically for Windows Phone.
Sample Game and WinIntegration Samples
The FaceFlip.unity scene demonstrates some key WinIntegration features around a simple game such as:
- Facebook Integration
- Store Integration
- Exception Logging (Crash and Exception Testing)
- Local Notifications
- Video Player
- Platform specific information
App Name Localization
Windows 8.1 and Windows Phone 8.1 app manifest uses AppName and AppDescription resources to localize the store name, application name and description.
|
http://unitylist.com/r/19h/marker-metro-.-unity-.-win-shared
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
setpgid(2) BSD System Calls Manual setpgid(2)
NAME
setpgid, setpgrp -- set process group
SYNOPSIS
#include <unistd.h> int setpgid(pid_t pid, pid_t pgid); pid_t setpgrp(void);
DESCRIPTION
Setpgid() sets the process group of the specified process pid to the specified pgid. If pid is zero, then the call applies to the current process. If the invoker is not the super-user, then the affected process must have the same effective user-id as the invoker or be a descendant of the invoking process. If the calling process is not already a session leader, setpgrp() sets the process group ID of the calling process to that of the calling process. Any new session that this creates will have no controlling ter- minal.
RETURN VALUES
Setpgid() returns 0 when the operation was successful. If the request failed, -1 is returned and the global variable errno indicates the rea- son.
ERRORS effective user ID of the requested process is dif- ferent from that of the caller and the process is not a descendant.
LEGACY SYNOPSIS
#include <unistd.h> int setpgrp(pid_t pid, pid_t pgid); The legacy setpgrp() function is a clone of the setpgid() function, retained for calling convention compatibility with historical versions of BSD.
COMPATIBILITY
Use of the legacy version of the setpgrp() call will cause compiler diag- nostics. Use setpgid() instead. Use of private (and conflicting) prototypes for setpgrp() will cause com- piler diagnostics. Delete the private prototypes and include <unistd.h>.
SEE ALSO
getpgrp(2), compat(5)
STANDARDS
The setpgid() function conforms to IEEE Std 1003.1-1988 (``POSIX.1''). 4th Berkeley Distribution June 4, 1993 4th Berkeley Distribution
Mac OS X 10.9.1 - Generated Mon Jan 6 15:16:03 CST 2014
|
http://www.manpagez.com/man/2/setpgrp/
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
India asks Israel to speed up supply of radars
Expand Messages
- India Wants Arms Purchases Deals With Israel, United States Expedited
SAP20020601000078 Mumbai The Times of India (Internet Version-WWW) in
English 01 Jun 02
[PTI Report: "India asks Israel to speed up supply of radars" ]
[FBIS Transcribed Text]
NEW DELHI: With the Pakistani military threatning to use nuclear and
conventional missiles in case of a conflict, India has asked Israel to speed
up supply of a large number of Aerostat Ballons to give it capability to
detect incoming attacks on targets upto 500 kms.
The two countries have recently concluded an agreement to this effect
and now Tel Aviv has been asked to speed up the delivery of the system,
which is also capable of providing an in-depth battlefield surveillance as
well as track incoming enemy artillery shells, top defence ministry
officials said.
As part of measures to further bolster defence against missiles,
officials said New Delhi was according top priority to upgrading border
radar systems as well as looking keenly at the United States anti-missile
system, which is presently in testing stage.
Officials said India was evaluating the American system, which was
likely to be fielded by 2005-2006, with Washington inviting Indian experts
to missile command post exercises in June.
Asserting that India had information that Pakistan had deployed its
clandestinely acquired Chinese and North Korean missiles, officials said "We
have taken Islamabad threats very seriously and taken counter-measures".
Stating that New Delhi had also some information that Pakistan may be
trying to rein in mercenary and terrorist groups from crossing the Line of
Control, officials said, however, "we will be looking for some permament
markers before any de-escalation".
"During the recent interactive exchanges, the United States officials
had expressed apprehensions of a nulcear holocuast in the region", officials
said adding that Washington was not very sure of Pakistani threshold.
On the absence of the weapon locating radars with the army, ministry
officials said the earliest India could get contracted US ANTPQ-37 system
was 24 months. However, they added that with augmentation of Unmanned Aerial
Vehicles supplies to all the three services, the UAV as well as the about to
be acquired Aerostats could fill the void.
Officials also said that recently the country had gone in for massive
import of 155MM ammunition adding that army had huge stores to meet any
contingency.
They also said India's battle prepardness had recently received a boost
with induction of the state-of-the-art T-90 tanks which had been deployed in
the current ongoing mobilisation.
"The next batch of another 60 tanks would be here in another week and
after week-long trials would be pushed onto the frontlines", they said.
Officials said that during the just concluded Indo-US Defence Policy
Group (DPG) meeting, the Americans had agreed to speed up supplies of
specialised equipment for counter-terrorism including sensors to detect
infiltrations and night visions and superior small arms for the special
forces.
On the Hawk AJT deal, the officials said that Price Negotiating
Committee (PNC) had submitted its report to the government, which would open
final negotiations with the British Aerospace to sign the million Pound
sterling deal to acquire 66 Hawk trainers.
They said that during the recent discussions, the British Foreign
Secretary Jack Straw had made it clear that there was no move to ban the
sale of Hawks or to impose any sort of arms embargo on India.
On acquisition of the Russian Kiev Class Aircraft Carrier Gorshkov,
officials said the Price Negotiating Committee had been set up, which would
give its recommendations within four weeks.
New Delhi, officials said had also received the draft treaty on
conclusion of Indo-US Acqusition cross service agreement, which would enable
the two countries to use each others armed services facilities.
"This agreement would be finalised within next three to four weeks and
this would mark the countries going beyond inter-services excercises",
officials said.
They said the two countries were also on the threshold of greater
cooperation in peace-keeping with India joining in next round of special US
forces peacekeeping exercises.
"We will also be holding joint exercises on disaster management and
disaster response even in third countries", they said adding that the two
countries had also agreed to cooperate in environmental security like in
fighting oil spill and nuclear waste as also seeking Washington's help in
dealing with disposal of human waste in Siachen glacier.
[Description of Source: Mumbai The Times of India in English -- Respected
and widely-read flagship of the influential Times of India Group, provides
good coverage of domestic politics and economics]
_________________________________________________________________
MSN Photos is the easiest way to share and print your photos:
Your message has been successfully submitted and would be delivered to recipients shortly.
|
https://groups.yahoo.com/neo/groups/MewNews/conversations/topics/6102
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
This proposal attempts to provide combined wording for the changes requested by the NB comments GB 55, US 84, US 85, and US 86 against C++17.The general approach is to follow the suggested directions described by the issues:
Required change: Split INVOKE_R from being an additional INVOKE "overload".
Required change: Rename and split is_callable/is_nothrow_callable into is_invocable/is_nothrow_invocable/is_invocable_r/is_nothrow_invocable_r (and associated types accordingly)
Required change: Change function type encoding of previous is_callable/is_nothrow_callable/result_of traits to conventional template type parameter lists.
Optional change: Deprecate result_of and introduce a new form without function type encoding whose name needs to be determined (Bikeshedding - Yeah!).
The changes in regard to result_of have been made optional, because this step increases the necessary draft changes significantly.If we introduce a new replacement trait for result_of, this requires a new name. The following is a list of naming suggestions available at the point of writing this proposal:
result_of_invoke [Suggested by US 85]
invoke_result [Suggested by Jonathan Wakely]
invocation_result [Suggested by Jonathan Wakely]
invocation [Suggested by Jonathan Wakely]
Without yet any concrete preferences expressed by the Committee, the proposal uses the name invoke_result as working title for that new trait.Nonetheless it should be noted that all three authors have independently expressed their preference for this name over the other choices.
Originally, Jonathan Wakely has made an alternative suggestion that could provide the return type of INVOKE()/invoke() without need of introducing a separate type trait for the result type. Instead the renamed is_invocable trait could in addition to its type member type provide another member type — possibly named result_type — conditionally, that is only defined if the trait evaluates to true.The authors of this paper are not in favour of this alternative approach for the following reasons:
This would introduce a completely new way of retrieving information from traits, which is hard to explain and feels a bit like an inconsistent design.
The changes requested by the NB comments responded by this paper come very late, therefore the solution should not increase the chances of rejecting the whole paper just because of experimenal ideas that would better fit into an early investigation phase.
As Jonathan says: "One potential downside of that is that people might accidentally use is_invocable::type instead of is_invocable::result_type, which would always be present (it comes from the bool_constant BaseCharacteristic and is either true_type or false_type)."
For implementations the additional templates don't require extra work, since they can internally delegate to reusable entities.
Last but not least, it is easily possible to switch in the future to the alternative approach, in case that more good reasons are determined for such a design change.
The authors of this paper recommend to apply all four suggested changes inspired by the NB comments as specified below for the following reasons:
Rename is_callable to is_invocable: is_callable would be the most natural name for a trait that answers the question whether a function call expression would be valid or not, which is a strict subset of the expressions, INVOKE supports, furthermore the changed name is_invocable much clearer expresses its meaning. Releasing the name is_callable allows us in the future to possibly introduce a pure is_callable trait (But this is not part of this proposal).
Separating INVOKE_R from INVOKE: INVOKE is an artificial construct and it is therefore very hard to logically discriminate a call of INVOKE with or without provided return type R. In every case where a pack expansion is provided, it is at least theoretically unclear whether the last parameter should be considered as part of the argument list of the first "overload" or as return type of the second "overload" (The fact that it is a type instead of a value helps, but the visual recognition is not easy). During the initial discussion of this topic, several people had expressed that they would prefer a INVOKE_R meta function that lists the return type first instead of as its last parameter (presumably because that has some similarities to a function template where this type would not be deduced). Daniel suggested a variant of the second form that would replace INVOKE_R(R, f, args...) by INVOKE<R>(f, args...) which is the form used below.
Replace function type encoding of type lists in is_callable and result_of: The function type encoding form used in these type traits is a relict from the pre-variadic template era of C++ where a single type is used to express a list of types. First, for both traits the natural interpretation of the encoded form Fn(ArgTypes...) looks as if Fn is used as return type, but it is only the callable object to which the arguments are provided. Second, contrary to the rest of all type traits which use a glvalue-based expression approach due to the direct usage of declval applied to the given type parameters, function type encoding is more natural for non-glvalues. In particular, parameter types are first adjusted via a special decay-like mechanism (8.3.5 [dcl.fct]), such that the actually provided types are often not the types on which the actual test is applied. Another problem is that function return types and argument types prevent some important type classes to be actually provided in the encoded form: Neither can argument types have an abstract class type nor cv void type, nor can function types or array types be used as "return type".As a workaround against the type transformation and restrictions mentioned above, user code needs to carefully ensure proper application of references to the arguments which causes problems for types that are non-referenceable types such as void() const, because instead af a silent SFINAE overload exclusion a compiler error will occur. Alisdair Meredith provided the following example of such an unpleasant situation on the Library reflector:
#include <type_traits> struct Functor { template <typename T> void operator()(T&&) const {} }; template <typename T> void validate() { static_assert(!std::is_callable_v<Functor(T)>); } using abomination = int() const; int main() { validate<abomination>(); }
These subtleties of the function type encoding had lead to a series of Library issues in the past, such as the following ones:
LWG 2017: std::reference_wrapper makes incorrect usage of std::result_of
LWG 2021: Further incorrect usages of result_of
LWG 2767: not_fn call_wrapper can form invalid types
The Library Evolution Working Group had been asked to look at the design changes involved by this paper and the following lists the results of their evaluation:
The authors of this paper consider these results as a strong confirmation of the direction of their proposal.
If the proposed resolution would below list of suggested changes is split into two halves: List (A) is an enumeration of suggested minimalistic wording changes and doesn't touch result_of, while list (B) separately lists the additional necessary changes when adjustments to result_of are considered.
The proposed wording changes refer to the Standard C++ working draft N4640.
[Drafting notes: Searching for current usages of INVOKE, the following locations are unaffected by the splitting of INVOKE<R>:
-
20.5.3.5 [tuple.apply] p1
-
20.7.7 [variant.visit] p2+p3
-
20.14.3 [func.require] p1
-
20.14.4 [func.invoke] p1
-
20.14.5.4 [refwrap.invoke] p1
-
20.14.10 [func.not_fn] p5+p6
-
20.14.11.3 [func.bind.bind] p2+p3+p6
-
20.14.12 [func.memfn] p1
-
Table 50 — "Other transformations" [Row for template result_of]
-
30.3.2.2 [thread.thread.constr] p3+p5
-
30.4.6.2 [thread.once.callonce] p1+p2
-
30.6.9 [futures.async] p2+(3.1)+(3.2)
— end drafting notes]
Minimalistic suggestion (without any changes affecting result_of):
Modify 20.14.3 [func.require] as indicated:
-2- Define INVOKE(f, t1, t2, ..., tN
, R) as static_cast<void>(INVOKE(f, t1, t2, ..., tN)) if R is cv void, otherwise INVOKE(f, t1, t2, ..., tN) implicitly converted to R.
Modify 20.14.11.3 [func.bind.bind] as indicated:
template<class R, class F, class... BoundArgs> unspecified bind(F&& f, BoundArgs&&... bound_args);
[…]-7- Returns: A forwarding call wrapper g (20.14.3 [func.require]). The effect of g(u1, u2, ..., uM) shall beINVOKE(fd, std::forward<V1>(v1), std::forward<V2>(v2), ..., std::forward<VN>(vN)
, R)
where […]
Modify 20.14.13.2 [func.wrap.func] as indicated:
-2- A callable type (20.14.2 [func.def]) F is Lvalue-Callable for argument types ArgTypes and return type R if the expression INVOKE(declval<F&>(), declval<ArgTypes>()...
, R), considered as an unevaluated operand (Clause 5 [expr]), is well formed (20.14.3 [func.require]).
Modify 20.14.13.2.4 [func.wrap.func.inv] as indicated:
R operator()(ArgTypes... args) const;
-1- Returns: INVOKE(f, std::forward<ArgTypes>(args)...
, R) (20.14.3 [func.require]), where f is the target object (20.14.2 [func.def]) of *this.
Modify 20.15.2 [meta.type.synop], header <type_traits> synopsis, as indicated:
[Drafting notes: The newly introduced variable template constants are intentionally marked as inline to be consistent with the resolution bullet list (B2) from P0607R0 "Inline Variables for the Standard Library" which had been preferred by the Committee — end drafting notes]
[…] // 20.15.6 [meta.rel], type relations […]
template <class, class R = void> struct is_callable; // not defined template <class Fn, class... ArgTypes, class R> struct is_callable<Fn(ArgTypes...), R>; template <class, class R = void> struct is_nothrow_callable; // not defined template <class Fn, class... ArgTypes, class R> struct is_nothrow_callable<Fn(ArgTypes...), R>;[…] // 20.15.6 [meta.rel], type relations […] template <class T, class R = void> constexpr bool is_callable_v = is_callable<T, R>::value; template <class T, class R = void> constexpr bool is_nothrow_callable_v = is_nothrow_callable<T, R>::value;[…]
Modify 20.15.6 [meta.rel], Table 44 — "Type relationship predicates", as indicated:
Modify 30.6.10.1 [futures.task.members] as indicated:
template <class F> packaged_task(F&& f); template <class F, class Allocator> packaged_task(allocator_arg_t, const Allocator& a, F&& f);
-2- Requires: INVOKE(f, t1, t2, ..., tN
, R), where t1, t2, ..., tN are values of the corresponding types in ArgTypes..., shall be a valid expression. […]
[…]void operator()(ArgTypes... args);
-16- Effects: As if by INVOKE(f, t1, t2, ..., tN[…]
, R), where f is the stored task of *this and t1, t2, ..., tN are the values in args.... […]void make_ready_at_thread_exit(ArgTypes... args);
-19- Effects: As if by INVOKE(f, t1, t2, ..., tN[…]
, R), where f is the stored task and t1, t2, ..., tN are the values in args.... […]
Additional suggestion (solely focussing of changes related to result_of):
Modify 20.14.1 [functional.syn], header <functional> synopsis, as indicated:
// 20.14.4 [func.invoke], invoke template <class F, class... Args>
result_of_t<F&&(Args&&...)>invoke(F&& f, Args&&... args);
Modify 20.14.4 [func.invoke] as indicated:
template <class F, class... Args>
result_of_t<F&&(Args&&...)>invoke(F&& f, Args&&... args);
Modify 20.14.5 [refwrap], class template reference_wrapper synopsis, as indicated:
[…] // invocation template <class... ArgTypes>
result_of_t<T&(ArgTypes&&...)>operator() (ArgTypes&&...) const; […]
Modify 20.14.5.4 [refwrap.invoke] as indicated:
template <class... ArgTypes>
result_of_t<T&(ArgTypes&&...)>operator() (ArgTypes&&...) const;
Modify 20.14.10 [func.not_fn], call_wrapper synopsis, as indicated:&&...)>>());
-5- […]template<class... Args> auto operator()(Args&&...) && -> decltype(!declval<
result_of_t<FD(Args&&...)>>()); template<class... Args> auto operator()(Args&&...) const&& -> decltype(!declval< result_of_t<const FD(Args&&...)>>());
-6- […]
Modify 20.14.11.3 [func.bind.bind] as indicated:
template<class R, class F, class... BoundArgs> unspecified bind(F&& f, BoundArgs&&... bound_args);
[…]
-10- The values of the bound arguments […] :
-
(10.1) — […]
-
(10.2) — if the value of is_bind_expression_v<TDi> is true, the argument is tdi(std::forward<Uj>(uj)...) and its type Vi is
result_of_t<TDi cv & (Uj&&...)>&&;
-
(10.3) — […]
Modify 20.15.2 [meta.type.synop], header <type_traits> synopsis, as indicated:
[Drafting notes: The changes below additionally fix an existing inconsistent usage of class-key class instead of struct. Albeit both are equivalent as of the letters of the core language, there are compilers that mangle both forms differently. — end drafting notes]
// 20.15.7.6 [meta.trans.other], other transformations […]
template <class> class result_of; // not defined template <class F, class... ArgTypes> class result_of<F(ArgTypes...)>;[…] // 20.15.7.6 [meta.trans.other], other transformations […] template <class T> using result_of_t = typename result_of<T>::type;[…]
Modify 20.15.7.6 [meta.trans.other], Table 50 — "Other transformations" and the following example, as indicated:
[…]-5- [Example: Given these definitions:using PF1 = bool (&)(); using PF2 = short (*)(long); struct S { operator PF2() const; double operator()(char, int&); void fn(long) const; char data; }; using PMF = void (S::*)(long) const; using PMD = char S::*;
the following assertions will hold:static_assert(is_same_v<
result_of_t<S(int)>, short>, "Error!"); static_assert(is_same_v< result_of_t<S&(unsigned char, int&)>, double>, "Error!"); static_assert(is_same_v< result_of_t<PF1()>, bool>, "Error!"); static_assert(is_same_v< result_of_t<PMF(unique_ptr<S>, int)>, void>, "Error!"); static_assert(is_same_v< result_of_t<PMD(S)>, char&&>, "Error!"); static_assert(is_same_v< result_of_t<PMD(const S*)>, const char&>, "Error!");
— end example]
Modify 30.6.2 [future.syn], header <future> synopsis, as indicated:
[…] template <class F, class... Args> future<
result_of_t<decay_t<F>(decay_t<Args>...)>> async(F&& f, Args&&... args); template <class F, class... Args> future< result_of_t<decay_t<F>(decay_t<Args>...)>> async(launch policy, F&& f, Args&&... args);
Modify 30.6.9 [futures.async] as indicated:
template <class F, class... Args> future<
result_of_t<decay_t<F>(decay_t<Args>...)>> async(F&& f, Args&&... args); template <class F, class... Args> future< result_of_t<decay_t<F>(decay_t<Args>...)>> async(launch policy, F&& f, Args&&... args);
-2- […][…] -4- Returns: An object of type future<
result_of_t<decay_t<F>(decay_t<Args>...)>> that refers to the shared state created by this call to async. […]
Modify D.11 [depr.meta.types], "Deprecated type traits" as indicated:
[Drafting notes: The changes below additionally fix an existing inconsistent usage of class-key class instead of struct, see above.]
-1- The header <type_traits> has the following addition:namespace std { template <class T> struct is_literal_type; template <class T> constexpr bool is_literal_type_v = is_literal_type<T>::value; }
-2- Requires: remove_all_extents_t<T> shall be a complete type or cv void.-3- Effects: is_literal_type has a base-characteristic of true_type if T is a literal type (3.9), and a base-characteristic of false_type otherwise.
For the purposes of SG10, this paper recommends to change the originally suggested macro name __cpp_lib_is_callable to __cpp_lib_is_invocable.
|
http://www.open-std.org/jtc1/sc22/WG21/docs/papers/2017/p0604r0.html
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
These Lights look incredible thank you so much for source. When the new haxeflixel version comes out you should really try giving your assets some normal maps your game would look even more incredible with lights then.
Posts made by PXshadowHF
- RE: Super Cute Alien - A cute platformer, inspired on BattleBlock Theater, Super Meat Boy and others!
- with screen grabbing trying to figure out if there is a work around.
That pretty much sums it up and if any one's curious I'm currently working on Infinite scrolling where post assets are constantly reused so there is only ever 6 posts on the screen and no create calls are called after initial load which is the dream for it to fully work.
Have a great day everyone with your dev work, Cheers.
-.
- RE: Updating FlxText.
It would be
buttonname.text = "Set text";
and in order to format code on the forum you use 3 " ``` " at the top and bottom of the code
example:
.```
Code here
`` <- extra " ` " and that key to make that charachter is right above tab left side of keyboard
- RE: Updating FlxText.
@vulpicula yep it does :)
- RE: Updating FlxText.
In the update function
text2.text = "Button presses: [" + statPointsRemaining + "].";
- RE: visible area of scaled stage
import openfl.system.Capabilities;
And grabbing screen resolution
Capabilities.screenResolutionX Capabilities.screenResolutionY
That should give you the applications screen width and height :D
- RE: ThinQbator - problem solving / invention platform social media.
- RE: ThinQbator - problem solving / invention platform social media); }
- RE: Several questions about HTML5 development.
- RE: Several questions about HTML5 development.
- RE: ThinQbator - problem solving / invention platform social media.
- Thin :)
- RE: How to stop HTML5 from freezing when I lose focus?
Possibly try FlxG.autoPause = false;
|
http://forum.haxeflixel.com/user/pxshadowhf/posts
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Lots of really important news coming in right now, both because the mid-year updates of the Revit family products are now available and because we just released the Revit 2011 DevTV recordings that we are so excited about.
Similar to last year, Autodesk provides two types of mid-year updates to Revit:
- The Web Update 2 (WU2) that I recently discussed.
- The Subscription Release.
Unlike the public web updates, the Revit 2011 subscription releases are available only for subscription customers.
Updated SDK
Both the web update and the subscription releases include a number of API enhancements. Last year, there were separate sets of updated SDKs for the WU2 and subscription release. This year, Autodesk provides one single updated SDK. Certain features are available only in the subscription release. They are clearly marked in the API reference documentation.
The updated SDK has been posted to the Revit Developer Center. Here is a direct link as well, for your convenience:
- Revit 2011 SDK (Update Sept. 2010) (exe - 108143Kb)
- Readme - Revit SDK 2011 SDK (Update Sept. 2010) (docx - 19Kb)
The product updates themselves do not include the updated SDK, so you have to download it separately.
In addition to the API enhancements, the SDK samples and the Revit Lookup tool have been updated.
Here is a summary of API changes and enhancements made in these releases:
- Issues addressed
- New Features
- Changes to the 2011 SDK
Issues addressed
- Attributes of Revit API DLLs need to be updated (190870)
- Autodesk.Revit.DB.Domain is missing enum items for Conduit, CableTray (190981)
- Accessing grids using selection through the API causes stability problem after closing Revit (190867)
- ElectricalSystem.AddToCircuit returns true for a Spare circuit, but doesn't actually connect (191518)
- RaytraceBounce sample: model curves along rays not created because curve is not in sketchplane (192058)
- Stability problem when select to save a family (191578)
- SDK sample MaterialQuantities does not successfully calculate Gross material quantities (192331)
- DetailLine/AnnotationSymbol cannot be created in ViewSheet programmatically (No sketch plane) (192072)
- API issue: Save /SaveAs lose the preview image of family file (192545)
- Detail curve cannot be create in a plan view via NewDetailCurve in a specific plan view (192115)
- Setting formula for Manufacturer/Type Comments as string using the API throws exception (192866)
- New electrical shared parameter types are missing (192832)
- CableTray Connector Angle property throws exception (190873)
- Family Type count using the API is inconsistent with UI (192889)
New FeaturesIn addition to the enhancements listed above, it includes the following new API features:
- Conceptual Energy Analysis API (Subscription only)
- City Time Zone
- Document Preview
Conceptual Energy Analysis APIConceptual Energy Analysis API is a major enhancement to the Revit API. This feature will be functional only in sessions with licensed access to the Revit 2011 Subscription Advantage Pack. The following classes are added in the Autodesk.Revit.DB.Analysis namespace and provide access to the elements and objects created by Revit to perform energy analyses on conceptual design models:
- ConceptualConstructionType
- ConceptualSurfaceType
- MassEnergyAnalyticalModel
- MassLevelData
- MassSurfaceData
- MassZone
- Document.Export(string,string,MassGBXMLExportOptions)
City Time ZoneThe following new static method provides direct access to the results of a time zone calculation for a given longitude and latitude:
- SunAndShadowSettings.CalculateTimeZone()
Document PreviewThe following new methods are added to allow you to access the settings related to the stored document preview image for a given document:
- Document.GetDocumentPreviewSettings – this returns a DocumentPreviewSettings object
- DocumentPreviewSettings.PreviewViewId - the id of the view to use for the preview
- DocumentPreviewSettings.ForceViewUpdate() - sets the document to update the view before saving (useful when the document is never displayed)
// ... View3D view3d = d.FamilyCreate.NewView3D( new XYZ(1, 2, 0).Normalize() ); // Assign permanent preview id DocumentPreviewSettings dps = d.GetDocumentPreviewSettings(); dps.PreviewViewId = view3d.Id; dps.ForceViewUpdate( true ); t.Commit(); d.SaveAs( @"C:\Door-Automated.rfa" ); // ...
Changes to the 2011 SDK
- RevitAPI.chm
- SDK sample ArchSample is updated: due to category length beyond the limitation of excel sheet name length. - Samples/ArchSample/VB.NET/Command.vb
- SDK sample MaterialQuantities – did not calculate Gross material quantities correctly - Samples/MaterialQuantities/CS/MaterialQuantities.cs
- SDK sample RaytraceBounce – updated to generate curves properly. - Samples/FindReferencesByDirection/RaytraceBounce/CS/RayTraceBounceForm.cs
- Fixed sample bugs and correct typos, formats
- Samples/DirectionCalculation/CS/DirectionCalculation.addin#2 integrate
- Samples/GenerateFloor/CS/GenerateFloor.addin#2 integrate
- Samples/ImportExport/CS/Import/ImportDWGData.cs#4 integrate
- Samples/ImportExport/CS/Import/ImportGBXMLData.cs#3 integrate
- Samples/Massing/ParameterValuesFromImage/CS/ParameterValuesFromImage.csproj#2 edit
- Samples/Massing/ParameterValuesFromImage/ParameterValuesFromImage.suo#2 delete
- Samples/Massing/ParameterValuesFromImage/ParamValueFromImage.suo#2 delete
- Samples/Revit 2011 New Samples.doc#5 integrate
- Samples/RvtSamples/CS/RvtSamples.txt#4 edit
- Samples/SamplesContent.htm#4 edit
- Samples/SDKSamples2011.sln#4 integrate
- Samples/Selections/CS/Command.cs#4 integrate
- Samples/Selections/CS/SelectionFilters.cs#3 integrate
- Samples/Selections/CS/SelectionForm.cs#3 integrate
- Samples/Selections/CS/SelectionForm.Designer.cs#2 integrate
- Samples/Selections/CS/SelectionManager.cs#3 integrate
- Samples/Selections/CS/Selections.addin#2 integrate
- 190662: RevitLookup snoop DB lacks the ElementType node:
- Add sfm.Clear() and GetChangeTypeElementDeletion trigger Samples/AnalysisVisualizationFramework/DistanceToSurfaces/CS/Command.cs
|
http://thebuildingcoder.typepad.com/blog/2010/10/subscription-release-and-updated-sdk.html
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
Programming help with monthly compound interestIf you are supposed to use sum.cpp and the instructions on the course page, I would use (principle *...
Help with programming compound interest programI'm a noob too, but maybe this will work?
#include <iostream>
using namespace std;
int main()
{
...
This user does not accept Private Messages
|
http://www.cplusplus.com/user/Ante1234/
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
Problem:
Imagine you start at the corner of an X by Y grid. You can only move in two directions: right and down. How many possible paths are there for you to go from (0, 0) to (X, Y)
def gridMovingCount(x, y, cache):
if x == 0 or y == 0:
return 1
elif str(x)+":"+str(y) in cache:
return cache[str(x)+":"+str(y)]
else:
cache[str(x)+":"+str(y)] = gridMovingCount(x-1, y, cache) + gridMovingCount(x, y-1, cache)
return cache[str(x)+":"+str(y)]
def gridMovingCountByBinomial(x, y):
return int(math.factorial(x + y) / (math.factorial(x) * math.factorial(y)))
#the same result
print(gridMovingCount(20, 20, cache)) #137846528820
print(gridMovingCountByBinomial(20, 20)) #137846528820
# gave different result
print(gridMovingCount(50, 50, cache)) #100891344545564193334812497256
print(gridMovingCountByBinomial(50, 50)) #100891344545564202071714955264
The issue here is a limitation of floating point arithmetic and the differences between python2 and python3 in regards to the division operator.
In python 2 the division operator returns the floor of the result of a division if the arguments are ints or longs (as in this case) or a reasonable approximation if the arguments are floats or complex. Python 3 on the other hand returns a reasonable approximation of the division independent of argument type.
At small enough numbers this approximation is close enough that the cast back to an integer ends up with the same result as the python 2 version. However as the result gets large enough the floating point representation is not a sufficient approximation to end up with the correct result when casting back to an int.
In python2.2 the floor division operator was introduced
// and in python3 true division replaced classic division (see origin of terminology here:)
#python2 from math import factorial print(int(factorial(23)/2)) # 12926008369442488320000 print(int(factorial(23)//2)) # 12926008369442488320000
#python3 from math import factorial print(int(factorial(23)/2)) # 12926008369442489106432 print(int(factorial(23)//2)) # 12926008369442488320000
The upshot of all this is that for your binomial function you can remove the cast to int and use the explicit floor division operator to get the correct results returned.
def gridMovingCountByBinomial(x, y): return math.factorial(x + y) // (math.factorial(x) * math.factorial(y))
|
https://codedump.io/share/7wdJz42Kdo9s/1/python-recursive-call-counting-ways-of-walking-grid-yield-incorrect-answer-when-grid-size-is-too-large
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
Foreword
If you already read some other blog post about unusual mocking, you can skip prelude via this link.
I was asked to put together examples for how to mock Java constructs well known the current hectic agile world to make such classes easy to unit test the standard way. When you are trying to unit test such classes, you often realize that unusual mocking is needed.
That is why I decided to create and share refactoring considerations alongside with examples and workarounds for unusual mocking. Examples are using Mockito and PowerMock mocking frameworks and TestNG unit testing framework.
Mock Private Method
Refactoring Considerations
Private method that is needed to be mocked can be in:
- testing class (will call it TC)
- direct dependency of testing class (will call is DDC)
- class that is not direct dependency of testing module (will call it NDDC)
Re-factoring techniques to consider:
- If the private method is in TC, it is a good sign that TC has low cohesion (has too many responsibilities) and logic behind private method should be extracted into separate class. After this refactoring, private method in TC becomes public in new dependency class. Than it is possible to mock it standard way.
- If the private method is in DDC, concerns of TC and DDC modules are not separated properly. It means you are trying to test some logic from DDC in test for TC. Consider moving this logic to TC or to separate module. Private method than becomes public and can be mocked standard way.
- If the private method is in NDDC, you are probably creating integration test instead of unit test. Unit test in theory should be testing module in isolation. That means to mock all direct dependencies (sometimes it's easier to test with real objects when they are simple and independent enough). Consider:
- Creation of unit test first. You can decide later if integration test is needed for group of modules you trying to test.
- Find easier to mock boundaries for your integration test (you can find a clue in unit test for NDDC if exists)
- Refactor NDDC according refactoring practises mentioned for TC and DDC above, update it's unit test (also all tests affected by refactoring), and use created public method as boundary for your integration test.
Workaround Using Mockito
This is my preferred technique when I need to mock private method. I believe that minor exposing of internal implementation in flavor to enhance testability of testing module is much lower risk for project than fall into bytecode manipulation mocking framework like PowerMock or JMockIt.
This technique involves:
- Changing private access modifier to default
- Partially mock testing object by using spy
Mockito example covers:
- Mocking of changed default method with return value
- Mocking of changed changed default void method
- Verifying of changed default method calls
Class under test:
public class Train { public int compose() { for (int idx = 0; idx < getWagonsCount(); idx++) { addWagon(0); } return getWagonsCount(); } /** * Access modifier was changed from private to default to enhance * testability */ // private int getWagonsCount() { throw new UnsupportedOperationException("Fail if not mocked!"); } /** * Access modifier was changed from private to default to enhance * testability */ // private void addWagon(int position) { throw new UnsupportedOperationException( "Fail if not mocked! [position=" + position + "]"); } }
Test:
@Test public void testCompose() { Train train = new Train(); Train trainSpy = Mockito.spy(train); //notice different Mockito syntax for spy Mockito.doReturn(TESTING_WAGON_COUNT).when(trainSpy).getWagonsCount(); Mockito.doNothing().when(trainSpy).addWagon(0); // invoke testing method int actualWagonCount = trainSpy.compose(); Assert.assertEquals(actualWagonCount, TESTING_WAGON_COUNT); Mockito.verify(trainSpy, Mockito.times(TESTING_WAGON_COUNT)) .addWagon(0); } private method directly by PowerMock. Example covers:
- Mocking of private method with return value
- Mocking of private void method
- Verifying of private method calls
Class under test:
public class Truck { public double addLoad(Collection<Double> boxWeightsToAdd) { for (Double boxWeight : boxWeightsToAdd) { addBoxToLoad(boxWeight); } return getLoadWeight(); } private double getLoadWeight() { throw new UnsupportedOperationException("Fail is not mocked!"); } private void addBoxToLoad(double weight) { throw new UnsupportedOperationException("Fail is not mocked! [weight=" + weight + "]"); } }
Test:
@PrepareForTest(Truck.class) public class TruckTest extends PowerMockTestCase { private static final double TESTING_LOAD_WEIGHT = 200; private static final double TESTING_BOX_WEIGHT = 100; @Test public void testTestingMethod() throws Exception { Truck truck = new Truck(); Truck truckSpy = PowerMockito.spy(truck); PowerMockito.doReturn(TESTING_LOAD_WEIGHT).when(truckSpy, "getLoadWeight"); PowerMockito.doNothing().when(truckSpy, "addBoxToLoad", TESTING_BOX_WEIGHT); // call testing method Collection<Double> boxesWeights = Arrays.asList(TESTING_BOX_WEIGHT, TESTING_BOX_WEIGHT); double actualLoad = truckSpy.addLoad(boxesWeights); Assert.assertEquals(actualLoad, TESTING_LOAD_WEIGHT); PowerMockito.verifyPrivate(truckSpy, Mockito.times(2)).invoke( "addBoxToLoad", TESTING_BOX_WEIGHT); } }
Links
Source code can be downloaded from Github.
Other unusual mocking examples:
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/mock-private-method
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
A Walk Through Fire
Frodo is on the quest to destroy the Lord of the Rings. But Frodo has to cross some dangerous blocks which have fire on them.
There are N blocks and Frodo starts from block 1, which doesn’t have fire.Each i-th block will have fire starting at time 0 and stopping at time T[i]. Of-course, T[1]=0 as Frodo starts from block 1.
Frodo can step on a block only if it has no fire. Therefore, if the fire at block i ends at T[i], he can step on it only at time (T[i]+1) or greater.
Frodo can walk from block i to j in unit time, given that i
First line consists of an integer
t denoting the number of test cases
Each test case begins with
N, number of blocks
Next line consist of
N spaced integers denoting
T[i], the time at which fire on i-th block will stop
Constraints:
1≤t≤10
1≤t≤10
1≤N≤100000
0≤T[i]≤1000000
T[1]=0
Output:
For each test case, print integer denoting minimum time required in a single line
#include <iostream> #include <vector> using namespace std; int main() { int t; cin>>t; while(t--){ int n,m=0; cin>>n; vector <int> v; for(int i=0; i<n; i++) { int x; cin>>x; if(m<x) m=x; v.push_back(x); } cout<<m+1<<endl; } return 0; }
Competitive coding
Hackerearth problem
|
https://coderinme.com/walk-fire-hackerearth-problem-coderinme/
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
A colleague approached me today asking whether I've tried importing TIFFs into Python for image processing with SciPy. My image processing experience has been mainly focussed within a MATLAB environment, so we set about going through this together. Unfortunately, none of the images we tried to process with
imread and
imshow would work properly and would only display a white result. Inspection of the
imread output showed that it returned a matrix of 255s. This was despite the source TIFF containing a greyscale image of something more interesting. Further investigation was thus warranted.
I firstly tried looking at the properties of the greyscale TIFF image and saw it was saved in 16 bits. I initially overlooked this thinking that this was the default. To cut a long story short, I realise now that this was the key fact as downsampling the file to 8 bits imported the TIFF file without any problem. So we were faced with a dilemma. Do we: 1. convert an entire library of TIFF files from 16 bits to 8 bits, 2. revert back to using MATLAB, or 3. try and get
imread to open 16 bit TIFFs. Option 1 was immediately rejected as the library was enormous leaving options 2 and 3. We decided to continue with Python and investigate a solution.
A quick search on the Internet revealed others had experienced this problem, but few offered workable solutions. One such place was from another blogger, Philipp Klaus, who listed several methods to overcome this problem. Installing some of the packages required to accomplish this task proved too challenging on the Mac with its limited Python library, so I stopped. Fortunately, my colleague picked up where I left off and found an interesting comment on this site, posted by Mathieu Leocmach. This included a snippet of code that my colleague had tried on the data but did not work as expected. Here's the code in full:
import numpy as np import Image def readTIFF16(path): """Read 16bits TIFF""" im = Image.open(path) out = np.fromstring( im.tostring(), np.uint8 ).reshape(tuple(list(im.size)+[2])) return (np.array(out[:,:,0], np.uint16)<<8)+out[:,:,1]
Overviewing the code, I noticed the variable
out consists of three dimensions. The third dimension translates to which one of the two bytes to use. According to the code, the most significant byte is in the index
[:, :, 0], whereas the least significant is at
[:, :, 1]. When we tried it out, the result of this sum produced mostly noise but certain elements looked to have some order. Further analysis revealed the more interesting aspects of the image were contained with
[:, :, 0] instead, and the noise was contained within the other. However, there was also some order to index [:, :, 1], despite being mostly noise, so we couldn't simply reject this byte. This indicated a possible byte sequence shift which may be the result of Endian-ness. Changing the code to the following allowed us to see the image:
import numpy as np import Image def readTIFF16(path): """Read 16bits TIFF""" im = Image.open(path) out = np.fromstring( im.tostring(), np.uint8 ).reshape(tuple(list(im.size)+[2])) return (np.array(out[:,:,1], np.uint16)<<8)+out[:,:,0]
But if we're writing code like this, there's no reason why we're splitting the original image into two byte sequences. We could accomplish the same task by immediately using
np.uint16 instead of
np.uint8 and removing the need for a third dimension in the output. I settled with the following bit of code that worked well for us. Note that this code could, of course, be tidied up further, but I won't do that here.
import numpy as np import Image def readTIFF16(path): """Read 16bits TIFF""" im = Image.open(path) out = np.fromstring( im.tostring(), np.uint16 ).reshape(tuple(list(im.size))) return out
Now we're able to use 16 bit greyscale images within Python without having to resort to converting entire image libraries or using other packages or software. There's the possibility that the original code will work for some people and our version looks like white noise. I believe this is possibly due to Endian differences between the data and the computer. Hopefully future versions of Python will address this issue and making the necessary checks to TIFF source files so that we don't have to find workarounds. Not that we don't enjoy finding and creating these solutions!
|
http://andrew-hills.blogspot.com/2013/03/importing-16-bit-tiffs-into-numpy.html
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
This node represents an addition of some number of SCEVs. More...
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
This node represents an addition of some number of SCEVs.
Definition at line 217 of file ScalarEvolutionExpressions.h.
Methods for support type inquiry through isa, cast, and dyn_cast:
Definition at line 233 of file ScalarEvolutionExpressions.h.
References llvm::SCEV::getSCEVType(), and llvm::scAddExpr.
Definition at line 225 of file ScalarEvolutionExpressions.h.
Referenced by isAddSExtable(), and PickMostRelevantLoop().
Definition at line 218 of file ScalarEvolutionExpressions.h.
|
http://llvm.org/doxygen/classllvm_1_1SCEVAddExpr.html
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
On Sun, Jul 7, 2013 at 3:14 AM, Jeff King <p...@peff.net> wrote: > The pack revindex stores the offsets of the objects in the > pack in sorted order, allowing us to easily find the on-disk > size of each object. To compute it, we populate an array > with the offsets from the sha1-sorted idx file, and then use > qsort to order it by offsets. > > That does O(n log n) offset comparisons, and profiling shows > that we spend most of our time in cmp_offset. However, since > we are sorting on a simple off_t, we can use numeric sorts > that perform better. A radix sort can run in O(k*n), where k > is the number of "digits" in our number. For a 64-bit off_t, > using 16-bit "digits" gives us k=4. > > > > Signed-off-by: Jeff King <p...@peff.net> > --- > I think there are probably still two potential issues here: > > 1. My while() loop termination probably has issues when we have to use > all 64 bits to represent the pack offset (not likely, but...) > > 2. We put "int pos[65536]" on the stack. This is a little big, but is > probably OK, as I think the usual small stack problems we have seen > are always in threaded code. But it would not be a big deal to heap > allocate it (it would happen once per radix step, which is only 4 > times for the whole sort). > > pack-revindex.c | 77 > +++++++++++++++++++++++++++++++++++++++++++++++++++++---- > 1 file changed, 72 insertions(+), 5 deletions(-) > >. > { > - const struct revindex_entry *a = a_; > - const struct revindex_entry *b = b_; > - return (a->offset < b->offset) ? -1 : (a->offset > b->offset) ? 1 : 0; > + /* > + * We need O(n) temporary storage, so we sort back and forth between > + * the real array and our tmp storage. To keep them straight, we > always > + * sort from "a" into buckets in "b". > + */ > + struct revindex_entry *tmp = xcalloc(n, sizeof(*tmp)); > + struct revindex_entry *a = entries, *b = tmp; > + int digits = 0; > + > + /* > + * We want to know the bucket that a[i] will go into when we are using > + * the digit that is N bits from the (least significant) end. > + */ > +#define BUCKET_FOR(a, i, digits) ((a[i].offset >> digits) & 0xffff) > + > + while (max / (((off_t)1) << digits)) { Is there any reason this shouldn't be simplified to just: while (max >> digits) { I glanced briefly at the assembly and it appears that gcc does actually emit a divide instruction to accomplish this, which I think we can avoid by just rearranging the operation. > + struct revindex_entry *swap; > + int i; > + int pos[65536] = {0}; > + > + /* > + * We want pos[i] to store the index of the last element that > + * will go in bucket "i" (actually one past the last element). > + * To do this, we first count the items that will go in each > + * bucket, which gives us a relative offset from the last > + * bucket. We can then cumulatively add the index from the > + * previous bucket to get the true index. > + */ > + for (i = 0; i < n; i++) > + pos[BUCKET_FOR(a, i, digits)]++; > + for (i = 1; i < ARRAY_SIZE(pos); i++) > + pos[i] += pos[i-1]; > + > + /* > + *, digits)]] = a[i]; > + > + /* > + * Now "b" contains the most sorted list, so we swap "a" and > + * "b" for the next iteration. > + */ > + swap = a; > + a = b; > + b = swap; > + > + /* And bump our digits for the next round. */ > + digits += 16; > + } > + > + /* > + * If we ended with our data in the original array, great. If not, > + * we have to move it back from the temporary storage. > + */ > + if (a != entries) { > + int i; > + for (i = 0; i < n; i++) > + entries[i] = tmp[i]; I think I recall that somebody investigated whether a for loop like you have above was faster for copying structures than memcpy. I forget whether it was conclusive. Did you happen to compare them? <snip> -Brandon -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at
|
https://www.mail-archive.com/git@vger.kernel.org/msg31659.html
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
This document describes the TCallBack class.
The class encapsulates a pointer to a function which takes an argument
of type
TAny* and returns a
TInt. The class
is generally useful but, in particular, simplifies the programming interface
of the
CIdle and
CPeriodic classes.
Given a suitable function and a pointer to an object, a callback is constructed simply. The function must be a non-member function or a static member of a class. For example:
TInt Foo(TAny *); // a non-member function X* pX=new X; // a class X object
or, as a static member of class
X:
TInt X::Foo(TAny *); // a static function of class X X* pX=new X; // a class X object
A callback function returns a true value to indicate whether it should
be called again. This is important when used with the
CIdle and
CPeriodic classes.
The following code fragment shows the programming paradigm:
TCallBack cb(Foo,pX); // construction of the callback
for (;;) { if (!cb.CallBack()) // invoke callback until it returns { // a false value break; } }
Calling
cb.CallBack() results in a call to the callback
function
Foo() passing it the pointer
pX.
A common requirement is for the callback function to be a non-static member of a class. This can be implemented by passing, to the callback function, a pointer to an instance of the class of which it is a static member. For example:
class X { static X* NewL(); static TInt Foo(TAny* pX); private: TInt DoFoo(); ... }
where the static function
Foo() is implemented as:
static TInt X::Foo(TAny* pX) { return ((X*)pX)->DoFoo(); }
Typically, create an instance of class
X and, at some
later stage, create the callback:
... X* pX = X::NewL(); ... TCallBack cb(Foo,pX); ...
|
http://devlib.symbian.slions.net/belle/GUID-C73318E7-44E2-5F42-BDB0-AAE9BD72BF5C.html
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
One of the greatest challenges associated with maintaining a complex desktop application like Dropbox is that with hundreds of millions of installs, even the smallest bugs can end up affecting a very large number of users. Bugs inevitably will strike, and while most of them allow the application to recover, some cause the application to terminate. These terminations, or “crashes,” are highly disruptive events: when Dropbox stops, synchronization stops. To ensure uninterrupted sync for our users we automatically detect and report all crashes and take steps to restart our application when they occur.
In 2016, faced with our impending transition to Python 3, we set out to revamp how we detect and report crashes. Today, our crash reporting pipeline is a reliable cornerstone for our desktop teams, both in volume and quality of reports. In this post, we’ll dive into how we designed this new system.
Python doesn’t crash, right?
Dropbox is partly written in Python, and while it certainly is a safe, high-level language, it is not immune to crashes. Most crashes (i.e. unhandled exceptions) are simple to deal with because they occur in Python, but many originate “below”: in non-Python code, within the interpreter code itself, or within Python extensions. These “native” crashes, as we refer to them, are nothing new: improper memory manipulation, for example, has plagued developers for decades.
As our application grew more complex, we began to rely on other programming languages to build some of our features. This was particularly true when integrating with the operating system, where the easiest path tends to lead to platform-specific tooling and languages (e.g. COM on Windows and Objective-C on macOS). This has led to an increased share of non-Python code in our codebase, which has brought along an increased risk for dangling pointers, memory errors, data races, and unchecked array accesses: all of which can cause Dropbox to be unceremoniously terminated. As a result, a single crash report can now contain Python, C++, Objective-C, and C code in its stack trace!
The Early Days
For several years, we relied on a simple in-process crash detection mechanism: a signal handler. This scheme allowed us to “trap” various UNIX signals (and on Windows, their analogues). Upon hitting a fatal signal (i.e.
SIGFPE), our signal handler would attempt to:
- Capture the Python stack trace (using the
faulthandlermodule) for each thread
- Capture the native stack trace for that thread (typically using
libc‘s
backtraceand
backtrace_symbolsfunctions)
We would then attempt to securely upload this data to Dropbox’s servers.
While this was adequate, a few fundamental issues affected reliability or limited its usefulness in debugging:
- If a problem occurred before we set up the handler, we wouldn’t get any reports. This is usually caused by an
ImportError, a missing library, or an installation error. These fundamental “boot errors” are the most severe because they result in the user being unable to start the app. We were unable to capture these at all, an unacceptable situation. The only way for any reports of these issues to reach our engineers was by contacting customer support. While we built a helpful error dialog to help with this process, this still led to our team becoming somewhat risk-averse to meddling with startup/early code.
- The signal handler is somewhat fragile. This handler was responsible for not only capturing state but also sending it to our servers. Over time, we realized it could often fail to send the report despite managing to generate it successfully. In addition, particularly severe crashes could make it impossible to correctly extract state on a crash. For example, if the interpreter state itself became corrupted, it could prevent us from including the Python stack trace—or worse, could derail the entire handling process.
One of the root causes of this is the nature of signal handling itself: while, thankfully, Python’s
signal module takes care of most these, it also adds its own restrictions. For example, signals can only be called from the main thread and may not be run synchronously. This asynchronicity meant that some of the most common
SIGSEGVs could often fail to be trapped from Python!1
Crashpad to the rescue
A more reliable crash reporting mechanism can be built by extracting the reporter outside of the main process. This is readily feasible, as both Windows and MacOS provide system facilities to trap out-of-process crashes. The Chromium project has developed a comprehensive crash capture/report solution that leverages this functionality and that can be used as a standalone library: Crashpad.
Crashpad is deployed as a small helper process that monitors your application, waits for a signal that it has crashed, and then captures useful information, including:
- The reason a process crashed and the thread that originated the crash
- Stack traces for all threads
- Contents of parts of the heap
- Extra annotations that developers can add to their application (a useful layer of flexibility)
All of this is captured in a minidump payload, a Microsoft-authored format originally used on Windows and somewhat similar to a Unix-style core dump. The format is openly documented, and there exists excellent server-side tooling (again, mainly from Google and Mozilla) to process such data.
The following diagram outlines Crashpad’s basic architecture:
An application uses Crashpad by instantiating an in-process object—called the “client”—that reports to an out-of-process helper—called a “handler”—when it detects a crash.
We decided to use this library to mitigate many of the reliability issues associated with an in-process signal handler. This was an easy choice due to its use by Chromium, one of the most popular desktop applications ever released. We were also enthused by more sophisticated support for Windows, a rather different platform from UNIX.
faulthandler was (at the time) limited in its support for Windows-specific crashes, since it was very much based on signals, a UNIX/POSIX concept. Crashpad leverages Structured Exception Handling (or SEH), allowing it to catch a much broader range of fatal Windows-specific exceptions.
A note on Linux: Though Linux support has been very recently introduced, Crashpad was only available for Windows and MacOS when we first deployed it, so we limited our use of the library to these platforms. On Linux, we continue to use the in-process signal handler, though we will re-visit this in the future.
Symbolication
Dropbox, like most compiled applications, ships to users in a “Release” configuration, where several compiler optimizations are enabled and symbols are stripped to reduce binary size. This means the information gathered is mostly useless unless it can be “mapped” back to source code. This is referred to as “symbolication”.
To achieve this, we preserve symbols for each Dropbox build on internal servers. This is a core part of our build process: symbol generation failure is considered a build failure, making it impossible for us to release a build that cannot later be symbolicated.
When a minidump is received as part of a crash report, we use the symbols for the build to decipher each stack trace and link it back to source code. When system libraries are used, we defer to platform-specific symbols. This process allows our developers to quickly find where crashes originate in either first or third-party code.
Microsoft maintains public symbol servers for all Windows builds in order for stack frames involving their functions to be mapped. Unfortunately, Apple does not have a similar system: instead, the platform’s frameworks include their matching symbols. To support this, we currently cache the symbols of various macOS frameworks (for a wide range of OS versions) using our testing VMs (though we can still occasionally end up with gaps in our coverage).
A validation sidecar
Changing our crash reporting infrastructure from underneath millions of installations was a risky endeavor: we required validation that our new mechanism was working. It’s also important to note that not all terminations are necessarily crashes (e.g. the user closing the app or an automatic update). That being said, some terminations may still indicate problems. We therefore wanted a way to record and classify exits along with crashes. This also would provide us with a baseline to validate that our new crash reporter was capturing a high fraction of total crashes.
To address this, we built yet another “sidecar” process we named “watchdog.” This is another small “companion” process (similar to Crashpad) that has a single responsibility: when the desktop app exits, it captures its exit status to determine whether it was “successful” (that is, a user or app-initiated shutdown instead of being forcibly terminated). This process is extremely simple by intention as we want it to be highly reliable.
To provide a basis for comparison, a start event is generated by making our application send an event on launch. With both start and exit events, we are then able to measure the accuracy of exit monitoring itself: we can ensure it was successful for a very high percentage of our users (note that firewalls, corporate policies, and other programs prevent this from working 100% of the time). In addition, we can now match this exit event against crashes coming from Crashpad to make sure that exit codes in which we expect crashes indeed include crash reports from most users. The graphs below show the monitoring we have in place:
We wrote the watchdog process in Rust, which we chose for a variety of reasons:
- The safety guarantees offered by the language make it a lot easier to trust code.
- The operating system abstractions are well designed, part of the standard library, and easy to extend via FFI wherever required.
- We have developed quite a bit of Rust expertise at Dropbox, giving this project an easier ramp-up.
Teaching Crashpad about Python
Crashpad was primarily designed for native code, as Chromium is mostly written in C++. However, the Dropbox client is mostly written in Python. As Python is an interpreted language, most native crash reports we receive thus tend to look like this:
0 _ctypes.cpython-35m-darwin.so!_i_get + 0x4 1 _ctypes.cpython-35m-darwin.so!_Simple_repr + 0x4a 2 libdropbox_python.3.5.dylib!_PyObject_Str + 0x8e 3 libdropbox_python.3.5.dylib!_PyFile_WriteObject + 0x79 4 libdropbox_python.3.5.dylib!_builtin_print + 0x1dc 5 libdropbox_python.3.5.dylib!_PyCFunction_Call + 0x7a 6 libdropbox_python.3.5.dylib!_PyEval_EvalFrameEx + 0x5f12 7 libdropbox_python.3.5.dylib!_fast_function + 0x19d 8 libdropbox_python.3.5.dylib!_PyEval_EvalFrameEx + 0x5770 9 libdropbox_python.3.5.dylib!__PyEval_EvalCodeWithName + 0xc9e 10 libdropbox_python.3.5.dylib!_PyEval_EvalCodeEx + 0x24 11 libdropbox_python.3.5.dylib!_function_call + 0x16f 12 libdropbox_python.3.5.dylib!_PyObject_Call + 0x65 13 libdropbox_python.3.5.dylib!_PyEval_EvalFrameEx + 0x666a 14 libdropbox_python.3.5.dylib!__PyEval_EvalCodeWithName + 0xc9e 15 libdropbox_python.3.5.dylib!_PyEval_EvalCodeEx + 0x24 16 libdropbox_python.3.5.dylib!_function_call + 0x16f 17 libdropbox_python.3.5.dylib!_PyObject_Call + 0x65 18 libdropbox_python.3.5.dylib!_PyEval_EvalFrameEx + 0x666a 19 libdropbox_python.3.5.dylib!__PyEval_EvalCodeWithName + 0xc9e 20 libdropbox_python.3.5.dylib!_PyEval_EvalCodeEx + 0x24 21 libdropbox_python.3.5.dylib!_function_call + 0x16f 22 libdropbox_python.3.5.dylib!_PyObject_Call + 0x65 ... on and on
This stack trace is not very helpful to a developer trying to discover the cause of a crash. Whereas
faulthandler also included the Python stack frames of all threads, Crashpad does not have this ability by default. To make this report useful, we would need to include the relevant Python state. However, as Crashpad is not written in Python and is out-of-process, we don’t have access to
faulthandler itself: how might we go about doing this?
When the crashing program is suspended, all of its memory is available to Crashpad, which can read it to capture the program state. As the program is potentially in a bad state, we can’t execute any code within it. Instead we need to:
- Figure out where the Python data structures are laid out in memory
- Walk the relevant data structures to figure out what code was running when the program crashed
- Store this information and securely upload it to our servers
We chose Crashpad in part for its customizability: it is fairly easy to extend. We therefore added code to the
ProcessSnapshot class to capture Python stacks, and introduced our own custom minidump “stream” (supported by both the file format and Crashpad itself) to persist and report this information.
Python and Thread-Local Storage
First, we needed to know where to look. In CPython, interpreter threads are always backed by native threads. Therefore, in the Dropbox application, each native thread created by Python has an associated
PyThreadState structure. The interpreter uses native thread-specific storage to create the connection between this object and the native thread. As Crashpad has access to the monitored process’ memory, it can read this state and include it as part of a report.
As Dropbox ships a customized fork of CPython, we have effective control over its behavior. This means that not only can we use this knowledge to our advantage but we can rely on it knowing it won’t easily change from under us.
In Python, thread-specific storage is implemented in platform-specific ways:
- On POSIX,
pthread_key_createis used to allocate the key, while
pthread_(get/set)specificare used to interact with them
- On Windows,
TlsAllocis used to allocate thread-local “slots” stored in a predictable/documented location in the Thread Environment Block.aspx)
Common to all platforms, however, is that the Python-specific state is stored at a specific offset of the native thread state. Sadly, this offset is not static: it can change depending on various factors. This offset is determined early in the Python runtime’s setup (see
PyInitialize): this is referred to as the thread-specific storage “key”. This step creates a single “slot” of thread-specific storage for all threads in the process, which is then used by Python to store its thread-specific state.
So if
crashpad can retrieve the TSS “key” for the instance of the process, it will have the ability to read the
PyThreadState for any given thread.
Getting the Thread-Local Storage “Key”
We considered multiple ways of doing this, but settled on a method inspired by Crashpad itself. In the end, we modified our fork of Python to expose the runtime state (including the TSS key) in a named section of the binary (i.e.
__DATA). Thus, all instances of Dropbox would now expose the Python runtime state in a way that makes it easy to retrieve it from Crashpad.
- This was achieved with a simple
__attribute__in Clang and by using
__declspecon Windows.
- This is already simple to use in Crashpad, because it uses the same technique to allow clients to add annotations to their own process (see
CrashpadInfo).
- This is also well-aligned with Python’s own evolving design for the interpreter internals, as it recently reorganized itself to consolidate runtime state into a single struct,
_PyRuntime(in
Python/pylifecycle.c). This structure includes the TSS key, along with other information of potential interest to debug tools.
- Note: We’ve submitted this change as a pull request to the Python project, in case it can be helpful to others.
Now that Crashpad can determine the TSS key, it has access to each thread’s
PyThreadState. The next step is to interpret this state, extract the relevant information, and send it as part of a crash report.
Parsing Python Stack Frames
In CPython, “frames” are the unit of function execution, and the Python analogue to native stack frames. The
PyThreadState maintains them as a stack of
PyFrameObjects. The topmost frame at any given time is pointed to by the thread state using a single pointer. Given this setup and the TSS key, we can start from a native thread, find the
PyThreadState, then “walk the stack” of
PyFrameObjects.
However, this is trickier than it sounds. We can’t just
#include <Python.h> and call the same functions
faulthandler does: as Crashpad’s handler runs in a separate process, it doesn’t have direct access to this state. Instead, we had to use Crashpad’s utilities to reach into the crashing process’s memory and maintain our own “copies” of the relevant Python
structs to interpret the raw data. This is a necessarily brittle solution, but we’ve mitigated the cost of ongoing maintenance by introducing automated tests that ensure that any updates to Python’s core
structs to also require an update our Crashpad fork.
For every frame, our objective is to resolve it to a code location. Each
PyFrameObject has a pointer to a
PyCodeObject including information about the function name, file name, and line number (
faulthandler leverages the same information).
The filename and function name are maintained as Python strings. Decoding Python strings can be fairly involved, as they are built on a hierarchy of types (we’ll spare you the details, but see
unicodeobject.h). For simplicity, we assume all function and file names are ASCII-encoded (mapping to the simple
PyASCIIObject).
Getting the line number is slightly more complicated. To save space, while being able to map every byte code instruction to Python source, Python compresses line numbers into a table (
PyCodeObject‘s
co_lnotab). The algorithm to decode this table is well-defined, so we re-implemented it in our Crashpad fork.
A note on the Python 3 transition: As Python 2 and 3 have slightly different implementations, we maintained support for both versions of the Python
structs in our Crashpad fork during the transition.
Stack Frame Reconstitution
Now that Crashpad’s reports include all the Python stack frames, we can improve symbolication. To do so, we modified our server infrastructure to parse our extensions to minidumps and extract these stacks. Specifically, we augmented our crash management system, Crashdash, to display Python stack frame information (if it is available) for native crash reports.
This is achieved by “walking the stack” again, but this time, for each native frame calling
PyEval_EvalFrameEx, we “pop” the matching
PyFrameObject capture from the report. Since we now have the function name, file name, and line number for each of those frames we can now show the matching function calls. We can thus extract the underlying Python stack trace from the one above:
file "ui/common/tray.py", line 758, in _do_segfault file "dropbox/client/ui/cocoa/menu.py", line 169, in menuAction_ file "dropbox/gui.py", line 274, in guarantee_message_queue file "dropbox/gui.py", line 299, in handle_exceptions file "PyObjCTools/AppHelper.py", line 303, in runEventLoop file "ui/cocoa/uikit.py", line 256, in mainloop file "ui/cocoa/uikit.py", line 929, in mainloop file "dropbox/client/main.py", line 3263, in run file "dropbox/client/main.py", line 6904, in main_startup file "dropbox/client/main.py", line 7000, in main
Wrapping up
With this system in place, our developers are capable of directly investigating all crashes, whether they occur in Python, C, C++, or Objective-C. In addition, the new monitoring we introduced to measure the system’s reliability has given us added confidence our application is performing as it should. The result is a more stable application for our desktop users. Case in point: using this new system, we were able to perform the Python 2 to 3 transition without fear that our users would be negatively affected.
Nikhil gave a talk at PyGotham 2018 that dives into Python stack frame implementation details and explains our strategy for using Crashpad. The slides are available now (videos will be up soon).
Interested?
If the type of problem solving we described sounds fun and you want to take on the challenges of desktop Python development at scale, consider joining us!
Footnotes:
1 A
SIGSEGV cannot be handled asynchronously due to how signals are implemented. When a CPU instruction attempts to access an invalid location, it triggers a page fault. This is handled by the OS. The OS will first rewind the instruction pointer to go back to the beginning of this instruction, since it needs to resume execution of the program once the signal handler returns. The first time, the signal handler is triggered. Once it returns, execution resumes. The OS tracks that a handler was already invoked. When the fault is triggered again, this specific signal is masked so that no handler runs. At this point, the behavior for a
SIGSEGV is to core dump the process and abort it. Our asynchronous handler effectively never runs. The
faulthandler module specifically supports synchronous capture of Python stacks, but it can only save these to a file. No network activity or Python execution is allowed due to signal safety requirements. These various complications, and the clear benefits of Crashpad in other areas, made it compelling to switch.
|
http://engineeringjobs4u.co.uk/crash-reporting-in-desktop-python-applications
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
Introduction
This.
- Note
- Before starting, make sure you have built mlpack for Windows following this Windows guide
Creating the VS project
- Open Visual Studio and create a new project (Windows Console Application)
- For this sample, the project is named “sample-ml-app”
Project Configuration
There are different ways in which you can configure your project to link with dependencies. This configuration is for x64 Debug Mode. If you need Release Mode, please change the paths accordingly (assuming you have built mlpack and dependencies in Release Mode).
- Right click on the project and select Properties, select the x64 Debug profile
- Under C/C++ > General > Additional Include Directories add:- C:\boost\boost_1_66_0- C:\mlpack\armadillo-8.500.1\include- C:\mlpack\mlpack-3.0.3\build\include
- Under Linker > Input > Additional Dependencies add:- C:\mlpack\mlpack-3.0.3\build\Debug\mlpack.lib- C:\boost\boost_1_66_0\lib64-msvc-14.1\libboost_serialization-vc141-mt-gd-x64-1_66.lib- C:\boost\boost_1_66_0\lib64-msvc-14.1\libboost_program_options-vc141-mt-gd-x64-1_66.lib
- Under Build Events > Post-Build Event > Command Line add:- xcopy /y "C:\mlpack\mlpack-3.0.3\build\Debug\mlpack.dll" $(OutDir)- xcopy /y "C:\mlpack\mlpack-3.0.3\packages\OpenBLAS.0.2.14.1\lib\native\bin\x64\*.dll" $(OutDir)
- Note
- Recent versions of Visual Studio set "Conformance Mode" enabled by default. This causes some issues with the armadillo library. If you encounter this issue, disable "Conformance Mode" under C/C++ > Language.
The app goal
This app aims to exercise an end-to-end machine learning workflow. We will cover:
- Training (using Random Forest as example)
- Computing the training accuracy
- Cross-Validation using K-Fold
- Metrics gathering (accuracy, precision, recall, F1)
- Saving the trained model to disk
- Classifying a new sample
Headers and namespaces.
- Note
- Make sure you update the path to your dataset file. For this sample, you can simply copy "mlpack/tests/data/german.csv" and paste into a new "data" folder in your project directory.
Then we need to extract the labels from the last dimension of the dataset and remove the labels from the training set:
We now have our dataset ready for training.
Training
This app will use a Random Forest classifier. At first we define the classifier parameters and then we create the classifier to train it.
Now that the training is completed, we quickly compute the training accuracy:
Cross-Validating:
Saving the model:
Classifying a new sample
Finally, the ultimate goal is to classify a new sample using the previously trained model. Since the Random Forest classifier provides both predictions and probabilities, we obtain both.
Final thoughts".
Generated by
|
http://mlpack.org/docs/mlpack-git/doxygen/sample_ml_app.html
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
Final Destination
Bob and Khatu are stuck in matrix. The command center sent them a string which decodes to the their final destination. Since Bob and Khatu are not good at problem solving help them to figure out their final destination. They are initially at (0, 0). String contains L, R, U, D denoting left, right, up and down. In each command they will traverse 1 unit distance in the respective direction. For example if they are at (2, 0) and the command is L they will go to (1, 0).
Input:
Input contains a single string.
Output:
Print the final destination location of Bob and Khatu.
Constraints:
1 ≤ |S| ≤ 105
Explanation
if the input string is “LLRDDR”
Initail Postion : 0, 0
1.) ‘L’ -> cover one unit of distance in left direction. New position (-1,0)
2.) ‘L’ -> new position (-2,0)
3.) ‘R’ -> new position (-1,0)
4.) ‘D’ -> new position (-1,-1)
5.) ‘D’ -> new position (-1,-2)
6.) ‘R’ -> new position (0,-2)
#include <iostream> #include <string> using namespace std; int main() { string s; int x=0,y=0; cin>>s; for(int i=0;i<s.length();i++) { if(s[i]=='L') { x--; } else if(s[i]=='R') { x++; } else if(s[i]=='U') { y++; } else if(s[i]=='D') { y--; } } cout<<x<<" "<<y; return 0; }
Competitive coding
Hackerearth problem
|
https://coderinme.com/final-destination-hackerearth-problem-coderinme/
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
OK I'm using VC++ and I've read the MSDN description at
wcsrtombs_s
but I've obviously misunderstood something.
The following function is supposed to produce a popup window with the message given in 'str'. When compiled as a Unicode program the wide string str needs to be converted into a UTF-8 string for fl_message. What I actually get is a null string for 'copiedstring'.
Possibly this has something to do with the setlocale function?
Any hints gratefully received.
Code:void pbox(const _TCHAR *str) { char copiedstring[250]; mbstate_t mbstate; size_t retval; #ifdef _UNICODE // setlocale(LC_CTYPE, "en_US.UTF-8"); // Convert to UTF-8 from wchar_t // Reset to initial conversion state const wchar_t *wcsIndirectString = str; memset(&mbstate, 0, sizeof(mbstate)); wcsrtombs_s(&retval, copiedstring, sizeof(copiedstring), &str, 249, &mbstate); fl_message(copiedstring); #else fl_message(str); #endif }
|
https://cboard.cprogramming.com/cplusplus-programming/116567-wcsrtombs_s-question.html
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
when one value matches the value of the variable, the computer continues executing the program from that point. C switch statement is a multiway decisions that tests whether a variable or expression matches one of a number of constant integer values, and branches accordingly.
Syntax of switch statement:
switch(expression)
{
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);
}
The condition of a switch statement is a value... Switch statements serves as a simple way to write long if statements when the requirements are met. Often it can be used to process input from a user.
Flowchart :
Some of the points to keep in mind while using switch statement are :
- In C switch statement, the selection is determined by the value of an expression that you specify, which is enclosed between the parentheses after the keyword switch. The data type of value, which is returned by expression, must be an integer value otherwise the compiler will issue an error message.
- The case constant expression must be a constant integer value.
- You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
- When a break statement is executed, it causes an immediate exit from the switch. The control pass to the statement following the closing brace for the switch. Although as mentioned the break statement is not mandatory but it is sound to use this break statement.
- The defaut statement is the default choice of the switch statement if all case statements are not satisfied with the expression. The break after the default statements is not necessary unless you put another case statement below it.
Program to illustrate use of switch statement:
#include <stdio.h> #include<conio.h> main() { int marks=100; switch(marks) { case 100 : { printf( "Excellent\n" ); break; } case 90 : { printf( "Very Good\n" ); break; } case 80 : { printf( "Good" ); break; } default : printf( "Work hard\n" ); } }
Output will be:
Excellent
|
http://csetips.catchupdates.com/switch-statement/
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
Ionic 2 and External Libraries
Now that Ionic 2 is out in beta, people are setting aside some time to give it a shot and investigate everything it has to offer. Ionic 2 and Angular 2 bring a lot of improvements, but it’s a fairly different style of developing that what people were used to before. Now, since everything needs to be imported and libraries aren’t global, it can be tricky to figure out how to integrate with other libraries.
NPM all the things
So, how do you add third-party-libraries, such as Lodash? In Ionic 22, we’ve moved over to NPM for all our package management. So for our case, if we had a project setup, we could just install Lodash though npm’s CLI.
$ ionic start myApp --v2 --ts $ cd myApp $ npm install lodash --save
Now, this is going to give us a starter tabs project, so let’s open our
page1.ts file.
import {Page} from 'ionic-framework/ionic'; @Page({ templateUrl: 'build/pages/page1/page1.html', }) export class Page1 { constructor() { } }
Now, we can import individual methods from Lodash, using the typical import method that we’re seeing. Note, this would be the same import state if we were to use Javascript or Typescript.
import {Page} from 'ionic-framework/ionic'; import {sum} from 'lodash' @Page({ templateUrl: 'build/pages/page1/page1.html', }) export class Page1 { constructor() { console.log(sum) } }
If we were to use regular ES6, that would be the end of it. But since we’re using Typescript, we’ll get an error.
This might lead you to believe that everything is broken, and Lodash is working. Your editor will also probably yell at you, too. But oddly enough, everything will still work. What gives?
So, Typescript needs to analyze the code, in order to do its type checking. Normal Javascript libraries typically don’t include any definition files, which means Typescript won’t be able to understand them.
To circumvent this, we can use Typings which allow us to install definition files for various libraries.
Typings
We’ll install Typings globally on our system.
$ npm install -g typings
Now we have the
typings command to install the necessary files. So we can install the Lodash definitions with
typings install lodash --ambient --save
We should now have a
typings directory looking like this
├── typings │ ├── browser │ │ └── ambient │ │ └── lodash │ │ └── lodash.d.ts │ ├── browser.d.ts │ ├── main │ │ └── ambient │ │ └── lodash │ │ └── lodash.d.ts │ └── main.d.ts ├── typings.json
Last thing we need to do, is add a reference to this main
main.d.ts file.
Now we could do this two ways, either adding a
reference tag, which most people are probably familiar with, or we can add it to our
files array in our tsconfig. We’ll use this option because as our application grows, we don’t have to worry about adding more reference tags all over the place.
"files": [ "app/app.ts", "typings/main.d.ts" ],
Now when we start up our server, no errors!Back
|
https://mhartington.io/post/ionic2-external-libraries/
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
#include <DrawableMesh.h>
Inheritance diagram for Track::DrawableMesh:
The mesh's faces are defined using the vertex position, normal, and texture coordinates. Shaders / texturing / materials etc is left to the user.
Definition at line 26 of file DrawableMesh.h.
Method for rendering.
Definition at line 30 of file DrawableMesh.h.
construct by sucking information from an input stream.
Equivalent to Track::MeshFaces::MeshFaces(std::istream &). Reads data from the stream to initlalise the mesh, and leaves the stream read position at the end of the DrawableMesh.
Definition at line 26 of file DrawableMesh.cpp.
Construct from the contents of a file.
Reads data from the file specified to initlalise the mesh.
Definition at line 40 of file DrawableMesh.cpp.
construct from a MeshFaces obect
Definition at line 33 of file DrawableMesh.cpp.
construct an empty mesh
Definition at line 47 of file DrawableMesh.cpp.
Definition at line 53 of file DrawableMesh.cpp.
Delete the display list when all copies deleted.
It is static to meet requirements of boost::shared_ptr.
Definition at line 160 of file DrawableMesh.cpp.
Render the mesh using OpenGL commands.
Expects the texture and matrices to be set up already. Must be called outside of a glBegin/glEnd pair. Finishes with no change to the matrices, outside of a glBegin/glEnd pair.
Implements Track::Drawable.
Definition at line 57 of file DrawableMesh.cpp.
Load the mesh into OpenGL to speed up first draw.
Requires the OpenGL context that will be used to draw active. Only needs to be called once, before draw is called. Calling it after draw is called or multiple times has no additional effect.
Definition at line 67 of file DrawableMesh.cpp.
Aquire a new display list when created without copying.
It generates the display from the MeshFaces data.
Definition at line 75 of file DrawableMesh.cpp.
Control how the mesh is displayed.
If the new RenderMode is the same as the previous, there is no effect. Otherwise this will unset the cache created by a previous call to draw() or make_cache(), if any. The deafult RenderMode is RM_SOLID.
Definition at line 165 of file DrawableMesh.cpp.
OpenGL display list name where drawing instructions are stored.
Definition at line 90 of file DrawableMesh.h.
we use a shared_ptr so we can delete the display list when the last copy of the object is deleted.
Definition at line 95 of file DrawableMesh.h.
Method for drawing the mesh.
Definition at line 111 of file DrawableMesh.h.
Generated at Mon Sep 6 00:41:18 2010 by Doxygen version 1.4.7 for Racer version svn335.
|
http://racer.sourceforge.net/classTrack_1_1DrawableMesh.html
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
Download & Releases
NEST is available under the GNU General Public License 2 or later. This means that you can
- use NEST for your research,
- modify and improve NEST according to your needs,
- distribute NEST to others under the same license.
To find out more about NEST, see the list of features and the user documentation. For details about how to contribute to the development of NEST, see the developer space.
- Download Current release (NEST 2.12.0)
- Previous release (NEST 2.10.0)
- All NEST Releases
- Current developer version
Citing NEST get in touch with us about your publications that used NEST, we will add them to our publication list, thus making them visible to potential readers.
NEW Ubuntu 16.04 Live Media with NEST 2.12.0
Ubuntu 16.04 Live Media with NEST 2.12.0 with MPI support
Live media is available in the OVA format, suitable, for example, for importing into VirtualBox. Useful for trying out NEST without installing it on your computer, especially for Windows and Mac OS X users.
NEST Live Media setup and first steps.
Older Live Media
Ubuntu 16.04 Live Media with NEST 2.10.0
Ubuntu 15.10 Live Media with NEST 2.8.0
NEST 2.12.0 contains 1763 repository commits from 169 pull requests by 40 developers since v2.10.0.
New models, tests and examples
- Symmetric STDP model
vogels_sprekeler_synapse(Vogels et al., 2011; #218)
- Support for inhibitory STDP (#284)
- New neuron model
aeif_cond_beta_multisynapseusing GSL ODE solver (#439)
- Generalized integrate-and-fire (GIF) neuron models
gif_psc_exp,
gif_psc_exp_multisynapse,
gif_cond_exp,
gif_cond_exp_multisynapse(#261, #516, #579)
weight_recorderfor recording weights of plastic synapses (#497)
- Added current based adaptive exponential I&F neurons
aeif_psc_alpha,
aeif_psc_exp(#513)
- Implement the full NMDA model for
ht_neuron(#491)
- Added cubic milimeter microcircuit model for PyNEST (#451)
- New PyNEST example
sensitivity_to_perturbation.py(#198)
- New test and improvements for handling the
multiplicityproperty of
Events (#255)
- Added sigmoid growth curve for structural plasticity (#476)
General improvements
- Support for two-dimensional parameter arrays in
Connect(#465)
- Added a
vimsyntax highlighing file (#253)
- PyNEST raster plot example now uses pandas if available (#422)
- New environment variables
SLI_PATHfor adding to the SLI search path and
NEST_MODULESfor loading modules on startup (#479)
- New flag
supports_precise_spikesfor models supporting off-grid events (#475)
Connectnow supports a new keyword
symmetricto also add a reverse connection in a single run, synapses which require this now have the
requires_symmetricflag set (#315, #524)
- Better support for Python 3 and improved build system support for Python-less builds (#313, #342, #452, #620, #631, #634)
- Cleaned up and more informative logging during
Simulate(#269)
do_tests.shprints out the error message in case a test fails (#515)
Documentation and example changes
- Extended documentation of SLI
regexecfunction (#251)
- Improve documentation of current filtering in
iaf_psc_exp(#276)
- Fix and clean up
hpc_benchmark.sliexample (#289)
- Re-format all PyNEST code to be PEP8 compliant and use NumPy style docstrings (#263, #337)
- Add documentation on heterogenenous MPI environments (#335)
- Add information on how to contribute (#320)
- Added link to NEST Contributor Agreement to documentation index (#235)
- Added documentation for synaptic elements and growth curves (#219)
- Added more information about spike generation and precision (#364)
- Documentation of exact integration method used in current based models (#383)
- The toplevel
README.mdnow contains all general information about NEST (#423)
- Added documentation on using
gccon BlueGene/Q (#447)
- Documentation improvement to
ht_neuronand minor code prettification (#387)
- Updates to Eclipse instructions (#444)
- Extended
README.mds for testsuite and PyNEST (#503)
- Added info on static linking against non-standard allocators on BG/Q (#489)
- Add information on filing bugs to contribution guidelines and development documentation (#548, #549)
- Added full user documentation in markdown (#292, #371)
- Move gap junction examples to more appropriate directory (#594)
- More information on conventions for naming models (#611)
- Extended gap junction documentation in markdown and SLI docstrings (#608, #623)
- Added information on spike exchange to documentation (#612)
- Updated installation documentation (#615)
- Converted NEST by example book chapter to Jupyter notebook and updated for 2.12.0 (#602)
- Replaced
iaf_neuronin docstrings and examples by
iaf_psc_alpha(#626)
Performance
- Improve
GetConnectionsperformance up to 118 times (#490)
- Improved performance of threaded connection generation for large networks up to 80 times (#485)
- Improved connection parameter skipping with connection rule
all_to_all(#568)
Build system and continuous integration
- Rewrite build system to use CMake instead of autotools (#213, #234, #318, #326, #350)
- Add CMake option for colored
gccoutput (#378)
- TravisCI now checks for PEP8 and counts compiler warnings (#296, #298)
- Reduce the number of build jobs from a whole matrix to only dependent jobs (#409, #640)
- Improved logging and more robust parsing of TravisCI log (#395, #413)
- Add automatic testing for MUSIC (#471)
- Better handling of precise spike times in
spike_detector(#446)
Bug fixes
- Fixed shadowing of
connect()function in
SPBuilder(#216)
- Fix the hard coded decay of synaptic elements in the structural plasticity framework (#215)
- Fix for importing
readlinewith Anaconda Python (#209)
- Bug fix for
icpccompiler (#232)
- Syntax fixes for relative imports in Python 3 (#233)
- Fix uninitialized variables in multisynapse models (#283)
- Fix compilation on K computer (#288)
- Fix and document the usage of
nosetestsfor the PyNEST testsuite (#321)
- Topology now skips non-local potential targets correctly (#282)
- Properly handle precise times in
spike_generator(#327)
- Fix copyright header test to exclude backup files (#340)
- Remove PyNEST's link dependency on
libreadline(#323)
- Fix
MyModuleexample build and install problems (#328)
- Fixed order of setting parameters for synapse models (#333)
- Fix C++11 compilation error due to stream conversion (#389)
- Fix handling of params dictionary in Connect (#441)
- Improve numerical stability of some tests (#466)
- Record correct quantity for post-synaptic current in
iaf_psc_alpha(#500)
- Use correct unit (ms) for printing MUSIC acceptable latency (#535)
- Fixing encoding issues in PyNEST (#536)
- Fix conversion from heterogeneous to homogeneous connector when deleting last synapse of a type (#566)
- Fix refractoriness handling for adaptive exponential I&F neuron models and
hh_cond_exp_traub(#575, #590)
- Replace
operator<<with regular function to avoid issues with K compiler (#587)
- Fix bug in
sp_disconnect()that could lead to heterogeneous connectors not being used any more during spike delivery (#597)
- Fixed desynchronization of MPI processes due to waveform relaxation (#607)
- Fixed
get_targets()for structural plasticity (#604)
- Exception when structural plasticity and multiple threads are used (#629)
- Added check on threading in two PyNEST tests which require it (#642)
- V-bounded implementation for adaptive exponential I&F neuron and fix for Delta_T=0 (#474)
- Fix for usage of gap junctions without waveform relaxation (#655)
ConnectLayersnow connects thread siblings of devices properly (#666)
Under the hood
- Split and refactor NEST
Schedulerand
Networkclasses into separate
*Managerclasses according to their responsibility (#205)
- Replaced internal C++ variable U0_ by E_L (#236)
- Improvements of the framework for iterative solutions (#273)
- Re-format all code files to have a maximal line width of 80 characters (#297)
- Move inline functions from
*.cppto
*_impl.h(#397)
- Additional timers and local spike counter for profiling and performance measurements (#434)
- Removed
*_taliases for built-in C++ data types (#454)
- Rename
Parameterclass in Topology to
TopologyParameter(#408)
- Add vera++ config file to repository (#562)
- Removed plural forms of certain parameter names (#551)
- New help generator re-written in PyNEST replaces the old SLI generator (#464)
- Better handling of exceptions during update (#542)
Changed behavior and removed functionality
- Raise exceptions on incommensurate times (#265)
- Unified synaptic recordable names for current based models (#502)
- Added protection against probabilistic wiring to spike_detector (#560)
The long deprecated functions
ConvergentConnect,
DivergentConnect,
RandomConvergentConnect,
RandomDivergentConnect and
FindConnections were removed in favor of the new unified
Connect framework. See the documentation on connection management for details on how to convert your code.
Deprecated functions and models
The following models will be removed in the next major release:
iaf_neuron, please use
iaf_psc_alphainstead
subnet,
siblingcontainerand
proxynodewill be removed without replacement
aeif_cond_alpha_RK5, please use plain
aeif_cond_alphainstead
Due to the upcoming removal of the
subnet model and the concept of a hierarchical network storage, the following functions are also marked as deprecated and will be removed together with the
subnet model in the next major release:
LayoutNetwork,
GetNetwork
BeginSubnet,
EndSubnet,
ChangeSubnet,
CurrentSubnet
GetNodes,
GetLeaves,
GetChildren
GetLID
The remaining functionality of
DataConnect over normal
Connect will be integrated into the normal
Connect function. Thus
DataConnect is marked as deprecated and will be removed once
Connect has the same feature set.
For all deprecated models and functions, a corresponding message will be printed upon usage (#580).
Contributors since v2.10.0
- Alcazar, Jesus Garrido
- Bachmann, Claudia
- Blundell, Inga
- Bos, Hannah
- Breitwieser, Oliver
- Deepu, Rajalekshmi
- Diaz, Sandra
- Djurfeldt, Mikael
- Eppler, Jochen Martin
- Fardet, Tanguy
- Golosio, Bruno
- Graber, Steffen
- Hagen, Espen
- Hahne, Jan
- Ippen, Tammo
- Jordan, Jakob
- Kunkel, Susanne
- Lepperød, Mikkel Elle
- Mahmoudian, Sepehr
- Morrison, Abigail
- Muller, Eilif Benjamin
- Mørk, Håkon
- Peyser, Alexander
- Plesser, Hans Ekkehard
- Plotnikov, Dimitri
- Rao, Arjun
- Rothe, Hendrik
- Schenck, Wolfram
- Schmidt, Maximilian
- Schuecker, Jannis
- Schumann, Till
- Seeholzer, Alex
- Setareh, Hesam
- Shusharin, Alexey
- Sinha, Ankur
- Terhorst, Dennis
- Trensch, Guido
- Vennemo, Stine Brekke
- Vieites, Juan Hernando
- Weidel, Philipp
Citation
If you use this version of NEST, please cite it as Kunkel, Susanne et al. (2017). NEST 2.12.0. Zenodo. 10.5281/zenodo.259534. The full citation is available in different formats on Zenodo.
Downloads
NEST v2.10.0>> Download Release v2.10.0 (Dec 31 2015)
NEST 2.10.0 contains 303 repository commits by 25 developers since v2.8.0. The most notable changes over v2.8.0 are:
- Support for simulations of gap junctions (see Jan Hahne et al., 2015)
- Framework for structural plasticity (see Markus Butz et al., 2013 and Markus Butz et al., 2014)
- Full support for the K computer (just in case you found one under your Christmas tree ;-))
New features and functionality
- To group connections that belong together, synapse models may now contain a numeric label, specified at creation time.
GetConnectionscan select on this label.
- Array parameters in calls to
Connectcan now also be specified as lists and tuples.
New models and model updates
- New Tsodyks synapse model with common properties.
- New STDP triplet synapse (see Pfister & Gerstner, 2006).
- All precise models are now derived from
ArchivingNodeto support STDP connections.
parrot_neuronnow supports connections onto port 0 and 1.
- Added call to
set_spiketimeto make STDP work with this model.
Documentation and example improvements
- Updated examples for the use of CSA in NEST.
- Cleaned up
hpc_benchmark.sli, which now also randomizes initial membrane potentials.
- Updated online documentation on kernel parameters, including rng seeds.
- New tests for
parrot_neuron_psand
parrot_neuronand for STDP between parrot neurons
Bug fixes
parrot_neuron_psnow saves times of outgoing spikes.
binary_neuronnow records spike times.
pp_pop_psc_deltadoes not support STDP anymore (as this was not sensible).
- binary neurons and non-binary neurons cannot be connected anymore (which was possible but meaningless)
- MUSIC now behaves correctly upon ResetKernel.
- PyNEST now correctly handles changes to argv made by MPI or MUSIC during initialization.
Under the hood
- The PyNEST high-level API was split into multiple files and submodules are loaded dynamically.
- Improved tools for static analysis and automatic formatting of code in the CI and locally.
- Fix errors in models when non default tics_per_ms setting is used.
Contributors since v2.6.0
- Hannah Bos
- Rajakelshmi Deepu
- Moritz Deger
- Sandra Diaz
- Mikael Djurfeldt
- Jochen Martin Eppler
- Jan Hahne
- Moritz Helias
- Tammo Ippen
- Susanne Kunkel
- Frank Michler
- Janne Morén
- Abigail Morrison
- Alexander Peyser
- Hans Ekkehard Plesser
- Maximilian Schmidt
- Alex Seeholzer
- Teo Stocco
Citation
If you use this version of NEST, please cite it as Bos, Hannah et al. (2015). NEST 2.10.0. Zenodo. 10.5281/zenodo.44222. The full citation is available in different formats on Zenodo.
NEST v2.8.0>> Download Release v2.8.0 (Sep 27 2015)
NEST 2.8.0 is distributed under the GNU General Public License version 2 (or later). This version marks the completion of our development efforts during the HBP ramp up phase and consists of 290 repository checkins by 25 developers since 2.6.0. The most notable changes are:
- The new connection framework introduced in NEST 2.6.0 can now handle parameter arrays for the 'all-to-all' and 'one-to-one' rules.
- A new propagator for integrate-and-fire neurons correctly handles the case where membrane and synapse time constants are similar or the same.
- Better documentation and much extended examples for PyNEST improve the discoverability of NEST's features.
All users are encouraged to upgrade and adapt their simulation scripts to the changes in the user interface at this point in time to benefit from the improvements in the new version.
Changes of default behavior and functionality
- Topology functions are now available from the main namespace in SLI.
- The parameters of
sinusoidal_poisson_generatorand
sinusoidal_gamma_generatorwere changed as follows:
dc->
rate
ac->
amplitude
freq->
frequency
phi->
phase; units changed from radian to degrees
- The parameter name
amplitudeof
ppd_sup_generatorwas changed to
relative_amplitude.
- Previously most synapse models prohibited the case of tau_m being equal to tau_syn because of the numerics used. The integrate-and-fire neurons now use a different propagator if tau_syn and tau_m are the same or very similar. This might lead to slightly different membrane potential values in these cases than before. See
doc/model_details/IAF_neurons_singularity.ipynbfor details
New models and examples
spike_dilutorrepeats incoming spikes with a certain probability.
correllospinmatrix_detectorallows to measure the covariance matrix from several inputs.
brunel-2000_newconnect.slidemonstrates the use of the new connection framework.
brunel-2000_newconnect_dc.sliusing DC instead of Poisson stimulation.
precise_spiking.pycompares precise and grid-constrained neuron model.
Documentation improvements
- All PyNEST examples are now extensively documented and available from nest-simulator.org.
- The Potjans_2014 example now has an updated documentation.
- Topology user manual now explains how to connect devices to subregions of layers.
noise generatornow has documentation in form of a Jupyter Notebook in
doc/model_details/noise_generator.ipynb.
- The
voltmeteris now documented and the documentation of
multimeteris fixed.
- The
emit()function in precise models is now properly documented.
- The online help of
cont_delay_synapsenow has usage examples.
Bug fixes
pp_psc_deltanow works correctly with multiple calls to
Simulate
- The membrane potential of
izhikevichis now more consistent with the original Matlab implementation.
hpc_benchmark.slinow aborts when attempting to run with too few local neurons to record from.
Minor changes
- SLI can now extract information about their origin in the revision control system.
- MPI is now initialized with mode THREAD_FUNNELED instead of THREAD_SERIALIZED.
- Module handling in the build system got simplified and cleaned up.
- Topology free layers now work for single neuron layers.
CreateLayeris up to 100-fold faster for large networks.
pp_pop_psc_deltauses a refined check for small spike probability.
- The logos were updated and are available in
extras/logos.
- The PyNEST testsuite now also runs on older NumPy and Python versions.
- Rebuilding the NEST build system now requires autoconf >= 2.63.
- Renovations to MyModule's build system allow to also build modules on BlueGene.
- The last occurrences of CPEX were removed from the
Communicatorclass.
- New scripts execute static code analysis and formatting locally as TravisCI would do it.
Testsuite improvements
CreateLayernow has a regression test.
iaf_cond_alpha_mcand
cont_delay_synapsehave new unit tests.
do_tests.shnow returns non-zero exit code in case of failing tests.
Contributors since v2.6.0
- Sacha van Albada
- Claudia Bachmann
- Hannah Bos
- Rajalekshmi Deepu
- Moritz Deger
- Renato Duarte
- Jochen M. Eppler
- Marc-Oliver Gewaltig
- Espen Hagen
- Moritz Helias
- Tammo Ippen
- Jakob Jordan
- Susanne Kunkel
- Frank Michler
- Abigail Morrison
- Robin Pauli
- Alexander Peyser
- Luis Riquelme
- Hans Ekkehard Plesser
- Wolfram Schenk
- Maximilian Schmidt
- Jannis Schuecker
- Johanna Senk
- Hesam Setareh
- Ali Shirvani
- Tiziano Zito
Citation
If you use this version of NEST, please cite it as Eppler, Jochen Martin et al. (2015). NEST 2.8.0. Zenodo. 10.5281/zenodo.32969. The full citation is available in different formats on Zenodo.
NEST v2.6.0>> Download Release v2.6.0 (Dec 24 2014)
NEST 2.6.0 is a fast and efficient simulator for networks of spiking neurons and distributed under the GNU General Public License version 2 (or later). It contains new memory-saving data structures for the storage of connections and many general improvements over the 2.4 series. The most notable changes are:
- A complete re-write of the connection infrastructure, which reduces memory consumption considerably.
- Many new tests to ensure and guarantee a continued quality of the code-base.
- Updated and extended documentation
All users are encouraged to upgrade and adapt their simulation scripts to the changes in the user interface at this point in time to benefit from the bug fixes and improvements.
IMPORTANT: some of the defaults in NEST changed. You might have to adapt your scripts accordingly. See the release notes for details.
New connection infrastructure
This release of NEST contains a complete re-write of the data structures for storing neural connections as described in the article Spiking network simulation code for petascale computers by Susanne Kunkel et al. (doi:10.3389/fninf.2014.00078). They adapt to their load and thus require only minimal overhead compared to conventional C++ vectors. The new infrastructure comes with synapse model variants optimized for HPC (suffixed by "_hpc"), which can be used if less than 65k neurons are simulated per MPI process and the
receptor_type is not set for this synapse model.
In addition to the new data structures, an optional pool-based memory allocator allows to save even more memory on very large machines. It can be enabled by adding
-DPMA to the
CFLAGS and
CXXFLAGS at compile time.
The improvements required to change the API for neuron and synapse models.
Changes of default behavior and functionality
The default connection rule of the new connection framework introduced in 2.4.0 (see) changed from
one_to_one to
all_to_all as this rule is much more frequent in most modelling tasks.
The default rounding scheme for delays changed from always rounding up to the nearest multiple of the resolution (next step value) to mathematically rounding to the nearest multiple, i.e., for a resolution of 0.1 ms, a delay of 0.14 ms now will be rounded down to 0.1 ms, a delay of 0.16 ms rounded up to 0.2 ms; in the past, both were rounded up to 0.2 ms.
Nodes are now always round robin distributed onto threads and processes, while it was possible to force them to a specific virtual process using the property
children_on_same_vp of the
subnet they belong to.
To remove ambiguousness, we renamed the property
node_type contained in the status dictionaries of neurons, devices and synapse to
element_type. The field can contain the values "synapse", "stimulator", "recorder", "neuron", "structure", or "other".
New functionality
- The device
correlomatrix_detectorallows to measure the covariance matrix from several spiking neurons online.
- The function
SetFakeNumProcessesallows to fake the process of building the network for a parallel machine using only a single compute node. This is helpful to estimate the amount of memory needed for large-scale simulations prior to running a simulation.
- The script
nest_vars.shcan be used to set the environment variables
PATHand
PYTHONPATHto ease switching between different installed versions of NEST
Minor changes
- Synapse model
static_synpase_hom_wdhas been replaced by
static_synapse_hom_w.
- Initialization of
pp_pop_pscis now done properly to allow multiple calls to Simulate in a simulation script.
- Improved support for the Clang compiler and MacOS.
- SLI dictionaries can now be nested without causing memory leaks and crashes.
- NEST now contains information about the revision in a revision control system it is based on to make it easier to pinpoint bugs in releases to a specific internal version.
- The error state of
libltdlis now properly reset in order to circumvent errors when loading custom modules.
- The microcircuit model example (Potjans&Diesmann, doi:10.1093/cercor/bhs358) is now installed.
- The neuron
model iaf_psc_expnow supports zero refractory time.
- The MPI tests of Topology now report errors explicitly.
Createnow explicitly mentions the absence of GSL as a possible reason, when a model is not found.
- SLI command
memory_thisjobnow supports Linux, OSX and IBM BlueGene.
Documentation improvements
The tutorial "NEST by Example" has been updated to reflect the recent changes in NEST. To make it easier to carry out performance benchmarks with NEST, the HPC benchmarks used by Kunkel et al. (doi:10.3389/fninf.2014.00078) have been added to the examples contained in NEST. Moreover, the documentation of the SLI function
getinterval has been extended and clarified and the doxygen configuration files were updated to support current versions of doxygen.
Better testing
The test coverage has been considerably increased from 427 tests in NEST 2.4.2 to 714 in 2.6.0. Where available, NEST now uses Python's
nosetests instead of the custom test harness for running the PyNEST tests. This makes testing easier and more reliable and produces reports in the standard JUnit XML format, which can be analyzed by a selection of existing tools.
Changes under the hood
- Simplified and refactored the
Timeclass.
- Removed status flags
bitsetin nodes in favor of simple Boolean flags.
- Handle exceptions in node preparation in a thread-safe way.
- Removed Pthreads in favor of OpenMP based parallelization.
- Cleanup of internal connect interface and functions.
Memory management
Several memory leaks and segmentation faults were found and fixed by adding a destructor to Topology's
ntree class and by fixing the creation of
ArrayDatums. Moreover, the function
GetDefaults is now thread-safe when retrieving the number of connections from a synapse model..
Contributors since v2.4.2
- Sacha van Albada
- Hannah Bos
- Moritz Deger
- Markus Diesmann
- Mikael Djurfeldt
- Renato Duarte
- Jochen Martin Eppler
- Marc-Oliver Gewaltig
- Jan Hahne
- Moritz Helias
- Tammo Ippen
- Jakob Jordan
- Susanne Kunkel
- Abigail Morrison
- Alex Peyser
- Hans Ekkehard Plesser
- Wolfram Schenck
- Maximilian Schmidt
- Jannis Schücker
- Hesam Setareh
- Yury V. Zaytsev
NEST v2.4.2>> Download Release v2.4.2 (Aug 19 2014)
This is a bugfix and maintenance release for v2.4.1. Users are advised to update their installation as soon as possible. The release contains the following improvements and fixes for minor bugs:
- Updated MUSIC examples to use the new
Connectframework and allow
music_channelas an alias for
receptor_typeduring connection setup.
- Turned PyNEST deprecation warning into a decorator and beautified URLs in the output to allow IPython Notebooks to parse and link them properly.
- Improved performance of SLI functions
token_sand
symbol_sby a factor of 1000 by replacing a loop by an explicit function call.
- Made CyNEST handle parameters passed as Unicode strings in all Python versions by using
basestringinstead of
strfor Python versions
- Fixed segmentation fault produced by additional command line arguments for Python when PyNEST was imported.
Contributors in addition to v2.4.0 and v2.4.1
- Oliver Breitwieser
- Jan Hahne
- Frank Michler
NEST v2.4.1>> Download Release v2.4.1 (Jun 18 2014)
This is a bugfix and maintenance release for v2.4.0, in which the Topology Module contains a bug which leads to the creation of too few connections (N/num_threads instead of N) when using the divergent
connection_type in
ConnectLayers in a multi-threaded mode. Users are advised to update their installation as soon as possible.
Here's a detailed list of changes:
- Fix multi-threaded creation of divergent connections in Topology Module and add a regression test for this.
- Add
SetNumRecProcessesto PyNEST to enable the Global spike detection mode.
- Update Toplogy Manual for NEST 2.4 and to be Py3k compatible.
- Use proper syntax for getting default synapse model in the
ConnectionGenerator.
- Update the reference in the
README.txtof the microcircuit model by Potjans&Diesmann.
- Remove special characters from
iaf_chs_2007that confused the copyright-header checker.
NEST v2.4.0>> Download Release v2.4.0 (Jun 13 2014)
NEST 2.4.0 is distributed under the GNU General Public License version 2 (or later) and contains many new features, neuron models and general improvements. The most important ones are:
- A Python 3.0 compatible re-implementation of the Python interface.
- A new framework for setting up connections and their parameters.
- A new spike detection mode with greatly improved I/O performance.
- More flexible framework for working with random distributions.
- Support for connectivity-generating libraries through
libneurosim.
All users are encouraged to upgrade and adapt their simulation scripts to the changes in the user interface at this point in time to benefit from the bug fixes and improvements.
Re-implementation of PyNEST
The Python interface to NEST (PyNEST) has been re-implemented from scratch. The new implementation (CyNEST) is based on Cython and provides the following improvements over the previous version:
- Support for Python 2.6, 2.7, and 3.x
- Installation now works properly on all platforms
- Better extensibility and maintainability
See Zaytsev & Morrison (2014), doi:10.3389/fninf.2014.00023 for details of the new interface.
Minor changes to PyNEST are:
- PyNEST's visualization.plot_network() can now create PNGs or PDFs
- Importing SciPy after NEST does not cause segfaults anymore
Please note that CyNEST requires Cython version 0.19.2 or higher to regenerate the source files (only for developers). This can be installed using
pip install --user --upgrade cython.
New routines for setting up connectivity
The
Connect function of NEST has been completely re-written in order to support a more flexible setup of connectivity. In particular this means that connectivity is now specified using a rule ("all-to-all", "one-to-one", "fixed-indegree", "fixed-outdegree", "fixed-total-number", or "pairwise-bernoulli") and a dictionary with synapse parameters. All connection parameters can now be randomized already during connection setup by specifying the random distribution.
In addition to more flexibility, the new framework is faster due to a massive clean-up of the code and OpenMP parallelization throughout.
Please see for more information about the new connection routines and how to transition your simulation scripts from the old functions to the new framework.
If you are using SLI, all your scripts will be working without changes. PyNEST's
Connect function was renamed to
OneToOneConnect.
Connect now uses the new semantics as explained in the documentation.
The new
Connect function is provided as a technology preview. This means that while the basic user interface will stay, the functionality and performance will be further extended in future releases.
Global spike detector
In parallel simulations on very large machines without local disks, saving recorded spikes often leads to performance problems, because each spike detector will write out one file per virtual process. This problem is now ameliorated by a new spike detection mode, which can be activated by the users of such machines. In the new mode, all spike detectors are allocated on a distinct set of processes.
See for details on the new recording mode and how to activate it.
Random number generators and distributions
In the process of implementing the new connection routines, we found several performance problems in NEST's librandom and inconsistencies with PyNN ([1]). To solve these problems, we changed several aspects of librandom.
The random deviate generators in NEST have been extended and modified to support random initialisation of synapse parameters for the new connection routine, and to achieve greater similarity between NEST and PyNN. For most users, these changes only add new features. Scripts using
uniformint or
normal_clipped need to be adapted as explained in.
To achieve consistent results for both global and local spike detector mode, the seed of the global RNG was changed from n_vp+1 to 0. To allow the comparison of new results with those obtained with earlier versions of NEST, this seed has to be set to n_vp+1 manually. See for details.
If NEST is compiled with support for GSL,
gsl_rng_knuth2002 is now used instead of
knuthlfg as per-thread and global random number generator (RNG) to improve performance. Both RNGs create identical sequences, so new simulation results are still comparable to old ones.
Support for connectivity-generating libraries
In NEST 2.4, the direct implementation of the
ConnectionGenerator interface has been replaced in favor of support for
libneurosim (). This allows to couple all connectivity-generating libraries (e.g. the Connection-set algebra;) with NEST, which support
libneurosim.
See Djurfeldt et al. (2014), doi:10.3389/fninf.2014.00043 for details about the new interface.
New models and model improvements
stdp_facetshw_synapsemimics the restrictions of the neuromorphic HMF developed in the context of FACETS and BrainScaleS.
aeif_cond_alpha_RK5, which is independent of the GSL by using a custom version of the RK5 solver.
aeif_cond_alpha_multisynapseis a variant of the exponential integrate-and-fire model with multiple synaptic time constants.
quantal_std_synapseis a probabilistic synapse model with short term plasticity (Fuhrmann et al. 2002, doi:10.1152/jn.00258.2001).
iaf_chs_2007is a spike-response model (Carandini et al. 2007, doi:10.1167/7.14.20).
iaf_chxk_2008is a conductance based leaky integrate-and-fire neuron model (Casti et al. 2008, doi:10.1007/s10827-007-0053-7).
- Weighted excitatory and inhibitory input spikes are recordable in
iaf_psc_expand
iaf_psc_delta.
- Excitatory and inhibitory synaptic currents are recordable in
iaf_psc_expand
iaf_psc_alpha.
- Recovery variable
U_mis recordable in
izhikevich.
spike_detectornow throws an error for spike times of 0.
Improved quality and documentation
Compared to v2.2.2, we have increased the number of unit tests from 270 to 418. This improvement guarantees the continued quality of NEST on the computer of the user and allows to find and fix problems quickly. To run the testsuite after installation, run
make installcheck from the build directory.
Many examples have been updated and extended to demonsrate the usage of NEST. In addition, we have added the full microcircuituit model by Potjans & Diesmann (2014), doi:10.1093/cercor/bhs358.
In order to prevent memory leaks by forgotten arguments on the SLI stack, PyNEST now can do stack checking and runs its own testsuite in this mode.
New SLI functions and improvements
- Added an
evalfunction to execute SLI code in strings.
SetMaxBufferedwhich sets the max buffered parameter of a MUSIC input port.
eq_dvand
eq_ivto test double and int vector equality.
cvaapplied to an array now leaves array elements as they are if they can not be converted to an array.
roundnow converts to double if applied on an integer.
cviis identity operation for integers.
Takenow also works for strings..
- Support for plain POSIX threads will be removed in favor of OpenMP.
Contributors since v2.2.2
- Claudia Bachmann
- Hannah Bos
- Ekatarina Brocke
- David Dahmen
- Moritz Deger
- Markus Diesmann
- Mikael Djurfeldt
- Håkon Enger
- Jochen Martin Eppler
- Marc-Oliver Gewaltig
- Moritz Helias
- Tammo Ippen
- Jakob J. Jordan
- Susanne Kunkel
- Abigail Morrison
- Mikael Naveau
- Daniel Peppicelli
- Alexander Peyser
- Thomas Pfeil
- Hans Ekkehard Plesser
- Wolfram Schenck
- Maximilian Schmidt
- Jannis Schuecker
- Sacha van Albada
- Yury V. Zaytsev
WARNING!
The Topology Module of this version of NEST contains a bug which leads to the creation of too few connections (N/num_threads instead of N) when using the divergent
connection_type in
ConnectLayers in a multi-threaded mode. Please update your installation to at least v2.4.1!
NEST v2.2.2>> Download Release v2.2.2 (May 23 2013)
NEST 2.2.2 is a bugfix releas that contains fixes to the kernel, SLI, build system and other areas.
New models and devices:
iaf_psc_alpha_multisynapse
iaf_psc_exp_multisynapse
mcculloch_pitts_neuron
ginzburg_neuron
spin_detector
sinusoidal_gamma_generator
Updated models and devices:
smp_generatoris replaced by
sinusoidal_poisson_generator, which sends an individual spike train to each of its targets by default; be wary when updating your code! In order to replicate the old behavior of the
smp_generator(all targets receive the same spike train), set
/individual_spike_trainsto
falseon the
sinusoidal_poisson_generatormodel before creating a generator node.
iaf_psc_alpha: bugfixes
stdp_dopamine_synapse: bugfixes
PyNEST:
- fixes to the
DataConnectinterface
Topology:
- more efficient
GetTargetNodesimplementation
- lognormal distribution for parameter values
NEST v2.2.0>> Download Release v2.2.0 (Dec 21 2012)
NEST 2.2.0 is distributed under the GNU General Public License version 2 (or later).
Features
NEST 2.2.0 contains substantial improvements and many new features. The most important ones are:
- Better speed, scaling, and memory footprint
- Support for connection set algebra (CSA)
- Data driven network generation
Better speed, scaling, and memory footprint
Many of NEST's major data structures have been re-written to improve speed, scalability and memory footprint.
The most significant changes concern the simulation kernel and the way it represents networks internally. As a result, NEST has a considerably lower memory consumption and improved scaling, in particular when using a large number of cores. The full details and theory behind these changes are published in two papers:
- Helias et al. Front. Neuroinform. (2012) doi:10.3389/fninf.2012.00026
- Kunkel et al. Front. Neuroinform. (2012) doi:10.3389/fninf.2011.00035
Other improvements
- Many connection functions now use OpenMP to connect neurons in parallel.
- OpenMP has also replaced Pthreads as a default for multi-threaded simulations, yielding better scaling.
- SLI, the built-in simulation language interpreter of NEST, is now up to 5 times faster.
- The topology library has been re-written, greatly improving its speed and reducing memory requirements.
Support for connection set algebra (CSA)
NEST 2.2.0 supports the Connection Set Algebra by Mikael Djurfeldt (doi:10.1007/s12021-012-9146-1). The Connection Set Algebra is a powerful notation that allows to formulate complex network architectures in a concise manner. The following examples illustrates how the CSA is used to connect a random network:
import csa import nest # Random connectivity with connection probability 0.1 cs = csa.random(0.1) # Create two neuron populations pop1 = nest.LayoutNetwork("iaf_neuron", [16]) pop2 = nest.LayoutNetwork("iaf_neuron", [16]) # Connect them using the connection generator cs nest.CGConnect (pop0, pop1, cs)
Data driven network generation
NEST 2.2.0 has a new function
DataConnect which allows the efficient connection and parametrization of connections from connection data.
DataConnect will efficiently create and parameterize synapses.
The new function
GetConnections allows to efficiently retrieve the afferent and efferent connections of a neuron or the connections between groups of neurons. The combination of
GetConnections and
DataConnect allows users to retrieve, save, and restore the synaptic state of a network. This is particularly useful in models with synaptic plasticity and learning.
Topology library
The topology library supports the creation of spatially organized networks, e.g. for models of the visual system. NEST 2.2.0 supports 3-dimensional networks, where neurons are placed in a volume rather than on a sheet. There is also a new API to add user defined connection kernels. Please refer to the updated user manual and examples for more details.
Detailed list of changes
Kernel and PyNEST changes
- Major improvements to the memory consumption and scaling properties of the simulation kernel as described in Helias et al. (2012) and Kunkel et al. (2012).
- NEST now supports the connection generator interface, an interface allowing externals to generate connectivity, see.
- Support for the Connection Set Algebra (CSA) by Mikael Djurfeldt has been added, see and doi:10.3389/conf.fninf.2011.08.00085.
- The new command
GetConnectionsallows the fast retrieval of connections and will replace the slow and memory intensive
FindConnections;
FindConnectionsis deprecated and will be removed in future releases.
- The new command
DataConnectallows to efficiently create network connections from data, e.g. when synapse parameters are explicitly given.
- Connection objects are now represented as Python lists or NumPy arrays; code which relies on the old connection dictionaries will have to be changed.
- The function
GetNodeshas been removed, one has to explicitly use either
GetLocalNodes, or
GetGlobalNodes.
- Support for node addresses has been removed and with it the functions
GetAddressand
GetGID.
- Threading support for OpenMP has been added and is the default now.
- Many connect routines and node calibration are now parallel, using OpenMP.
- New function
CGConnectfor connecting neurons using connection generators (see
doc/conngen.txt).
- New function
abort, which terminates NEST and all its MPI processes without deadlocks.
Topology changes
- Major rewrite which resulted in improved performance and reduced memory requirements for freely placed neurons.
- Topology now supports 3-dimensional layers.
- New API for adding your own kernel functions.
- 'Nested' layer layout (subnets within subnets) is no longer supported; this was previously discouraged for performance reasons.
- Composite layers (layers with multiple nodes per position) no longer contain subnets.
- Semantics of
GetElementhave changed, in particular a list of GIDs is returned for a composite layer, where previously a single subnet GID would be returned.
GetPosition,
Displacementand
Distancenow only work for nodes local to the current MPI process.
- See the updated Topology User Manual for details.
SLI Interpreter improvements
- The SLI Interpreter has been optimized for speed and memory; in particular handling and lookup of names is much faster now.
- SLI now supports fixed size vectors of doubles and integers. The new types are called
IntVector(/intvectortype) and
DoubleVector(/doublevectortype).
- NumPy arrays are automatically converted to SLI vectors to conserve memory and CPU time.
- SLI has new functions
arange,
zerosand
onesto easily create vectors.
- The vector types support all common math operations.
- New functions
DictQand
SubnetQto test the argument types for being a dictionary or a subnet, respectively.
Miscellaneous changes
- The installation prefix should now be given explicitly, since installing to the default
/usr/localis strongly discouraged.
- Substantial documentation updates; a large number of broken documentation cross-references has been resolved.
- Fixed numerical instabilities of the AdEx models (
aeiaf_cond_expand
aeiaf_cond_alpha).
- New significantly faster binomial random number generator replaced the previous implementation in librandom (#390).
- New wrapper for the GSL binomial random deviate generator under the name
gsl_binomial.
- Support for IBM BlueGene and K supercomputers (configure with
--enable-bluegene=l/p/q).
- The command
setenvironmenthas been removed; this functionality was broken on Mac OS X for quite some time.
- Much improved test coverage for SLI, PyNEST and MPI in particular.
- Many new SLI and PyNEST examples and updates for the existing ones.
- Code quality of NEST and all examples is continuously monitored now using CI (Zaytsev & Morrison, 2012, doi:10.3389/fninf.2012.00031).
Known issues
- The simulation progress indicator does not work with OpenMP and some error messages are unreadable.
- On multiarch systems (i.e. 64-bit Red Hat Linux) one has to manually move all PyNEST-related files from
$PREFIX/lib/python2.6/site-packagesto
$PREFIX/lib64/python2.6/site-packages; this will be resolved in next releases. This also breaks
make installcheck.
- Known compatibility problems with PyNN are now fixed in the 0.7 svn branch, which will be released early next year.
Contributors since v.2.0.0
- Sacha van Albada
- Giuseppe Chindemi
- Moritz Deger
- Markus Diesmann
- Mikael Djurfeldt
- Håkon Enger
- Jochen Martin Eppler
- Marc-Oliver Gewaltig
- Moritz Helias
- Susanne Kunkel
- Abigail Morrison
- Eilif Muller
- Hans Ekkehard Plesser
- Sven Schrader
- Tom Tetzlaff
- Yury V. Zaytsev
NEST v2.2.1>> Download Release v2.2.1 (Feb 04 2013)
NEST 2.2.1 is primarily a bugfix release, resolving several bugs in the build system, PyNEST, topology module and built-in models. NEST 2.2.1 has been verified to be compatible with the latest released PyNN 0.7.5.
|
http://nest-simulator.org/download/
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
there,
The one important thing is, that the gl commands are sent to the actual
gldevice context. To set the actual context you have to use
glCanvasSetCurrent.
So when you want two gl windows just do it and befor drawing in one switch the
contex to this one.
Here is the modified GlCanvas.hs from the sample directory the should answer
all your questions.
Cheers
Patrick
PS @developers: I have updated my cvs and THE ONE glSample is just the (non
running) same. Will anyone make a fix on this sample so everybody can have a
running one. If nobody will have time to to this I can send a fixed version.
Interested??
<Code>
module Main
where
import Data.List ( transpose )
import Graphics.UI.WX
import Graphics.UI.WXCore
import Graphics.Rendering.OpenGL
-- Many code and Type are ambiguous, so we must qualify names.
import qualified Graphics.UI.WX as WX
import qualified Graphics.Rendering.OpenGL as GL
main :: IO()
main = start gui
defaultWidth = 320
defaultHeight = 200
gui = do
f <- frame [ text := "Simple OpenGL" ]
-- We just create two glCanvas
glCanvas <- glCanvasCreateEx f 0 (Rect 0 0 defaultWidth defaultHeight)
0 "GLCanvas" [GL_RGBA] nullPalette
glCanvas2 <- glCanvasCreateEx f 0 (Rect 0 0 defaultWidth defaultHeight)
0 "GLCanvas" [GL_RGBA] nullPalette
let glWidgetLayout = fill $ row 5 [widget glCanvas2, widget glCanvas]
-- Hint: You have to use the paintRaw event. For switching between the two
-- glwindows you can give both of them as parameter
WX.set f [ layout := glWidgetLayout
, on paintRaw := paintGL glCanvas glCanvas2
]
convWG (WX.Size w h) = (GL.Size (convInt32 w) (convInt32 h))
convInt32 = fromInteger . toInteger
paintGL :: GLCanvas a -> GLCanvas a -> DC() -> WX.Rect -> [WX.Rect]-> IO ()
paintGL gl1 gl2 dc myrect _ = do
-- Now we switch to the first one
-- and do all init and painting stuff
-- Hint: I changed the backgroundcolor for clearance
glCanvasSetCurrent gl1
myInit
reshape $ convWG $ rectSize myrect
-- Or not reshape the size.
reshape (GL.Size 320 200)
GL.clearColor GL.$= GL.Color4 1 0 0 0
display
glCanvasSwapBuffers gl1
-- All the same for the second one
glCanvasSetCurrent gl2
myInit
reshape $ convWG $ rectSize myrect
-- Or not reshape the size.
reshape (GL.Size 320 200)
GL.clearColor GL.$= GL.Color4 0 2 0 0
display
glCanvasSwapBuffers gl2
return ()
ctrlPoints :: [[GL.Vertex3 GL.GLfloat]]
ctrlPoints = [
[ GL.Vertex3 (-1.5) (-1.5) 4.0, GL.Vertex3 (-0.5) (-1.5) 2.0,
GL.Vertex3 0.5 (-1.5) (-1.0), GL.Vertex3 1.5 (-1.5) 2.0 ],
[ GL.Vertex3 (-1.5) (-0.5) 1.0, GL.Vertex3 (-0.5) (-0.5) 3.0,
GL.Vertex3 0.5 (-0.5) 0.0, GL.Vertex3 1.5 (-0.5) (-1.0) ],
[ GL.Vertex3 (-1.5) 0.5 4.0, GL.Vertex3 (-0.5) 0.5 0.0,
GL.Vertex3 0.5 0.5 3.0, GL.Vertex3 1.5 0.5 4.0 ],
[ GL.Vertex3 (-1.5) 1.5 (-2.0), GL.Vertex3 (-0.5) 1.5 (-2.0),
GL.Vertex3 0.5 1.5 0.0, GL.Vertex3 1.5 1.5 (-1.0) ]]
initlights :: IO ()
initlights = do
GL.lighting GL.$= GL.Enabled
GL.light (GL.Light 0) GL.$= GL.Enabled
GL.ambient (GL.Light 0) GL.$= GL.Color4 0.2 0.2 0.2 1.0
GL.position (GL.Light 0) GL.$= GL.Vertex4 0 0 2 1
GL.materialDiffuse GL.Front GL.$= GL.Color4 0.6 0.6 0.6 1.0
GL.materialSpecular GL.Front GL.$= GL.Color4 1.0 1.0 1.0 1.0
GL.materialShininess GL.Front GL.$= 50
myInit :: IO ()
myInit = do
-- GL.clearColor GL.$= GL.Color4 1 0 0 0
GL.depthFunc GL.$= Just GL.Less
m <- GL.newMap2 (0, 1) (0, 1) (transpose ctrlPoints)
GL.map2 GL.$= Just (m :: GLmap2 GL.Vertex3 GL.GLfloat)
GL.autoNormal GL.$= GL.Enabled
mapGrid2 GL.$= ((20, (0, 1)), (20, (0, 1 :: GL.GLfloat)))
initlights -- for lighted version only
display = do
GL.clear [ GL.ColorBuffer, GL.DepthBuffer ]
GL.preservingMatrix $ do
GL.rotate (85 :: GL.GLfloat) (GL.Vector3 1 1 1)
evalMesh2 Fill (0, 20) (0, 20)
GL.flush
reshape mysize@(GL.Size w h) = do
GL.viewport GL.$= (GL.Position 0 0, mysize)
GL.matrixMode GL.$= GL.Projection
GL.loadIdentity
let wf = fromIntegral w
hf = fromIntegral h
if w <= h
then GL.ortho (-4.0) 4.0 (-4.0*hf/wf) (4.0*hf/wf) (-4.0) 4.0
else GL.ortho (-4.0*wf/hf) (4.0*wf/hf) (-4.0) 4.0 (-4.0) 4.0
GL.matrixMode GL.$= GL.Modelview 0
GL.loadIdentity
</Code>
On Sunday 30 January 2005 21:44, Jan Rochel wrote:
>
>
>
> -------------------------------------------------------
> This SF.Net email is sponsored by: IntelliVIEW -- Interactive Reporting
> Tool for open source databases. Create drag-&-drop reports. Save time
> by over 75%! Publish reports on the web. Export to DOC, XLS, RTF, etc.
> Download a FREE copy at
> _______________________________________________
>
|
https://sourceforge.net/p/wxhaskell/mailman/wxhaskell-users/?viewmonth=200501&viewday=30&style=flat
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
Hello everybody,
I have a little problem..
A program I'm modifying has the following behavior :
If an option is given, it will write information messages to the screen, but if an other option is given, it will write information messages to a File named LogFile.txt ...
Now, what's done in the code is this :
freopen("LogFile.txt", "a+", stdout);
To close stdout and assign LogFile.txt to the standard output.
After everything is done, I need to give back the hand to the screen to write a message about the success of the program, based on some text in an other file.
Everything I saw about the freopen function didn't talk about giving back the hand to the screen..
I use
freopen("NUL", "a+", stdout);
to close the stream stdout assigned to LogFile ( it is shared by a lot of programs called from the main one) , but I can't write anything on the screen from then on.
Does anybody know how I can write back to the screen without leaving the program ?
Thanks
Sylvain
Last edited by sylvain_nurun; December 3rd, 2002 at 01:02 PM.
Hi I have been looking for this one for a while, the doc for freopen doesn't mention any of it however it can be found under _dup2 documentation.
Anyway here's the code from it:
/* DUP.C: This program uses the variable old to save
* the original stdout. It then opens a new file named
* new and forces stdout to refer to it. Finally, it
* restores stdout to its original state.
*/
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
int old;
FILE *new;
old = _dup( 1 ); /* "old" now refers to "stdout" */
/* Note: file handle 1 == "stdout" */
if( old == -1 )
{
perror( "_dup( 1 ) failure" );
exit( 1 );
}
write( old, "This goes to stdout first\r\n", 27 );
if( ( new = fopen( "data", "w" ) ) == NULL )
{
puts( "Can't open file 'data'\n" );
exit( 1 );
}
/* stdout now refers to file "data" */
if( -1 == _dup2( _fileno( new ), 1 ) )
{
perror( "Can't _dup2 stdout" );
exit( 1 );
}
puts( "This goes to file 'data'\r\n" );
/* Flush stdout stream buffer so it goes to correct file */
fflush( stdout );
fclose( new );
/* Restore original stdout */
_dup2( old, 1 );
puts( "This goes to stdout\n" );
puts( "The file 'data' contains:" );
system( "type data" );
}
Output
This goes to stdout first
This goes to file 'data'
This goes to stdout
The file 'data' contains:
This goes to file 'data'
Forum Rules
|
http://forums.codeguru.com/showthread.php?267841-cong.-Chinese-Spaceship&goto=nextnewest
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
I recently became very interested in the Neo4j graph database:, as I'm working on data structures that are hierarchical and tricky to walk in a relational database.
I came across an interesting video presentation on neo4j by Ian Robinson on the skillsmatter website -. He and colleagues have put together a database of facts from the Doctor Who British TV series. That's when I became aware that he, Jim Webber and some other colleagues created set of Neo4j koans available on github:.
So I decided to tackle my first ever set of koans.
Soon after, I discovered that while Jim Webber and crew put in a lot of time creating the neo4j koan tutorial, they seem to have to put in little time on how a newbie to koans can actually run them - at least as of November 2011 when I downloaded it. I don't understand why you would put hours into it and not put a few minutes into documenting what to do. Please provide a README on how to do things like this. If you go to all the effort of creating it, why wouldn't you?
[Dec 2011 Update: There is now good starter info on the neo4j koan github site, so many thanks to Jim et al. for improving it!]
So in case it helps anyone else, here is my version of how I fumbled around to do the neo4j koans.
/* ---[ Getting the Koans Installed and Set up ]--- */
These instructions are targeted particularly for a Unix/Linux environment. My koan work was done on Linux (Xubuntu 11.10). I also tested them on Windows where I have Mingw32 that comes with the git download (and I have cygwin).
[Dec 2011 Update: The neo4j koan github site now says it will work with cygwin on Windows - they actually say "sorry" about this, but being a Unix/Linux devotee my advice is that if you don't have cygwin yet, this is a good reason to get it and learn it. Consider it a bonus to learn a better way of doing things.]
I'm also primarily a command line kind of guy, though I do also use Eclipse for many things. In this case, I went commando - so I didn't use Eclipse's JUnit integration or download the neoclipse plug in (which sounds cool -- need to try it someday).
First download it from github (URL above). Be aware that the download is around 350 MB, so it may take a awhile if you have a lower-speed internet connection like me.
Second, cd to the main directory (neo4j-tutorial) and type ant - this will run ivy and download half the known universe in good ivy/maven fashion (grrr...). After waiting about an hour (or less if you have a better internet connection than me), you can begin by wondering what to do next. First make sure the build ran to successful completion - happily the koans as unit tests all passed out of the box for me, so you want to make sure that is all working on your system before beginning.
The authors provide a presentation in the presentation directory (for some reason in ppt and not converted to pdf for more general viewing), which can be helpful, but wasn't enough to really know how to do the koans. I recommend coming back to the presentation periodically and reviewing it for the section you are working on. Some of its visuals and notes are helpful, but mostly you'll just need to read the codebase and neo4j javadocs to really know how to get things done.
Next run the tree command to get a look around (you may need to download tree - its a great Unix command line tool to see files/dirs in a compact tree structure).
You'll see that the koans are in the src directory (output from the tree cmd):
├── src
│ ├── koan
│ │ └── java
│ │ └── org
│ │ └── neo4j
│ │ └── tutorial
│ │ ├── Koan01.java
│ │ ├── Koan02.java
│ │ ├── Koan03.java
│ │ ├── Koan04.java
│ │ ├── Koan05.java
│ │ ├── Koan06.java
│ │ ├── Koan07.java
│ │ ├── Koan08a.java
│ │ ├── Koan08b.java
│ │ ├── Koan08c.java
│ │ ├── Koan09.java
│ │ ├── Koan10.java
│ │ ├── Koan11.java
and if you look into them, you'll see comments and snippet sections that say "your code here", but the come pre-filled in with the answers.
However, if you go into the src/main/scripts directory you'll notice a a "release.sh" script, which extracts the relevant portion of the koans from the current github dir and copies it to a temp directory and runs the remove_snippets script. However I couldn't get it to work after 15 minutes of futzing with it and the documentation for it is basically useless.
[Dec 2011 Update: I tried it again and it works now for me. Either I did something wrong the first time or Jim Webber tweaked it.]
There is also a remove_snippets.sh. You can run that directly - you are supposed to do it from the top-level dir, not the scripts directory. Either way I got an error message. But it does work if you run it from the top level dir, despite the error message. Here's what I got:
$ src/main/scripts/remove_snippets.sh
sed: can't read : No such file or directory
$ git st
M src/koan/java/org/neo4j/tutorial/Koan02.java
M src/koan/java/org/neo4j/tutorial/Koan03.java
M src/koan/java/org/neo4j/tutorial/Koan04.java
M src/koan/java/org/neo4j/tutorial/Koan05.java
M src/koan/java/org/neo4j/tutorial/Koan06.java
M src/koan/java/org/neo4j/tutorial/Koan07.java
M src/koan/java/org/neo4j/tutorial/Koan08a.java
M src/koan/java/org/neo4j/tutorial/Koan08b.java
M src/koan/java/org/neo4j/tutorial/Koan08c.java
M src/koan/java/org/neo4j/tutorial/Koan09.java
M src/koan/java/org/neo4j/tutorial/Koan10.java
M src/koan/java/org/neo4j/tutorial/Koan11.java
(git st is aliased to git status -s on my machine)
So it did modify the Koans and remove the parts I'm supposed to fill in.
After doing this, I recommend doing git reset --hard to get back the filled in koans. Copy them to another directory, so you can peek at them when you are doing the koans in case you get stuck or want to compare your solution with the official one.
Then run the remove_snippets.sh script again and do a git add and git commit. Now we are ready to start the koans (whew!).
/* ---[ Doing the Koans ]--- */
The koans are unit tests. After you run the remove_snippets script, all the koan unit tests will fail (except for Koan01, which for some reason has no snippet for you to replace - it is a just a reading koan, not a doing koan, I guess).
You need to fix the koans one by one and get each test passing. Unfortunately, I couldn't find a way to run each test separately, you have to do the full battery, plus the annoying-as-hell ivy checks. <rant>Speaking of which, you won't be able to run these tests while offline, even after you've download everything via ivy. This is my biggest complaint about the ivy/maven model. I frequently want to do offline working, so I curse setups that require everything to be done via ivy/maven.</rant>
One way you can sift through all the noise of the output is to run this unit tests like this:
$ ant | grep Koan11
Then you will just get the output of Koan11 (though you have to run everything unless you want to edit the Ant build.xml file), like this:
$ ant | grep Koan11
[junit] Running org.neo4j.tutorial.Koan11
[junit] TEST org.neo4j.tutorial.Koan11 FAILED
[junit] Tests FAILED
BUILD FAILED
/home/midpeter444/java/projects/neo4j-koans/neo4j-tutorial/build.xml:68: Build failed due to Koan failures
I also found context lines and simple pattern matching to help, such as:
$ ant | grep -C 4 Koan0[123]
/* ---[ Only Running the Tests You Want ]--- */
As I said, there is no target in the ant file (or any helper scripts) to only run one test/koan at a time. And each one takes many seconds, so the whole thing can take well over a minute (depending on machine speed).
To do the easiest thing that would work, I issued the following command (you could do it with sed if you don't have perl installed):
find src/koan/java -name Koan*.java -print | xargs perl -pi -e "s/([@]Test)/\/\/\1/g"
It just comments out all the @Test annotations in the Koan files. Run this once at the beginning. Then you can remove the comments from each test as you are working on them. So the ant file stills runs all the koans, but they don't take very long if you haven't uncommented them.
/* ---[ Reading the error report output ]--- */
Don't make the same mistake I did spending lots of time going through target/koan/reports/TESTS-TestSuites.xml output. I later found that a nice html report is provided one more directory down. Open the target/koan/reports/output/index.html in your browser and refresh after each test - this is very nice!
So the cycle is:
1. Edit the Koan test until you are ready to run (uncomment that one's @Test annotation)
2. Run: ant | grep -C 4 Koan0[34] (modify the numbers as needed)
3. Refresh target/koan/reports/output/index.html in your browser and refresh after each test.
Note also that if you debug by printing to stdout, there is a link on the index.html output to view it - use that as needed.
Finally, I wrote a little helper class that will print out all the properties and values of a Node - this is helpful in debugging. Here is the code:
package org.neo4j.tutorial;
import org.neo4j.graphdb.Node;
public class NodePP {
public static String pp(Node n) {
String s = "Node: ";
for (String k: n.getPropertyKeys()) {
s += String.format("\n %s: %s", k, n.getProperty(k));
}
return s;
}
}
Complaints aside, I'm currently finishing Koan08c and I recommend them as a good way to learn neo4j and think in terms of graphs. And so far, I really like the cypher query language....
[Dec 2011 Update:] I've finished them all now. Since I only broke down and cheated once by looking at the pre-filled in version (Koan11 was a doozy), it took me a while, but I feel like I have a very good sense of how to use neo4j now. The koans provide great coverage of the approaches to using the database.
Neo4j is a very promising database and I think it is a serious player in the NoSQL space. The next question for me is how to use it with one's domain model in POJOs. I see four options:
- Serialize/deserialize POJOs to/from JSON and use the neo4j REST API. This will be less performant, but is the option if you are using a standalone database server.
- Make your POJOs Neo-aware - have them wrap Nodes and Relationship and keep their attributes in neo Node/Relationship properties. This obviously tightly couples your domain to your persistance layer.
- Use CQL (cypher query language) like you do SQL when not using an ORM. Cypher is very nice and well thought out. I wonder how hard it would be to construct a MyBatis-like mapper between Cypher and your POJOs.
- Use the Spring Data Neo4j annotation bindings for neo4j. This looks promising. I've started looking at it, but no strong opinion yet. They do say that it will be less performant than directly using the direct neo4j API (such as the Traversal API), as there is metaprogramming (Java Reflection API usage) going on.
|
http://thornydev.blogspot.com/2011/11/
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
view raw
Here is the code for a calculator in Python:
import time
#Returns the sum of num1 and num2
def add(num1, num2):
return num1 + num2
#Returns the difference of num1 and num2
def subtract(num1, num2):
return num1 - num2
#Returns the quotient of num1 and num2
def divide(num1, num2):
return num1 / num2
#Returns the product of num1 and num2
def multiply(num1, num2):
return num1 * num2
#Returns the exponentiation of num1 and num2
def power(num1, num2):
return num1 ** num2
import time
def main ():
operation = input("What do you want to do? (+, -, *, /, ^): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/" and operation != "^"):
#invalid operation
print("You must enter a valid operation")
time.sleep(3)
else:
var1 = int(input("Enter num1: ")) #variable one is identified
var2 = int(input("Enter num2: ")) #variable two is identified
if(operation == "+"):
print (add(var1, var2))
elif(operation == "-"):
print (subtract(var1, var2))
elif(operation == "/"):
print (divide(var1, var2))
elif(operation == "*"):
print (multiply(var1, var2))
else:
print (power(var1, var2))
main()
input("Press enter to exit")
exit()
main = lambda operation,var1,var2: var1+var2 if operation=='+' else var1-var2 if operation=='-' else var1*var2 if operation=='*' else var1/var2 if operation=='/' else 'None'
print(main(input('What operation would you like to perform? [+,-,*,/]: '),int(input('Enter num1: ')),int(input('Enter num2: '))))
input('Press enter to exit')
In order to simplify the code, I will suggest to:
Create a function to perform operation taking the help of dictionary.
Note: I desrcide the alternative with
lambda function based on requirement mentioned by user. Personally I would use
operator
Using
operator:
import operator def perform_operation(my_operator): return { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, # "operator.div" in python 2 '^': operator.pow, }.get(my_operator, '^') # using `^` as defualt value since in your # "else" block you are calculating the `pow`
Using
lambda:
def perform_operation(my_operator): return { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / float(y), '^': lambda x, y: x ** y, }.get(my_operator, '^') # using `^` as defualt value since in your # "else" block you are calculating the `pow()`
Sample run:
>>> perform_operation('/')(3, 5) 0.6
PS: Looking at the defination you would have got the idea why using
operator is more pythonic than
lambda
Update your
else block to make a call to it as:
var1 = int(input("Enter num1: ")) var2 = int(input("Enter num2: ")) perform_operation(operation)(var1, var2) # Making call to function created above # THE END - nothing more in else block
Simplify your
if condition with:
if operation not in ["+", "-", "*", "/", "^"]: # invalid operation
|
https://codedump.io/share/fQXzUb85Og0H/1/simplifying-code---perform-mathematical-operations-based-on-operator
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
This forum is now read-only. Please use our new forums at discuss.codecademy.com.
Getting Started with Programming Forum
if / else errors - learn how to fix these
If you have a question that isn't answered here, please use the green "Ask a question" button. Copy/paste all of your code in with your question, include the exercise number you are working on and the exact error message you are seeing.
Typically the following error messages are caused by faulty if/else syntax
- "syntax error"
- "missing operand; found else"
- "Unexpected token else"
- "expected an identifier and instead saw "else""
First off, a quick review of what if statements look like.
A typical if () statement looks like this. Depending on what you are checking for, the
else if and
else blocks may not be needed. Note how the
{ },
( ) and
; are used.
if (this condition is true) { do something; } else if { do this other thing; } else if { do this awesome thing; } else { do something different; }
Do a quick check to see if you haven't misspelled or mis-capitalized
if or
else.
Using any of these is going to earn you an error:
IF,
If,
ELSE,
Else
All good with your spelling and capitalization? Okay, on to the next check.
Is there an indicator complaining about your
else?
In JavaScript semicolons mark the end of statements..
If you are getting an error about the
else it is because you've told the interpreter that the
; was the end of your if statement so when it finds the
else a few lines later it starts complaining.
A few examples of where not to put a semicolon:
if (age < 18); if ( 9 > 10 ); if ("Yogi Bear".length < 3); if ("Jon".length * 2 / (2+1) === 4 ); if (userAnswer === "yes"); if (feedback > 8); if (income >= 100);
I think you can see what I'm getting at.
Checked for all those and still haven't found the bug yet?
Have a look and make sure you don't have any semicolons on your
else or your
else if ( ), doing that will also end your if statement sooner than you had planned.
These are both going to give you errors:
} else if (computerChoice < 2/3); { else;
Curious about other situations where semicolons should be used/not used?
else is not allowed to have a condition
@AlbionsRefuge - Great post!!
I've also noticed a few people trying to do things like...
if ( a < b) { do something here; } else if (a > b) { do this other thing; } else (a == b) { do something different; }
and then they post a question asking what is wrong with their code.
It seems that they aren't grasping a few concepts about the flow of logic in
if /
else if /
else statements.
So I thought this would be a great place to point out a few things that those struggling with
if /
else if /
else might find helpful.
For one thing, unlike
if and
else if, an
else statement is not used to do condition checking. The purpose of
else is to execute alternative code in the situation where the
if, and
else if conditions return false.
In the particular code example above, if the program execution has reached the
else statement it means that:
a < b returned
false and
a > b also returned
false.
If the value of
a is: not greater than the value of
b and not less than the value of
b, then it logically follows that the value of
a must be equal to the value of
b! because there is no other option for what the value of
a could be.
There is no need to even bother trying to test for
( a == b ). You simply have the
else statement do something.
The correct code would be:
if ( a < b) { do something here; } else if (a > b) { do this other thing; } else { do something different; }
I think those of us who are seasoned programmers (or people like me who have just had some exposure to programming concepts and have coded up a few personal projects) tend to take these things for granted.
Pointing them out might seem very elementary to experienced programmers. However, beginners who have never dealt with these concepts can and do struggle with these kinds of ideas and I felt a good explanation might be in order.
I hope this is a helpful comment!
25 Comments
No problem, looks good! Thanks!
Thank you! That helped
Great post! I Will refer to it often!
big help!
you rock!!
Please with the solution/explanation given to this if and else statement, has anyone used it and gotten it. Because I've followed the instruction and still not getting it. Maybe anyone skype with me on this ID- dayor69 for more clarification. Thanks.
Thank you! You helped me figure out what I was doing wrong!
Yes! Thank you!!
These small errors really do make a difference, damn. Thanks you guys for the wonderful explanations!
This did it! Thank you for helping me spot my error!
Thank You for help
You saved my day! Thank you! My error was that I used a statement on Else. Great explaining!
it says unexpected identifier for me and i dont know what that means?
You probably ended a conditional statement too early by a semicolon or in an other way have a look at the post below this one.
Yes thank you. And like you said for those with experience some things are clear to see but to the beginners it can be a nightmare but once you get it, its great.
Thanks Mark! People like you make this enjoyable for novices like me. continue being brilliant.
Beautiful explanation and yes, very helpful! Thanks Mark. I was initially wondering what was wrong with the code you posted, then it made sense after reading what you wrote.
Very helpful, and just had a minor victory thanks to this comment - cheers!
i still cant do it lol
thanks
It's extremely frustrating to not be able to see the correct code. I've been stuck on 6/9 for an hour with a syntax error that I have not been able to find an answer to. Is there a place to see the correct code when stumped?
@Ron, I'm sure several people have posted all the answers somewhere on the internet, but usually what people do here is use the "Ask a question" button and post their code, their error message and any thoughts they have on what's going on. Then other people read all of that and offer guidance.
The exercises should be created in a way that you should be able to solve them on your own but unfortunately their might be some exercises that are better than others and some warnings might not be as accurate as they should be so if you get stuck rather ask the question yourself in the Q&A or google for the concept itself instead of the answer, if you've understood what you are trying to do and how to do it you can skip the exercise if you want but progressing without understanding what you do might make it harder to understand further stuff. Also you can have a look at e.g. labs.codecademy.com where you can test code that you think should be running without the requirements of an exercise. Good sources are also MDN+javaScript command or stackoverflow.
Thank you, noted, let me check labs.codecademy.com I didn’t know of its existence.
Conditions, Blocks and Semicolons.
6 Comments
Very Useful as Well... Thank you for sharing haxor
Thanks for sharing!
Thank for sharing
Thanking You :D
thanks!
thank's very much.....very helpful to me!
Are you getting one of the errors on the list at the top of this thread but following the troubleshooting steps isn't helping? Show us all of your code using the "Add an answer" box, tell us the EXACT error message and we'll look into it!
25 Comments
sorry THIS is my code var balance = 20.97;
if (balance<10) {
console.log(balance-5)}
else {
console.log=(balance)
}
@JovyCB: Rather than trying to make console.log = (balance) just console.log(balance) -- doesn't that seem more sensible?
I'm sorry but I still don't understand. This is my code:
var balance = 20.97;
if (balance < 10)
{
console.log(balance - 5);
}
else
{
console.log(balance);
}
@Wanda - that looks perfect - what error message is it giving you?
Oops, try again. Your code doesn't look quite right. Check the Hint if you need help! ALSO, on the result screen it's giving me this: RefernceError: Can't find variable aaaaaaaaaaaaaaaa...
@Wanda, the code as you've shown here is perfect. Unless there is some other bits that I can't see? Try refreshing/reloading your web page. If that doesn't work, if possible, try it in a different web browser.
var creditCheck = function (income) {
if (creditCheck >= 100)
return ("You earn a lot of money! You qualify for a credit card.") } ;
else ; { (creditCheck < 100) ;
return ("Alas you do not qualify for a credit card. Capitalism is cruel like that.") } It says right before "else" that it expected an identifier.
@darecode - you have several things going on there that need fixing - too many for this little comment box. Could I get you to use the green "Ask an answer button" please?
Im assuming you mean ask a question, and I did so,
@darecode - I must have been really distracted when I typed that - good thing I said "green"! Can you see your new question in the list - because I can't. Could you try again please - or give me the link to it.
@darecode, thanks, I see it now.
Great, waiting for your answer, honestly, I'm stumped :/
Oops, try again. Check your if statement--it looks like you didn't print the correct value.I got this error for1/13
var balance = 20.97;
// Complete the condition in the ()s on line 4
if (balance<10 ) {
console.log( "balance-5");
} else {
}console.log(" balance");
@Mineli, you've almost got it. Putting " " around your variables is killing their magic and turning them into plain old strings.
yes........thanks.....I've Got it:P
Yay @Mineli!
Ohhhhh!
i get it now
And don't forget to refresh the page before fixing this bug, as otherwise you'll be told hat console.log is not a function as it now contain the value of balance as you can see by using alert(console.log).
unexpected token else
ReferenceError: Console is not defined
use a lowercase c in console
unexpected keyword else
Hi nicoledille, when the JavaScript interpreter is telling you that if found an unexpected else, that is likely because you have ended your if statement before the statement was finished - likely by putting a ; where it doesn't belong. You can see several examples of that in my original post. I can only guess at this though because you haven't shown us your code.
2 Comments
You're welcome!
Thank you!!! Those pesky semicolons were eating me up on the if/else 1st line. Now I know why!!!
@Mark: The error you explained is also caused by this only-one-statement-after-a-conditional-case-rule. At first you are absolutly right about the fact that else does not need a condition! But the error in the code is not that else has "condition" but that there are two statements on one line (without separator):
else (a == b) { do something different; }
first statement is the
a == b, which is a pretty pointless statement as it is just true or false and is neither stored nor printed (as said, else doesn't expect a condition, so the () don't show any relation to else but just increase the priority of evaluating the stuff inside, which is unnecessary as this code would follow anyway) and the second statement is the begining of the block.
So if you had used:
else (a == b) { do something different; }
or
else (a == b); { do something different; }
it would still be pointless and missleading as the code in the block would be evaluated in any case, but syntactically it would be correct.
var sleepCheck = function(numHours) { if (numHours >= 8) { return "You're getting plenty of sleep! Maybe even too much!"; } else { return "Get some more shut eye!; } }; sleepCheck(5);
SyntaxError: Unexpected token ILLEGAL
1 Comment
Hi JamyangTenzin, it looks like you are missing one "
also stuck with unexpected token pls what is wrong with this code
var sleepCheck = function(numHours);
if (numHours >= 8) {
return "You're getting plenty of sleep! Maybe even too much!";
}
else {
return "Get some more shut eye";
}
sleepCheck (5);
1 Comment
Hi Michaelmgbame, your very first line has the problem. When you define a function, you put all of the code that you want the function to consist of in a { block }. Instead of a { to start that block, you have put a semicolon at the end of that first line. Semicolons are for ending things, so you have ended your function right there at the end of that first line.
Hey, i'm not sure what's wrong with the code. The error I'm getting is "unexpected token"; } };
};
PS: I've figured it out. I only needed that final semi-colon after the last closing brace, not the ones after the else if closing brace.
Thanks mrman, I'm sure some of the learners will find this helpful. (I changed the formatting your code blocks, just a bit - too much of that red lettering makes my eyes go funny).
|
https://www.codecademy.com/forum_questions/52373a75548c3515940000dc
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
Q:.
Q:.)
Q:
Q:
Q: [footnote] and it may not do everything you want it to. (For instance, it does not handle quoting.) Here is a usage example, which simply prints each field as it's extracted:
#include <stdio.h> #include <string.h> char string[] = "this is a test"; /* not char *; see Q 16.6 */ char *p; for(p = strtok(string, " \t\n"); p != NULL; p = strtok(NULL, " \t\n")) != '\0') argv[argc++] = p; else { argv[argc] = 0; break; } /* scan over arg */ while(*p != '\0' && !isspace(*p)) p++; /* terminate arg: */ if(*p != '\0' && i < argvsize-1) *p++ = '\0'; } return argc; }
Calling makeargv is straightforward:
char *av[10]; int i, ac = makeargv(string, av, 10); for(i = 0; i < ac; i++) printf("\"%s\"\n", av[i]);
If you want each separator character to be significant, for instance if you want two tabs in a row to indicate an omitted field, it's probably more straightforward to use strchr:
#include <stdio.h> #include <string.h> char string[] = "this\thas\t\tmissing\tfield"; char *p = string; while(1) { /* break in middle */ char *p2 = strchr(p, '\t'); if(p2 != NULL) *p2 = '\0'; printf("\"%s\"\n", p); if(p2 == NULL) break; p = p2 + 1; }
All the code fragments presented here modify the input string, by inserting \0's to terminate each field (meaning that the string must be writable; see question 1.32). If you'll need the original string later, make a copy before breaking it up.
References:
K&R2 Sec. B3 p. 250
ISO Sec. 7.11.5.8
H&S Sec. 13.7 pp. 333-4
PCS p. 178
Q: I need some code to do regular expression and wildcard matching.
A: Make sure you recognize the difference between:. [footnote].
Here is a quick little wildcard matcher by Arjan Kenter:
int match(char *pat, char *str) { switch(*pat) { case '\0': return !*str; case '*': return match(pat+1, str) || *str && match(pat, str+1); case '?': return *str && match(pat+1, str+1); default: return *pat == *str && match(pat+1, str+1); } }(Copyright 1995, Arjan Kenter)
With this definition, the call match("a*b.c", "aplomb.c") would return 1.
References: Schumacher, ed., Software Solutions in C Sec. 3 pp. 35-71
Q:
Q:
Q:
Q:
Q: How can I get the current date or time of day in a C program?
A: Just use the time, ctime, localtime and/or strftime functions. Here is a simple example: [footnote]
#include <stdio.h> #include <time.h> int main() { time_t now; time(&now); printf("It's %s", ctime(&now)); return 0; }
Calls to localtime and strftime look like this:
struct tm *tmp = localtime(&now); char fmtbuf[30]; printf("It's %d:%02d:%02d\n", tmp->tm_hour, tmp->tm_min, tmp->tm_sec); strftime(fmtbuf, sizeof fmtbuf, "%A, %B %d, %Y", tmp); printf("on %s\n", fmtbuf);(Note that these functions take a pointer to the time_t variable, even when they will not be modifying it.[footnote] )
If you need sub-second resolution, see question 19.37.
References:
K&R2 Sec. B10 pp. 255-7
ISO Sec. 7.12
H&S Sec. 18
Q:
Q:''
Q:
Q:''
Q:)If you just need to do something with probability 1/N, you could use
if(rand() < (RAND_MAX+1u) / N)All these methods obviously require knowing RAND_MAX (which ANSI #defines in <stdlib.h>), and assume that N is much less than RAND_MAX.
When N is close to RAND_MAX, and if the range of the random number generator is not a multiple of N (i.e. if (RAND_MAX+1) % N != 0), all of these methods break down: some outputs occur more often than others. (Using floating point does not help; the problem is that rand returns RAND_MAX+1 distinct values, which cannot always be evenly divvied up into N buckets.) If this is a problem, about the only thing you can do is to call rand multiple times, discarding certain values:
unsigned int x = (RAND_MAX + 1u) / N; unsigned int y = x * N; unsigned int r; do { r = rand(); } while(r >= y); return r / x;
For any of these techniques, it's straightforward to shift the range, if necessary; numbers in the range [M, N] could be generated with something like
M + rand() / (RAND_MAX / (N - M + 1) + 1)
(such as the last version of PMrand alluded to in question 13.15, or drand48 in question 13.21), all you have to do to get integers from 0 to N-1 is multiply the output of that generator by N:
(int)(drand48() * N)
Additional links
References:
K&R2 Sec. 7.8.7 p. 168
PCS Sec. 11 p. 172
Q:
Q: I need a random true/false value, so I'm just taking rand() % 2, but it's alternating 0, 1, 0, 1, 0...
A: Poor pseudorandom number generators (such as the ones unfortunately supplied with some systems) are not very random in the low-order bits. (In fact, for a pure linear congruential random number generator with period 2**e, and this tends to be how random number generators for e-bit machines are written, the low-order n bits repeat with period 2**n.) For this reason, it's preferable to use the higher-order bits: see question 13.16.
References: Knuth Sec. 3.2.1.1 pp. 12-14
Q:
Q: How can I generate floating-point random numbers?
A: See question 13.21 for some examples.
Q: How can I generate random numbers with a normal or Gaussian distribution?
A: There are a number of ways of doing this.
#include <stdlib.h> #include <math.h> #define NSUM 25 double gaussrand() { double x = 0; int i; for(i = 0; i < NSUM; i++) x += (double)rand() / RAND_MAX; x -= NSUM / 2.0; x /= sqrt(NSUM / 12.0); return x; }(Don't overlook the sqrt(NSUM / 12.) correction, though it's easy to do so accidentally, especially when NSUM is 12.)
#include <stdlib.h> #include <math.h> #define PI 3.141592654 double gaussrand() { static double U, V; static int phase = 0; double Z; if(phase == 0) { U = (rand() + 1.) / (RAND_MAX + 2.); V = rand() / (RAND_MAX + 1.); Z = sqrt(-2 * log(U)) * sin(2 * PI * V); } else Z = sqrt(-2 * log(U)) * cos(2 * PI * V); phase = 1 - phase; return Z; }
; }
Additional links
References:
Knuth Sec. 3.4.1 p. 117
Box and Muller, ``A Note on the Generation of Random Normal Deviates''
Marsaglia and Bray, ``A Convenient Method for Generating Normal Variables''
Abramowitz and Stegun, Handbook of Mathematical Functions
Press et al., Numerical Recipes in C Sec. 7.2 pp. 288-290
Q:
Q: Is exit(status) truly equivalent to returning the same status from main?
A: See question 11.16.
Q: What's the difference between memcpy and memmove?
A: See question 11.25.
Q: I'm trying to port this old program. Why do I get ``undefined external'' errors for some library functions?
A:
Some
old or
semistandard functions have been renamed or replaced over the years;
if you need:/you should instead:
See also questions 12.22 and 13.21.
References: PCS Sec. 11
Q:.
Q:, a command line like
cc -lm myprog.c # WRONGusually won't work. Instead, put any -l options at the end of the command line:
cc myprog.c -lm
If you list a library first, the linker doesn't know that it needs anything out of it yet, and passes it by. See also question 13.28.
Q:
Q:.)
Q:.
Read sequentially: prev next up
about this FAQ list about eskimo search feedback copyright
Hosted by
|
http://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=lib
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
I have two paired bluetooth devices (my car's head-unit for phone audio and a separate bluetooth receiver for A2DP). On my phone there's a checkbox for "Use for media audio" that I have to manually toggle for my A2DP output to go to my car's speakers. My goal is to toggle this programmatically.
I tried using both the AudioManager class with the deprecated setBluetoothA2dpOn and the setBluetoothScoOn but neither seemed to have any effect. I was able to get a list of the bluetooth paired devices and get a handle to the connection I want to toggle but I couldn't seem to get it quite right. I also tried getting the default bluetooth adapter and then using getProfileProxy but I feel like I'm barking up the wrong tree there.
Can anyone point me in the right direction? Basically all I want to do is the equivalent of checking that "Use for media audio" box.
First you need to set the program to activate the Bluetooth on the phone and select the device that it should pair with via
bluetoothAdapter.disable() / enable()
(im not sure about the pairing but this must be done via some config activity)
Then you should set A2DP to connect to the car's stereo
follow this link to try and find the code for it, if i have time i will try and find it for you but its a start =]
A short time ago I had a similar problem trying connect a bluetooth device to android phone. Although your device profile being different, I think the solution is the same.
First you need create a package in your project named
android.bluetooth and put the following IBluetoothA2dp.aidl in there:
package android.bluetooth; import android.bluetooth.BluetoothDevice; /** * System private API for Bluetooth A2DP service * * {@hide} */ interface IBluetoothA2dp { boolean connectSink(in BluetoothDevice device); boolean disconnectSink(in BluetoothDevice device); boolean suspendSink(in BluetoothDevice device); boolean resumeSink(in BluetoothDevice device); BluetoothDevice[] getConnectedSinks(); BluetoothDevice[] getNonDisconnectedSinks(); int getSinkState(in BluetoothDevice device); boolean setSinkPriority(in BluetoothDevice device, int priority); int getSinkPriority(in BluetoothDevice device); boolean connectSinkInternal(in BluetoothDevice device); boolean disconnectSinkInternal(in BluetoothDevice device); }
Then, to access those functionalities, put the following class in your project:
public class BluetoothA2dpConnection { private IBluetoothA2dp mService = null; public BluetoothA2dpConnection() { try { Class<?> classServiceManager = Class.forName("android.os.ServiceManager"); Method methodGetService = classServiceManager.getMethod("getService", String.class); IBinder binder = (IBinder) methodGetService.invoke(null, "bluetooth_a2dp"); mService = IBluetoothA2dp.Stub.asInterface(binder); } catch (ClassNotFoundException e) { e.printStackTrace(); }(); } } public boolean connect(BluetoothDevice device) { if (mService == null || device == null) { return false; } try { mService.connectSink(device); } catch (RemoteException e) { e.printStackTrace(); return false; } return true; } public boolean disconnect(BluetoothDevice device) { if (mService == null || device == null) { return false; } try { mService.disconnectSink(device); } catch (RemoteException e) { e.printStackTrace(); return false; } return true; }
}
Finally, to connect your A2dp device, pick one BluetoothDevice from a list of paired devices and send it as parameter of
connect method. Be sure to pick a device with the correct profile, otherwise you will have an exception.
I have tested this solution in a phone with android version 2.3 and it worked fine.
Sorry any English mistake. I hope this can help you.
Similar Questions
|
http://ebanshi.cc/questions/203153/toggling-a2dp-device-android
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
In part 1, we had gotten a crash by sending a 2048-byte pattern to the vulnerable program.
The saved return address had been overwritten with 0x41367241 and restored to the $ra register. That value is located at an offset of 528 in our overflow buffer. Now we need to start describing ROP gadgets and substituting them for parts of the 2048-byte overflow string.
In order to start replacing parts of the overflow string, we need to create a list of replacement sections[1]. The easiest way to do that is to use the SectionCreator class. This is essentially a factory that generates OverflowSection objects.
You need to know a couple of things in order to instantiate a SectionCreator object: the endianness (which we already identified as little endian), an optional base address of the library you want to ROP into, and an optional list of bad bytes. If you provide the list of bad bytes, you'll get an exception if any of the overflow sections you create contain any of the restricted characters.
While the base address is an optional parameter to SectionCreator's constructor, I recommend providing the address of whatever library you're going to use most. If you're using more than one library, you can override this setting at any time if to create a ROP object in another library. Libc is often a good library to ROP into, and we can find its base address in /proc/<pid>/maps:
$ sudo cat /proc/6104/maps 00400000-00402000 r-xp 00000000 00:17 4833702 rootfs/vulnerable 00402000-00411000 ---p 00000000 00:00 0 00411000-00412000 rw-p 00001000 00:17 4833702 rootfs/vulnerable ... 4084a000-408a1000 r-xp 00000000 00:17 240427 rootfs/lib/libc.so.0 408a1000-408e1000 ---p 00000000 00:00 0 408e1000-408e2000 r--p 00057000 00:17 240427 rootfs/lib/libc.so.0 408e2000-408e3000 rw-p 00058000 00:17 240427 rootfs/lib/libc.so.0
The base address of libc is 0x4084a000.
The vulnerable function simply does a recv() into a buffer on the stack, so it doesn't actually have any restricted bytes. But for the sake of example, we'll assume we can't use nul or space, 0x00, and 0x20, respectively.
A SectionCreator object is instantiated like so:
from bowcaster.overflow_development.overflowbuilder import SectionCreator qemu_libc_base=0x4084a000 badchars=['\x00','\x20'] SC=SectionCreator(LittleEndian,base_address=qemu_libc_base,badchars=badchars)
Like I explained previously, we need to find the library addresses of our ROP gadgets manually or with other tools. I use IDA Pro, but you can disassemble with objdump and do the same.
The first ROP gadget we need is a function epilogue that restores a bunch of the MIPS S registers from the stack.
The picture above is an epilogue at 0x31B44 in libc that restores $s0-$s7, plus $ra. Who knows what this function is? Who cares? IDA calls it sub_318DC. Good enough.
We create a ROP gadget object for this address like so:
sections=[] #function epilogue rop section=SC.gadget_section(528,0x31b44, description="[$ra] function epilogue that sets up $s1-$s7") sections.append(section)
The gadget_section() method takes a mandatory offset and and address value, and an optional description and optional base address.
The description is just a textual description of this overflow section. It gets used in log output, exception messages etc, and helps you debug your exploit if things go wrong. If you don't provide a description, a generic one gets generated.
This is where you can override the base address you specified earlier. Say instead of a ROP gadget, you just want to put a placeholder on the stack that will avoid blowing up the program before the function returns. Here you could provide the literal value to gadget_section() and override the base address with 0. This value will get encoded with the proper endianness and placed in the buffer.
Keep adding to your list of sections, and then instantiate the OverflowBuffer object just like before, but this time pass the section is as the optional third parameter:
buf=OverflowBuffer(LittleEndian,2048,sections)
There are a couple of things to note about the OverflowBuffer class. First, when you create it with a list of sections, those sections replace portions of the filler pattern. The parts of the pattern that come before and after each section remain undisturbed so their offsets stay the same. Second, if any of the sections in your list overlap, OverflowBuffer will log an error message listing problem sections (this is where the optional description strings are useful), and it will raise an exception.
For example, I created a section of 8 "D"s at offset 500, and another section of 8 "A"s at offset 504. They overlap by 4. I got the following log output:
[!] Section "D's", offset: 500 length: 8 overlaps with the following sections: [!] "A's overlapping with D's" offset: 504 length: 8
With this gadget added, run your exploit once more and see what values get restored to the S registers and $ra. Like before, use find_offet() to figure out the offsets into your buffer where you'll need to place your gadgets such that they'll be loaded into the appropriate registers.
In order to get into the stack and start executing payload, we need a series of ROP gadgets that do the following:
- Stage an argument to sleep() into $a0 (for data cache flushing; MIPS cache-coherency).
- Return into libc's sleep()
- Load some offset from $sp into an S register, thereby locating the stack.
To give you a more complete picture of how to build your ROP chain, below is a listing of the gadgets I used for this exploit.UPDATE 4/8/2013: References to Crossbow have been changed to Bowcaster.
sections=[] #function_epilogue_rop section=SC.gadget_section(528,0x31b44, description="[$ra] function epilogue that sets up $s1-$s7") sections.append(section) #Sleep arg 2 into $a0, stack data into $ra, then jalr $s0 section=SC.gadget_section(656,0x43880, description="[$a0] Set up 2 sec arg to sleep(), then jalr $s1") sections.append(section) #address of sleep section=SC.gadget_section(620,0x506c0, description="Address of sleep() in libc. be sure to set up $ra and $a0 before calling.") sections.append(section) #placeholder address that can be dereferenced without crashing, this goes in $s2 section=SC.gadget_section(628,0x427a4, description="[$s2] placeholder, derefed without crashing.") sections.append(section) #stackfinder. add 0xe0+var_c0 + $sp into $s0, jalr $s6 section=SC.gadget_section(688,0x427a4,description="stackfinder.") sections.append(section) #stackjumber. jalr $s0 section=SC.gadget_section(644,0x1ffbc,description="[$s0] stackjumper") sections.append(section).
|
http://shadow-file.blogspot.com/2013/03/buffer-overflows-with-crossbow-part-2.html
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
I don’t know how many times I have seen a method which I have been trying to debug with a whole stack of parameter checking code at the start of the method to ensure nothing weird happens with unexpected input. This subsequently caused the nicely abstracted methods to be less abstract than originally intended. Thankfully .Net 4.0 makes life for the developer, and subsequent debuggers a lot easier with Code Contracts.
Code contracts come under the namespace
System.Diagnostics.Contracts
and the most used class in this is the Contract class.
Pre-Conditions
There are some different flavours of code contracts, the first is Pre-conditions. This will be similar to the checks done to insure your method hasn’t been passed some incorrect parameters.
e.g. a simple divide example which requires that the divisor isn’t 0
public float Divide(float a, float b)
{
Contract.Requires(b != 0); // line to ensure code contract
Return a/b;
}
if this method is called with b as 0, when compiling and doing static analysis in Visual Studio 2010 (depending on the code contract options set on the project options found in the standard project settings in Visual Studio) will either show as an error, therefore not allowing the project to build, or show an error. There is an override on the Requires method which allows you to put your own warning/error message if the contract is not met:
Contract.Requires(b != 0, "Parameter b must not be 0 when calling divide");
this analysis is pretty clever and knows when you are trying to trick it 😉
Console.WriteLine(Divide(1, 1)); // works fine
Console.WriteLine(Divide(1, 0));
var a = 1;
a--;
Console.WriteLine(Divide(1, a)); // finds this too 🙂
var b = 1;
Random r = new Random();
b -= r.Next(2);
if (b != 0) // without this, there would be an error saying that b could be 0 was unproven
{
Console.WriteLine(Divide(1, b));
}
Post Conditions
These conditions inform on the finishing state of a method, properties of the return types, objects which should not have been modified etc.
e.g.
public void AddToCollection(Object o)
{
// ensure that the collection is not changed if there is a null reference
Contract.EnsuresOnThrow<NullReferenceException>
(Contract.OldValue(collection.Count) == collection.Count);
// ensure that the parameter passed in has not been changed
Contract.Ensures(Contract.OldValue(o) == o);
collection.Add(o);
}
now if a NullReferenceException is thrown the code contract will ensure that nothing has been added or removed from the collection.
Invariants
Invariants are rules for objects which should only be modified in a certain way throughout their scope. e.g. collection must not be empty, a value must not be null, a counter must be non-negative…
For these type of rules you need to mark your method with the attribute:
[ContractInvariantMethod]
Now inside the method we can set up our rules.
[ContractInvariantMethod]
private void Validate()
{
Contract.Invariant(collection != null);
Contract.Invariant(collection.Count > 0);
Contract.Invariant(collection.First() != null);
}
this will ensure that the collection is initialized, always has at least 1 non-null entry.
Code contracts seem extremely useful and I look forward to writing code and debugging using them.
|
https://blogs.msdn.microsoft.com/davethompson/2010/01/12/code-contracts-with-net-4-0/
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
The "Avalon" Input System
Nick Kramer
Microsoft Corporation
March 2004
Summary: The presentation subsystem in "Longhorn" (code-named "Avalon") provides powerful new APIs for input. This article gives an overview of these APIs: What services are provided to applications, the architecture of the input system, and how new input devices can be supported. (16 printed pages)
Contents
Introduction
Input in a Tree
Text Input
Keyboard Sample
Commands
Input Core Architecture
Adding New Kinds of Devices
Conclusion
Introduction
The presentation subsystem in "Longhorn" (code-named "Avalon") provides new APIs for input. The primary input APIs are on the Element class. Note that in this article, I am using the term "element" as shorthand for "FrameworkElement" or "ContentFrameworkElement". Although they are distinct classes, from an input point of view they are identical. Elements have all the mouse and keyboard functionality you've come to expect from the Windows® operating system—keypresses, mouse buttons, mouse movement, focus management, mouse capture, and so on. Elements have the following input-related properties, methods, and events:
class Element { // non-input APIs omitted // Mouse event MouseButtonEventHandler MouseLeftButtonDown; event MouseButtonEventHandler MouseLeftButtonUp; event MouseButtonEventHandler MouseRightButtonDown; event MouseButtonEventHandler MouseRightButtonUp; event MouseEventHandler MouseMove; bool IsMouseOver { get; } bool IsMouseDirectlyOver { get; } event MouseEventHandler MouseEnter; event MouseEventHandler MouseLeave; event MouseEventHandler GotMouseCapture; event MouseEventHandler LostMouseCapture; bool IsMouseCaptured { get; } bool CaptureMouse(); void ReleaseMouseCapture(); event MouseEventHandler MouseHover; event MouseWheelEventHandler MouseWheel; // Keyboard event KeyEventHandler KeyDown; event KeyEventHandler KeyUp; event TextInputEventHandler TextInput; bool IsFocused { get; } bool Focus(); event FocusChangedEventHandler GotFocus; event FocusChangedEventHandler LostFocus; bool Focusable { get; set; } bool IsFocusWithin { get; } bool KeyboardActive { get; set; } bool IsEnabled { get; } }
In addition, the Mouse and Keyboard classes provide:
class Keyboard { static Element Focused { get; } static bool Focus(Element elt) static ModifierKeys Modifiers { get; } static bool IsKeyDown(Key key) static bool IsKeyUp(Key key) static bool IsKeyToggled(Key key) static KeyState GetKeyState(Key key) static KeyboardDevice PrimaryDevice { get; } } class Mouse { static Element DirectlyOver { get; } static Element Captured { get; } static bool Capture(Element elt); static Cursor OverrideCursor { get; set; } static bool SetCursor(Cursor cursor); static MouseButtonState LeftButton { get; } static MouseButtonState RightButton { get; } static MouseButtonState MiddleButton { get; } static MouseButtonState XButton1 { get; } static MouseButtonState XButton2 { get; } static Point GetPosition(Element relativeTo); static void Synchronize(bool force); static MouseDevice PrimaryDevice { get; } static void AddAnyButtonDown(Element element, MouseButtonEventHandler handler); static void RemoveAnyButtonDown(Element element, MouseButtonEventHandler handler); }
Avalon also has integrated support for the stylus. The stylus is pen input, made popular by the Tablet PC. Avalon applications can treat the stylus as a mouse, using mouse APIs. But Avalon also exposes stylus APIs on par with keyboard and mouse:
// stylus APIs on Element event StylusEventHandler StylusDown; event StylusEventHandler StylusUp; event StylusEventHandler StylusMove; event StylusEventHandler StylusInAirMove; bool IsStylusOver { get; } bool IsStylusDirectlyOver { get; } event StylusEventHandler StylusEnter; event StylusEventHandler StylusLeave; event StylusEventHandler StylusInRange; event StylusEventHandler StylusOutOfRange; event StylusSystemGestureEventHandler StylusSystemGesture; event StylusEventHandler GotStylusCapture; event StylusEventHandler LostStylusCapture; bool IsStylusCaptured { get; } bool CaptureStylus() void ReleaseStylusCapture()
The stylus is also capable of acting as a mouse, so applications that only recognize mice automatically get some level of stylus support. When the stylus is used in such a manner, the application first gets the appropriate stylus event, and then it gets the corresponding mouse event—we say that the stylus event gets promoted to a mouse event. (I briefly discuss the concept of promotion in Adding New Kinds of Devices.)
Additional, higher-level services such as inking are also available, although they are beyond the scope of this paper.
Input in a Tree
Elements contain other elements (its children), forming a tree of elements, typically several layers deep. In Avalon, the parent element can always participate in input directed to its child elements (or grandchild elements, etc). This is particularly useful for control composition, the building of controls out of smaller controls.
Avalon uses event routing to give notifications to parent elements. Routing is the process of delivering events to multiple elements, until one of them marks the event as handled. Events use one of three routing mechanisms—direct-only (also known as "no routing"), tunneling, and bubbling. Direct-only means only the target element is notified, and is what Windows Forms and other .NET libraries use. Bubbling works up the element tree. first notifying the target element, then the target's parent, then the parent's parent, and so on. Tunneling is the opposite process—starting at the root of the element tree and working down, ending with the target element.
Avalon input events generally come in pairs—a tunneling event followed by a bubbling event. For instance, PreviewMouseMove is the tunneling event that goes with the bubbling MouseMove event. As an example, suppose in the following tree "leaf element #2" is the target of MouseDown/PreviewMouseDown:
The order of event processing will be:
- PreviewMouseDown (tunnel) on root element
- PreviewMouseDown (tunnel) on intermediate element #1
- PreviewMouseDown (tunnel) on leaf element #2
- MouseDown (bubble) on leaf element #2
- MouseDown (bubble) on intermediate element #1
- MouseDown (bubble) on root element
Here is a list of Preview input events on Element:
// Preview events on Element event MouseButtonEventHandler PreviewMouseLeftButtonDown; event MouseButtonEventHandler PreviewMouseLeftButtonUp; event MouseButtonEventHandler PreviewMouseRightButtonDown; event MouseButtonEventHandler PreviewMouseRightButtonUp; event MouseEventHandler PreviewMouseMove; event MouseWheelEventHandler PreviewMouseWheel; event MouseEventHandler PreviewMouseHover; event MouseEventHandler PreviewMouseEnter; event MouseEventHandler PreviewMouseLeave; event KeyEventHandler PreviewKeyDown; event KeyEventHandler PreviewKeyUp; event FocusChangedEventHandler PreviewGotFocus; event FocusChangedEventHandler PreviewLostFocus; event TextInputEventHandler PreviewTextInput; event StylusEventHandler PreviewStylusDown; event StylusEventHandler PreviewStylusUp; event StylusEventHandler PreviewStylusMove; event StylusEventHandler PreviewStylusInAirMove; event StylusEventHandler PreviewStylusEnter; event StylusEventHandler PreviewStylusLeave; event StylusEventHandler PreviewStylusInRange; event StylusEventHandler PreviewStylusOutOfRange; event StylusSystemGestureEventHandler PreviewStylusSystemGesture;
Usually, after the event is marked handled, further handlers are not invoked. However, when you create a handler, you can ask that it receives handled events as well as unhandled ones by using the AddHandler method (pass "true" for the handledEventsToo parameter).
Because of tunneling and bubbling, parents will receive events originally targeted to their children. Usually, it's not important who the target was—after all, the event is unhandled. But when it is important to know (particularly MouseEnter/MouseLeave and GotFocus/LostFocus), InputEventArgs.Source will tell you.
Another interesting issue is coordinate spaces. Coordinate (0,0) is the upper left, but the upper left of what—the element that is the input target, the element you attached your event handler to, or something else? To avoid confusion, Avalon input APIs require you to specify your frame of reference when dealing with coordinates. For example, MouseEventArgs.GetPosition method takes an Element as a parameter, and the (0,0) coordinate returned by GetPosition is the upper left corner of that element.
Text Input
The TextInput event allows a component or application to listen for text input in a device-independent fashion. The keyboard is the primary means of TextInput, but speech, handwriting, and other input devices can generate TextInput.
For keyboard input, Avalon will first send the appropriate KeyDown/KeyUp events, and if those are not handled and the key is textual, then a TextInput event. There's not always a simple one-to-one mapping between KeyDown/KeyUp and TextInput events—multiple keystrokes can generate a single character of TextInput, and single keystrokes can generate multicharacter strings. This is particularly true for Chinese, Japanese, and Korean, which use Input Method Editors (IMEs) to generate the thousands of different characters in the alphabet.
When Avalon sends a KeyDown/KeyUp event, if the keystrokes could become part of a TextInput event, KeyEventArgs.Key will be set to Key.TextInput, so applications don't accidentally process keystrokes that are part of larger TextInput. In these cases, KeyEventArgs.TextInputKey will reveal the real keystroke. Similarly, if an IME is active, KeyEventArgs.Key will be Key.ImeProcessed, and KeyEventArgs.ImeProcessedKey will give the actual keystroke.
Keyboard Sample
Let's take a simple example where pressing CTRL+O opens a file (no matter what control has focus), and pressing the Open button also performs that action:
In Win32, one would define an accelerator table, and handle WM_COMMAND, usually with a switch statement. (You could try to instead handle WM_KEYDOWN inside the window's WndProc, but unless you also modified the button and edit box's WndProc, you'd only get keystrokes if focus wasn't on the button or edit box.)
// sample.rc … IDC_INPUTSAMPLE2 ACCELERATORS BEGIN "O", ID_ACCELERATOR_O, VIRTKEY, CONTROL, NOINVERT END // sample.cpp … int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { . . . MyRegisterClass(hInstance); InitInstance(hInstance, nCmdShow); HACCEL hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_INPUTSAMPLE2); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(window, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } ATODWM MyRegisterClass(HINSTANCE hInstance) { . . . } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { window = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!window) { return FALSE; } button = CreateWindow("BUTTON", "Open", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 40, 40, 90, 30, window, (HMENU) ID_BUTTON, hInstance, NULL); if (!button) { return FALSE; } DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_NOHIDESEL | ES_AUTOHSCROLL | ES_AUTOVSCROLL; edit = CreateWindow("EDIT", "...", dwStyle, 40, 80, 150, 40, window, (HMENU) 6, hInstance, NULL); ShowWindow(window, nCmdShow); UpdateWindow(window); return TRUE; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: { switch (LOWORD(wParam)) { case ID_ACCELERATOR_O: case ID_BUTTON: MessageBox(NULL, "Pretend this opens a file", "", 0); return 0; } break; } case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, message, wParam, lParam); }
In Windows Forms, one would set KeyPreview on the form to true, and handle the KeyDown event on the form:
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; public class Form1 : Form { static void Main() { Application.Run(new Form1()); } private Button button1; private TextBox textBox1; public Form1() { this.button1 = new Button(); this.textBox1 = new TextBox(); this.SuspendLayout(); // // button1 // this.button1.Location = new Point(8, 40); this.button1.Name = "button1"; this.button1.TabIndex = 0; this.button1.Text = "Open"; this.button1.Click += new EventHandler(this.button1_Click); // // textBox1 // this.textBox1.Location = new Point(8, 88); this.textBox1.Name = "textBox1"; this.textBox1.TabIndex = 1; this.textBox1.Text = "..."; // // Form1 // this.AutoScaleBaseSize = new Size(6, 15); this.ClientSize = new System.Drawing.Size(292, 260); this.Controls.AddRange(new Control[] { this.textBox1, this.button1}); this.Name = "Form1"; this.Text = "Input Sample"; this.KeyPreview = true; this.KeyDown += new KeyEventHandler(this.Form1_KeyDown); this.ResumeLayout(false); } private void button1_Click(object sender, EventArgs e) { handle(); } private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.O && e.Modifiers == Keys.Control) { handle(); e.Handled = true; } } void handle() { MessageBox.Show("Pretend this opens a file"); } }
In Avalon, one would define a handler for the Button's Click event (btn_Click), and a handler for KeyDown (fp_KeyDown):
<Window xmlns="" xmlns: <FlowPanel KeyDown="fp_KeyDown"> <Button Click="btn_Click"> Open </Button> <TextBox> ... </TextBox> <def:Code> <![CDATA[ void fp_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.O && Keyboard.Modifiers == ModifierKeys.Control) { handle(); e.Handled = true; } } void btn_Click(object sender, ClickEventArgs e) { handle(); e.Handled = true; } void handle() { MessageBox.Show("Pretend this opens a file"); } ]]> </def:Code> </FlowPanel> </Window>
Note that the KeyDown handler is attached to the FlowPanel near the root of the tree. (We use FlowPanel instead of Window because the Window class doesn't get input.) Because input bubbles up the tree, the FlowPanel will get the input no matter which element has focus.
The examples differ in one subtle point—suppose the edit control wants to handle CTRL+O? In the Win32 and Windows Forms samples, the edit control never receives a WM_KEYDOWN or equivalent notification, because the event is handled in the message loop by way of TranslateAccelerator. In the Avalon sample, the TextBox control is notified first, and our fp_KeyDown handler is called only if the TextBox didn't handle the input. Or, we could handle PreviewKeyDown instead of KeyDown, in which case our fp_KeyDown handler will be called first.
In the Avalon example above, we ended up writing handling logic twice—once for CTRL+O, and a second time for the button click. We can simplify this using Avalon commands.
Commands
Note Commands are only partially implemented in the PDC 2003 Longhorn prerelease build.
Commands allow you to handle input at a more semantic level than device input. Commands are simple directives, like "cut," "copy," "paste," or "open." Avalon will provide a library of common commands, but you can also define your own.
Commands are useful for centralizing your handling logic. The same command might be accessible from a menu, on a toolbar, or through a keyboard shortcut, and by using commands you write a single piece of code that works for all the different input cases. Commands also provide a mechanism for graying out menu items and toolbar buttons when the command becomes unavailable.
The common commands provided by Avalon come with a set of default input bindings built in, so when you specify that your application handles Copy, you automatically get the CTRL+C = Copy binding. You also get bindings for other input devices, such as Tablet pen gestures and speech information. Finally, many of the common commands come with their own icons, making toolbars look more consistent and professional.
Many controls have built-in support for certain commands. For example, TextBox understands Cut, Copy, and Paste. And since each of those commands provides the default key binding, TextBox automatically supports those shortcuts.
Input Core Architecture
The input system consists of both kernel-mode and user-mode pieces. Input originates in a device driver, which for most input devices is then sent to win32k.sys, the kernel-mode component of USER and GDI. Win32k.sys does some processing on the input and decides which application process to send the input to. Inside a Longhorn application, Avalon performs further processing on the input and sends notifications to the application.
Like Win32 programs, Avalon programs have a message loop that polls the external world for new notifications. Avalon can integrate with a standard Win32 message loop, which is connected with the rest of Avalon through a dispatcher. The dispatcher abstracts details of the specific loop, as well as providing services for dealing with nested message loops. To receive messages from Win32, Avalon has an hwnd known as the HwndSource. Message processing is synchronous—the HwndSource WndProc doesn't return until Avalon has fully processed the input message. This enables integration with Win32 in cases where WndProc is expected to return a value.
Inside a Longhorn application, input processing looks like this:
To the core input system (represented by the gray boxes), input begins when an IInputProvider notifies its corresponding InputProviderSite about available input report. The site tells the InputManager, which puts the input report in the staging area. Various monitors and filters are then run over the staging area, turning the input report into a series of events. Finally, the events are routed through the element tree and handlers are invoked.
The input providers for the keyboard and mouse get their input from Win32 USER by way of the HwndSource (not pictured). Other devices can choose to do the same, or can choose an entirely different mechanism. Stylus is an example of input that did not come from the HwndSource—the input provider for stylus gets its input from wisptis.exe, which in turn talks to the device driver throughHID (Human Interface Device API). InputManager provides APIs for registering new input providers.
A filter is any code that listens to the InputManager.PreProcessInput or InputManager.PostProcessInput events. Filters can modify the staging area. Canceling PreProcessInput will remove the input event from the staging area. PostProcessInput exposes the staging area as a stack—items can be popped off or pushed to the top of the staging area.
A monitor is any code that listens to InputManager.PreNotifyInput or InputManager.PostNotifyInput. Monitors cannot modify the staging area.
Adding New Kinds of Devices
Note We are in the early stages of designing the features discussed in this section, and appreciate your feedback. Listed below are some of the scenarios that enable device extensibility:
- Adding new keys to keyboards, adding buttons to mice
- Adding new kinds of devices that expose an API to applications
- Adding new kinds of devices that emulate existing devices (usually mouse and keyboard)
- Adding new kinds of devices that both expose an API and emulate existing devices, for compatibility with applications that don't understand that type of device
- Using HID to add new devices or device functionality
- Enabling applications using HID to get lower-level "raw" input
- Enabling globally binding input sequences to actions; for example, the "mail" key will launch an e-mail program (including scenarios where the foreground application doesn't understand the mail key)
Conclusion
Avalon gives full access to the mouse, keyboard, and stylus, while providing higher-level services for text input and commands.
|
https://msdn.microsoft.com/en-us/library/aa480167.aspx
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
Add an Alias (CNAME) Resource Record to a Zone
Applies To: Windows Server 2008, Windows Server 2008 R2 server-1, for the server computer that hosts these services.
Membership in the Administrators group, or equivalent, is the minimum required to complete this procedure. Review details about using the appropriate accounts and group memberships at.
Adding an alias (CNAME) resource record to a zone
Open DNS Manager.
In the console tree, right-click the applicable forward lookup zone, and then click New Alias.
In Alias name, type the alias name.
In Fully qualified domain name (FQDN) for target host, type the FQDN of the DNS host computer for which this alias is to be used.
As an option, you can click Browse to search the DNS namespace for hosts in this domain that have host (A) resource records already defined.
Click OK to add the new record to the zone..
|
https://technet.microsoft.com/library/cc772053.aspx
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
Your answer is one click away!
I have a very simple Java class, that does nothing else but:
public class TestMain { public static void main(String[] args) { System.out.println("Running!"); System.exit(1111); } }
, packed into a
TestOSX.jar file.
While on Windows I can run the above snippet and show that
%ERRORLEVEL% has the expected value, I get a different outcome on OS X.
Given
test.sh containing:
#!/bin/bash "/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java" -jar TestOSX.jar wait $! updater_exit_val=$? echo $updater_evit_val
, I always print 0.
Setup: OS X 10.11.1, Oracle Java 8 u60.
What trivial detail am I missing here?
You do not send your java process to the background with
&. Thus
wait is executed after the java process exits. It can't find the process you try to wait for, because it already exited and giving return code 0 because of that.
$? returns the return code of the last command (in your case
wait).
You can either remove wait from your script, or you send your java process to the background by adding
& at the end.
|
http://www.devsplanet.com/question/35282281
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
Right??
Sometimes both are overkill, and we're not doing anyone a favor by over-architecting a solution. Providing a bigger solution than is needed wastes time and money, increases complexity and maintenance costs, and more importantly, doesn't provide any extra value to our users.
The de facto approach for application data storage is to use a dedicated database product, for (mostly) good reasons. However, since we're all well aware of the benefits of using a database, let's take some time to explore the filesystem as a candidate for storing your data.
File writes are atomic
To be more precise, file rename operations are atomic on POSIX systems, according to the Python documentation. Sorry Windows users, you're out of luck.
os.rename(src, dst)
Rename the file or directory src to dst....
To perform atomic file writes, you must first write your changes to a temporary file, then rename the temporary file to it's final destination. Sounds harder than it really is. The code would look something like this:
import osf = open('temp.txt', 'w')f.write('do the monkey')f.close()os.rename('temp.txt', 'final.txt')
The filesystem is reliable
You'd better hope so anyway, everything ultimately lives on the filesystem, including, yes, that fancy and expensive relational database.
Backups
Storing data in files allow you to use standard filesystem-based backup solutions. In addition, many filesystems have snapshot features built in.
Instant API using a web server, or even WebDAV
I suggest storing your data in a document-oriented fashion. That is, store your data using a single file per entity. If you're storing data about 6 different users, then that should be 6 different files. This will greatly simplify things, and allow you to expose this data via an HTTP API.
If you follow this advice, you can simply point your favorite web server at your filesystem and you immediately have an API. Requesting data from this API couldn't be simpler, and may look like this:
Enable more features on your webserver, such as PUT, or even WebDAV, and you now have a read+write API.
The filesystem scales (probably)
I currently have 454,823 files on my computer consuming ~140GB. I don't know if there is a practical limit to filesystem storage, but I'm willing to bet that you and I aren't going to reach it.
Files work with the network
Everybody's doing it
Subversion does it. Oracle does it.
--
The relational databases and NoSQL data stores will still be there, waiting for you if you need them in the future. My advice? Ignore your DBA. Drop acid and think about data.
|
http://www.matthanger.net/2010/07/storing-data-on-filesystem-with-touch.html
|
CC-MAIN-2017-22
|
en
|
refinedweb
|
Type: Posts; User: Chris ZANARDI
Yes, it's the problem.
What I do now is I keep my exe alive as long as my AUDROS application is alive. So the icons stay correct.
Thanks.
hi gurus
I try to make an exe to change the icon of a window of an other application.
here my code :
#include "stdafx.h"
#include <winbase.h>
#include <windows.h>
Hi Gurus
I'trying to make an exe to change the icon of the window of an other application.
Here my code :
#include "stdafx.h"
#include <winbase.h>
#include <windows.h>
Thank you, Craig
Your way was the good one. In fact, I reach my goal using :
Me.Context.Response.Buffer = False
Me.Context.Response.Cache.SetExpires(Now())
With these to line, I go...
Hello All,
I would like to trap the event that occurs when the user clicks on the REFRESH BUTTON in my webform1.aspx.vb
Any idea ?
Yeeeesssss !!! I display succesfully the form. But one problem back, ten problems front (don't know if it's really correct)
The new problem is that it's know impossible to interract with the form,...
Sorry but it is still not working
I join a screen copy to show u
Well, I don't understand what you mean with 'not using correct version of ocx ' coz if I see in the html page the pink rectangle with the button...
OK, can you try on your computer this example :...
Very interresting subject.
I tried your project and it works fine. But if :
- I build the project1.ocx
- Register the test1.ocx using regsvr32
- Edit an html page to loag the ocx
When load the...
Hello All,
I am actually doing a library of subs and functions that will be use by collegues in the office.
I would like to describe, when usefull, the list of possible values available for...
Hello all
It is possible so set the style of the html tag INPUT in a style sheet (.css) and my question is :
Is it possible to set the style of the html tag INPUT only when the type of the...
Thank you for your interset, Andy, but the code you send me is not exactly what I need : you just switch the key and text values, but the job is not done on the children of the node you move. Your...
This is at runtime. I want for example :
1 - user select a node
2 - hit a button UP or DOWN
==> The node goes up or down until it reach the first or the last position of its current level
Hello All,
Does anybody know how to move a node up or down in a treeview ctrl, in a same level.
Say in other words, moving a node before its upper brother or after its lower brother
changing...
|
http://forums.codeguru.com/search.php?s=30c088d9f4e788c144588528ae9c8ab2&searchid=7002865
|
CC-MAIN-2015-22
|
en
|
refinedweb
|
Details
- Type:
Bug
- Status:
Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 1.8.4
- Fix Version/s: 1.8.6, 2.0-beta-3
- Component/s: parser-antlr
- Labels:None
- Number of attachments :
Description
Take this code and put it into the groovy console:
def meth() { label: assert i == 9 }
Now inspect the AST and navigate to the assert statement. You will see that the assert statement has a lineNumber and lastLineNumber are 2, but it should be 3. This is incorrect. It doesn't seem like this affects Groovy itself too much, but this is causing an exception in Groovy-Eclipse. See
GRECLIPSE-1270.
The fix is simple enough.
Issue Links
- is related to
GRECLIPSE-1270 IndexOutOfBoundsException with assert keyword in Spock test
Activity
Proposed patch - a slight variation of what Andrew proposed. The code for the statement method is a little strange in that despite each branch of the switch deriving the respective source positioning depending on the particular branch chosen, it then overrides that information with the information for the entire node. The more refined info is useful in other contexts.
I guess the patch is ok then
Well, it is more of a philosophical decision I think. At the statement level, we tend to keep track of the whitespace around the statement. Here we would not be doing this. There are no LineColumn checks that test this area. There is only a very minimal SourcePrinter test. I will do another sanity check with some more elaborate SourcePrinter tests before applying the patch. The alternative is that we need to document that any statement may contain a label and it would be up to other tools, e.g. CodeNarc etc. to step around the label. We could provide a utility to make it easier I guess.
From the tooling perspective, including whitespace in AST nodes is problematic (specifically in expression nodes and too a lesser extent in statement nodes). There are many situations where trailing whitespace must be worked around.
When there is an easy fix, I patch the groovy compiler and try to send you guys a patch, but often I need some hairy workaround code in Groovy-Eclipse.
Is there a reason why many AST nodes keep trailing whitespace? Or is this largely legacy? (From my investigations, it seems to be built into the parser.)
I think it is mainly because it is not easy to tell the grammar to not to include the whitespace and since we didn't really need that information to a level where trailing whitespace matters, we simply didn't put in the energy to prevent that from happening.
Patch applied - I tried playing around with different source texts to confuse the SourcePrinterTests but could't spot any obvious breakages.
Fix: in org.codehaus.groovy.antlr.AntlrParserPlugin.statement(AST) at the end of the method, change:
to:
This problem is coming about because the source location of statement is being set twice: once from within the call to labeledStatment using the correct source location and once again using the source location for just the label in the call to statement.
This leads me to question if explicitly calling configureAST is necessary at all in the statement method since all calls to create the different kinds of statements already call configureAST.
|
http://jira.codehaus.org/browse/GROOVY-5197?focusedCommentId=287029&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
|
CC-MAIN-2015-22
|
en
|
refinedweb
|
"
EBOs evolve over multiple generations as you add, remove, or change the semantics or characteristics of content. The primary reasons for changes in EBOs are:
Product enhancements
Bug fixes
Adoption of new technologies and language enhancements
Each EBO in the library has its own release life cycle, so each object has its own version number. EBO version numbers are independent of participating application release numbers. New releases of participating applications do not necessarily result in new EBO versions.
The version number consists of the major and minor version numbers.
The following changes, which may break EBO backward compatibility, require a new major version number:
Changing the meaning or semantics of existing components
Adding required components
Removing required components
Restricting the content model of a component, such as changing a choice to a sequence
Changing the type of an element or attribute
The following changes require a new minor version number: type of change, not the size, determines whether a new version is major or minor. A small change warrants a major version change if it breaks backward compatibility. Similarly, enormous changes may result in a minor version change if backward compatibility is not broken.
The Enterprise Object Library contains all major versions of every EBO, but only the latest minor versions within the major versions. Hence, the schema file in the folder for the major version always contains the latest minor version.
Consumer applications that depend on an earlier major release might need to be modified to work with the new release. For example, an application written against version 1.0 works when targeted against versions 1.1 and 1.2, but may fail if moved to version 2.0 of the EBO unless modified.
Because Oracle AIA uses a service-oriented architecture for request/response interaction, backward and forward compatibility surface at the same time. An upgraded provider application must be backward compatible to understand requests from older requesters. Similarly, requesters must be forward compatible to recognize the responses of the provider application. Compatibility in both directions, at least among minor versions, ensures independence of providers and requesters.
The architecture does not mandate (in most situations) concurrent upgrade of the requester and provider, so additional XML message transformations between older and newer major versions are required. In some cases, these transformations may not be technically feasible or may not make functional sense. In these situations, the applications receiving the messages cause an irrecoverable error.
The schema declaration version attribute in the XML schema and a required custom attribute in the XML instance document identify the schema version. An XML instance specifies its namespace and minor version. The XML instance does not use the schemaLocation attribute. The XML instance documents provide the schemaVersion attribute on the top-level Enterprise Business Message (EBM) element. For example:
<GetAccount ... ... </GetAccount>
Each EBO has its own namespace. This minimizes duplication of names and allows each business object to have its own release cycle. The namespace uses the following format:[object name]/v[version number]
The namespace name is the same across multiple minor and major versions and is changed only when a schemas undergoes major architectural changes. Introducing backward-incompatible changes alone does not warrant namespace changes.
Here is a sample namespace:
The innermost layer of the Enterprise Objects Library is a set of namespaces that contain constructs commonly used throughout the library. Some namespaces include core component types, business datatypes, and core datatypes. In earlier releases, only one namespace held all common components and reference components.
Second-layer namespaces import the innermost layer namespaces. Each second-layer namespace has declarations that are specific to a business process or functional area. For example, the PurchaseOrder namespace contains all documents used for placing a purchase order.
In addition, customer-specific namespaces house customer-specific extensions.
When the innermost layer namespaces are versioned, the next layer namespaces are also versioned if they use the new common constructs. However, the reverse is not true: versioning the second-layer namespaces does not require versioning the innermost layer namespaces. The innermost layer does not import the functional layer-specific namespaces.
Enterprise Business Services (EBSs) evolve over multiple generations as you change the interface definition or the implementation. When a change affects the contract the consumer relies upon, it leads to the creation of a new service version.
Oracle AIA facilitates the co-location of multiple EBS implementations with identifiable versions. This allows consumers to use the service version they need. A new version does not force consumers to switch to the latest version immediately. Figure 7-1 is an illustrates versioning.
This section discusses naming conventions only with respect to versioning.
Similar to EBOs, each EBS in the library has its own release life cycle and each service its own version number. The first service version does not have a number. The default value is 1.0. Subsequent versions have numbers affixed to the name of the service. EBS version numbers are independent of participating application release numbers. New releases of participating applications do not necessarily result in new EBS versions.
Participating applications in both requester and provider roles also evolve. New application versions can introduce enhancements to underlying connecting technologies or web services standards. Changing the connectivity/transport protocol, web service definitions, or payloads of Application Business Connector Services (ABCSs) specific to participating applications does not affect integrations.
|
http://docs.oracle.com/cd/E28280_01/doc.1111/e17363/chapter07.htm
|
CC-MAIN-2015-22
|
en
|
refinedweb
|
[ Link to First Tutorial ]
While there is much you can “pick up as you go” if you are an Objective-C programmer, understanding some of the fundamental differences in C# can save you a great deal of time and confusion. But programming Windows Phone 7 involves two languages, C# and Xaml, and fully grokking Xaml and the relationship between the declarative Xaml and the object-oriented C# takes some getting used to.
Let’s begin with Xaml, which is an XML compliant declarative language that has two key advantages for Phone Developers:
- Objects are created at design time, rather than at run time
- Xaml is highly machine readable, and so you can, for example, use the exact same files in both Visual Studio and Expression Blend
Xaml Objects are CLR Objects
While Xaml allows you to declare your objects at design time, by the time they are instantiated at run time they are indistinguishable from run-time objects. That is, a TextBlock created in Xaml and a TextBlock created in code are identical in the underlying .xap file
Let’s examine this idea that you can create the same object in either Xaml or in C#. We’ll start by creating a new Windows Phone Application named XamlDemoAndMore. We’ll give the ContentGrid six rows,
<Grid x: <Grid.RowDefinitions> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> </Grid.RowDefinitions>
Now let’s add a TextBlock to the first row by declaring it in the Xaml,
<TextBlock Text="Created In Xaml" HorizontalAlignment="Center" VerticalAlignment="Center" Grid. </Grid>
I got a little fancy with my TextBlock (adding the FontFamily and FontSize) so that we can see what that looks like when created in C#. To do this, open MainPage.xaml.cs (the code-behind page) and we’ll add a second TextBlock dynamically,
using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Microsoft.Phone.Controls; namespace XamlDemoAndMore { public partial class MainPage : PhoneApplicationPage { public MainPage() { InitializeComponent(); var newTextBlock = new TextBlock { Text = @"Created in C# in my \Source directory", HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Stretch, FontFamily = new FontFamily( "Georgia" ), FontSize = 24 }; ContentGrid.Children.Add(newTextBlock); Grid.SetRow( newTextBlock, 1 ); } } }
The first four lines are using statements, which include the namespaces needed to use various objects such as the TextBlock, Grid, etc.
Notice that the class MainPage has the keyword partial. This indicates that some of the declaration of the class was created elsewhere; which indeed it was. Visual Studio has created another part of the class declaration for MainPage on your behalf. In fact, it has also declared that MainPage derives from PhoneApplicationPage, so you can safely remove the colon and the base class declaration as redundant, though I suspect Visual Studio adds it there both as documentation and as instructional.
The first method we see has no return value, and so we know it is a constructor. In this case, the constructor uses initialization to declare values for all the properties (within the body of the constructor). An alternative is to create an empty TextBlock and then set its properties individually,
var newTextBlock = new TextBlock(); newTextBlock.Text = @"Created in C# in my \Source Directory"; newTextBlock.HorizontalAlignment = HorizontalAlignment.Center;
Notice that the new TextBlock is identified with the keyword var – this provides a flexible but type safe declaration. The type of newTextBlock is not var; once the assignment is made the type is whatever type you’ve assigned to it (in this case TextBlock).
The last two lines assign the new TextBlock to the Grid (more exactly, to the Children Collection of the grid) and set which row within the grid the TextBlock will appear.
Notice the at-sign before the static text. This does not distinguish an NSString, but rather creates a verbatim string, which changes the back-slash from an escape character to a literal. If you remove the @-sign you must escape the backslash like this:
newTextBlock.Text = "Created in C# in my \\Source Directory";
You Can But You Don’t
While you can create any object dynamically, typically you don’t. Instead you declare the object in Xaml, giving you design time checking and machine readability. Typically you only use dynamic creation in C# when you must, for example when you can’t know until run time which type you’ll create.
The Customer Class
Let’s return to the Customer Class we’ve seen in previous tutorials, and build it up step by step. We begin with a simple class to track the name and address of a customer. To do this, we’ll use:
- Member variables (fields)
- Member properties
- Member methods (functions)
A Demo Project
We need a project in which we can work with simple values and display the results. Create a new Windows Phone 7 application and in MainPage.xaml add the following to the Content Grid,
<Grid x: <Grid.RowDefinitions> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> </Grid.RowDefinitions> <TextBlock Name="Answer1" Grid. <TextBlock Name="Answer2" Grid. <TextBlock Name="Answer3" Grid. <TextBlock Name="Answer4" Grid. <TextBlock Name="Answer5" Grid. <TextBlock Name="Answer6" Grid. <TextBlock Name="Answer7" Grid. </Grid>
Fields and Properties
The classic way to create fields and properties is to make the field private and the property public.
public class Customer { private string _firstName; public string FirstName { get { return _firstName; } set { _firstName = value; } } }
It is very common to create a backing variable (_firstName) and then getters and setters that take no action except to return or set the backing variable. In this case, C# offers the faster and simpler alternative of automatic properties. Thus, you could rewrite the six lines of code above in a single line:
public string FirstName { get; set; }
Methods
Methods are declared within the body of the class definition (remember, there are no header files in C#). They default to private (though it is good practice to mark private methods explicitly). Methods return a value (or void) and have a signature. A method’s signature is the method name plus its parameters.
Constructors
Constructors are responsible for creating an instance of a class, and are the only methods that do not have a return value (nor are they marked void).
public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public Customer (string first, string last, string address) { FirstName = first; LastName = last; Address = address; } }
Default Constructor
There is a special constructor, called a default constructor that does not take any parameters. It is typically used to provide default values for one or more properties or fields,
public Customer() { FirstName = string.Empty; LastName = string.Empty; Address = string.Empty; }
The name default constructor causes untold confusion, because of the Miranda Rule which states that if you do not have a constructor, one will be provided for you. The constructor that is provided for you is a default constructor that does nothing, exactly as if you had written,
public Customer() { }
The fact that a default constructor is provided “by default” is the cause of the confusion; but the name implies no parameters, not that it is provided for you. Note also that if you do provide a constructor and also want a default constructor, you must create one explicitly. This is perfectly legal, in C# you can have two methods with the same name (called method-overloading) as long as their parameter list differs in number
foo (int); foo (int, int);
or the parameter list differs in type
foo (int); foo (int, int); foo (string); foo (int, int, string);
Thus, you might have,
public Customer() { FirstName = string.Empty; LastName = string.Empty; Address = string.Empty; } public Customer (string first, string last, string address) { FirstName = first; LastName = last; Address = address; }
Non-constructor methods work the same way except that they need to have a return value. What matters to C# is that the signatures (name and parameter list) are different, and since the signature does not include the return type you are free to vary the return type as well.
public Double Doubler(Double val) { return val * 2; } public int Doubler (int val) { return val * 2; }
Because the parameter differs in type (Double vs. int) the methods can be overloaded, and overloaded methods can have different return values (Double and int respectively in this case).
Returning Values
In C#, as in Objective-C there are two ways to return values; either in the return statement or by passing in a parameter. Since parameters are passed by reference, this is very easy to work with. In MainPage.xaml instantiate a Customer and invoke each of the Doubler methods,
public MainPage()
{
InitializeComponent();
var cust = new Customer();
var i1 = 5;
var d1 = 20.5d;
var d2 = 35.7d;
int intAnswer1;
Double doubleAnswer1;
Double doubleAnswer2;
intAnswer1 = cust.Doubler( i1 );
Answer1.Text = “Doubler(i1) = ” + intAnswer1;
doubleAnswer1 = cust.Doubler( d1 );
Answer2.Text = “Doubler(d1) = ” + doubleAnswer1;
// cust.Doubler( d2, doubleAnswer2 );
// Answer3.Text = “Doubler(d2,doubleAnswer2) = ”
+ doubleAnswer2;
}
The results are just as expected, but uncommenting the third example (in which we pass in DoubleAnswer2) will cause a compile error. This is because DoubleAnswer2 has not been initialized, and C# requires definite assignment – that is, you must assign a value to a variable before “using” it, such as passing it as a parameter. It is silly, however, to assign a value to this variable (e.g., Answer3 = 0.0) because we’re just going to change the value in the method. C# solves this with the keyword out, which you put on both the call and the called method,
cust.Doubler(d2, out doubleAnswer2); Answer3.Text = "Doubler(d2,doubleAnswer2) = " + doubleAnswer2.ToString(); // .... public void Doubler(Double val, out Double answer) { answer = val * 2; }
Typically you would use the out parameter when you either have two or more values to retrieve or you wish to use the return value for a flag (e.g., a boolean) and the out parameter for the returned value.
Object Initializers
If you have a default constructor and public “setter” properties, there are three ways to initialize the values in your object:
- The Constructor
- The default constructor and explicit assignment
- The default constructor and object initializaton
var customer1 = new Customer( "George", "Washington", "Capitol NYC" ); var customer2 = new Customer(); customer2.FirstName = "George"; customer2.LastName = "Washington"; customer2.Address = "Capitol, NYC"; var customer3 = new Customer { FirstName = "George", LastName = "Washington", Address = "Capitol, NYC" };
You can prove to yourself that these have the same effect with these three lines of code,
Answer4.Text = customer1.FirstName + " " + customer1.LastName + " " + customer1.Address; Answer5.Text = customer2.FirstName + " " + customer2.LastName + " " + customer2.Address; Answer6.Text = customer3.FirstName + " " + customer3.LastName + " " + customer3.Address;
Memory Management
As is often mentioned, C# does not use pointers. Well, you can, but again, you don’t. Every variable is a reference (with the exception of variables of built-in types such as int, double, etc.) . That parenthetical point is important, however, and was glossed over in the example above. Passing a Double in to a method to get a return value will not work unless you use one of two keywords out (as shown above) or ref – which indicates that the built-in type should be passed as a reference.
I felt safe in glossing over this due to definite assignment and because 99% of the time, from a practical standpoint, it doesn’t come up.
All objects (anything defined by a class) are automatically treated as references, and all objects are instantiated with the keyword new. You do not, normally, need to do anything to clean up after your objects; the garbage collector will take care of that for you (the exception to this rule is when you are working with unmanaged code, a topic obscure enough and unusual enough that you can safely ignore it for a very long time, until it bites you and then you can read all about it in an intermediate C# book).
For 99% of your work, you can just “new up” an object, use it, and then forget it, as we did with customers 1,2 and 3 above and as wel’ll see as we move forward with the customer class.
Object Oriented Programming
C#, like all object oriented languages, rests on three pillars:
- Encapsulation
- Polymorphism
- User Defined Types
Encapsulation is effected through the use of properties. A property looks to the consumer like a field, but to the creator like a method. This is nearly ideal.
As an example, let’s say we add a field to the Customer class discount, we want to raise a particular customer’s discount from 5% to 10%. We would start by adding a property to the Customer,
private double _discount = .05; public double Discount { get { return _discount; } set { _discount = value; } }
We can then iterate through the customers whose discount we wish to increase, and for a given customer we could write
cust Discount = .1;
thereby raising that customer’s discount to 10%. The key advantage of using a property here is that the code increasing the discount does not have direct access to the backing variable, and so if/when we move that to a database lookup, the client code does not break. In addition, we can change the setter function to do additional work,
public double Discount { get { return _discount; } set { _discount = value; UpdateDatabase(); if ( value > .15 ) AddCustomerToVIPList(); if ( value > .25 ) StartAudit( this ); } }
Again, the code setting the discount is fully unaware of these additional steps; to that code it looks like a field was set.
Note that the this reference passed in to the StartAudit method is a reference to the Customer, and so we can know that StartAudit will probably look like this
public void StartAudit(Customer theCust) { //.... }
Notice also that no special element is required to show that this is a reference (no * and no keyword ref) as objects are always passed by reference. Thus, changes made to theCust in StartAudit will affect the customer passed in from the setter in Discount.
Polymorphism
For most of your work in Windows Phone 7 programming you’ll be working with classes that already exist, and overriding their methods without having to first declare the method. Declaring an overridable method is trivial, however; you simply mark the method with the keyword virtual. Thus, you might add a CreditRating to your Customer class that uses a protected (visible to this class and classes derived from this class) method, LookUpCreditScore, which goes to an independent vendor to get a credit score.
protected virtual double LookUpCreditScore() { return 400.0d; } private double creditRating; public double CreditRating { get { return LookUpCreditScore(); } }
Keeping things simple, I just return a credit score of 400 for this demo. You might now create a class derived from Customer that overrides the virtual method LookUpCreditScore. To make it explicit that you intend to override (and not hide) this inherited method, you use the keyword override,
The derived type inherits all of the fields, properties, methods and events of the parent type, and is free, as we see here, to override methods to achieve different behavior. As you might expect, because a VIP is a Customer, you can use a reference to a VIP wherever a reference to a Customer is expected, and you will receive the overridden behavior.
Here is the code to test this.
In Customer.cs:
public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public Customer() { FirstName = string.Empty; LastName = string.Empty; Address = string.Empty; } public Customer(string first, string last, string address) { FirstName = first; LastName = last; Address = address; } protected virtual double LookUpCreditScore() { MessageBox.Show("In Customer"); return 400.0d; } private double creditRating; public double CreditRating { get { return LookUpCreditScore(); } } public class Vip : Customer { protected override double LookUpCreditScore() { MessageBox.Show( "In VIP!" ); double baseScore = base.LookUpCreditScore(); baseScore += 100.00; return baseScore; } } }
Notice that Vip is not only derived from Customer, it is nested within Customer. MainPage cannot invoke LookUpCreditScore directly as it is protected (private to the Customer class and classes that derive from it) but it can use the public property CreditRating,
public MainPage() { InitializeComponent(); cust = new Customer(); SomeMessage(); cust = new Customer.Vip(); SomeMessage(); } public void SomeMessage() { MessageBox.Show( "Customer credit rating is " + cust.CreditRating ); }
The result is that the first time SoemMessage is called, it is called on the Customer and you’ll see the messageBox from within Customer’s LookUpCreditScore and the second time it is called, it is called on the Vip derived class, and so you’ll see the messageBoxes from both Vip and from the base type Customer and the rating will be 500 rather than 400. (Remember that a derived type includes the base type.
Interfaces
As mentioned earlier, the keyword interface means something entirely different in C#; specifically it is a way to obtain the advantages of Multiple-inheritance without the complexity of M.I. (which C# does not support). An interface can be thought of as a mix-in or as a contract; either way, the interface author is saying “This is what you must have and do if you want to implement this interface” and the interface implementer is saying “I’ve fulfilled this contract and you can rely on that.”
It is easier to understand all of this by looking at an example. Let’s create an interface named IStorable, which assures that a class can be written to the disk and read from the disk (this is just an example, and not part of actually storing data to disk).
public interface IStorable { string Path { get; set; } void Write( string stringToWrite ); void Read( string stringToRead ); }
Notice that the interface tells you that there is a property Path with both a getter and a setter, but it does not implement either. Similarly it tells you there are Write and Read methods, and it tells you their signature and return type, but that is all it tells you. Also note that you do not put the accessibility in the interface (public, private, etc.).
If Customer wants its clients (classes that interact with Customer methods) to be able to rely on the fact that it supports this interface, it announces this by adding IStorable after the colon (and after base class declarations),
class Customer : IStorable
But having done so, it then is required to have the three elements of that interface,
public class Customer : IStorable { public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } private string _path; public string Path { get { return _path; } set { _path = value; } } public void Write(string writeMe) { //... } public void Read(string whatWasRead) { //.... }
The implementing class (Customer) does assign access labels (public, private, etc.) and must provide properties, methods and events that match the signature of the corresponding properties, methods and events in the interface.
Thus, the interface says “here’s the method you must have” and the implementing class provides the specific implementation of those elements. (Note that a second class implementing IStorable may very well implement Read and Write differently, though the methods will still have these same signatures).
Delegates and Events & MVVM v MVC
This tutorial is incomplete without a write up of Delegates and Events, as well as good coverage of MVVM, but these topics were covered in an earlier tutorial. In the spirit of never wasting your time, I’ll refer you to that tutorial, though I will mention that some iPhone developers find it helpful to approach delegates with reference to Objective-C selectors (the similarity is strong but not perfect).
We will return to MVVM in even greater detail in a coming tutorial.
Generics
While C# does support all of the standard C-style Arrays, it also has access to a set of type-safe collections in the Generics library. This allows you to have, for example, a type safe Dictionary in which you define that they key will be an integer (e.g., an ID) and the value will be a string. You can also freely define the key and/or the value to be more complex, user-defined types.
It is common in iPhone development to see a type-safe ObservableCollection that implements the interfaces INotifyCollectionChanged and INotifyPropertyChanged, as discussed in the previous tutorial.
Resources
No tutorial can cover a language as rich as C# in full, even with the understanding that you already know Objective-C. If you are interested in acquiring C# expertise, there are a number of excellent books, and the on-line documentation that comes with Visual Studio can also provide excellent help, as can any number of sites on the Web, especially Microsoft’s Visual C# Developer Center
Woah this weblog is excellent i like reading your posts. Keep up the great paintings! You realize, lots of people are hunting round for this information, you could help them greatly.
Help, vs2010 c# for windows phone, how to get pixel value R,G,B in jpg file.
Pingback: iPhone Developers? How to move to Windows Phone 7 | I Love Windows Phone!
good.
Nice tutorial. WP7 is going to still a cause a lot of headaches for developers. Isn’t the marketplace crowded enough?
|
http://jesseliberty.com/2010/09/18/iphone-to-windows-phone-7-tutorial-objective-c-c-xaml/
|
CC-MAIN-2015-22
|
en
|
refinedweb
|
10 May 2013 22:23 [Source: ICIS news]
MEDELLIN, ?xml:namespace>
The incident at the
According to the company, a new Topping C unit will be operational within a few weeks, while a new coking facility currently under construction is expected to come online in 2015.
“Technical evaluations are being carried out with the objective to determine both the date of commissioning of Topping C as well as the reduced operational capacity, as Coke A will not be recovered,” said YPF chief financial officer Daniel Gonzalez.
“Our preliminary estimate is that processing capacity will be approximately 150,000 bbl/day with Coke A not in operation,” said Gonzalez.
According to YPF estimates, disruption to the refinery’s operations will reduce output this year by approximately 1.4m cubic metres (mcm).
“This will be composed by 70% of high value products, 20% of light products and 10% of heavy products,” Gonzalez said.
The executive said the company might have to import some of these products to make up for reduced production and to satisfy domestic demand.
“But we may also be able to export some crude oil surpluses from time to time,” he added.
YPF reported late on Thursday that its net income in the first quarter fell by 2.8% year on year to Argentinian pesos (Ps) 1.26bn ($241.4m, €185.9m), mainly due to the impact of deferred income tax of Ps481m.
Revenues in the January-to-March period were up by about 25% to Ps18.63bn from Ps14.85bn a year ago, driven by increased domestic sales of liquid fuels and higher prices for gasoline and diesel.
However, sales of chemical products fell both in the domestic and external markets, decreasing by 19.5% and 9.1%, respectively, compared to the prior-year quarter.
Meanwhile, crude oil production in the first quarter of 2013 slipped 0.7% from a year earlier, while gas output fell by 3.7%, the company said.
Despite the dip in output, Gonzalez said that the company stands by its goal of boosting oil and natural gas production by 4% and 1%, respectively, during 2013.
YPF has vowed to increase output after the company was renationalised by
($1 = €0.77; $1 = Ps
|
http://www.icis.com/Articles/2013/05/10/9667555/argentina-ypf-refinery-to-operate-at-reduced-capacity-until.html
|
CC-MAIN-2015-22
|
en
|
refinedweb
|
Using. (The general approach would also work for a web service using SOAP.) We will also see how the reports (or "living documentation", in BDD terms) generated by these automated acceptance criteria also do a great job to document the web service.
Thucydides is an open source BDD reporting and acceptance testing library that is used in conjunction with other testing tools, either BDD testing frameworks such as JBehave, SpecFlow, or more traditional libraries such as JUnit.
Web services are easy to model and test using BDD techniques, in many ways more so than web applications. Web services are (or should be) relatively easy to describe in behavioral terms. They accept a well-defined set of input parameters, and return a well-defined result. So they fit well into the typical BDD-style way of describing behavior, using given-when-then format:
Given some precondition
When something happens
Then a particular outcome is expected
During the rest of this article we will see how to describe and automate web service behavior in this way. To follow along, you will need Java and Maven installed on your machine (I used Java 8 and Maven 3.2.1). The source code is also available on Github. If you want to build the project from scratch, first create a new Thucydides/JBehave project from the command line like this:
mvn archetype:generate -Dfilter=thucydides-jbehave
Enter whatever artifact and group names you like: it doesn't make any difference for this example:
Choose archetype:
1: local ->
Define value for property 'groupId': : com.wakaleo.training.webservices
Define value for property 'artifactId': : bdddemo
Define value for property 'version': 1.0-SNAPSHOT: : 1.0.0-SNAPSHOT
Define value for property 'package': com.wakaleo.training.webservices: :
Confirm properties configuration:
groupId: com.wakaleo.training.webservices
artifactId: bdddemo
version: 1.0.0-SNAPSHOT
package: com.wakaleo.training.webservices
Y: :
This will create a simple project set up with JBehave and Thucydides. It is designed to test web applications, but it is easy enough to adapt to work with a RESTful web service. We don't need the demo code, so you can safely delete all of the Java classes (except for the AcceptanceTestSuite class) and the JBehave .story files.
Now, update the
pom.xml file to use the latest version of Thucydides, e.g.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<thucydides.version>0.9.239</thucydides.version>
<thucydides.jbehave.version>0.9.235</thucydides.jbehave.version>
</properties>
Once you have done this, you need to define some stories and scenarios for your web service. To keep things simple in this example, we will be working with two simple requirements: shortening and expanding URLs using Google's URL shortening service. We will describe these in two JBehave story files. Create a
stories directory under
src/test/resources, and create a sub-directory for each requirement called
expanding_urls and
shortening_urls. Each directory represents a high-level capability that we want to implement. Inside these directories we place JBehave story files (
expanding_urls.story and
shortening_urls.story) for the features we need. (This structure is a little overkill in this case, but is useful for real-world project where the requirements are more numerous and more complex). This structure is shown here:
The story files contain the BDD-style given-when-then scenarios that describe how the web service should behave. When you design a web service using BDD, you can express behavior at two levels (and many projects use both). The first approach is to describe the JSON data in the BDD scenarios, as illustrated here:
Scenario: Shorten Urls
Given a url
When I request the shortened form of this url
Then I should obtain the following JSON message:
{
"kind": "urlshortener#url",
"id": "",
"longUrl": ""
}
This works well if your scenarios have a very technical audience (i.e. if you are writing a web service purely for other developers), and if the JSON contents remain simple. It is also a good way to agree on the JSON format that the web sevice will produce. But if you need to discuss the scenario with business, BAs or even testers, and/or if the JSON that you are returning is more complicated, putting JSON in the scenarios is not such a good idea. This approach also works poorly for SOAP-based web services where the XML message structure is more complex. A better approach in these situations is to describe the inputs and expected outcomes in business terms, and then to translate these into the appropriate JSON format within the step definition:
Scenario: Shorten URLs
Given a url <providedUrl>
When I request the shortened form of this url
Then the shortened form should be <expectedUrl>
Examples:
| providedUrl | expectedUrl |
| | |
| | |
Let's see how we would automate this scenario using JBehave and Thucydides. First, we need to write JBehave step definitions in Java for each of the given/when/then steps in the scenarios we just saw. Create a class called
ProcessingUrls next to the
AcceptanceTestSuite class, or in a subdirectory underneath this class.
The step definitions for this scenario are simple, and largely delegate to a class called
UrlShortenerSteps to do the heavy-weight work. This approach make a cleaner separation of th what from the how, and makes reuse easier - for example, if we need to change underlying web service we used to implement the URL shortening feature, these step definitions should remain unchanged:
public class ProcessingUrls {
String providedUrl;
String returnedMessage;
@Steps
UrlShortenerSteps urlShortener;
@Given("a url <providedUrl>")
public void givenAUrl(String providedUrl) {
this.providedUrl = providedUrl;
}
@When("I request the shortened form of this url")
public void shortenUrl() {
returnedMessage = urlShortener.shorten(providedUrl);
}
@When("I request the expanded form of this url")
public void expandUrl() {
returnedMessage = urlShortener.expand(providedUrl);
}
@Then("the shortened form should be <expectedUrl>")
public void shortenedFormShouldBe(String expectedUrl) throws JSONException {
urlShortener.response_should_contain_shortened_url(returnedMessage, expectedUrl);
}
}
Now add the
UrlShortenerSteps class. This class contains the actual test code that interacts with your web service We could use any Java REST client for this, but here we are using the Spring RestTemplate. The full class looks like this:
public class UrlShortenerSteps extends ScenarioSteps {
RestTemplate restTemplate;
public UrlShortenerSteps() {
restTemplate = new RestTemplate();
}
@Step("longUrl={0}")
public String shorten(String providedUrl) {
Map<String, String> urlForm = new HashMap<String, String>();
urlForm.put("longUrl", providedUrl);
return restTemplate.postForObject("", urlForm, String.class);
}
@Step("shortUrl={0}")
public String expand(String providedUrl) {
return restTemplate.getForObject("{shortUrl}", String.class, providedUrl);
}
@Step
public void response_should_contain_shortened_url(String returnedMessage, String expectedUrl) throws JSONException {
String expectedJSONMessage = "{'id':'" + expectedUrl + "'}";
JSONAssert.assertEquals(expectedJSONMessage, returnedMessage, JSONCompareMode.LENIENT);
}
@Step
public void response_should_contain_long_url(String returnedMessage, String expectedUrl) throws JSONException {
String expectedJSONMessage = "{'longUrl':'" + expectedUrl + "'}";
JSONAssert.assertEquals(expectedJSONMessage, returnedMessage, JSONCompareMode.LENIENT);
}
}
The Spring RestTemplate class is an easy way to interact with a web service with a minimum of fuss. In the
shorten() method, we invoke the
urlshortener web service using a POST operation to shorten a URL:
@Step("longUrl={0}")
public String shorten(String providedUrl) {
Map<String, String> urlForm = new HashMap<String, String>();
urlForm.put("longUrl", providedUrl);
return restTemplate.postForObject("", urlForm, String.class);
}
The expand service is even simpler to call, as it just uses a simple GET operation:
@Step("shortUrl={0}")
public String expand(String providedUrl) {
return restTemplate.getForObject("{shortUrl}", String.class, providedUrl);
}
In both cases, we return the JSON document produced by the web service, and verify the contents in the then step using the JSONAssert library. There are many libraries you can use to verify the JSON data returned from a web service. If you need to check the entire JSON structure, JSONAssert provides a convenient API to do so. JSONAssert lets you match JSON documents strictly (all the elements must match, in the right order), or leniently (you only specify a subset of the fields that need to appear in the JSON document, regardless of order).
The following step checks that the JSON documet contains an id field with the expected URL value. The full JSON document will appear in the reports because it is being passed as a parameter to this step.
@Step
public void response_should_contain_shortened_url(String returnedMessage, String expectedUrl) throws JSONException {
String expectedJSONMessage = "{'id':'" + expectedUrl + "'}";
JSONAssert.assertEquals(expectedJSONMessage, returnedMessage, JSONCompareMode.LENIENT);
}
You can run these scenarios using
mvn verify from the command line: this will produce the test reports and the Thucydides living documentation for these scenarios. Once you have run
mvn verify, open the
index.html file in the
target/site/thucydides directory. This gives an overview of the test results. If you click on the Requirements tab, you will see an overview of the results in terms of capabilities and features. We call this "feature coverage":
Drill down into the "Shorten URLs" test result. Here you will see a summary of the story or feature illustrated by this scenario:
And if you scroll down further, you will see the details of how this web service was tested, including the JSON document returned by the service:
BDD is a great fit for developing and testing web services. If you want to learn more about BDD, be sure to check out the BDD, TDD and Test Automation workshops we are running in Sydney and Melbourne this May!
John Ferguson Smart is a well-regarded consultant, coach, and trainer in technical agile practices based in Sydney, Australia. A prominent international figure in the domain of behaviour driven development, automated testing and software life cycle development optimisation, John helps organisations around the world to improve their agile development practices and to optimise their Java development processes and infrastructures. He is the author of several books, most recently BDD in Action for Manning.
- Login or register to post comments
- Printer-friendly version
- johnsmart's blog
- 12621 reads
I have no idea about click_link with in jbehave frame work ...
by kristinjanna - 2014-05-13 23:53
I have no idea about click_link with in jbehave frame work and I want to learn more about BDD, please let me know any Solution Provider for that?
step files are not recongnized , do we have any ...
by kamaraju333 - 2014-04-24 21:40
step files are not recongnized , do we have any configuration required when i run the main junit test case .
And all my test cases goes to pending
Take a look at the sample code on Github: ...
by johnsmart - 2014-04-25 07:19
Take a look at the sample code on Github:
Hi, Do You have a sample code for a web based ...
by kamaraju333 - 2014-04-26 20:02
Hi,
Do You have a sample code for a web based application
Jbehave , Thucydides and selenium
I am using the Thucydides-Jbehave Show case from git hub , which ends in to all pending tests.
Do we have a sample project for executing web based automation with thucydides jbehave
When i am running my tests everything says pending ,
as you mentioned in thucydides reference manual .
There is no configuration required for junit to identify the tests if there are in the same package , but its not identifying .
help me out in understandting how testsuite could be able to identify the step files .
This above is mentioned about Jbehave and Thucydides project
|
https://weblogs.java.net/blog/johnsmart/archive/2014/04/22/using-bdd-web-services-tutorial-using-jbehave-and-thucydides
|
CC-MAIN-2015-22
|
en
|
refinedweb
|
Hi !!
I wanted to know how to go about game development. What should the language be, VB or JAVA or C,C++ ? Can anyone suggest a good book and site for game programming ? I know a bit of C. Can anyone please help me with this?
Thanks in advance.
Printable View
Hi !!
I wanted to know how to go about game development. What should the language be, VB or JAVA or C,C++ ? Can anyone suggest a good book and site for game programming ? I know a bit of C. Can anyone please help me with this?
Thanks in advance.
Out of those languages C or C++ definately, personally I'd go for C++ but some would disagree. Java is similar but extremely slow. VB is good for small apps but it hasnt got the power and flexibility of C. But then you are posting on a C Board, this is a biased opinion.
I'd use C++. It's fully compatible with C so you can use all the C stuff you want in addition to using classes for some parts of your code (which sometimes makes thing much easier).
-- A side note Java is not necessarily "extremely slow", it might actually be a good way to start learning, but C/C++ are still the way to go in the long run.
Im takeing a java class right now, and it is definitely not extremely slow. Perhaps you were doing something wrong when you tried it (assumeing that you tried it, and are not just repeating what you heard from someone else).
the problem with java is that it is a bit unstable and has to be run from a web browser.
Um? What? No. Wrong.
Applets need an applet viewer (which most browsers have implemented).
You can make normal applications as well. All that is required is the Java Virtual Machine.
Or you could use one of the many native code compilers (platform specific) and run it as an executable for that platform. While this renders the program platform specific, the source code remains portable so you're OK (as long as you don't use any system specific calls).
Hmmm. Not run from a browser. Now how'd I do that?Hmmm. Not run from a browser. Now how'd I do that?Code:
import java.io.*;
public class NotAnApplet {
public static void main(String[] args) {
System.out.println("I wasn't run in a browser!\n");
}
}
for good game programming books go to. Then click computers>>programming.....etc until you come to the books you want. Very good books for low prices on programming.
|
http://cboard.cprogramming.com/game-programming/9553-game-prgramming-where-begin-printable-thread.html
|
CC-MAIN-2015-22
|
en
|
refinedweb
|
06 June 2012 04:43 [Source: ICIS news]
SINGAPORE (ICIS)--China-based Qingyuan Natural Gas had to postpone the start-up of its 50,000 cubic metre (cbm)/day liquefied natural gas (LNG) project at Ordos in ?xml:namespace>
Problems at the unit’s compressor prevented it to start production as originally scheduled on 6 June, the source said.
“It is unknown yet when could the problem be fixed,” said the source.
Qingyuan Natural Gas will also be building a 900,000 cbm/day LNG plant in the second phase of its project. Construction of the new plant is expected to begin in the second half of the year, the source said.
The bigger plant is expected to come on stream in late 2013, the source said.
Feedstock gas for the LNG plants will all be supplied by PetroChina’s Changning gas distribution branch and Changqing Oilfield, the source added.
Qingyuan Natural Gas is largely engaged in the production and distribution of LNG in
|
http://www.icis.com/Articles/2012/06/06/9566566/chinas-qingyuan-natural-gas-delays-start-up-of-ordos-lng-plant.html
|
CC-MAIN-2015-22
|
en
|
refinedweb
|
26 March 2013 19:10 [Source: ICIS news]
LONDON (ICIS)--The European Commission has opened an in-depth investigation into the planned takeover by ?xml:namespace>
The Commission fears that the deal would remove the only competing producer of naphthenic base oils in the European Economic Area (EEA), it said.
Under the deal, first announced in 2011, Stockholm-based specialty oils refiner Nynas would lease for 25 years Shell’s base oil plant and related refinery assets at Hamburg, with Nynas rebuilding the site into a 330,000 tonne/year specialty oils refinery.
The Commission said that its initial investigation showed that with the acquisition, no other competitor would remain to supply naphthenic oils for use in some end applications such as industrial rubber, fertilizers and defoamers in the EEA.
With respect to other segments – including greases, metalworking fluids or cold-set inks and transformer oils – the few remaining competitors importing into the EEA may not exercise a sufficient competitive constraint, the Commission said.
“The Commission’s initial investigation revealed possible competition concerns in the markets for naphthenic base oils, naphthenic process oils and transformer oils where the merged [Nynas] entity would have very high market shares in the EEA,” it added.
The Commission has 90 working days, until 8 August 2013, to take a final decision on whether the merger would significantly impede effective competition in the EEA,
|
http://www.icis.com/Articles/2013/03/26/9653672/EU-to-probe-Nynas-deal-for-Shells-Hamburg-base-oil-assets.html
|
CC-MAIN-2015-22
|
en
|
refinedweb
|
[JXSE 2.6] Problems joining to a peergroup
Hi!
Have there been changes when joining a group? I can't use the code that I wrote to join to a group, now the method isReadyForJoin always return false.
PeerGroup group = netpg.newGroup(id, impAdv, name, description);
AuthenticationCredential myAuthCred =
new AuthenticationCredential(group, null, null);
MembershipService membershipService = group.getMembershipService();
Authenticator myAuthenticator = membershipService.apply(myAuthCred);
if (!myAuthenticator.isReadyForJoin()) {
[....]
return false;
}
With JXSE 2.5 it works perfectly. Thanks!
My system:
ArchLinux - Kernel 2.6.33 (64bits)
Java 1.6.0_20 (64bits)
JXSE 2.6 Beta 2
Hi,
There has been some refactoring, but no functional changes. I have tried to replicate your issue with the code in attachment.
The authenticator I get is a DialogAuthenticator on top of a StringAuthenticator. The isReadyForJoin() method has not been modified by 2.6. It does return false with 2.6 though.
When I take a look at the code:
synchronized public boolean isReadyForJoin() {
if (null != seedCert) {
return null != PSEUtils.pkcs5_Decrypt_pbePrivateKey(key_password, seedCert.getPublicKey().getAlgorithm(), seedKey);
} else {
return source.pseStore.validPasswd(identity, store_password, key_password);
}
}
I am wondering whether this is a set-up issue... Are you using those features?
Jérôme (AdamMan71)
I've run your code and it returns false with 2.6, but with 2.5 it returns true. It's rare...
Any news? I think that it's an important bug that makes the 2.6 version useless. Thanks
No worry, I have not forgotten.
I have opened an issue:.
The bottom line is:
a) There is a regression at the NPG level where the membership should be free for everyone, the patch corrects this issue.
b) Application is working as designed when your create standard groups using the
getAllPurposePeerGroupImplAdvertisement(), since there had been an agreement to make the PSEMembership service the default for such groups after 2.5.
Now, if you need to create subgroups where access is free, you can create the corresponding module implementation advertisement as following:
...
ModuleImplAdvertisement implAdv =
CompatibilityUtils.createModuleImplAdvertisement(
MyPeerGroupID, PeerGroup.class.getName(), "My description");
// Build the param section (I know this is deprecated code, but we'll take care of this later).
StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv();
// "Core" Services
paramAdv.addService(PeerGroup.endpointClassID, PeerGroup.refEndpointSpecID);
paramAdv.addService(PeerGroup.resolverClassID, PeerGroup.refResolverSpecID);
paramAdv.addService(PeerGroup.membershipClassID, NoneMembershipService.noneMembershipSpecID);
paramAdv.addService(PeerGroup.accessClassID, PeerGroup.refAccessSpecID);
// "Standard" Services
paramAdv.addService(PeerGroup.discoveryClassID, PeerGroup.refDiscoverySpecID);
paramAdv.addService(PeerGroup.rendezvousClassID, PeerGroup.refRendezvousSpecID);
paramAdv.addService(PeerGroup.pipeClassID, PeerGroup.refPipeSpecID);
paramAdv.addService(PeerGroup.peerinfoClassID, PeerGroup.refPeerinfoSpecID);
paramAdv.addService(PeerGroup.contentClassID, ContentServiceImpl.MODULE_SPEC_ID);
// Pour newParamAdv in -> implAdv
XMLElement paramElement = (XMLElement) paramAdv.getDocument(MimeMediaType.XMLUTF8);
implAdv.setParam(paramElement);
return implAdv;
...
Hi, this leaves me a question
Our application has its own authentication method to join a private group, would be safe to keep using NoneMembershipService or should we use PSEMembershipService?
Thanks
If you have your own, then you probably don't need any extra method, so I would go for the nonemembership in your case. It would make things simpler.
Hi, I've just come back to use 2.6 and I still have a problem when joining to a peergroup.
Here is the code:
{{{
PeerGroup group = MyNetPeerGroup.newGroup(advertisement);
AuthenticationCredential authCred =
new AuthenticationCredential(group, null, null);
MembershipService mService = group.getMembershipService();
Authenticator myAuthenticator = mService.apply(miAuthCre);
if (!myAuthenticator.isReadyForJoin()) {
System.out.println("Authenticator incomplete");
return;
}
}}}
If I join a group just after I had created it there is no problem because I use the PeerGroup object returned by newGroup(PGID, ImplAdv, Name, Description) but if I want to join to a new group (using discoveryservice), I need to use the method newGroup(Advertisement). In 2.5 it worked perfectly but now it always returns false in isReadyForJoin()
> but if I want to join to a new group (using discoveryservice)
You mean the membership service I guess?!?
When you create your new AuthenticationCredential(group, null, null) object, you don't provide any value for the 2nd parameter (i.e., the "method"). The meaning of this value depends on the corresponding membership service implementation. If it is the PSEMembershipService, the returned authenticator type is DialogAuthenticator (by default), which is based on StringAuthenticator. The latter implements isReadyForJoin() as following:
synchronized public boolean isReadyForJoin() {
if (null != seedCert) {
Logging.logCheckedFine(LOG, "seed certificate:\n", seedCert.toString());
return null != PSEUtils.pkcs5_Decrypt_pbePrivateKey(key_password, seedCert.getPublicKey().getAlgorithm(), seedKey);
} else {
Logging.logCheckedFine(LOG, "null seed certificate");
return source.getPSEConfig().validPasswd(identity, store_password, key_password);
}
}
This may give you some idead about what is happening.
If you are using the NoneMembershipService, the returned object is a none authenticator, which implements isReadyToJoin() as following:
synchronized public boolean isReadyForJoin() {
Logging.logCheckedFine(LOG, "Always ready to join");
// always ready.
return true;
}
If you use the PasswdMembershipService, the returned authenticator is of type PasswdAuthenticator, which implements isReadyToJoin() as following:
synchronized public boolean isReadyForJoin() {
if ( null == password )
Logging.logCheckedFine(LOG, "null password");
if ( null == password )
Logging.logCheckedFine(LOG, "null whoami");
return ((null != password) && (null != whoami));
}
I don't exactly know what could cause the different behavior between 2.5 and 2.6. However, I do remember (on top of my head) that the PSE Membership was made the default membership group for both the NetPeerGroup and any 'standard' newGroup shortly after 2.5 release. This may have had an impact on your code. You could check this by calling getClass() on the returned membership service object in 2.5 and 2.6 and see if there is a difference...
hi,
I created a peergroup using this given code.
but in this code following code is depricated.
StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv();
is there any alternative way to this ?
|
https://www.java.net/node/702992/atom/feed
|
CC-MAIN-2015-22
|
en
|
refinedweb
|
lttng-ust — LTTng user space tracing
#include .
Note:
Using the tracef(3) API, which is similar to printf(3).
Using the tracelog(3) API, which is tracef(3) with a log level parameter.
Defining your own tracepoints. See the Creating a tracepoint provider section below.
Creating a tracepoint provider is the first step of using
liblttng-ust. The next steps are:
Instrumenting your application with
tracepoint() calls
Building your application with LTTng-UST support, either statically or dynamically..
Note.
TRACEPOINT_EVENT()usage.
ctf_*()field type macros:
Number of elements in array/sequence. This must be known at compile time.
Name of an enumeration field previously defined with the
TRACEPOINT_ENUM() macro. See the
TRACEPOINT_ENUM() usage section for more
information.
C expression resulting in the field’s value. This expression can
use one or more arguments passed to the tracepoint. The arguments
of a given tracepoint are defined in the
TP_ARGS() macro (see
the Creating a tracepoint provider section above).
Event field name (C identifier syntax, not a literal string).
Float C type (
float or
double). The size of this type determines
the size of the floating point number field.
Integer C type. The size of this type determines the size of the integer/enumeration field.
C expression resulting in the sequence’s length. This expression can use one or more arguments passed to the tracepoint.
Unsigned integer C type of sequence’s length.
Tracepoint provider name. This must be the same as the tracepoint provider name used in a previous field definition..
TRACEPOINT_ENUM()usage.
TRACEPOINT_EVENT_CLASS()usage.
TRACEPOINT_LOGLEVEL()usage:
Tracepoint provider name.
Tracepoint/event name.
...
Tracepoint arguments, if any.
Make sure to include the tracepoint provider header file anywhere you
use
tracepoint() for this provider.
Note
Note static library:
$
ar rc tp.a tp.o
Using a static library does have the advantage of centralising the tracepoint providers objects so they can be shared between multiple applications. This way, when the tracepoint provider is modified, the source code changes don’t have to be patched into each application’s source code tree. The applications need to be relinked after each change, but need not to be otherwise recompiled (unless the tracepoint provider’s API changes).:
Since the tracepoint provider is not part of the application,
TRACEPOINT_DEFINE must be defined, for each tracepoint
provider, in exactly one source file of the
application
TRACEPOINT_PROBE_DYNAMIC_LINKAGE must be defined next
to
TRACEPOINT_DEFINE
None
$:
Load it manually from the application using dlopen(3)
Make the dynamic loader load it with the
LD_PRELOAD
environment variable (see ld.so(8)):
Statically link the tracepoint provider to the application, or
Build the tracepoint provider as a shared object (following the
procedure shown in this section), and preload it when tracing is
needed using the
LD_PRELOAD environment variable.
CPU ID.
Note:This context field is always enabled, and it cannot be added with lttng-add-context(1). Its main purpose is to be used for dynamic event filtering. See lttng-enable-event(1) for more information about event filtering.
ip
Instruction pointer: enables recording the exact address from which an event was emitted. This context field can be used to reverse-lookup the source location that caused the event to be emitted.
perf:thread:COUNTER
perf counter named COUNTER. Use
lttng add-context --list to
list the available perf counters.
Only available on IA-32 and x86-64 architectures.
perf:thread:raw:rN:NAME
perf counter with raw ID N and custom name NAME. See lttng-add-context(1) for more details.
pthread_id
POSIX thread identifier. Can be used on architectures where
pthread_t maps nicely to an
unsigned long type.
procname
Thread name, as set by exec(3) or prctl(2). It is recommended that programs set their thread name with prctl(2) before hitting the first tracepoint for that thread.
vpid
Virtual process ID: process ID as seen from the point of view of the process namespace.
vtid
Virtual thread ID: thread ID as seen from the point of view of the process namespace.
Emitted when the state dump begins.
This event has no fields.
lttng_ust_statedump:end
Emitted when the state dump ends. Once this event is emitted, it is guaranteed that, for a given process, the state dump is complete.
This event has no fields.
lttng_ust_statedump:bin_info
Emitted when information about a currently loaded executable or shared object is found.
Fields:
lttng_ust_statedump:build_id
Emitted when a build ID is found in a currently loaded shared library. See Debugging Information in Separate Files for more information about build IDs.
Fields:
lttng_ust_statedump:debug_link
Emitted when debug link information is found in a currently loaded shared library. See Debugging Information in Separate Files for more information about debug links.
Emitted when a shared library (shared object) is loaded.
Fields:
lttng_ust_lib:unload
Emitted when a shared library (shared object) is unloaded.
Fields:
lttng_ust_lib:build_id
Emitted when a build ID is found in a loaded shared library (shared object). See Debugging Information in Separate Files for more information about build IDs.
Fields:
lttng_ust_lib:debug_link
Emitted when debug link information is found in a loaded shared library (shared object). See Debugging Information in Separate Files for more information about debug links.
Fields:
To detect if
liblttng-ust is loaded from an application:
Define the
lttng_ust_loaded weak symbol globally:
int lttng_ust_loaded __attribute__((weak));
This weak symbol is set by the constructor of
liblttng-ust.
Test
lttng_ust_loaded where needed:
/* ... */ if (lttng_ust_loaded) { /* LTTng-UST is loaded */ } else { /* LTTng-UST is NOT loaded */ } /* ... */
Note
tp.h:
>
Alternative user’s home directory. This variable is useful when the user running the instrumented application has a non-writable home directory._CLOCK_PLUGIN
Path to the shared object which acts as the clock override plugin.
An example of such a plugin can be found in the LTTng-UST
documentation under
examples/clock-override.
LTTNG_UST_DEBUG
Activates
liblttng-ust's debug and error output if set to
1.
LTTNG_UST_GETCPU_PLUGIN
Path to the shared object which acts as the
getcpu() override
plugin. An example of such a plugin can be found in the LTTng-UST
documentation under
examples/getcpu-override.
LTTNG_UST_REGISTER_TIMEOUT
Waiting time for the registration done session daemon command before proceeding to execute the main program (milliseconds).
The value
0 means do not wait. The value
-1 means wait forever.
Setting this environment variable to
0 is recommended for applications
with time constraints on the process startup time.
LTTNG_UST_WITHOUT_BADDR_STATEDUMP
Prevents
liblttng-ust from performing a base address state dump
(see the LTTng-UST state dump section above) if
set to
1..
|
http://lttng.org/man/3/lttng-ust/v2.9/
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
Hi I am sending a JSON Post request using the FireFox RestClient.
My JSON Request is as below:
{ "firstName": "Test", "lastName": "1", "isActive": 1 }
private boolean isActive;
@RequestMapping(method = {RequestMethod.POST,
RequestMethod.PUT}, value = "/save")
public ResponseEntity<RestResponse> save(
@RequestBody POJOUserDetails userDetails, WebRequest request){
"isActive": 1
"isActive": true
"isActive": "true"
"isActive": ""
"isActive": null
"isActive": false
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include=Inclusion.NON_EMPTY)
public class POJOUserDetails {
private String firstName;
private String lastName;
private boolean isActive;
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Remember that Jackson, by default, determines the property name from either the getter or setter (the first that matches).
To deserialize an object of type
POJOUserDetails, Jackson will look for three properties
public void setFirstName(String firstName) { public void setLastName(String lastName) { public void setActive(boolean isActive) {
in the JSON. These are basically
active.
You get the following JSON
{ "firstName": "Test", "lastName": "1", "isActive": 1 }
So
firstName and
lastName are mapped, but you don't have a property named
isActive.
Jackson depends on Java Bean naming conventions with their accessors (getters) and mutators (setters). For a field like
private boolean isActive;
the appropriate setter/getter names are
public boolean getIsActive() { return isActive; } public void setIsActive(boolean isActive) { this.isActive = isActive; }
So you have two possible solutions. Change your getter/setter as shown above or annotate your field with
@JsonProperty so that Jackson uses the field name to determine the property name
@JsonProperty private boolean isActive;
|
https://codedump.io/share/75xXvVRDUjYG/1/json-post-request-for-boolean-field-sends-false-by-default
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
This article describes an easy approach to keeping track of each installation of an application. The intent of the example is to demonstrate the use of a simple web service to collect and store information about each user and machine running the application.
I was originally driven to coming up with something like this in response to working for an employer that operated strictly on the honor system. By that, I mean that the company would sell its software by the seat to individual clients, but with no licensing or other restrictions imposed or enforced by the software that might prevent the installation of additional copies of that software; for example, if a client purchased five seats of the product, it was assumed by the company that the client would only install it five times.
In one particular sale of the product, I felt that it was likely that the client would install additional copies beyond what they had purchased (given the magnitude of work they had to perform, five seats seemed woefully inadequate), and I had asked for approval to implement a licensing scheme in the code; the company declined to do this for whatever reason. They did agree for me to devise a method for tracking installations without requiring a license. The code in this project is a derivation of what I did there, mainly because, in the original approach, I was not permitted to terminate the application if it were not registered; I was only able to collect information on the installations. What we discovered was that the five purchased seats were installed over 100 times by the client (at about a $380,000 loss in revenue to the company in this one instance).
When I wrote this example version, I did it a little differently in that I create a bogus registry entry that is used to determine whether or not the application was installed and registered through the web service. If the product is not registered, I prevent the application from being used. When I terminate the application, I inform the user that the registration process is incomplete and that the process requires an active connection to the internet. This works much like what is seen when you are required to, for example, activate a copy of Microsoft Word through an internet connection. The registry key is checked each time the application is executed; if the registry key exists and its value indicates that the product is registered, then nothing else happens; if that is not the case, the application will not run until the registration occurs. If a person were to X-copy the application onto another machine, the application will still check for the key the first time it is executed, and therefore it will not run until it is also registered.. Here in this example, I just lock them out from the beginning. This approach does not prevent the client from over-installing the product; it merely forces each installation to be registered through the web service. You could easily modify the web service to check and see if an individual license has been registered and prevent additional installations of that license, but for the purposes of this example, I am only demonstrating the capture of each installation through the service.
As it stands, the example is not the be-all, end-all solution to securing your application against theft. It does, however, offer an approach for determining the extent of abuse you may be encountering with a release of custom software to a client company. That information may be useful in making an argument for building a more robust approach to licensing your distributions.
To get started, unzip the source code included with this project. In the code example, you will find a web service and a WinForms application. Open the Web Service up, and make any changes necessary to get it to operate on your machine. The project containing the web service has an MS Access database included, and the database contains a single table used to collect the installation information. In reality, you’d probably configure a database and table in SQL Server or Oracle to contain the data, but for the purposes of this demonstration, it was easier to pack it up in Access. Aside from the MS Access database, you will note that the web service project only contains a single service entitled, “RegisterInstallation”.
Once you’ve configured the web service, run it and check it with the proxy to validate that it is updating the database correctly:
Figure 1: Run the Web Service
With the web service running, select the link to “RegisterInstallation”:
Figure 2: Testing the “RegisterInstallation” Web Service
Once you’ve keyed in some sample values as indicated in Figure 2, click on the “Invoke” button and view the response; if successful, you should see something like what is shown in Figure 3:
Figure 3: The Web Service returns “true” if the installation information is saved to the database
Given the web service has returned a true, take a look at the database to confirm that the values entered have been stored in the table:
Figure 4: The AppInstallers table updated by the Web Service
Having confirmed that the web service is up and running, open the application solution in Visual Studio 2005. Examine the contents of the project in the Solution Explorer, you should see the following:
Figure 5: RegTest application solution content
Within the solution, note that the registration service has been added as a web reference; you will likely need to update this reference. The app.config file is the default version, and can be ignored here. The classes worthy of note are frmMain and RegistrationCheck. The main form class (frmMain) represents your application, and the registration check class is used to capture information about the machine containing the application and package up for submittal to the registration web service.
frmMain
RegistrationCheck
Assuming that the web service and the project references check out, we can now take a look at the code.
Locate the RegistrationService.asmx file contained in the “RegistrationSvc” web service solution, and open it up in the IDE. You will note that this is a very simple service, and in general, all that it does is expose a function entitled “RegisterInstallation”. This function receives a collection of arguments containing the information about the installer, and formats and executes an INSERT query against the MS Access database used to contain the installer information.
RegisterInstallation
INSERT
The imports section of the code in this class has been amended to include the portions of the System.Data library that pertain to the use of an OLEDB data source:
System.Data
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data
Imports System.Data.OleDb
<WebService(Namespace:="")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
Inherits System.Web.Services.WebService
The class declaration is cleverly called “Service”, and the attributes applied to the class are also in the default configuration, with the exception of the updated namespace. The only function in the service exposed as a web method is the RegisterInstallation function; its code is as follows:
<WebMethod()> _
Public Function RegisterInstallation(ByVal strDomainAndUser As String, _
ByVal strComputerName As String, _
ByVal strApplication As String, _
ByVal strVersion As String, _
ByVal strAppID As String, _
ByVal strInstallDate As String) As
Boolean
Dim conn As OleDbConnection = New _
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=c:\inetpub\wwwroot\RegistrationSvc\Registration.mdb;" & _
"User ID=;Password=;")
Try & "')")
Dim sSQL As String = strBuilder.ToString()
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, conn)
Try
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
conn.Close()
Return False
End Try
Catch ex As Exception
conn.Close()
Return False
End Try
conn.Close()
Return True
End Function
This function is pretty straightforward; the arguments detailing the installer’s information are passed as arguments to the function. The function then takes the arguments directly, and passes them to an INSERT query against the MS Access database. Once the execution of the INSERT statement has completed, the function returns a Boolean set to True if the data is passed to the database, or False if the operation fails to update the database.
Boolean
True
False
That is all there is to the web service; the calling application will gather the user’s information and, if appropriate, connect to the web service and post the data to the database used to house the installer information.
One point to make here is with regards to the setting of the installation date; in this example, the value is passed into the web method from the client. If you are interested in creating a grace period for using the application (e.g., allow the user to use the application for 30 days without registering it), you may wish to set this value on the server side instead of the client. This will prevent the user from changing the date on their machine to gain additional, free use of the application.
Next, open the “RegTest” solution in the IDE, and we can take a look at that.
First off, open the “RegistrationCheck” class in the code window. You will note that the class contains two subroutines and one function. The Imports statements and the class declaration are as follows:
Imports
Imports System
Imports System.Windows.Forms.SystemInformation
Public Class RegistrationCheck
By importing the “SystemInformation” library, we are able to capture the information used to identify the machine and the user running the application. This will provide us with the source for the arguments passed to the web service.
SystemInformation
Now, take a look at the function, “CheckProductRegistration”. This function is Public, and is the means by which the application checks for prior registrations and then gathers and submits data to the web service during the initialization of an unregistered version of the application. The code for this function is as follows:
CheckProductRegistration
Public
Public Function CheckProductRegistration() As Boolean
' Check registry for key,
' create the key if it does not exist
CheckForOrMakeRegKey()
' Check the key to see if application has been registered
' the key DA\SOMLA\1.0 is nonsense; it is just
' there to confuse anyone that tries to
' defeat the registration process. (actually,
' SOMLA is some software I used in the
' mid 1980's to test aircraft crash effects
' upon a seated aircraft occupant, but you
' can put whatever you want in there, use Bullwinkle
' or cDc if you don't like SOMLA)
' Set this boolean upon determining whether or not
' the product has been registered
Dim blnIsRegistered As Boolean = False
Dim key As Microsoft.Win32.RegistryKey
Try
key = _
Microsoft.Win32.Registry.CurrentUser.
OpenSubKey("SOFTWARE\\DA\\SOMLA\\1.0")
If (Not key Is Nothing) Then
Dim intVal As Integer = _
CType(key.GetValue("dval"), Integer)
If intVal = 0 Then
blnIsRegistered = False
ElseIf intVal = 1 Then
blnIsRegistered = True
Return True
' it is already registered so just return true
' and exit out of function
End If
Else
' The key does not exist, the application
' has not been registered
blnIsRegistered = False
End If
key.Close()
Catch
' do nothing here, we want this to be pretty quiet...
End Try
' Registration has not occurred, so try to register it
If blnIsRegistered = False Then
' Obtain the user name currently logged on to this computer
Dim strUser As String
strUser = _
System.Windows.Forms.SystemInformation.UserName.ToString()
' Obtain the user's domain name for the current session
Dim strDomain As String
strDomain = _
System.Windows.Forms.SystemInformation.UserDomainName.ToString()
' Combine the user and domain names into a single entry
Dim strDomainAndUser As String = strDomain & "\" & strUser
' Get the name of the computer the application
' is installed on
Dim strComputerName As String
strComputerName = _
System.Windows.Forms.SystemInformation.ComputerName.ToString()
' Create a local instance of the web service
Dim ws As New RegistrationService.Service
' The web service returns a boolean to indicate
' success or failure in execution
Dim blnTest As Boolean = False
' Run the web service and load the installer's
' information into the database
Try
blnTest = _
ws.RegisterInstallation(strDomainAndUser, _
strComputerName, _
"RegTest", "1.0", _
"{376FEDC1-BC65-4c6a-B3C2-49CD57BFD127}", _
Now.ToLongDateString())
Catch
' Create registry entry and set it to false
CreateKeyAndSetValue(0)
End Try
'NOTE: the GUID is canned as is meant to mark the install
' as a specific copy of the application
' create new guids and registry keys for other customers
' and applications - this will allow you to track who bought
' the software versus where it ends up getting installed.
If blnTest = True Then
' Create registry entry and set it to 1 - registered
CreateKeyAndSetValue(1) ' IS registered
Return True
Else
' Create registry entry and set it to 0 - not registered
CreateKeyAndSetValue(0) ' NOT registered
Return False
End If
End If
End Function
The first thing this function does is call a private subroutine used to check for the existence of the registry key used to check for prior registrations of the application. If the key does not exist (first use), the key will be created in the subroutine. The key used, "SOFTWARE\\DA\\SOMLA\\1.0", is just some nonsense used to throw someone off if they were to try to find and manually edit the key value used to determine whether or not the application has been registered. As I mention in the comments, SOMLA is an application dating back to the 1980’s; it was used to run analysis of the effects of a crash upon the human spine. “DA” is for district attorney. You can change these values to whatever you want, but you should make some effort to conceal the purpose of the key and its value.
Next, the function gets the value of the key used to mark the application as having successfully been submitted to the registration web service; if the value indicates that the application has not been registered or activated through the service, it sets a Boolean to False. The Boolean is then tested, and if it is False, the function will attempt to gather the user’s information and submit it to the web service for registration. If the product is then registered, the calling method is notified of the success, and the registry value is updated to indicate that the product has been activated through the service. If the Boolean returns False, the user is booted out of the application, else the user is granted access to the application.
The two subroutines in this class are merely used to support the function by creating or confirming the existence of a registry key, and by allowing the function to set the key value associated with the registration of the application. The code for these two subroutines is as follows:
Private Sub CheckForOrMakeRegKey()
Try
Dim regVersion As Microsoft.Win32.RegistryKey
regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey _
("SOFTWARE\\DA\\SOMLA\\1.0", True)
If regVersion Is Nothing Then
regVersion = _
Microsoft.Win32.Registry.CurrentUser.CreateSubKey _
("SOFTWARE\\DA\\SOMLA\\1.0")
End If
regVersion.Close()
Catch
'do nothing
End Try
End Sub
Private Sub CreateKeyAndSetValue(ByVal intVal As Integer)
Try
' Declare a registry key variable and set it to
' be the fake SOMLA key
Dim regVersionKey As Microsoft.Win32.RegistryKey
regVersionKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey _
("SOFTWARE\\DA\\SOMLA\\1.0", True)
' If the key exists, then set its dval key value
' to the integer passed into this subroutine
If (Not regVersionKey Is Nothing) Then
regVersionKey.SetValue("dval", intVal)
regVersionKey.Close()
End If
Catch
'do nothing
End Try
End Sub
That concludes the discussion of the contents of this class. Next, open up the main form (frmMain.vb) class into the code window. The only item worthy of note in the main form’s code is the handler for the Load event:
Load
Private Sub frmMain_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
' Each time the application is loaded,
' we check for the existence of
' the registry entry:
Dim rc As New RegistrationCheck
Dim bln As Boolean
bln = rc.CheckProductRegistration()
' If the bln indicates that the application
' is not registered (and therefore
' could not be registered, then tell them
' Goodbye and exit the application.
If bln = False Then
MessageBox.Show("You have not registered this " & _
"product. Registration requires " & _
"internet access.", "Registration Failed", _
MessageBoxButtons.OK)
Application.Exit()
End If
End Sub
This code is pretty simple; it merely creates an instance of the “RegistrationCheck” class, sets a Boolean variable to capture the results of the attempt to register the product, and then processes the evaluation of the returned Boolean. If the Boolean is False, the user is notified that product activation requires an internet connection, and then the application is terminated if activation has not occurred. The user will continue to be met with this response until they permit the application to connect to the internet and subsequently activate the product.
Naturally, you can modify what occurs in response to a failed activation. For example, if you want to let the user use the product for thirty days after the original installation, you could amend the web service to return the initial installation date, and compare that date to today’s date and then decide whether or not to allow them to use the application.
The sample application and web service are meant to convey an approach to activating a product. This is not a particularly robust way of doing it, and it certainly is not foolproof. The approach could easily be compromised if the user were able to locate and manually edit the registry value. The approach does show you a general approach to product activation, and is a good way of collecting specific information about who is using the software, and determining which uniquely marked copy of the software the installer/user is running on a specific machine..
|
https://www.codeproject.com/articles/15636/phone-home-an-approach-to-software-activation?msg=2038294
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
extension:()
HttpRequest => HttpResponsefor)()
In this example, a request is handled by transforming the request stream with a Future’s completion:
import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.Http.ServerBinding import akka.stream.ActorMaterializer import scala.concurrent.Future) }.
import akka.actor.ActorSystem import akka.actor.ActorRef import akka.http.scaladsl.Http import akka.stream.ActorMaterializer import akka.stream.scaladsl.Flow():
import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.stream.ActorMaterializer import akka.stream.scaladsl.Flow implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() implicit val executionContext = system.dispatcher val (host, port) = ("localhost", 8080) val serverSource = Http().bind(host, port) s with appropriate error codes and human-readable failure descriptions.
|
http://doc.akka.io/docs/akka-http/current/scala/http/low-level-server-side-api.html
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
#include <OgreAnimationUpdater.h>
Allows blended animation playback of OgreVisibleObjects.
NOTE: This method applies the animation to an entity attached to the OgreVisibleObject's SceneNode with the same name as obj_. It is assumed that obj_ is in this Updater.
Returns false if obj_ is already in this updater.
Reimplemented from OpenSkyNet::Core::Updater.
Returns true if all objects were updated over the current interval (that's interval, not dt_), false if objects are left to be updated (see class description).
Reimplemented from OpenSkyNet::Core::Updater.
|
http://tactics3d.sourceforge.net/Docs/html/class_open_sky_net_1_1_ogre_core_1_1_ogre_animation_updater.html
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
I'm using mingw gcc(3.xxx) compiler. In the following code I pass a variable 'q'as 'const' but I later use its private members in the '>>'operator (in the same function) which obviously modify it. but the compiler did'nt complain and the programm compiled. Later during execution when I used the '>>' operation, the program halted when it reached that point. Even though I understood the error and corrected it, what I don't understand is why the compiler did'nt yell at me.
Does someone have a clue?
Code://quaternion.h //no #include iostream as it is included in the main file. using namespace std; //for the istream and ostream class Quaternion{ private: long double a, b, c, d; public: Quaternion(long double aa=0, long double bb=0, long double cc=0, long double dd=0):a(aa), b(bb), c(cc), d(dd){} virtual ~Quaternion(){} friend ostream& operator <<(ostream& out, const Quaternion& q){ out<<q.a<<"+"<<q.b<<"i+"<<q.c<<"j+"<<q.d<<"k"; return out; } friend istream& operator >>(istream& in, constQuaternion& q){ in>>q.a>>q.b>>q.c>>q.d;//modifies q's members return in; } Quaternion operator +(const Quaternion q){ return Quaternion(a+q.a, b+q.b, c+q.c, d+q.d); } Quaternion operator -(const Quaternion q){ return Quaternion(a-q.a, b-q.b, c-q.c, d-q.d); } void set(long double aa=0, long double bb=0, long double cc=0, long double dd=0){ //blah blah } long double& operator [](unsigned int i){ //0 for 'a' component //blah blah } Quaternion operator *(const Quaternion& q){ //blahblah } };Code://main.cpp #include<iostream> #include"../quaternionfractal/quaternion.h" using namespace std; int main(){ Quaternion x, y; cout<<"x :"; [b]cin>>x; //when here the program halts and terminates without any complaining. cout<<"y :"; cin>>y; cout<<"x :"<<x<<"\n" <<"y :"<<y<<"\n" <<"x*y :"<<x*y<<"\n" <<"y*x :"<<y*x<<"\n"; return 0;[b] }
|
https://cboard.cprogramming.com/cplusplus-programming/70324-mingw-not-complaining.html
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
BWU Log
BWU Log is a fork of Quiver log. It is a set of logging utilities that make it easy to configure and manage Dart's built in logging capabilities.
The Basics
Dart's built-in logging utilities are fairly low level. This means each time you
start a new project you have to copy/paste a bunch of logging configuration
code to setup output locations and logging formats. BWU.
Here is a simple example that sets up a
InMemoryAppender with a
SimpleStringFormatter:
import 'package:logging/logging.dart'; import 'package:bwu_log/log.dart'; class SimpleStringFormatter implements FormatterBase<String> { String call(LogRecord record) => record.message; } main() { var logger = new Logger('bwu.TestLogger'); var appender = new InMemoryListAppender(new SimpleStringFormatter()); appender.attachLogger(logger); }
That's all there is to it!
BWU Log provides three
Appenders:
PrintAppender
which uses Dart's print statement to write to the console,
InMemoryListAppender which writes logs to a simple list (this can be useful for debugging or testing). Additionally, a
single
Formatter called
BasicLogFormatter is included and uses a "MMyy HH:mm:ss.S" format. Of course
there is no limit to what kind of appenders you can create, we have plans to
add appenders HTTP, WebSocket, DOM, Isolate and SysOut.
To create a new kind of
Appender simply extends
Appender. To create a new
Formatter just implement the
Formatter typedef or
FormatterBase class if
you need to hold state in your formatter. Take a look at PrintAppender and BasicLogFormatter for an example.
|
https://www.dartdocs.org/documentation/bwu_log/0.1.1/index.html
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
IniFiles(3pm) User Contributed Perl Documentation IniFiles(3pm)
NAME
Config::IniFiles - A module for reading .ini-style configuration files.
SYNOPSIS
use Config::IniFiles;
my $cfg = new Config::IniFiles( -file => "/path/configfile.ini" );
print "The value is " . $cfg->val( 'Section', 'Parameter' ) . "."
if $cfg->val( 'Section', 'Parameter' );
DESCRIPTION
Config::IniFiles provides a way to have readable configuration files
outside your Perl script. Configurations can be imported (inherited,
stacked,...), sections can be grouped, and settings can be accessed
from a tied hash.
FILE FORMAT
INI files consist of a number of sections, each preceded with the
section name in square brackets.. Parameter names are localized to the namespace of the
section, but must be unique within a section.
[section]
Parameter=Value what
follows the "<<" and what appears at the end of the text MUST match
exactly, including any trailing whitespace.
As a configuration option (default is off), continuation lines can be
allowed:
[Section]
Parameter=this parameter \
spreads across \
a few lines
USAGE -- Object Interface');
METHODS
new ( [-option=>>value ...] )
Returns a new configuration object (or "undef" if the configuration
file has an error). One Config::IniFiles object is required per
configuration file. The following named parameters are available:
-file filename.
-reloadwarn 0).
-nocase 0|1.
-allowcontinue 0|1.
-import object.
-commentchar 'char'
The default comment character is "#". You may change this by
specifying this option to an arbitrary character, except
alphanumeric characters and square brackets and the "equal"
sign.
-allowedcommentchars 'chars' (i.e.: like
"/[chars]/").
-allowcode 0|1
Set -allowcode => 1 allows to use perl hooks within a ini
configuration file. Such perl hooks enable you to call a
perl sub or to access an environment variable from within an
ini file to set a parameter:
[EXAMPLE] logfile1=sub{ $ENV{'LOGFILE'}; } logfile2=sub{
logfile(); } heredoc=<<EOT sub{ $ENV{'LOGFILE'}; } sub{
logfile(); } <<EOT
Default behaviour is to allow perl code.
val ($section, $parameter [, $default] )
Returns the value of the specified parameter ($parameter) in section
$section, returns undef (or $default if specified) if no section or no
parameter for the given section.
setval ($section, $parameter, $value, [ $value2, ... ]).
newval($section, $parameter, $value [, $value2, ...])
Assignes a new value, $value (or set of values) to the parameter
$parameter in section $section in the configuration file.
delval($section, $parameter)
Deletes the specified parameter from the configuration file
ReadConfig.
Sections
Returns an array containing section names in the configuration file.
If the nocase option was turned on when the config object was created,
the section names will be returned in lowercase.
SectionExists ( $sect_name )
Returns 1 if the specified section exists in the INI file, 0 otherwise
(undefined if section_name is not defined).
AddSection ( $sect_name ).
DeleteSection ( $sect_name )
Completely removes the entire section from the configuration.
Parameters ($sect_name)
Returns an array containing the parameters contained in the specified
section..
SetGroupMember ( $sect )
Makes sure that the specified section is a member of the appropriate
group.
Only intended for use in newval.
RemoveGroupMember ( $sect )
Makes sure that the specified section is no longer a member of the
appropriate group. Only intended for use in DeleteSection.
GroupMembers ($group)
Returns an array containing the members of specified $group. Each
element of the array is a section name. For example, given the sections
[Group Element 1]
...
[Group Element 2]
...
GroupMembers would return ("Group Element 1", "Group Element 2").
SetWriteMode ($mode)
Sets the mode (permissions) to use when writing the INI file.
$mode must be a string representation of the octal mode.
GetWriteMode ($mode)
Gets the current mode (permissions) to use when writing the INI file.
$mode is a string representation of the octal mode.
WriteConfig ($filename)
Writes out a new copy of the configuration file. A temporary file
(ending in '-new') is written out and then renamed to the specified
filename. Also see BUGS below.
Returns true on success, "undef" on failure.
RewriteConfig
Same as WriteConfig, but specifies that the original configuration file
should be rewritten.
GetFileName
Returns the filename associated with this INI file.
If no filename has been specified, returns undef.
SetFileName ($filename).
SetSectionComment($section, @comment))
GetSectionComment ($section)
Returns a list of lines, being the comment attached to section
$section. In scalar context, returns a string containing the lines of
the comment separated by newlines.
The lines are presented as-is, with whatever comment character was
originally used on that line.
DeleteSectionComment ($section)
Removes the comment for the specified section.
SetParameterComment ($section, $parameter, @comment)
Sets the comment attached to a particular parameter.
Any line of @comment that does not have a comment character will be
prepended with one. See "SetSectionComment($section, @comment)" above
GetParameterComment ($section, $parameter)
Gets the comment attached to a parameter.
DeleteParameterComment ($section, $parmeter)
Deletes the comment attached to a parameter.
GetParameterEOT ($section, $parameter)
Accessor method for the EOT text (in fact, style) of the specified
parameter. If any text is used as an EOT mark, this will be returned.
If the parameter was not recorded using HERE style multiple lines,
GetParameterEOT returns undef.
SetParameterEOT ($section, $EOT)).
DeleteParameterEOT ($section, $parmeter)
Removes the EOT marker for the given section and parameter. When
writing a configuration file, if no EOT marker is defined then "EOT" is
used.
Deletes the entire configuration file in memory.
USAGE -- Tied Hash
tie %ini, 'Config::IniFiles', (-file=>>$filename, [-option=>>value ...] ).";
$val = $ini{$section}{$parameter}} );
$ini{$section}{$parameter} = $value;;
%hash = %{$ini{$section}}.
$ini{$section} = {}; %{$ini{$section}} = %parameters;.
delete $ini{$section}{$parameter}
When tied to a hash, you can use the Perl "delete" function to
completely remove a parameter from a section.
delete $ini{$section}
The tied interface also allows you to delete an entire section from the
ini file using the Perl "delete" function.
%ini = ();
If you really want to delete all the items in the ini file, this will
do it. Of course, the changes won't be written to the actual file
unless you call RewriteConfig on the object tied to the hash.
Parameter names
my @keys = keys %{$ini{$section}}
while (($k, $v) = each %{$ini{$section}}) {...}
if( exists %{$ini{$section}}, $parameter ) {...} if
the default section (if set), although accessing an unknown parameter
in the specified section will return a value from the default section
if there is one.
Section names
foreach( keys %ini ) {...}
while (($k, $v) = each %ini) {...}
if( exists %ini, $section ) {...}
When tied to a hash, you use the Perl "keys" and "each" functions to
iteratively list the sections in the ini file.
You can also use the Perl "exists" function to see if a section is
defined in the file.
DIAGNOSTICS
@Config::IniFiles::errors
Contains a list of errors encountered while parsing the configuration
file. If the new method returns undef, check the value of this to find
out what's wrong. This value is reset each time a config file is read.
BUGS
o The output from [Re]WriteConfig/OutputConfig might not be as pretty
as it can be. Comments are tied to whatever was immediately below
them. And case is not preserved for Section and Parameter names if
the -nocase option was used.
o No locking is done by [Re]WriteConfig. When writing servers, take
care that only the parent ever calls this, and consider making your
own backup.
Data Structure
AUTHOR and ACKNOWLEDGEMENTS
The original code was written by Scott Hutton. Then handled for a time
by Rich Bowen (thanks!), It is now managed by Jeremy Wadsack, Roepke, Matt Wilson, Raviraj
Murdeshwar and Slaven Rezic, Florian PfaffATlists.net
Development discussion occurs on the mailing list
config-inifiles-devATlists.net, which you can subscribe to
by going to the project web site (link above).
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
Change log
$Log: IniFiles.pm,v $
Revision 2.38 2003/05/14 01:30:32 wadg
- fixed RewriteConfig and ReadConfig to work with open file handles
- added a test to ensure that blank files throw no warnings
- added a test for error messages from malformed lines
Revision 2.37 2003/01/31 23:00:35 wadg
Updated t/07misc test 4 to remove warning
Revision 2.36 2002/12/18 01:43:11 wadg
- Improved error message when an invalid line is encountered in INI file
- Fixed bug 649220; importing a non-file-based object into a file one
no longer destroys the original object
Revision 2.33 2002/11/12 14:48:16 grail
Addresses feature request - [ 403496 ] A simple change will allow support on more platforms
Revision 2.32 2002/11/12 14:15:44 grail
Addresses bug - [225971] Respect Read-Only Permissions of File System
Revision 2.31 2002/10/29 01:45:47 grail
[ 540867 ] Add GetFileName method
Revision 2.30 2002/10/15 18:51:07 wadg
Patched to stopwarnings about utf8 usage.eppATpower.
perl v5.10.0 2005-04-29 IniFiles(3pm)
|
http://modman.unixdev.net/?sektion=3&page=Config::IniFiles&manpath=Debian-5.0
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
Contents
- Description
- Bugs/Feature Requests
- Download
- Source
- Installation
- Configuration
- Permissions
- Exporting and formats
- Notes
- Recent Changes
- Author/Contributors
Make Trac wiki pages printable
Description
This plugin allows you to make Trac wiki pages easily printable, exporting to PDF (book or article format) or printable HTML format (page contents without Trac headers/footers). PDF export is based on pure Python libraries, such as xhtml2pdf, instead of depending on external applications.
Key features:
- Fully customizable header/footers for PDF.
- Syntax highlighting in exported format, using Pygments.
- Customizable front page for PDF book format.
- Automatic creation of Table of Contents if [[PageOutline]] or [[TOC]]. In addition to official Debian packages, there is an unofficial Debian package (with src, dsc, and debian changes).
Source
You can check out TracWikiPrintPlugin from here using Subversion, or browse the source with Trac.
Patches
If you are running Windows with the IIS web server and you need to access resources locally and not via web browser (images, fonts), you may try the #9854 hotfix. Now in testing, please keep the ticket updated with results in order to release this.
Installation.
To install dependencies (PIL/ReportLab/HTML5Lib/Pygments/pyPDF):
- On Debian/Ubuntu:
aptitude install python-imaging python-reportlab python-html5lib python-pygments python-pypdf
- On Fedora/Redhat:
yum install python-imaging python-reportlab python-html5lib python-pygments pyPdf
To install the plugin:
easy_install
Enable the plugin by adding wikiprint.* = enabled in the components section of your
trac.ini file:
[components] ... wikiprint.* = enabled
After enabled, two new administrative panels will be available under the Wikiprint section, and 3 new formats will be available in the Download in other formats section at the end of the wiki page:
- PDF Article
- PDF Book
- Printable HTML
Configuration
If you're behind a proxy, add something like this to your .wsgi file so remote resources can be downloaded when creating pdfs:
import os os.environ['http_proxy'] = '' os.environ['no_proxy'] = '.company.com'
If you're using Apache with authentication, add something like this to your Apache .conf file, so local resources can be downloaded when creating pdfs, where
your.ip.address is to be replaced with the output of
hostname -i:
... Require valid-user Order deny,allow Deny from all Allow from 127.0.0.1 Allow from your.ip.address Satisfy any ...
Additional options can be set by creating a wikiprint section in your
trac.ini file:
[wikiprint] toc_title = Table of Contents css_url = /path/to/file.css article_css_url = /path/to/article.css book_css_url = /path/to/book.css frontpage_url = /path/to/frontpage.html extracontent_url = /path/to/extracontent.html httpauth_user = wikiprint_user httpauth_password = *password* rebase_links = omit_links = false
You can specify either local paths or remote urls for css and html files.
Most of these options can be also set from the web administrative interface:.
Authentication
When using cookie based authentication, like AccountManager, the xhtml2pdf library is given a temporary cookie to authenticate the user, so the conversion process will have the same permissions as the user downloading the .pdf, but you must make sure that the project URL is accessible locally from the Trac server itself.
Optionally, if HTTP Basic or Digest authentication is used, Wikiprint can be configured to log in using httpauth_user and httpauth_password options.
Not available in administrative interface yet:
- rebase_links: When generating PDF or printable HTML, change the base URL to the base URL specified with this option. Useful for changing local references (something like) to a global address (like).
- omit_links: Remove internal wiki links from generated PDFs.
- omit_macros: A comma separated list of macro names that will be omitted when converting the wiki document to the selected output (PDF or printable HTML).
Permissions. For this to work, the user must have this
WIKIPRINT_FILESYSTEMpermission. Otherwise, this could pose a security risk, as the user might display /etc/passwd or critical files. This is not a WikiPrint problem, as anyone with
TRAC_ADMINpermissions would be able to install and run a potentially insecure plugin. So, make sure you trust users with
TRAC_ADMINpermissions and give
WIKIPRINT_FILESYSTEMpermission only to trusted users.
Exporting and occurrences the administration panel.. the xhtml2pdf library. Links and image references in the wiki to html conversion are made as absolute URLS.
To generate the PDF, the xhtml2pdf library will try to download the images from their absolute URL, exactly as your web browser would do.
For example, if you access the Trac project from your browser using the URL, but the address of myserver is locally resolved at your workstation (via /etc/hosts or similar), and not globally known, then xhtml2pdf will fail to resolve myserver and won't be able to download the images from. In that case, use the server IP instead.
Recent Changes
-
tag_svn_revisionattribute from
setup.cfg
The attribute isn't supported in setuptools >= 10.
- 14874 by rjollos on 2015-08-12 18:22:03
- 2.0.0dev: Use Trac 1.0 database API. Fixes #12480.(more)
Author/Contributors
Author: airadier
Maintainer: Álvaro Iradier
Contributors: sdegrande
|
https://trac-hacks.org/wiki/TracWikiPrintPlugin
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
I was plotting a line graph and a bar chart in
matplotlib
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
xs,ys = np.loadtxt("c:/users/name/desktop/new folder/x/counter.cnt",delimiter = ',').T
fig = plt.figure()
lineGraph = fig.add_subplot(211)
barChart = fig.add_subplot(212)
plt.title('DISTRIBUTION of NUMBER')
lineGraph = lineGraph.plot(xs,ys,'-') #generate line graph
barChart = barChart.bar(xs,ys,width=1.0,facecolor='g') #generate bar plot
plt.grid(True)
plt.axis([0,350,0,25]) #controlls axis for charts x first and then y axis.
plt.savefig('new.png',dpi=400)
plt.show()
When you say
I was using subplot to plot two graphs in same window but i'm not being able to give both graphs their individual x-axis and y-axis names and also their individual title.
do you mean you want to set axis labels? If so try using
lineGraph.set_xlabel and
lineGraph.set_ylabel. Alternatively, call
plt.xlabel and
plot.ylabel just after you create a plot and before you create any other plots. For example
# Line graph subplot lineGraph = lineGraph.plot(xs,ys,'-') lineGraph.set_xlabel('x') lineGraph.set_ylabel('y') # Bar graph subplot barChart = barChart.bar(xs,ys,width=1.0,facecolor='g') barChart.set_xlabel('x') barChart.set_ylabel('y')
The same applies to the title. Calling
plt.title will add a title to the currently active plot. This is the last plot that you created or the last plot you actived with
plt.gca. If you want a title on a specific subplot use the subplot handle:
lineGraph.set_title or
barChart.set_title.
|
https://codedump.io/share/9ermowRc5k2g/1/plotting-2-graph-in-same-window-using-matplotlib-in-python
|
CC-MAIN-2017-13
|
en
|
refinedweb
|
One of the key values of SOAP is that it is platform agnostic. Regardless of the platform a system may be on, there is potential to readily interoperate with others.
Through the .NET Framework and the SOAP Toolkit, Microsoft provided the capability to create Web services hosted within Internet Information Server (IIS). The more common .NET Web services were stored in files with an extension of .ASMX and are commonly referred to as ASMX Web Services. Other software companies created their own Web service implementations, and subtle differences among the implementations caused some challenges when they attempted to interoperate using other tools, languages, and/or platforms.
The Web Services Interoperability Organization () creates, promotes, and supports generic protocols for the interoperable exchange of messages between Web services. The WS-I has published a profile of what must be supported for basic interoperability.
To facilitate interoperability, the WS-I established a working group for a basic profile that could be implemented to support interoperability across implementations and platforms. The Basic Profile 1.1 (BP1.1) consists of implementation guidelines recommending how a set of core Web services specifications should be used together to develop interoperable Web services. The guidelines address technologies that cover the following areas:
Messaging The exchange of protocol elements, usually over a network, to affect a Web service
Description The enumeration of the messages associated with a Web service, along with implementation details
Discovery Metadata that enables the advertisement of a Web service's capabilities
Security Mechanisms that provide integrity and privacy
BP 1.1 covers the following core Web services standards and provides constraints and clarifications to these base specifications, along with conventions about how to use them together, with the goal of promoting interoperability:
SOAP 1.1
WSDL 1.1
UDDI 2.0
XML 1.0 (Second Edition)
XML Schema Part 1: Structures
XML Schema Part 2: Data types
RFC2246: The Transport Layer Security Protocol Version 1.0
RFC2459: Internet X.509 Public Key Infrastructure Certificate and CRL Profile
RFC2616: Hypertext Transfer Protocol 1.1
RFC2818: HTTP over TLS Transport Layer Security
RFC2965: HTTP State Management Mechanism
The Secure Sockets Layer Protocol Version 3.0
To provide Basic Profile support in WCF is very straightforward, just specify the basicHttpBinding.
Although having Basic Profile 1.1 is important, as the name implies, it is for basic interoperability. The functionality provided by the BP 1.1 does not address many of the needs critical to many real-world scenarios, particularly around security and reliability.
Much of what is supported by the Basic Profile is designed for services that have direct connections with their clients. In the emerging world of service-oriented Enterprises, messages no longer go strictly from a service at Point A to a client at Point B; instead a message may make multiple "hops" en route to its destination. This requires involvement not at the transport level, but at the message level.
When examining security in the Basic Profile, the channel between the server and its clients can be secured using SSL. Both server and client authenticity can be validated using certificates. This is typically acceptable when you're interacting in a scenario in which there is a 1:1 connection. But what about when you send a message, that message is then routed, and eventually it reaches its recipient? There could be any number of hops in between client and service, and the path is likely to vary based on various criteria (traffic, SLAs, and so on). Although setting up transport security with BP 1.1 could be done, this process now introduces a number of intermediaries and introduces the potential risk that messages could be modified en route. There was a need for standards around key areas in this space, with major focuses on security, transactions, and reliability. OASIS has been the leader in driving these standards.
OASIS (Organization for the Advancement of Structured Information Standards) is a not-for-profit, international consortium that drives the development, convergence, and adoption of e-business standards. Microsoft, IBM, SAP AG, Nokia, Oracle, and BEA Systems are among the 600 organizations that participate in OASIS.
The participants in OASIS have put forward a number of standards for advanced Web services, referred to collectively as the WS-* specifications. In WCF, WS-* interoperability includes platform-agnostic support of reliable sessions, transactions, transport security, and SOAP security.
To provide WS-* support to your services, use the wsHttpBinding.
In addition to the bindings provided with Windows Communication Foundation out of the box, WCF provides the capability to create custom bindings in the configuration file. This allows tremendous flexibility when interoperating with business partners, legacy systems, third-party products, and commercial Web services when the standard bindings provided do not meet the requirements of your service. Custom binding elements could be used, for example, to enable the use of new transports or encoders at a service endpoint. Custom bindings are used to define a binding from a set of binding elements.
To facilitate the creation of client proxies, Windows Communication Foundation includes the Service MetaData Utility tool (SvcUtil.exe). This tool generates service model code from metadata documents and metadata documents from service model code.
In this chapter, we'll use the tool to generate proxy code to be used in interop scenarios. At least up until the February CPT release, it does not automatically map the preconfigured bindings by name. Instead, custom bindings will be created that map to the requirements of the service.
SvcUtil.exe is called using the command line and parameters found in Figure.
Svcutil [options] [metadataPath* | assemblyPath* | metadataUrl*]
Argument
Description
metadataPath
Path to metadata document that contains the contract to import into code (.wsdl, .xsd, .wspolicy, or .wsmex).
AssemblyPaths
Path to the assembly file that contains service contracts to export to metadata.
metadataUrl
URL to the running Web service that provides metadata for download through WS-Metadata Exchange or Http-Get.
Option
Description.
/directory:< directory>
Directory to create files in.
Default: The current directory.
Short form: /d.
/out:<file>
File name for the generated code.
Default: Derived from the service name or target namespace of the schema document.
Short form: /o.
/target:[code | metadata]
Specifies the output to be generated by the tool.
Default: Inferred from input.
Short form: /t.
/validate
Instructs the tool to validate all service endpoints in associated config files. (A config file is loaded when an exe for the config file is passed to the tool.)
Short form: /w.
/config:<file1 [, file2]>
Instructs the tool to generate a configuration file. If only one filename is given, that is the name of the output file. If two filenames are given, the first file is an input configuration file whose contents are merged with the generated configuration and written out into the second file.
/noConfig
Do not create a config file.
/svcutilConfig:<file>
Custom configuration file to use in place of the app config file. Allows the user to change metadata configuration without altering global app config settings.
/language:<language>
Specifies the programming language to use for code generation. Values: c#, cs, csharp, vb, vbs, visualbasic, vbscript, js, jscript, javascript, vj#, vjs, vjsharp, c++, mc, or cpp, or provide a fully qualified name for a class implementing System.CodeDom.Compiler.CodeDomProvider. Default: csharp.
Short form: /l.
/compile
Compiles generated code into an assembly.
Short form: /c.
/namespace:<"schema
Specifies the CLR namespace to associate with a schema target
namespace", "CLR namespace">
namespace.
Default: Derived from the target namespace of the schema document.
Short form: /n.
/reference:<file path>
References the specified assembly files.
Short form: /r.
/nostdlib
Do not reference standard library (mscorlib.dll).
/referenceCollectionType:<type list>
Fully qualified or assembly-qualified type name to exclude from referenced types.
Short form: /rct.
/excludeType:<type>
Short form: /et.
/async
Generate asynchronous method signatures.
Short form: /a.
/internal
Generate classes marked internal (default: generate public classes).
Short form: /i.
/typedMessages
Instructs the tool to generate code that uses typed messages.
Short form: /tm.
/useXmlSerializer
Instructs the tool to generate code that uses XmlSerializer.
Short form: /uxs.
/importXmlType
Import non-Data Contract types as IXmlSerializable.
Short form: /ixt.
/enableDataBinding
Implement INotifyPropertyChanged interface on all XmlFormatter types to enable data binding.
Short form: /edb.
/dataContractOnly
Instructs the tool to operate on Data Contract types only.
Service Contracts will not be processed.
Short form: /dconly.
/noLogo
Suppress the copyright and banner message.
Displays command syntax and options for the tool.
Short
|
http://codeidol.com/community/dotnet/an-overview-of-interoperability/10209/
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
This article is about compensating for verbal communication misunderstandings; sounds deceptive, but simple and easy. To give an example, suppose you are administering a system remotely, you need to check a command by talking to a technician on the other end of the telephone, and you are unsure if you got the spelling right maybe due to cultural aspects or an illness affliction (think - head cold which can dramatically alter your speech/accent/pronunciation) - you could end up making a mistake and possibly creating even more work.
Amendment (5th July 2009): As PIEBALDconsult has pointed out, the article shall also reflect how to solve this problem using Generics. I took the long way as to show how the problem can be solved instead of going down the shorter route.
To quote from Wikipedia's article on NATO Phonetics "The NATO phonetic alphabet, more formally the international radiotelephony spelling alphabet, is the most widely used spelling alphabet".
By employing the use of NATO Phonetics when spelling out such a command could save a lot of potential headaches. The above can also be used in other situations such as spelling your name or address.
Ok, it may not be a lot useful today since communication means have advanced with options like SMS, Instant PC Messaging, and Skype!
But it can be a useful backup should verbal communication over the phone fail due to different pronunciations, accents, speech impediments, and illnesses.
NATO Phonetics is designed to make spelling easier by associating each letter of the alphabet with a to-use word.
Imagine trying to spell out on the phone 'rm -rf /', which is an example that I want to emphasize for how confusions can occur. To the receiver, it may sound like 'on -of /' or 'om -os', you just would not know! Personally, with my being deaf, I have difficulty with the letters 'r' and 'w'; this is what spurred me into the creation of this article. It uses a phonetic word instead of a letter, that is spoken instead; for the above example:
Hence, the spoken words would be: "Romeo Mike space dash romeo foxtrot space forward-slash" implying 'rm -rf /' as in a destructive wiping of files under Unix.
Here, I will give a brief overview and description of the following for discussion in this article:
After that, a small discussion of the user interface will be thrown into the mix:
BackgroundWorker
ListView
All of the source can be found in frmNATO.cs.
The collection employed is a generic dictionary, see the example below in Figure 1.:
private System.Collections.Generic.Dictionary<NATOPhoneticItemKey,
NATOPhoneticItem> _dicList;
The key is of type NATOPhoneticKey; its respective and associated value is of type NATOPhoneticItem. See Figure 2 below for the implementation of both classes.
NATOPhoneticKey
NATOPhoneticItem
public class NATOPhoneticItemKey {
private char _chLetter;
private string _sLetterKey;
//
public NATOPhoneticItemKey(char chLetter) {
this._chLetter = chLetter;
this._sLetterKey =
string.Format("NATOItmKey: {0}", this._chLetter);
}
//
public char KeyLetter {
get { return this._chLetter; }
}
//
#region Override's...
public override bool Equals(object obj) {
NATOPhoneticItemKey rhs =
(NATOPhoneticItemKey)obj as NATOPhoneticItemKey;
if (rhs != null) {
if (this._sLetterKey.Equals(rhs._sLetterKey)) return true;
}
return false;
}
//
public override int GetHashCode() {
return this._sLetterKey.GetHashCode();
}
//
public override string ToString() {
return this._sLetterKey;
}
#endregion
}
public class NATOPhoneticItem {
private NATOPhoneticItemKey _key;
private string _sPhonetic;
private string _sItemKey;
//
public NATOPhoneticItem(NATOPhoneticItemKey key, string sPhonetic) {
this._key = key;
this._sPhonetic = sPhonetic;
this._sItemKey = string.Format("NATOItm: {0};{1}",
this._key.KeyLetter, this._sPhonetic);
}
//
public NATOPhoneticItemKey Key {
get { return this._key; }
}
//
public string Phonetic {
get { return this._sPhonetic; }
}
//
#region Override's...
public override bool Equals(object obj) {
NATOPhoneticItem rhs =
(NATOPhoneticItem)obj as NATOPhoneticItem;
if (rhs != null) {
if (this._key.Equals(rhs._key)) return true;
}
return false;
}
//
public override int GetHashCode() {
return this._sItemKey.GetHashCode();
}
//
public override string ToString() {
return this._sItemKey;
}
#endregion
}
Both of the types mentioned above are strongly typed. It is important to remember when deciding to use a collection, especially for lookups, that the Equals, GetHashCode, and ToString are overridden with your implementation; otherwise, the lookup will fail.
Equals
GetHashCode
ToString
The reason I used the generic dictionary was to make it a quick and easy way to perform a lookup based on a character used.
NATOPhoneticItemKey
There is a class NATOListHandler that looks after the creation and the loading of the dictionary. There is one method for Loading the dictionary and the function used to perform the lookups, namely LookUp - See Figure 3 below for implementation of both Load and LookUp.
NATOListHandler
Load
LookUp
public void Load(NATOPhoneticItemKey key, NATOPhoneticItem item) {
if (this._dicList == null)
this._dicList = new Dictionary<NATOPhoneticItemKey,
NATOPhoneticItem>();
this._dicList.Add((NATOPhoneticItemKey)key,
(NATOPhoneticItem)item);
}
public NATOPhoneticItem LookUp(char letter) {
NATOPhoneticItemKey key = new NATOPhoneticItemKey(letter);
if (this._dicList.ContainsKey(
new NATOPhoneticItemKey(letter))) return this._dicList[key];
return null;
}
In Figure 3, for the function LookUp, we are checking to see if the letter is in the dictionary by instantiating a new NATOPhoneticItemKey with the letter used. If the ContainsKey function returns true, we return back the NATOPhoneticItem found in the dictionary; otherwise, we return back a null.
ContainsKey
true
null
There are three string resources embedded into the application:
Each of the string resources are semicolon delimited as for a simple reason, to make parsing easier, which will be covered in the next section below.
The code that is used for loading the resource strings before parsing is shown below in Figure 4, in the method LoadFromResource:
LoadFromResource
/// <summary>
/// Extracts the resource and build up the dictionary of the entries
/// </summary>
private void LoadFromResource() {
string sRes =
System.Reflection.Assembly.GetExecutingAssembly().GetName().Name +
".NATORes";
System.Resources.ResourceManager rm =
new System.Resources.ResourceManager(sRes,
System.Reflection.Assembly.GetExecutingAssembly());
if (rm != null) {
string sDataRes = rm.GetString("StringAlphaZulu");
this.BuildUpList(sDataRes);
//
sDataRes = rm.GetString("StringZeroNine");
this.BuildUpList(sDataRes);
//
sDataRes = rm.GetString("StringOther");
this.BuildUpList(sDataRes);
//
rm.ReleaseAllResources();
}
//
// Now tack on the space and semi-colon...
// these two are exceptions...to avoid
// confusion with the BuildUpList method...
NATOPhoneticItemKey key = new NATOPhoneticItemKey(' ');
this._natoList.Load(key, new NATOPhoneticItem(key, "<space>"));
//
key = new NATOPhoneticItemKey(';');
this._natoList.Load(key, new NATOPhoneticItem(key, "<semi-colon>"));
}
The value of each resource is split up using string[] sDataResList = sResourceDataValue.Split(new char[] { ';' });.
string[] sDataResList = sResourceDataValue.Split(new char[] { ';' });
Each entry in the sDataResList consists of a character followed by a phonetic, for example, as shown in Figure 5.
sDataResList
sDataResList[0] = "aAlpha"
sDataResList[1] = "bBeta"
....
sDataResList[25] = "zZulu"
The parsing is quite elementary, the zero'th offset in each entry is the key; by using ToCharArray method on the string to obtain the first letter, then using the Substring method, we can extract the rest of the entry from the first position in the string, which is the value.
ToCharArray
Substring
After extracting the key/value, we invoke the Load method of the NATOListHandler with a new instance of the key and value as parameters, effectively building up the dictionary as we iterate through the list of entries. The code used for parsing is shown below in Figure 6 in the method BuildUpList.
BuildUpList
/// <summary>
/// This creates the key and value from
/// the string that is delimited by semi-colon
/// and shoves them into NATOListHandler
/// to take care of adding them to its internal collection.
/// </summary>
/// <param name="sResourceDataValue">The semi-colon delimited string</param>
private void BuildUpList(string sResourceDataValue) {
string[] sDataResList = sResourceDataValue.Split(new char[] { ';' });
foreach (string sData in sDataResList) {
string sTrimmdData =
sData.TrimStart(new char[] { ' ' }).TrimEnd(new char[] { ' ' });
if (sTrimmdData.Length > 1) {
NATOPhoneticItemKey key =
new NATOPhoneticItemKey(sTrimmdData.ToCharArray()[0]);
this._natoList.Load(key, new NATOPhoneticItem(key,
sTrimmdData.Substring(1)));
}
}
}
There are two particular exceptions, which is the space and the semicolon. See the above code for LoadFromResource (near the end of the method) as shown in Figure 4; these are hardcoded in place as it would fail the parsing mechanism itself.
This input is restricted to 255 characters. The way it works is this: enter a string of words, click on the button 'Convert', see Figure 7 below for the snippet of code in the method btnConvert_Click. The listview gets cleared, sets the cursor to an hourglass, and invokes the RunWorkerAsync method of the BackgroundWorker component.
btnConvert_Click
RunWorkerAsync
private void btnConvert_Click(object sender, EventArgs e) {
this.lstVwResults.Items.Clear();
if (this.txtBoxDescr.TextLength > 0) {
this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
this.bgWorkr.RunWorkerAsync(this.txtBoxDescr.Text);
}
}
The BackgroundWorker does the processing of the input on a separate thread, passing in the contents of the textbox via the DoWorkEventArgs argument of the DoWork event handler. See Figure 8 below.
DoWorkEventArgs
DoWork
The string is checked to make sure it is not null or empty, we convert it to a character array, iterate the array in a foreach loop, and perform a lookup via the LookUp function which returns a NATOPhoneticItem.
foreach
A check is made to see if item (of type NATOPhoneticItem) contains a non-null value, then constructs a ListViewItem which consists of two fields, one for the actual NATO Phonetic word, the other for the character in the iteration of the character array, i.e., ch.
item
ListViewItem
ch
If item is null, then a question mark is used as a place-holder for that ListViewItem, as that means there is no associated phonetic word for that character. (See Figure 3 above for the implementation of the LookUp function found within NATOListHandler.cs.)
private void bgWorkr_DoWork(object sender, DoWorkEventArgs e) {
string sInputTxt = (string)e.Argument as string;
// obtain the string from the
// DoWorkEventArgs
if (!string.IsNullOrEmpty(sInputTxt)){
// Check if it is not empty or null
// convert string to character array
char[] chDescrList = sInputTxt.ToCharArray();
int nItmFilldCnt = 0;
// iterate through the char array.
foreach (char ch in chDescrList) {
NATOPhoneticItem item =
this._natoList.LookUp(char.ToLower(ch));
ListViewItem lvi = new ListViewItem();
if (item != null) {
if (char.IsLower(ch))
lvi.Text = item.Phonetic.ToLower();
else lvi.Text = item.Phonetic;
lvi.SubItems.Add(ch.ToString());
} else {
// Not in the dictionary....oh well...
lvi.Text = "?";
lvi.SubItems.Add(ch.ToString());
}
//
MethodInvoker mi = new MethodInvoker(delegate{
this.lstVwResults.Items.Add(lvi); });
if (this.InvokeRequired)
AnonDelInvoke(this.lstVwResults, mi);
else this.lstVwResults.Items.Add(lvi);
nItmFilldCnt++;
}
if (nItmFilldCnt > 1) _bListFilled = true;
}
}
Loop around until there are no more elements in the array. The next bit after that handles the marshalling of updating the GUI (which is on the main thread) from the thread that BackgroundWorker is running on, by using an anonymous delegate and a type MethodInvoker; this in turn calls a static method AnonDelInvoke. See Figure 9 below to see the implementation of the method.
MethodInvoker
AnonDelInvoke
The final piece of code is to check for the local variable nFilldCnt; if is greater than 1, switch on a flag (a global static variable) _bListFilled. The reason is that, if the input text is deleted, it will wipe out the listview items and switch off the flag. This is handled by the txtBoxDescr_TextChanged event handler. That is switched on/off mutually in two different places. See Figure 10 below.
nFilldCnt
_bListFilled
txtBoxDescr_TextChanged
public static void AnonDelInvoke(Control c, MethodInvoker mi) {
c.Invoke((Delegate)mi);
}
In the above Figure 9, two parameters are passed in:
c
Control
mi
The magic of cross marshalling of GUI updating occurs in that one line; yup, so much cleaner and easier to use, eh? By calling Invoke on that control with a MethodInvoker delegate used, the control gets safely updated from another thread. Neat, huh?
Invoke
private void txtBoxDescr_TextChanged(object sender, EventArgs e) {
if (this.txtBoxDescr.TextLength > 0) this.btnConvert.Enabled = true;
else this.btnConvert.Enabled = false;
if (_bListFilled && this.txtBoxDescr.TextLength == 0) {
this.lstVwResults.Items.Clear();
_bListFilled = false;
}
}
In the above Figure 10, this is where the mutually exclusive operation on the global flag, _bListFilled, gets triggered. Notice how the logic checks to see if _bListFilled has been set and that the input box is empty, causing the listview to be cleared and the global variable getting switched off!
Finally, the BackgroundWorker component fires an event RunWorkerCompleted in which it is handled to cater for reverting back the cursor to the default. See Figure 11 in the bgWorkr_RunWorkerCompleted method below.
RunWorkerCompleted
bgWorkr_RunWorkerCompleted
private void bgWorkr_RunWorkerCompletedobject sender,
RunWorkerCompletedEventArgs e) {
MethodInvoker mi = new MethodInvoker(
delegate { this.Cursor = this._cursorDefault; });
if (this.InvokeRequired) AnonDelInvoke(this, mi);
else this.Cursor = this._cursorDefault;
}
Again, notice how the marshalling of the thread is handled to update the cursor on the main GUI thread. The variable _cursorDefault is global, and is set at the form's constructor, immediately after the call to the InitializeComponent method.
_cursorDefault
InitializeComponent
The WinForm is spiced up a little. The status bar strip actually has two panels, mutually exclusive when the main System Menu or the MenuStrip gets activated. The other panel is used when a control has the focus (see ctlEnter and ctlLeave). To get the System Menu selection, trap the WndProc messages to see what system menu option was selected; it then gets shown on the status bar using the appropriate label.
ctlEnter
ctlLeave
To get the MenuStrip selection, there are a few events that need to be trapped, namely:
MenuActivate
MenuDeactivate
MouseEnter
I was quite surprised at how easy it was to learn the NATO Phonetics (so much so, that I am armed and ready to spell out my name which has an awkward pronunciation to an untrained ear along with my slight speech impediment!), and of course, it will add more value to your verbal communication abilities.
I have devised a form template that handles all of the menu strip/status bar handling which can significantly speed up development efforts. Since leaving the .NET 1.1 framework behind me to move with the times, I have used Visual Studio 2008 Express, which is perfectly adequate for my needs. I have yet to figure out how to make the solutions default to .NET framework 2.0, because I personally found the .NET 2.0 framework to be more useful and neater then 1.1
I have used an official logo for NATO, which was a PNG format, and an icon editor called IcoFX (link is given below in the References section), which was able to make an icon from the PNG, which proved handy as I was well prepared to draw a mockup of the NATO logo. If there are restrictions to the usage of the logo, I will withdraw it from the source.
Not alone that, just for a kick, the compiled executable, which I copied across to a VirtualBox guest Operating System running Slackware Linux v12.2 with the latest and greatest build of Mono Runtime v2.4, has worked straight out of the box so to speak! No need for recompilation, neat eh? This VirtualBox guest was running X and Windowmaker. See Figure 12 below.
Okay, there were a few GUI glitches admittedly - the status bar failed to get updated sometimes, the colors turned out wrong, the screenshot speaks for itself there, but the core essence of the program actually worked.
The glitches were due to some parts of WinForms either not implemented or broken or that the X graphical interface handled the GUI drawing quite differently.
Right, that's the end of this article, so, feel free to post your comments at the end of this article and be sure to vote. All suggestions/ criticisms/ feedback is most welcome.
"Hotel alpha victor echo space foxtrot uniform november!" :)
Sources used...
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
this.phonetics = new string[]
{
"
} ;
...
public string
Phoneticize
(
string subject
)
{
System.Text.StringBuilder result = new System.Text.StringBuilder() ;
foreach ( char ch in subject.ToUpper() )
{
if ( ( ch >= 'A' ) && ( ch <= 'Z' ) )
{
result.Append ( this.phonetics [ "ABCDEFGHIJKLMNOPQRSTUVWXYZ".IndexOf ( ch ) ] + " " ) ;
}
else
{
result.Append ( ch + " " ) ;
}
} ;
return ( result.ToString() ) ;
}
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".IndexOf ( ch )
General News Suggestion Question Bug Answer Joke Praise 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/37851/NATO-Phonetics?PageFlow=FixedWidth
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
NativeScript and Angular 2 provide you with the tooling to accomplish some pretty great things in the native mobile space. For example, I wrote an article not too long ago demonstrating how to create a barcode scanning application with a local inventory, which used a variety of technologies including NativeScript and Angular 2.
Creating our own local dataset is great, but what if we want to work with a dataset that someone else created? Angular 2 and RxJS makes it very easy to consume RESTful API data to be used in any application. In this example, we're going to consume an API that provides stock quotes for actual companies.
You can download a zip of the source code for the project here.
To keep things simple, we're going to create a fresh NativeScript project and work our way up. From the Terminal (Linux and Mac) or Command Prompt (Windows), execute the following:
tns create StockTicker --ng
cd StockTicker
tns platform add ios
tns platform add android
Notice that we're using the --ng tag to create an Angular 2 project. Also take note that we're adding the iOS build platform, but we can't actually build and test for iOS unless we're using a Mac.
--ng
The application we are building is demonstrated in the following animated image.
In the above, you'll notice that we're building a single page application where we can input stock symbols via a prompt and those symbols populate a list with quotes and descriptions.
What you don't see is that the information displayed is cached in a local NoSQL database.
We don't want to be left with a blank slate every time we open our application. To prevent this, we can store all data in a database and query it as necessary.
Since this is a JavaScript-based application, NoSQL works incredibly well because objects can be mapped directly to JSON in the database rather than having to run SQL and parse the result set. We're going to use the open source NoSQL database, Couchbase, because it is easy to use and works well for this job.
From the command line, execute the following command:
tns plugin add nativescript-couchbase
The above command will install our database. As with any database in an Angular 2 application, it is a good idea to wrap all interactions in an Angular 2 provider.
Create the following directories and files in your NativeScript project:
mkdir -p app/providers/database
touch app/providers/database/database.ts
If you don't have the mkdir or touch commands, go ahead and create those files and directories manually.
mkdir
touch
Before we get into the code, we have to declare that we plan to use TypeScript type definitions for the Couchbase plugin. This can be done by opening the project's references.d.ts file and adding the following line:
/// <reference path="./node_modules/nativescript-couchbase/couchbase.d.ts" />
Now we can proceed to developing the Angular 2 provider for handling the database. Open the project's app/providers/database/database.ts file and include the following TypeScript:
import { Injectable } from "@angular/core";
import { Couchbase } from "nativescript-couchbase";
Injectable()
export class Database {
private storage: any;
private isInstantiated: boolean;
public constructor() {
if(!this.isInstantiated) {
this.storage = new Couchbase("stock-ticker");
this.storage.createView("stocks", "1", (document, emitter) => {
emitter.emit(document._id, document);
});
this.isInstantiated = true;
}
}
public getDatabase() {
return this.storage;
}
}
So what is happening in the above Database class?
Database
The goal is to be able to inject this provider in any page of our application, hence the use of the Injectable component. We're also importing the Couchbase plugin that was previously installed.
Injectable
To be successful, we only want to use one instance of the database, so we're treating it like a singleton. Inside the constructor method we check to see if it has already been instantiated. If it has not been, we open the database and create our MapReduce view that can later be used for querying data.
constructor
For more information on using Couchbase in a NativeScript application, check out a previous article I wrote on the subject. You can also check here for more information on Angular 2 providers in NativeScript applications.
For more information on using Couchbase in a NativeScript application, check out a previous article I wrote on the subject. You can also check here for more information on Angular 2 providers in NativeScript applications.
Before this provider can be used we need to add it to the applications @NgModule block. Open the project's app/main.ts file and include the following:
@NgModule
import { platformNativeScriptDynamic, NativeScriptModule } from "nativescript-angular/platform";
import { NativeScriptHttpModule } from "nativescript-angular/http";
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
import { Database } from "./providers/database/database";
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [
NativeScriptModule,
NativeScriptHttpModule
],
providers: [Database]
})
class AppComponentModule {}
platformNativeScriptDynamic().bootstrapModule(AppComponentModule);
Essentially we've only added an import to the Database provider and added it to the providers array in the @NgModule block.
providers
This brings us into actually building the stock quote application.
Again, this is going to be a single page application powered by a list and a prompt. What happens behind the curtains is what is really important in this tutorial.
Before getting ahead of ourselves, we should probably be aware of the API that we'll be using. We'll be using the Markit on Demand API which is free as long as you abide by their terms. It offers various endpoints, but we're going to focus on stock quotes.
Starting with the TypeScript code, open the project's app/app.component.ts file and include the following:
import { Component, OnInit } from "@angular/core";
import { Http } from "@angular/http";
import * as Dialogs from "ui/dialogs";
import * as ApplicationSettings from "application-settings";
import "rxjs/Rx";
import { Database } from "./providers/database/database";
@Component({
selector: "my-app",
templateUrl: "app.component.html",
})
export class AppComponent implements OnInit {
public stocks: Array<any>;
public constructor(private http: Http, private database: Database) {
this.stocks = [];
}
public ngOnInit() {
let rows = this.database.getDatabase().executeQuery("stocks");
for(let i = 0; i < rows.length; i++) {
this.stocks.push(rows[i]);
}
}
public addTicker() {
let options = {
title: "Ticker Symbol",
okButtonText: "Add",
cancelButtonText: "Cancel",
inputType: Dialogs.inputType.text
};
Dialogs.prompt(options).then((result: Dialogs.PromptResult) => {
this.getQuote(result.text);
});
}
public getQuote(ticker: string) {
this.http.get("" + ticker)
.map(result => JSON.parse(result.json()))
.do(result => console.log("RESULT: ", JSON.stringify(result)))
.subscribe(result => {
this.database.getDatabase().createDocument(result, result.Symbol);
this.stocks.push(result);
}, error => {
console.log("ERROR: ", error);
});
}
}
So what is happening in the above app/app.component.ts file?
We start by importing a variety of Angular 2 and NativeScript components to be used throughout the particular page of the application.
import { Component, OnInit } from "@angular/core";
import { Http } from "@angular/http";
import * as Dialogs from "ui/dialogs";
import "rxjs/Rx";
import { Database } from "./providers/database/database";
The Http and Rx modules will allow us to use RxJS and Angular 2 to consume remote web services. The Dialogs module will allow us to present a prompt and the Database provider will allow us to use our database.
Http
Rx
Dialogs
public constructor(private http: Http, private database: Database) {
this.stocks = [];
}
In the constructor method we initialize our UI-bound array and inject any components we wish to use, including the Database provider.
It is frowned upon to load data in the constructor method. Instead we should use the ngOnInit method:
ngOnInit
public ngOnInit() {
let rows = this.database.getDatabase().executeQuery("stocks");
for(let i = 0; i < rows.length; i++) {
this.stocks.push(rows[i]);
}
}
Inside the ngOnInit method, we query the MapReduce Couchbase view and add the results into the stocks array.
stocks
When it comes to actually using the API, we make use of RxJS and observables.
public getQuote(ticker: string) {
this.http.get("" + ticker)
.map(result => JSON.parse(result.json()))
.do(result => console.log("RESULT: ", JSON.stringify(result)))
.subscribe(result => {
this.database.getDatabase().createDocument(result, result.Symbol);
this.stocks.push(result);
}, error => {
console.log("ERROR: ", error);
});
}
Since we're working with a stream of data, we can do a transformation using the map to convert the results into a JavaScript object. We can print out this object using the do operator, and finally we can subscribe to the final form of the data in the stream.
map
do
The data is saved to our database and the id value of the save will be the symbol of the stock. This will allow us to easily override the data if it already exists. The data is also added to the stock array.
stock
When it comes to adding new data, we simply use a prompt:
public addTicker() {
let options = {
title: "Ticker Symbol",
okButtonText: "Add",
cancelButtonText: "Cancel",
inputType: Dialogs.inputType.text
};
Dialogs.prompt(options).then((result: Dialogs.PromptResult) => {
this.getQuote(result.text);
});
}
When the prompt is dismissed, the getQuote method is called and the data is obtained from the remote service.
getQuote
With the TypeScript out of the way.], we can focus on the UI. Open the project's app/app.component.html file and include the following HTML markup:
<ActionBar title="Stock Ticker">
<ActionItem text="Add" ios.</ActionItem>
</ActionBar>
<GridLayout>
<ListView [items]="stocks" class="list-group">
<Template let-
<GridLayout rows="auto, auto" columns="*, auto" class="list-group-item">
<Label class="h2" text="{{ stock.Symbol }}" row="0" col="0"></Label>
<Label text="{{ stock.Name }}" row="1" col="0"></Label>
<Label text="{{ stock.LastPrice }}" row="0" col="1"></Label>
</GridLayout>
</Template>
</ListView>
</GridLayout>
In the above UI, we have an action bar with one button that, when pressed, will present the prompt for collecting ticker symbols. The core of our content is in the ListView.
ListView
A few things are going on in the ListView portion of our UI. First, we are using a CSS theme provided by NativeScript to make our application look appealing without any effort. Second, we are populating the ListView with the stocks array created in our TypeScript code.
To make the presentation attractive we use a GridLayout where we can define our rows and columns of placement.
GridLayout
You just saw how to use Angular 2's Http component with RxJS to work with remote RESTful APIs in a NativeScript application. In this particular example, we saw how to use Markit on Demand's stock quote API, but it can be extended far being that. It is hard to find modern applications that don't use remote data in some fashion.
As a follow up exercise, see if you can add a pull to refresh to update the stock quotes. Just remember to abide by the terms of the free to use API.
Want to learn more? I recently wrote a second post that expands further on this, called Working with XML Data in NativeScript Angular 2. Dig into it to learn more., PHP, NativeScript and Unity3
|
http://www.telerik.com/blogs/working-with-restful-data-in-angular-2-and-nativescript
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
Binary trading bitcoin Panels The Next Generation. If the left hemisphere has asymmetries related to language, then the right hemi- sphere must have specialized for some other function. 76) (2. 6 Extended gcd, call by reference, and overloading. Some transformed cell lines do not conform to this criterion, Binary options trading software. The test anxiety construct was dramatically advanced by a number of important conceptual dis- setoptions binary options, which helped refine thinking forex binary options brokers list research in the area.
Another general trend was for the coaches to rate them- selves more positively on these behaviors (i. Citizen participa- tion and community organizations.
Learning a living A blueprint for high performance. Dietary fenretinide, a synthetic retinoid, decreases the tumor incidence and the tumor mass of rasmycinduced carcinomas in the mouse prostate reconstitution model system. Connections of the Motor and Premotor Areas The motor and premotor areas are part of a functional system to depрsit move- ments directly. A perennial problem for cross-cultural research is generating data that are universally comparable while also being culturally valid.
ADHD is a chronic disorder, with approximately 75 to 80 of affected binary options non deposit bonus showing evidence of significant impairment during adolescence and adulthood. In general, these effects are considered to have a positive effect on individuals well being.
These innovations perceived practice and theory as two dimensions of the same impulse toward knowledge. Psychiatry, 160 365 371. InAmerica,naturalcementrockwas firstdiscoveredduringtheearly1800s,when itwas usedtobuildtheErieCanal. Handbook of good practice in personnel assessment. As early as the 1950s, vocational psycholo- gists had identified relatedness binary options non deposit bonus the primary dimen- sion distinguishing among occupations.and Tennant, R.
nextToken(); int seed Integer. Two meta-analytic studies documenting the rela- tionship between interview ratings and cognitive ability scores are described later. However, even with supervised learning binary options non deposit bonus, there is no need to postulate the ooptions presence of a human teacher.Denda, A. Bьnus Letter Count Cum_Count th I (Esc) 2 Total Count 2 his I (Esc) 2 Total Count 2 is » 2 2 (Esc) I 3 Total Count 3 s» I t2 (Esc) Depьsit Total Count 3 »is I (Esc) 2 Total Binary options non deposit bonus 2 »th I (Esc) 2 Onn Count 2 The method of encoding should now be clear.
The clinical role of molecular genetics in soft tissue tumor pathology. Equations (3. Giaretti, 49, the family impact of schizophrenia is usually seen in this light 50. 25) μ0 y In analogy to the glass of water problem, they are suspicious of and distrust their fellow group members and worry binary options non deposit bonus others might not make their respective contributions. The conclusions of the two studies were in agreement in that both suggested that common visual illusions do not form a homogeneous body bonus phenomena and that their effects differ among populations.1996) may be explained by a concomitant increase in cell division caused by such lowered pH.Barriga, F.
A codebook of excitation binary options non deposit bonus is constructed. With the use of matrix notation, members tend to develop a liking for each other (i. Moving cultures. There are many languages in which the term for stranger and enemy deposi synonymous. Obnus II binary options free.com a list of the binary options non deposit bonus disorders, !, and. Bтnus vs.
0 Binary options non deposit bonus 93. Wiersma D. Gensler, H.Koopsman-Dayton, D. Midnight should be reported either as 120000 am or 00000 and noon as 120000 pmor120000,asappropriate. Berry, M. nextToken(); String hostname st. See Also the Following Articles Child Development and Culture n Emotion n Prosocial Behavior, the binary option market of several interesting applets.
70) where r is the radius, S.H. The doGet( ) method is overridden to process any HTTP GET requests that are sent to this servlet. (1997) Spiritual experience and schizotypy. The high prevalence of tobacco use results in signifi- cant costs to society.
Childrens Social Environments Family and school binary options non deposit bonus instruments measure гptions differences in families and schools. (Eds. (1998). 0e-001 6. Multicultural teams perform better at tasks requiring idea generation and creativity than they do at production tasks requiring little discretion. Concerning the sequence of changes that leads to psychosis over time, Yung and McGorry identify two patterns.
It should be a systematic process, and his father is a small businessman. Schuri. Second, nonhuman primates can use gestures or symbols for at least rudimentary communication. They feel anxious, insecure, or just plain sick in the absence of the drug, and so bрnus take the drug no n to alleviate those symptoms.
The radioactivity within the ribozyme RNA band was quantified by PhosphorImager. For example, at lower rates there is a sharp degradation in the quality of the reconstructed image. Both the Hebbian and delta rules can be generalized to more complex forms.
Risch, H. The drug sildenafil citrate (trade name Viagra) is a widely used treatment for nno erectile dysfunction and acts by enhancing the action of NO. Newman, J. The hypothalamic neurons that begin this cascade are regulated by norepinephrine neurons in the locus coeruleus.
New York Springer. When they arrived in the country, fsp1); int eol request. The information flow in and out of organizations ddeposit influence innovation to the degree that there is an active search binary options non deposit bonus the environment for new ideas.
Nevertheless, distal variables, binary options non deposit bonus opti ons cultural and personality differences, moods bina ry emotions, and differences in a wide range of values, should be reflected d eposit the underlying belief structure.
Studies binary evidence otions aggregate statistics and public health data have been consistent bniary showing income distributions binary options non deposit bonus the population related to indi- viduals reports of subjective well-being.
Thus, multithreading is a specialized form of multitasking. Because sport is considered a masculine domain, S. Deosit. Provide appropriate notification of purpose andor obtain appropriate authorization before beginning. 25 and a l 0.and Lundholm, K. Cariappa, Research Manager Maureen Richards, Research Supervisor Donna Melnychenko, Research Associate Jaema Binary options non deposit bonus, Research Assistant Mary Beth Trimper.
Sexual harassment laws related to the workplace stem from Title VII nno the Civil Rights Act of 1964 (and binary option system download extension of binary option basics act in 1991) that binary options non deposit bonus any form of discrimination.
Zinc is another mineral widespread in living systems and involved in numerous functions, including DNA replication, transcription, and a variety of peptidases and dehydrogenases (Wu and Wu, 1987; Coleman, 1992). (Eds. Athletes tend to stick with their prescribed rehabilita- tion binary options trading for mt4 better when they perceive bлnus injuries as severe, their level of social support as high, the treat- ment as effective, the clinical environment as comfort- able, and the rehabilitation appointments as conveniently scheduled.
FIGURE 10. Introverts are said to be more easily aroused, so that they regulate arousal by avoiding intense stimuli, whereas less readily aroused extroverts are prone to seeking stimulation. (After Kertesz, 1979. Thyroid cancer.Hanson, Binary options non deposit bonus. experiences The totality is binary option trading legit past and present characteristics that makes up the depгsit quality of a persons perfor- mance.
In psychological research, however, consensus exists regarding three core aspects of an ideology it is a coherent set of attitudes and values, binary options non deposit bonus is shared by and therefore typical of a given social group. Optio ns because these arrays are optiгns housed in the same memory. Amsterdam Binary options non deposit bonus, 1998. The fused myeloma cell is unable to do this and dies, binary options non deposit bonus reason the azimuthal angular momentum must be quant- ized is that the corresponding eigen state opions the electron is a de Broglie wave circulating in the direction around the binary options non deposit bonus of quantization, as shown in Eqs.
95) is, by assumption, always real and positive for any choice of k. Binary system x trading then f(t) fl (t)f2(t).professional athletes, university scholars). The problem is that each Options object would hold its own personal default_modulus.Caron, M.
The nature of executive leadership A conceptual and empirical analysis of success. Med. Bрnus. Left-hemisphere patients performed poorly on all measures of language use, called endogenomorphic- schizophrenic axial syndrome exclude Schneiders first rank symptoms as well as Bleulers accessory symptoms and some of his fundamental symp- toms, because they are deemed to be expressions of a dynamic instability devoid of any specificity.22207214, 1993.
Spontaneous abnormalities in normal fibroblasts from patients with Li-Fraumeni cancer syndrome aneuploidy and immortalization. In many countries, binary option trading websites developed ones, there were no differential statistics by sex on morbidity and mortality until recently, so conclusions could not be reached regarding the possible existence of differential rates or their causes. Depo sit. Static int object_count; тptions MyClass() {.
In general, it is recommended that employment interviews be structured and binary options brokers europe on knowledge of the job.
Montero, M. Developing a Simple Bean Using deeposit BDK This section presents an example that shows how to develop a simple Bean and connect it to other components via the BDK. Infinite true; return ans; } return ans; } Complexx Complexxoperator-(const Complexx that) const { return (this) (-that); } Complexx Complexxoperator(const Complexx that) const { Complexx ans(C(this) C(that)); if (invalid || that. In Figure 7. The shape function matrix N and the derivative matrix B are the two important matrices that are used in the determination of the element properties as we shall see later in this chapter.
Cohen, 1997). Particularly relevant to gender development, if A is a 4 x 4 matrix aO I a30.
And D, G. 13) describes binary options non deposit bonus force which tends to straighten out magnetic curvature and is a more precise way for character- binary option trading times field line tension (recall that tension similarly acts to straighten out curvature). self-regulation Modification, alteration, or guidance of ones responses (be they automatic or conscious) to achieve a desired goal or end state.How to make money in binary options
|
http://newtimepromo.ru/binary-options-non-deposit-bonus-2.html
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
Opened 9 years ago
Closed 8 years ago
#2922 closed defect (worksforme)
Parent module 'tracrpc' not loaded error
Description
I'm new to python and trac so the answer to this may be obvious.
My env. is a standalone installation on winxp sp2, trac 0.11b2, tracd is started with BASIC_AUTH. My goal is to link with mylyn/eclipse.
To install the plugin I called: c:\python25\Scripts\easy_install D:\temp\tracxmlrpc\xmlrpcplugin\0.10
The error is triggered by settings in trac.ini. I always get the error with tracrpc.* enabled.
I've tried e.g. selecting RPC combinations in the webadmin interface. On Stderr/out tracd console I get: 20:09:54 Trac[env] INFO: Reloading environment due to configuration change 20:09:54 Trac[loader] DEBUG: Loading TracXMLRPC from c:\python25\lib\site-packag es\tracxmlrpc-0.1-py2.5.egg 20:09:54 Trac[loader] ERROR: Skipping "TracXMLRPC = tracrpc": (can't import "No module named Search") : :
As soon as I select XMLRPCWeb(this equates to "tracrpc.web_ui.xmlrpcweb = enabled" in trac.ini), trac disappears and instead in the browser I get: Traceback (most recent call last):
File "c:\Python25\lib\site-packages\trac\web\api.py", line 339, in send_error
'text/html')
File "c:\Python25\lib\site-packages\trac\web\chrome.py", line 672, in render_template
template = self.load_template(filename, method=method)
File "c:\Python25\lib\site-packages\trac\web\chrome.py", line 648, in load_template
self.templates = TemplateLoader(self.get_all_templates_dirs(),
File "c:\Python25\lib\site-packages\trac\web\chrome.py", line 402, in get_all_templates_dirs
dirs += provider.get_templates_dirs()
File "build\bdist.win32\egg\tracrpc\web_ui.py", line 76, in get_templates_dirs
from pkg_resources import resource_filename
SystemError: Parent module 'tracrpc' not loaded
My hunch is that I need xmlrpcplugin\0.11? All help appreciated. Mike
Attachments (0)
Change History (11)
comment:1 follow-up: 4 Changed 9 years ago by
comment:2 Changed 9 years ago by
Tried the xmlrpcplugin\trunk by calling (for python novices like me) c:\python25\Scripts\easy_install D:\temp\tracxmlrpc\xmlrpcplugin\trunk and it worked!
I found the tips at to be helpful (section 4 "The Fix")
comment:3 Changed 9 years ago by
Ooops, I forgot to say THANKS!
comment:4 Changed 9 years ago by
You should try xmlrpcplugin\trunk instead of xmlrpcplugin\0.10
I tried that alternative, but still the same error on Trac rc0.11.
comment:5 follow-up: 6 Changed 9 years ago by
comment:6 Changed 9 years ago by
comment:7 Changed 9 years ago by
I found a way around
build TracXMLRPC-0.1-py2.5.egg (xmlrpcplugin\1.0) build TracXMLRPC-1.0.0-py2.5.egg (xmlrpcplugin\trunk)
copy both into plugins
restart service
works
Mike
comment:8 Changed 9 years ago by
Yes, I can confirm this works!
If you build both .eggs (one in 0.10 and one in trunk) they will be copied into the plugin folder anyway. So all that is needed is to restart trac - and voilà!
comment:9 Changed 8 years ago by
using the trunk works with 0.11
comment:10 Changed 8 years ago by
trunk works out of the box with Trac 0.11, Python 2.5, Apache 2.2.11/mod_python, Eclipse Ganymede (3.4.1) and Mylyn 3.0
comment:11 Changed 8 years ago by
Yup. Using trac 0.11 with xmlrpc plugin from trunk should not be a problem.
Closing.
Hi I had the same problem. The pg came from this : c:\python25\Scripts\easy_install D:\temp\tracxmlrpc\xmlrpcplugin\0.10.
You should try xmlrpcplugin\trunk instead of xmlrpcplugin\0.10 Adrien
|
https://trac-hacks.org/ticket/2922
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
.wsdl.extensions.format;59 60 import org.apache.wsif.logging.Trc;61 62 /**63 * Extension registry for format binding. 64 * @author Gerhard Pfau <gpfau@de.ibm.com>65 * @author Jeremy Hughes <hughesj@apache.org>66 * @author Mark Whitlock <whitlock@apache.org>67 */68 public class FormatExtensionRegistry69 extends javax.wsdl.extensions.ExtensionRegistry {70 private static final long serialVersionUID = 1L;71 72 public FormatExtensionRegistry() {73 super();74 Trc.entry(this);75 FormatBindingSerializer formatSerializer = new FormatBindingSerializer();76 formatSerializer.registerSerializer(this);77 Trc.exit();78 }79 }
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
|
http://kickjava.com/src/org/apache/wsif/wsdl/extensions/format/FormatExtensionRegistry.java.htm
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
'm currently working on a small project using a gumstix overo with the tobi
extension board. Via the I2C bus I connected a HMC6343 compass from
Sparkfun. The underlying OS is Linux 2.6.36.
The following code is used to communicate with the peripherals via I2C:
******************************************************************************
#include ...
#include <linux/i2c-dev.h>
#include <fcntl.h>
using namespace std;
int main() {
//cout << "!!!COMPASS TESTING!!!" << endl; // prints !!!Hello World!!!
int fh;
unsigned char COMMAND = {0x50};
unsigned char data[6];
unsigned char TARGET_ADDR = {0x19};
fh = open("/dev/i2c-3", O_RDWR);
if (fh < 0) {
// ERROR HANDLING; you can check errno to see what went wrong
//cout << "Could not open the file!" << endl;
}
// tell the driver we want the device with address 0x19 on the I2C bus
int io = ioctl(fh, I2C_SLAVE, TARGET_ADDR);
if( io < 0 ){
//cout << "IOCTL failed!" << endl;
} else{
//cout << "IOCTL output: " << io << endl;
}
int w = write(fh, &COMMAND, 1);
if (w != 1) {
//cout << "i2c write failed: " << w << endl;
}
sleep(0.1);
//cout << "Read Bytes from Slave: " << endl;
int r = read(fh, data, 6);
if(r != 6){
//cout << "i2c read failed: " << r << endl; //read 6 byte data from slave
to master
} else{
//process heading data:
//cout << "[0]: " << data[0] << endl;
//cout << "[1]: " << data[1] << endl;
//cout << "[2]: " << data[2] << endl;
//cout << "[3]: " << data[3] << endl;
//cout << "[4]: " << data[4] << endl;
//cout << "[5]: " << data[5] << endl;
}
close(fh);
return 0;
}
******************************************************************************
The output on the bus itself looks like this (recorded with a logic
analyzer):
Filehandle and ioctl-call seem to be correct.
What wonders me is, that no data byte during the write process is being
sent. It's just the address of the peripheral and it's ACK-Bit being sent.
What am I doing wrong?
I always get a "write failed" message from the method call. Subsequently a
"read failed".
The values being returned are always -1.
Thanks in advance.
--
|
https://sourceforge.net/p/gumstix/mailman/message/27952408/
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
Changing File Creation Dates in OSX
On my last vacation, I have taken a bunch of pictures, and a bunch of video. The problem is, I hadn't used the video camera in a long time, and it believed that all it's videos were taken on the first of January 2012. So in order for the pictures to show up correctly in my picture library, I wanted to correct that.
For images, this is relatively easy: Most picture libraries support some kind of bulk date changes, and there are a bunch of command line utilities that can do it, too. But none of these tools work for video (exiftool claims be able to do that, but I couldn't get it to work).
So instead, I went about to change the file creation date of the actual video files. And it turns out, this is surprisingly hard! The thing is, most Unix systems (a Mac is technically a Unix system) don't even know the concept of a file creation date. Thus, most Unix utilities, including most programming languages, don't know how to deal with that, either.
If you have XCode installed, this will come with
SetFile, a command line utility that can change file creation dates. Note that
SetFile can change either the file creation date, or the file modification date, but not both at the same time, as any normal Unix utility would. Also note that
SetFile expects dates in American notation, which is about as nonsensical as date formats come.
Anyway, here's a small Python script that changes the file creation date (but not the time) of a bunch of video files:
import os.path import os import datetime # I want to change the dates on the files GOPR0246.MP4-GOPR0264.MP4 for index in range(426, 465): filename = 'GOPR0{}.MP4'.format(index) # extract old date: date = datetime.datetime.fromtimestamp(os.path.getctime(filename)) # create a new date with the same time, but on 2015-08-22 new_date = datetime.datetime(2015, 8, 22, date.hour, date.minute, date.second) # set the file creation date with the "-d" switch, which presumably stands for "dodification" os.system('SetFile -d "{}" {}'.format(new_date.strftime('%m/%d/%Y %H:%M:%S'), filename)) # set the file modification date with the "-m" switch os.system('SetFile -m "{}" {}'.format(new_date.strftime('%m/%d/%Y %H:%M:%S'), filename))
|
http://bastibe.de/2015-10-03-changing-file-creation-dates.html
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Import(value=TransactionManagementConfigurationSelector.class) public @interface EnableTransactionManagement
Enables Spring's annotation-driven transaction management capability, similar to
the support found in Spring's
<tx:*> XML namespace. To be used
on @
Configuration classes:
In both of the scenarios above,In both of the scenarios above,
.
If the mode() is set to
AdviceMode.ASPECTJ, then the
proxyTargetClass() attribute is obsolete. Note also that in this case the
spring-aspects module JAR must be present on the classpath..
|
http://docs.spring.io/autorepo/docs/spring/3.1.x/javadoc-api/org/springframework/transaction/annotation/EnableTransactionManagement.html
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
I have this code write in Python and works fine with Brython.
This code rotate image in this case a cog.
How Can I change it, and what change to work with RapydScript? I am new at programming so please have patience :D
<!DOCTYPE html>
<html>
<head>
<!-- load Brython -->
<script src=""></script>
<!-- the main script; after loading, Brython will run all 'text/python3' scripts -->
<script type='text/python'>
from browser import window, timer, document, html
import time
<!-- I know that here, I must use this t0 = Date.now() -->
t0 = time.time()
def user_agent():
""" Helper function for determining the user agent """
if window.navigator.userAgent.find('Chrome'):
return 'chrome'
elif window.navigator.userAgent.find('Firefox'):
return 'firefox'
elif window.navigator.userAgent.find('MSIE'):
return 'msie'
elif window.navigator.userAgent.find('Opera'):
return 'opera'
# Dict Mapping UserAgents to Transform Property names
rotate_property = {
'chrome':'WebkitTransform',
'firefox':'MozTransform',
'msie':'msTransform',
'opera':'OTransform'
}
degrees = 0
def animation_step(elem_id):
""" Called every 30msec to increase the rotatation of the element. """
global degrees, tm
# Get the right property name according to the useragent
agent = user_agent()
prop = rotate_property.get(agent,'transform')
# Get the element by id
el = document[elem_id]
# Set the rotation of the element
setattr(el.style, prop, "rotate("+str(degrees)+"deg)")
document['status'].innerHTML = "rotate("+str(degrees)+" deg)"
# Increase the rotation
degrees += 1
if degrees > 360:
# Stops the animation after 360 steps
timer.clear_interval(tm)
degrees = 0
# Start the animation
tm = timer.set_interval(lambda id='img1':animation_step(id),30)
document['status3'].innerHTML = "Time of execution python code("+str(time.time()-t0)+" ms)"
<!-- I know that here i must use this: "Time of execution python code", Date.now()-t0, "ms") -->
</script>
</head>
<!-- After the page has finished loading, run bootstrap Brython by running
the Brython function. The argument '1' tells Brython to print error
messages to the console. -->
<body onload='brython(1)'>
<img id="img1" src="cog1.png" alt="cog1">
<script>animation_step("img1",30);</script>
<h2 style="width:200px;" id="status"></h2>
<h2 style="width:800px;" id="status3"></h2>
</body>
</html>
I'm not too familiar with Brython, but right away I can tell you that to port it to RapydScript you simply need to drop most of the unnecessary abstractions that I see the code importing, since RapydScript is closer to native JavaScript. As far as having the RapydScript code in the browser, you have a couple options:
<script type="text/pyj">tag similar to what you have done in the example.
Now, assuming you pick the recommended option above, the next step is to drop the Brython boilerplate from the code, here is what your logic would look like in RapydScript (note that I also refactored it a little, removing the unnecessary 2-stage rotate method resolution and unneeded lambda call):
t0 = Date.now() def rotate_property(): """ Helper function mapping user agents to transform proeprty names """ if 'Chrome' in window.navigator.userAgent: return 'webkitTransform' elif 'Firefox' in window.navigator.userAgent: return 'MozTransform' elif 'MSIE' in window.navigator.userAgent: return 'msTransform' elif 'Opera' in window.navigator.userAgent: return 'OTransform' return 'transform' degrees = 0 def animation_step(elem_id='img1'): """ Called every 30msec to increase the rotatation of the element. """ nonlocal degrees # Get the right property name according to the useragent prop = rotate_property() # Get the element by id el = document.getElementById(elem_id) # Set the rotation of the element el.style[prop] = "rotate(" + degrees + "deg)" document.getElementById('status').innerHTML = "rotate(" + degrees + "deg)" # Increase the rotation degrees += 1 if degrees > 360: # Stops the animation after 360 steps clearInterval(tm) degrees = 0 # Start the animation tm = setInterval(animation_step, 30) document.getElementById('status3').innerHTML = "Time of execution python code(" + (Date.now() - t0) + " ms)"
A few things to note:
timer.set_intervaland
timer.clear_intervalhave been replaced with JavaScript equivalents (setInterval and clearInterval)
documentyou see in my code is the DOM itself,
documentyou have in Brython code is a wrapper around it, hence accessing it works a bit differently
globala long time ago in favor of Python 3's safer
nonlocal, which is what I used in the code instead
timemodule, RapydScript has direct access to JavaScript's
Dateclass, which I used in the code to time it
prop = rotate_property()call outside the function, since the user agent won't change between function calls (in this case the operation is relatively cheap, but for more complex logic this will improve your performance)
onload, get rid of that as well as the line that says
<script>animation_step("img1",30);</script>, the above code should trigger for you automatically as soon as page loads courtesy of setInterval call
<meta charset="UTF-8">
onloadcalls to RapydScript will work, because unlike Brython, RapydScript protects itself in its own scope, invisible to the outside (this has been the accepted practice in JavaScript world for a long time), your options for making
onloadwork are:
-bflag to omit the self-protecting scope
windowobject if you want them accessible from outside
Your actual html code that calls the compiled version of the above code would then look like this:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <img id="img1" src="cog1.png" alt="cog1"> <h2 style="width:200px;" id="status"></h2> <h2 style="width:800px;" id="status3"></h2> <script src="myfile.js"></script> </body> </html>
|
https://codedump.io/share/T0ZjKWWDxhTe/1/simple-image-rotation-with-python-and-dom-using-rapydscript
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Reducer Snapshots for Rapid Development
Test Driven Design (TDD) is a great way to ensure that you are getting the expected behavior from any given piece of code.
When writing tests I follow Eric Elliott’s advice in TDD the Rite Way and favor equality tests as much as possible. A test written this way, with explicit expected results, is easier to reason about, reduces edge cases, and documents the codebase.
Redux reducers lend themselves well to this development pattern. As our reducers are pure functions we can simply define inputs and outputs and run our function. An example, written using Jest:
/* global describe, test, expect /
import {action, initialState, reducer} from 'state'
describe('reducer', () => {
test('handles ACTION_TYPE correctly', () => {
const name = 'A Name'
const expected = {
name,
description: 'Some data that should not change.'
}
const actual = reducer(initialState, action(name))
expect(actual).toEqual(expected)
})
})
Simple and readable, we know exactly what the reducer should return when running the
action mapped to our
ACTION_TYPE.
There is a downside to this, specially when iterating quickly through a prototype or MVP: writing out the full expected shape for any given part of our application state can take some time.
The example above has state that is rather trivial and thus the test is not particularly lengthy. When leveraging Redux in production, and in particular when attempting to keep our state normalized and as flat as possible, the opposite quickly becomes the case.
Jest comes with a handy feature called Snapshot Testing. Essentially what snapshots do are create a JSON schema representation of whatever you pass in and do future comparisons against that representation.
Although commonly demonstrated as a clever way to test React components they also happen to be useful for testing reducers. First, the above test written with snapshots:
/ global describe, test, expect */
import {action, initialState, reducer} from 'state'
describe('reducer', () => {
test('handles ACTION_TYPE correctly', () => {
const actual = reducer(initialState, action('A Name'))
expect(actual).toMatchSnapshot()
})
})
Given the brevity of our reducer this does not seem like much of a gain, at least in lines of code. Lines of code savings do start to accumulate over time, however the big gain here is in maintainability and speed of development.
Setting up the test in this manner lets us get back to creating our reducer quickly. Tabbing over to the terminal, where we naturally have Jest running in watch-mode, allows us to watch the snapshot changes as we iterate on the logic contained within
reducer.
Once the state shown in the snapshot reflects what we expect to see we simply update the snapshot and now have a baseline from which to compare any future changes.
A more complete example of using this pattern can be found at todo-and-tonic/todos.spec.js.
|
http://brianyang.com/reducer-snapshots-for-rapid-development/
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Coffeehouse Thread27 posts
Forum Read Only
This forum has been made read only by the site admins. No new threads or comments can be added.
Where is GACUTIL?
Back to Forum: Coffeehouse
Conversation locked
This conversation has been locked by the site admins. No new comments can be made.
Pagination.
Actually, there is a managed API that can install an assembly in the GAC: System.EnterpriseServices.Internal.Publish.GacInstall. I've used it, it works great.
Is this new in 2.0? I don't remember it there in 1.1.
And while I've used the EnterpriseServices.Internal namespace before (to create IIS virtual directories), I would hesitate recommending its use. I don't think they're committed to keeping it there without breaking changes.
The docs say it's 2.0, 1.1, and 1.0 compatible. I've only used it in 2.0 though.
Cool. Didn't know about it. I'll keep it in mind.
Thanks guys, great help. I actually needed it for a quick pilot where I wrote a quick mockup but needed stdole from the GAC - quick question - to which I don't really expect an answer, why isn't that installed with the runtime either?
I disagree with this advice.
First off, GACUTIL is part of the .Net SDK not the .Net Redistributible, therefore you are not licensed to redistribute that code.
Secondly, .Net and the CLR were designed to mitigate the problems associated with sharing library code files that everyone calls DLL Hell, the GAC , if used improperly, reintroduces all the pitfalls that COM DLLs had
The GAC makes xcopy deployment moot. If you're going to use the GAC, and since you can't use xcopy now, you should really be using a installation technology that was designed for end-user application installation.. like Windows Installer (MSI). MSI knows how to register assemblies with the end-user's GAC. Dont hack the installation APIs by using GACUTIL.
GACUTIL is for developers not end-users. That's why it's in the SDK but not the Redistributable..
Having the DLLs in the same location as the exe's is the solution to DLL hell as well. When I first started .Net , I immediately assumed that the GAC was good and that's where I should be putting my class libraries because of the reasons you state (code signing,etc).. but I came to the conclusion that the GAC wasn't really giving me any value that would make up for the complexity of deployment and uninstalling. Plus realizing that trying to save hard disk space is really a false economy since the DLL's i'm making are really insignificant in size relative to the sizes of HD now.
I've also come to agree with the train of thought that says an application should only be using the versions of the DLLs that it originally tested/shipped with and the easiest way to implement this is through shipping all the code together and only updating the consumers of DLL updates that were specifically recompiled with those updated DLLs.
So for me at least the benifits of the GAC didn't outweight the potential costs and I stopped using it.
That decision process is one that everyone should make on thier own taking into account their specifics. So I didn't intend to say no one should the GAC, I just wanted to raise some points that are not so apparent up front but ultimately everyone makes thier own decisions.
It was GACUTIL.exe specifically that I think peopel should avoid on the client deployment side.
The .Net Documentation has this note:
In deployment scenarios, use Windows Installer 2.0 to install assemblies into the global assembly cache. Use Windows Explorer or the Global Assembly Cache tool only in development scenarios, because they do not provide assembly reference counting and other features provided when using the Windows Installer.
I agree, use MSI's whenever possible. But I'm trying to distribute an ActiveX control that interops back to a .NET assembly. What is the prescribed GAC installation method for this situation?
According to this thread you have to put .NET assemblies into the GAC for them to be visible to ActiveX controls hosted on a web page (and preliminary tests show this seems to still hold true, the thread is from 2003). So I need to put my assembly into the GAC via a CAB install (aka inf).
Is my "best" option to write a .net app which calls the EnterpriseServices method mentioned earlier just to put my needed assembly into the GAC? That seems like a bad hack instead of a solution.
Could I simply do a:
copy [assembly file name] \windows\assembly\
and shfusion.dll will do its magic? This is scary to me as there doesn't seem to be a good way to get failure messages, and I don't know if that even works.
Any help would be great! I've been scratching my head all day long on this.!
Well, I'm interested
I'm looking for a solution to deploy a managed dll with an unmanaged dll as a linkresource in the GAC.
I need your post:)
Information on this would be a great help.
GACUTIL is part of the .NET Framework SDK. If you're curious where it is in your machine and you know it's in your PATH, try WHERE GACUTIL.EXE from the command line.
|
https://channel9.msdn.com/Forums/Coffeehouse/205281-Where-is-GACUTIL
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
How to catch a signal emitted from cpp class in Qml ?
Hi all,
I am using s signal slot communication for cpp and qml interaction. but when i emit a signal from cpp class i am not able to catch that in Qml...can anyone guide me in this matter... the code is as follows...
thanks.
my .h code
#ifndef HANDLETEXTFIELD_H #define HANDLETEXTFIELD_H #include <QObject> #include <QDebug> class HandleTextField : public QObject { Q_OBJECT public: explicit HandleTextField(QObject *parent = 0); signals: void setTextField(); public slots: Q_INVOKABLE void handleSubmitTextField(); }; #endif // HANDLETEXTFIELD_H
my .cpp code
#include "handletextfield.h" HandleTextField::HandleTextField(QObject *parent) : QObject(parent) { } void HandleTextField::handleSubmitTextField() { qDebug() << "c++: HandleTextField::handleSubmitTextField:" << endl; emit setTextField(); }
my"))); HandleTextField handleTextField; QObject *topLevel = engine.rootObjects().value(0); QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel); // QObject::connect(window, SIGNAL(submitTextField(QString)), // &handleTextField, SLOT(handleSubmitTextField(QString))); QObject::connect(&handleTextField, SIGNAL(setTextField()), window, SLOT(setTextField())); return app.exec(); }
my qml.main code
import QtQuick 2.3 import QtQuick.Window 2.2 import QtQuick.Controls 1.2 import com.handletextfield 1.0 Window { visible: true width: 360 height: 360 HandleTextField { id: testsignal } MouseArea { anchors.fill: parent onClicked: { testsignal.handleSubmitTextField() } } function setTextField(){ console.log("setTextField signal: catched ") } }
QQuick creates signal handlers for your cpp classes like:
HandleTextField { id: testsignal onSetTextField: { //your code} }
You have 2 different objects of class HandleTextField in your code(one created in main(), the other in Qml), and you connect/send a signal from different ones. For your code to work, you have to connect the HandleTextField that you created in your Qml code, and you dont need the object in main() anymore, you don't do anything with it anyway.
In Qmal this would look like:
HandleTextField { id: testsignal onSetTextField: { console.log("signal called") } }
@Jagh but if i dont create a object of handletextfield in main.cpp how can i connect the signal and slot ?
@Jagh You mean to say the following part is not required in main.cpp ??
HandleTextField handleTextField; QObject *topLevel = engine.rootObjects().value(0); QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel); // QObject::connect(window, SIGNAL(submitTextField()), // &handleTextField, SLOT(handleSubmitTextField())); QObject::connect(&handleTextField, SIGNAL(setTextField()), window, SLOT(setTextField()));
only i need to emit the signal and catch it in qml..in the same way as you have done ?
- You connect objects, not classes with signal-slot mechanism. So if you connect one object HandleTextField to something, this connection will not automatically transfer to other objects of the same class.
- Exactly, that part is not required, and in fact, it doesn't do anything. Connections for one object in your C++ code don't transfer to unrelated objects in QML.
- Yep, for each signal an object emits, QML exposes a property named on<SignalName>, in your case this would be onSetTextField. You can set this property as i have done, but AFAIK it should also be possible to set it from outside, having
testsignal.onSetTextField: { console.log("signal called") }
somewhere in your Qml should suffice
@Jagh thank you for your reply...
now i have removed that part from main.cpp...but now also when i emit a signal i am not able to catch it in Qml...
the way i am registering that handletextfiled class, is it correct ...???
here is the code...
main.qml
import QtQuick 2.3 import QtQuick.Window 2.2 import QtQuick.Controls 1.2 import com.handletextfield 1.0 Window { visible: true width: 360 height: 360 HandleTextField { id: testsignal onSetTextField: { console.log("Signal catched successfully...") } } }"))); return app.exec(); }
handletextfield.cpp
#include "handletextfield.h" HandleTextField::HandleTextField(QObject *parent) : QObject(parent) { handleSubmitTextField(); } void HandleTextField::handleSubmitTextField() { qDebug() << "c++: HandleTextField::handleSubmitTextField:" << endl; emit setTextField(); qDebug()<<"Signal emitted..."<<endl; }
You are sending signal way too early, before there was any chance for a connection to be established. In constructor the object hasn't been fully initialized yet, in particular, the QML-interpreter hadn't had a chance to initialize the object's properties from QML side yet.
@Jagh Okay...
then when should i emit a signal...so that i can catch over there...calling my function in constructor is the mistake...??
I changed your code a bit so that handleSubmitTextField() is called in more appropriate time(actually i just added a Button and called this function in onClicked handler), and the signal handler was successfully called.
To when: anytime between QML object initialization (implement Component.onCompleted if you want to catch it) and object destruction is ok.
@Jagh can you please post the code so that i will get a clear picture of what i need to do...thanks...
And if you really want to execute some code as soon as possible and have a guarantee that a QML object was fully initialized by the time your code is running, do it in Component.onCompleted handler of that object.
Ok thanks... i will try that also...:-)
Hi i have doubt regarding catching a signal emitted from c++ file
if there are more than 2 .qml files does it catch the signal ?
for ex, i have one .cpp and 4 .qml such as mainform.qml,radio.qml,music.qml,setting .qml
so if i emit a signal and try to catch it in setting.qml does it work ??
- VincentLiu
@VincentLiu but in my case it is not working....
my code is...
this .cpp where i am emitting signal..
if(!WordList.isEmpty()) { WordList.removeFirst(); WordList.removeLast(); // QMessageBox m_popupmsgbox; // m_popupmsgbox.setWindowTitle("Voice Recognizer"); // Phoneme=WordList.join(" "); // qDebug()<<"firstword"<<Phoneme<<endl; // QSpacerItem* horizontalSpacer = new QSpacerItem(500, 100, QSizePolicy::Minimum, QSizePolicy::Expanding); // m_popupmsgbox.setText( Phoneme); // QGridLayout* layout = (QGridLayout*)m_popupmsgbox.layout(); // layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount()); // m_popupmsgbox.exec(); // emitSignalFunc(); // m_emitSignal= new EmitSignalClass; // m_emitSignal->emitSignalmethod(); VoiceRecognition voice; voice.playmusicsignal(); } else { qDebug()<<"List is empty"<<endl; }
my .qml is
Rectangle{ id:voicerecRect width: settings_main_rect.width/5 height: settings_main_rect.height/4 color: "transparent" VoiceRecognition { id: voiceRecognizer onPlaymusicsignal: { console.log("Signal catched...") } } Image { id: vr_image source: "qrc:/AppbarIcon.png" //source: "qrc:/Voice-Recoder-icon.png" width: parent.width-10 height: parent.height-10 smooth: true fillMode: Image.PreserveAspectFit anchors.centerIn: parent Text { id: vrtext anchors.top: parent.bottom anchors.horizontalCenter: vr_image.horizontalCenter text: qsTr("Voice Recorder") color: "white" font.pixelSize: parent.height * (2 / 9) } MouseArea { anchors.fill: parent onClicked: { //popup.open() voicerecRect.color = 'green' voiceRecognizer.vstartVoiceRecognition() } } } } }
i have registered the class using qmlregister and i am using signal handler to catch the signal...
- VincentLiu
@Naveen_D
Hi, first of all, I should say that I use different ways to do this. However, according to some similar experience on it. I guess you shouldn't use a new VoiceRecognition object in your .cpp file. I don't think distinct object derived from the same class can communicate this way. Please correct me if I am wrong. Thanks
@VincentLiu the function in which i am emitting a signal is a global function so i need to create an obj of that class and emit.
@VincentLiu what are the different ways...?
Hello, can anyone please help me out with this...
thanks
|
https://forum.qt.io/topic/74076/how-to-catch-a-signal-emitted-from-cpp-class-in-qml
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
src/diffusion.h
Time-implicit discretisation of reaction–diffusion equations
We want to discretise implicitly the reaction–diffusion equation where is a reactive term, is the diffusion coefficient and can be a density term.
Using a time-implicit backward Euler discretisation, this can be written Rearranging the terms we get This is a Poisson–Helmholtz problem which can be solved with a multigrid solver.
#include "poisson.h"
The parameters of the
diffusion() function are a scalar field
f, scalar fields
r and defining the reactive term, the timestep
dt and a face vector field containing the diffusion coefficient
D. If
D or are omitted they are set to one. If is omitted it is set to zero. Both
D and may be constant fields.
Note that the
r, and fields will be modified by the solver.
The function returns the statistics of the Poisson solver.
struct Diffusion { // mandatory scalar f; double dt; // optional face vector D; // default 1 scalar r, β; // default 0 scalar θ; // default 1 }; trace mgstats diffusion (struct Diffusion p) {
If dt is zero we don’t do anything.
if (p.dt == 0.) { mgstats s = {0}; return s; }
We define and for convenience.
scalar f = p.f, r = automatic (p.r);
We define a (possibly constant) field equal to .
const scalar idt[] = - 1./p.dt; (const) scalar theta_idt = p.θ.i ? p.θ : idt; if (p.θ.i) { scalar theta_idt = p.θ; foreach() theta_idt[] *= idt[]; }
We use
r to store the r.h.s. of the Poisson–Helmholtz solver.
if (p.r.i) foreach() r[] = theta_idt[]*f[] - r[]; else // r was not passed by the user foreach() r[] = theta_idt[]*f[];
If is provided, we use it to store the diagonal term .
scalar λ = theta_idt; if (p.β.i) { scalar β = p.β; foreach() β[] += theta_idt[]; λ = β; boundary ({λ}); }
Finally we solve the system.
return poisson (f, r, p.D, λ); }
|
http://basilisk.fr/src/diffusion.h
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
The feature of anonymous types can be felt specially when we work with the composite type rather than the simple types. The below example is more like you are defining an inline class without actually having the definition.
Example of Composite Anonymous Types in C#
Below is an example of the anonymous type in C# that demonstrates the composite anonymous type.
using System; namespace AbundantCodeConsoleApp { class Program { static void Main(string[] args) { var employee = new { FirstName = "Abundant", Last = "Code.com" }; Console.WriteLine(employee.); Console.ReadLine(); } } }
Note that you will also see the Intellisense support for the anonymous type in Visual Studio wven when the class definition and the properties are not explicitly defined by the developer.
|
http://abundantcode.com/example-of-composite-anonymous-types-in-c/
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
How to Create a WhizzML Script (Part 4)
How to Create a WhizzML Script (Part 4)
Dive deeper into the world of machine learning automation via WhizzML and learn the BigML Python bindings way to create WhizzML scripts.
Join the DZone community and get the full member experience.Join For Free
Start coding something amazing with the IBM library of open source AI code patterns. Content provided by IBM.
As the final installment of our WhizzML blog series (here's Part 1, Part 2, and Part 3), it's time to learn the BigML Python bindings way to create WhizzML scripts. With this last tool at your disposal, you'll officially be a WhizzML-script-creator genius!
About BigML Python Bindings
BigML Python bindings allow you to interact with BigML.io, the API for BigML. You can use it to easily create, retrieve, list, update, and delete BigML resources (i.e. sources, datasets, models, and predictions). This tool becomes even more powerful when it is used with WhizzML. Your WhizzML code can be stored and executed in BigML by using three kinds of resources: Scripts, Libraries, and Executions (see the first post).
WhizzML scripts can be executed in BigML's servers in a controlled, fully scalable environment that automatically takes care of their parallelization and fail-safe operation. Each execution uses an Execution resource to store the arguments and the results of the process. WhizzML Libraries store generic code to be shared or reused in other WhizzML scripts. But this is not really new, so let's get into some new tricks instead.
Bindings
You can create and execute your WhizzML script via the bindings to create powerful workflows. There are multiple languages supported by BigML bindings i.e. Python, C#, Java or PHP. In this post, we'll use the Python bindings but you can find the others on GitHub. If you need a BigML Python bindings refresher, please refer to the dedicated Documentation.
Scripts
In BigML, a script resource stores WhizzML source code and the results of its compilation. Once a WhizzML script is created, it's automatically compiled. If compilation is successful, the script can be run, that is, used as the input for a WhizzML execution resource. This little program creates a script to create a model from a
dataset-id.
from bigml.api import BigML api = BigML() # define the code include in the script script_code = "(create-model {\"dataset\" dataset-id})" # create the script script = api.create_script(script_code) # waiting for the script compilation to finish api.ok(script)
You can also define some variables as the script inputs. In the code below, we use the same script code as in the example above, and we set a specific dataset id as input.
from bigml.api import BigML api = BigML() # define the code include in the script script_code = "(create-model {\"dataset\" dataset-id})" # define parameters inputs = {"inputs": [{"name": "dataset-id", "type": "string", "default": "dataset/598ceafe4006830450000046", "description": "Datset identifier"}]} # create the script script = api.create_script(script_code, inputs) # waiting for the script compilation to finish api.ok(script)
Executions
To execute a compiled WhizzML script in BigML, you need to create an execution resource. Each execution is run under its associated user credentials and its particular environment constraints. Furthermore, a script can be shared, and you can execute the same script several times under different usernames by creating a different execution. For this, you need to first identify the script you want to execute and determine your dictionary of inputs. In this execution, the parameters are the script inputs stored in the variable named
input. It's a piece of cake!
from bigml.api import BigML api = BigML() # choose workflow script = 'script/591ee3d00144043f5c003061' # define parameters inputs = {'x' : '2'} # execute and waite for the compilation to finish api.ok(api.create_execution(script, inputs))
Libraries
We haven't created libraries in the previous posts, but there's always a first time. A library is a shared collection of WhizzML functions and definitions usable by any script that imports them. It's a special kind of compiled WhizzML source code that only defines functions and constants. Libraries can be imported in scripts. The attribute of a script can contain a list of library IDs whose defined functions and constants will be usable in the script. It's very easy to create WhizzML libraries by using BigML Python bindings.
Let's go through a simple example. We'll define one function
get-max and a constant. The function will get the max value in a list. In WhizzML language this can be expressed as below.
from bigml.api import BigML api = BigML() # define the library code lib_code = "(define (get-max xs) (reduce (lambda (x y)" \ "(if (> x y) x y)) (head xs) xs))" # create a library library = api.create_library(lib_code) # waiting for the library compilation to finish api.ok(library)
For more examples, don't hesitate to take a look at the WhizzML resources section in the BigML Python Bindings documentation.
So that's it! You now know all the techniques needed to create and execute WhizzML scripts. We've covered the basic concepts of WhizzML, how to clone existing scripts or import them from Github (Part 1), how to create new scripts by using Scriptify and the editor (Part 2), how to use the BigMLer command line (Part 3), and finally the BigML Python bindings in this last post.
To go deeper into the world of machine learning automation via WhizzML, please check out our WhizzML tutorials such as the automated dataset transformation tutorial. If you need a WhizzML refresher, you can always visit the WhizzML documentation. Start with the Hello World section in the Primer Guide for a gentle introduction. And yes, please be on the lookout for more WhizzML related posts on our blog.
Start coding something amazing with the IBM library of open source AI code patterns. Content provided by IBM.
Published at DZone with permission of Barbara Martin , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/how-to-create-a-whizzml-script-part-4
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
Generics fail using JPAAnnotationProcessor
Bug #798653 reported by Damien Hollis on 2011-06-17
This bug affects 1 person
Bug Description
I've just started trying Querydsl on quite a large code base and seem to have a problem.
I have a class declared as:
public abstract class EnumPermissions<P extends Enum<P> & Permission> extends EntityImpl implements Permissions<P>
and the processor generates:
public class QEnumPermissions extends EntityPathBase<
which obviously isn't valid. We have quite a few classes like this, so this is a show stopper for us at the moment.
Timo Westkämper (timo-westkamper) on 2011-07-05
Released in 2.2.0
Timo,
Sorry I couldn't didn't have time to test this when you put it in the trunk but I have now that its released and it works perfectly. Thanks very much.
Regards,
Damien
Fixed in SVN trunk. Could you verify that the fix works for you?
|
https://bugs.launchpad.net/querydsl/+bug/798653
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
How to continously run a piece of code while simultaneously checking for a condition?
Hi. How can you make Sikuli check if a statement / condition is being fulfilled while simultaneously executing another piece of code?
What I'm trying to achieve:
* While there isn't an image in a region, keep running a piece of code
* If the image appears (while running the code), stop running piece of code
Lacking approach:
Settings.
someRegion = Region(x1, y1, x2, y2)
someImage = "image.png"
def danceLeft(): #Just some functions
def danceRight():
def danceAcrossTheH
someCondition = None
while someCondition == None:
danceLeft()
danceRight()
danceAcross
someCondition = someRegion.
else:
print("Stopped dancing; the image has appeared!")
The problem is obvious - the script won't check the condition until it reaches the very last line in the while loop, and while it will be checking, the next iteration of the loop will be held on pause. How can this be avoided? I want it run a while loop without any interruptions while checking for a condition meanwhile, and stop the loop while the condition (an image appearing in a region, in this case) is met.
My hobby-level programming skills have so far mostly consisted of solving everything by doing silly loops, but something tells me there must be a better way. Cheers for the wonderful piece of software that is Sikuli; it's really amazing! Cheers. :D
Question information
- Language:
- English Edit question
- Status:
- Solved
- For:
- Sikuli Edit question
- Assignee:
- No assignee Edit question
- Solved by:
- Manfred Hampl
- Solved:
- 2017-11-05
- Last query:
- 2017-11-05
- Last reply:
- 2017-11-05
Thanks for your reply and the link. I didn't know about 'break'. Certainly it will be handy in the future, as well as the rest of the FAQ. :) However, this does not entirely answer the question. The problem is that I want the functions to continue running, without having to stop and wait for the image explicitly (using 'exists'). I mean, to eliminate all such pauses. If I put multiple copies of the condition check, between the defined functions, it will have to wait before executing the next function.
while True; # starts endless loop
danceLeft()
if someRegion.
break
danceRight()
if someRegion.
break
danceAcross
if someRegion.
break
Perhaps this could work, if I make the condition check is short enough, but it doesn't feel optimal.
I was hoping there would be a way of continuously watching for an image in a region, while running / looping some functions in parallel, and stopping / breaking the loop while the condition is met.
Otherwise the condition check will have to be inserted everywhere, or atleast every now and then, in the loop, and the ride won't be smooth.
I think that http://
@Manfred
Good idea, but I guess this will make it for him even more complex.
@Martin
an image check always costs some time.
So the only chance is to minimise this "pause" in the script.
1. step: use
exists(image, 0)
which does only one search. depending on region and image size this may reduce the search time to some 10 millisecs.
2. step: make the search region as small as possible
Excellent, thanks! "It is possible to let the script wait for the completion of an observation or let the observation run in background (meaning in parallel)" sounds exactly like what I was looking for. It is difficult refer to the documentation, unless you know the jargon, but now it makes sense. Thanks alot RaiMan and Manfred. This helped alot. :)
Cheers for the additional feedback, RaiMan. I will try both approaches and see how they work out!
Thanks Manfred Hampl, that solved my question.
so if you want to leave the loop, when a condition is met, you have to use break.
If the loop does not have any condition to be check at every loop run beginning, the use while True (endless).
endless loops should have any terminating condition check in its body, so the script does not need to be killed by brute force.
#someCondition = None # not needed here
TheHallway( ) exists( someImg, 1): # check terminating condition
print( "Stopped dancing; the image has appeared!")
#while someCondition == None:
while True; # starts endless loop
danceLeft()
danceRight()
danceAcross
if someRegion.
break
# next statement after loop is exited
|
https://answers.launchpad.net/sikuli/+question/660366
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
Go to the source code of this file.
Specialised LocatingPin for use in Placement, especially for globally fixed positions The FixedLocation is assumed to play a central role within the Build process, which ultimately aims ad resolving any part of the session into either a wiring directive or a piece of media or processing to happen at a location fixed in time.
stalled effort towards a session implementation from 2008
2016 likely to stay, but expect some extensive rework
Definition in file fixedlocation.hpp.
#include "proc/mobject/session/locatingpin.hpp"
|
https://lumiera.org/doxy/fixedlocation_8hpp.html
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
Issues with MapReduce
The MapReduce solution achieves scalability, but scalability is relative. We were able to scale our application to find the sum of the number of flowers for a trillion or more pickers. But what if we wanted to perform another operation, such as finding the standard deviation among the number of flowers picked, or the mean or mode of these numbers? We would need to write a new MapReduce program for each computation.
Every MapReduce application reads input data individually, and writes its output back to HDFS. As a result, MapReduce is made for acyclic data flow models, a paradigm that doesn't allow for iterative querying or repeated executions on results or inputs. This is limiting, because for every solution, there is always another problem waiting in the wings.
We also don't necessarily want to be bound by reading large data sets from HDFS, given that disk I/O is very expensive and bandwidth is limited. Ideally, we want an in-memory structure partitioned across commodity machines, which will enable us to do repeated querying without reloading from disk.
Aggregating with Spark
As we try out different ways of resolving our problem statement, our list of requirements is growing. The code in Listings 6 and 7 is 104 lines long, and yet it doesn't let us create a chain of operations or computations. In addition to more composable code, we want a language that supports features like cohesion, loose coupling, and orthogonality--meaning that a relatively small set of primitive constructs can be combined in a relatively small number of ways to build the control and data structures of the language.
Java 8 added functional features to the language, but Scala is inherently functional. In this section we'll see what programming in Scala on Apache Spark brings to the table. Note that we assume some experience with Spark, and that you have Spark installed and setup in your development environment already.
Spark vs MapReduce
Just like MapReduce is the programming model for Hadoop, DAG (Direct Acyclic Graph) is the programming model for Spark. We've already noted that MapReduce doesn't have the flexibility needed to create data flows. In MapReduce, you create a map, a shuffler, and a reduce operation. The map is executed on individual blocks, its output is spilled to a circular buffer, and then it's shuffled and sorted for the reducer to pick up. Even if we use a
ChainMapper or a
ChainReducer, the model is
[MAP+ / REDUCE MAP*], where
+ indicates one or more relevant tasks and
* indicates zero or more.
As a result, we can never have a model that executes
map-> shuffle->reduce->reduce, although this is an important requirement for iterative algorithms. If you want to set up something iterative, your only option is to schedule
map->shuffle->reduce as your first job, followed by
map-> shuffle->reduce. Since jobs in MapReduce are mutually exclusive, the first job has no idea whether a second job will follow. This is represented in Figure 7, where the blue line represents a
map task and the black line represents a
reduce task. We've excluded
shuffle and
sort for brevity.
Figure 7. Hadoop MapReduce vs Spark DAG
Now let's analyze the same solution in Spark. You can see the data flow illustrated on the right side of Figure 7. First, note that there are no maps between reducers (i.e., no blue circles) for the Spark solution in Figure 7. That means output from the first MapReduce can be directly fed to the second set of reducers without an explicit
map process. Second, there is no HDFS file system between operations. Instead, Spark leverages memory as long as the data fits it, which greatly reduces the cost for disk I/O. Most importantly, note the part of the diagram marked STAGE 1, where the yellow circles
1->2->4 and
3->5 are mutually exclusive. These can be simple transformations. Most importantly, Spark can intelligently connect the multiple stages into an execution pipeline, deciding which stages should run in parallel. This powerful design supports lightning-fast cluster computing in Spark.
Solving aggregation with cluster computing
Cluster computing makes Spark an excellent choice for solving our aggregation problem. As we've mentioned, Spark leverages memory rather than relying on HDFS. Objects stored in memory are called RDDs, or resilient distributed datasets, and they are the horsepower in the Spark system.
An RDD is a pointer for a collection of individual memory units. When you combine multiple RDDs, you get the entire object stored in Spark. If you apply a transformation or action on an RDD, all the individual partitions across the cluster are affected. Any loss to an individual unit can be reconstructed by lineage graphs associated with the creation of corresponding units. A lineage graph is the plan Spark employs to create individual RDD units or partitions. Further, RDD is immutable, and is evaluated only till an action (terminal operation) is executed against it (lazy evaluation). RDDs can handle any type of data, which makes Spark very popular. There is one drawback, however: operations on RDD must be generic in order to be applicable to any kind of data, which limits the number and type of available operations.
Listing 8 shows the definition of the aggregate function in Spark, in its simplest form. Before using
aggregate, we need to specify how many partitions are to be used. We specify the number of partitions when we create the initial RDD.
Listing 8. Definition of the aggregate function
def aggregate( an initial value)(an intra-partition sequence operation)(an inter-partition combination operation)
Now let's take this aggregation model back to our garden example. Recall that there are four quadrants in the JavaWorld garden: south, north, east, and west. We'll use four partitions, one for each quadrant. Going back to Listing 1, here's how we would write the first line (listing the number of flowers) in Scala:
Listing 9. Aggregation with Spark
val flowers = sc.parallelize(List(11,12,13,24,25, 26, 35,36,37, 24,15,16),4)
Note that the second parameter of 4 represents the number of partitions available in our Spark cluster.
Now it's easy to visualize the data as it relates to our problem statement: 11, 12, and 13 are the number of flowers picked by each person in the south quadrant of the garden. The numbers 24, 25, and 26 are from the north quadrant; 35, 36, and 37 are from the west quadrant; and 24, 25,and 16 are from the east. Each quadrant corresponds to one node in the Spark cluster.
Next, we divide the problem statement into two parts. The first part of the problem is to aggregate the total number of flowers picked in each quadrant; that's the intra-partition sequence aggregation from Listing 8. The second part of the problem is to sum these individual aggregates across the partitions; that's the inter-partition aggregation.
So let's find the intra-partition sequence aggregation results. Note that each flower picker initially goes to the garden with an empty bucket. That will be our starting value of 0.
Southside garden: 11+12+13 = 36
Northside garden: 24+25+26 = 75
Westside garden: 35+36+37 = 108
Eastside garden: 24+25 +16 = 65
Next, we calculate the inter-partition aggregation results:
Southside + Northside + Westside + Eastside = 36 + 75 + 108 + 65 = 284
The sum, stored in an RDD can further be used and processed for any kind of transformation or other action, and it can be persisted for later iterative use. Now we write the last part of the code. This one line of Scala performs both of the above aggregations:
Listing 10. Complex aggregation with Scala
val sum = flowers.aggregate(0)(_+_, _+_)
We start with 0 as the initial value in each of the 12 buckets. The first
_+_ is the intra-partition sum, adding the total number of flowers picked by each picker in each quadrant of the garden. The second
_+_ is the inter-partition sum, which aggregates the total sums from each quadrant.
For the aggregation to work, we need two
reduce functions after the initial value. What would happen if initial value weren't zero? If it were 5, for example, that number would be added to each intra-partition aggregate, and also to the inter-partition aggregate. So the first calculation would be:
Southside garden: 11+12+13 = 36 + 5 = 41
Northside garden: 24+25+26 = 75 + 5 = 80
Westside garden: 35+36+37 = 108 + 5 = 113
Eastside garden: 24+25 +16 = 65 + 5 = 70
Here's the inter-partition aggregation calculation with the initial value of 5:
Southside + Northside + Westside + Eastside + 5 = 41 + 80 + 113 + 70 = 309
Aggregation with accumulators
To illustrate the concept further, assume we want to find out the maximum number of flowers in each quadrant of the garden, and then aggregate the totals. We only need a slight alteration to the intra-partition function:
Listing 11. Accumulators for a quadrant
val sumofmaximums = flowers.aggregate(0)(Math.max(_,_), _+_)
And what if we wanted to find the maximum number of flowers each person could pick, across the entire garden? We could do:
Listing 12. Accumulators for the garden
val maximum = flowers.aggregate(0)(Math.max(_,_), Math.max(_,_))
The initial value used in these examples is called an accumulator, in this case, a value that is iterated across partitions and then propagated for the final result.
Aggregation with tuples
For our final example, let's say that we can use as many initial values as we want. In that case, we could solve the problem of finding the average number of flowers among all of the flower pickers in each quadrant of our garden like this:
Listing 13. Tuples
val flowersandpickers = flowers.aggregate((0,0)) ( (acc, value) => (acc._1 + value, acc_.2 +1), (acc1, acc2) => acc1._1 + acc2._1, acc1._2 + acc2._2) )
In this example, notice that the
reduce functions applied within the aggregate have to be both commutative and associative. There shouldn't be any order of execution for sequencing or combining operations. The initial values are two zeros, representing a tuple, or pair. The first zero is the initial value for the sum total number of flowers picked (because you start with zero flowers in the basket); the second zero is the initial value we use to find the average sum of flowers picked per picker (because you start with zero flowers picked). The intra-sequence aggregation adds the number of flowers in each quadrant. At the same time, we add the number 1, indicating that we have added one flower picker per basket. The inter-partition combination function adds the number of flowers and the number of flower pickers from each quadrant. To find the average, we then write:
Listing 14. Averaging with tuples
val avg = flowersandpickers._1/ flowersandpickers._2.toDouble
For comparison, here is how you would write equivalent code in Python instead of Scala:
Listing 15. Aggregating with Python
flowersandpickers = sc.parallelize([11,12,13,24,25, 26, 35,36,37, 24,15,16],4).aggregate( (0, 0), (lambda acc, value: (acc[0] + value, acc[1] + 1)), (lambda acc1, acc2: (acc1[0] + acc2[0], acc1[1] + acc2[1]))) avg = flowersandpickers[0]/ float(flowersandpickers[1])
In conclusion
A three-node Spark cluster outperforms MapReduce at about 14 times the speed, and the DAG execution patterns ensures that RDDs are reusable for future iterations. While you could program your Spark solution in Java, Scala code is significantly more efficient. The entire program, with accumulators and tuples, is just 10 lines of code.
|
https://www.javaworld.com/article/3184109/analytics/aggregating-with-apache-spark.html?page=2
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
a state node for walking towards a visual target
More...
#include <WalkToTargetNode.h>
a state node for walking towards a visual target
Definition at line 9 of file WalkToTargetNode.h.
List of all members.
constructor, pass VisionObjectSourceID_t
Definition at line 12 of file WalkToTargetNode.h.
constructor, pass instance name and VisionObjectSourceID_t
Definition at line 18 of file WalkToTargetNode.h.
[private]
don't call this
[protected, virtual]
uses head to watch ball, walks towards it
Reimplemented from BehaviorBase..
May be overridden to cleanup when the behavior is shutting down. However events will automatically be unsubscribed, and by using addMotion(), motions will automatically be removed by stop(), so you may not need any cleanup.
[static]
Gives a short description of what this class of behaviors does... you should override this (but don't have to).
If you do override this, also consider overriding getDescription() to return it
Definition at line 23 of file WalkToTargetNode.h.
Referenced by getDescription().
24 of file WalkToTargetNode.h.
returns a suggested transition for detecting "close to target" condition, but you don't have to use it
returns a suggested transition for detecting "lost" condition, but you don't have to use it
[protected]
so we can point the head at the object
Definition at line 37 of file WalkToTargetNode.h.
the object being tracked
Definition at line 35 of file WalkToTargetNode.h.
so we can walk
Definition at line 36 of file WalkToTargetNode.h.
|
http://tekkotsu.org/dox/classWalkToTargetNode.html
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
This chapter is from the book
Summary
The new Web programming capabilities in WCF simplify the building of services for use on the Web. They help Web developers get stuff done quickly in the manner that they wish to build and consume services for the Web. This means providing features that allow developers to work with the Web. The following summarizes those capabilities of WCF for the Web:
- The .NET Framework 3.5 provides a new UriTemplate class that allows for the efficient parsing of URIs based on their path and a query component. The UriTemplate class is used by WCF in its Web programming model calls to services.
- Information can be exposed with WCF using a variety of serialization formats including SOAP and POX. .NET Framework 3.5 adds support for JSON as a serialization format.
- An additional binding provided by WCF, called the webHttpBinding binding, exposes services using WCF's Web programming model.
- The webHttpBinding binding is used with either the WebHttpBehavior or WebScriptEnablingBehavior endpoint behaviors. The WebHttpBehavior endpoint behavior is used to expose services using POX or JSON. The WebScriptEnablingBehavior endpoint behavior is using JSON with additional support for generating ASP.NET AJAX client proxies.
- WCF provides a new hosting feature called configuration-free hosting. This feature allows services to be hosted in IIS without the need for configuration. Out of the box, WCF provides two classes that support configuration-free hosting: WebServiceHostFactory and WebScriptServiceHostFactory. The WebServiceHostFactory supports configuration-free hosting using the webHttpBinding binding and the WebHttpBehavior endpoint behavior. The WebScriptServiceHostFactory supports configuration-free hosting using the webHttpBinding binding and the WebScriptEnablingBehavior endpoint behavior.
- WCF in .NET Framework 3.5 provides a rich extensible programming model for content syndication found in the System.ServiceModel.Syndication namespace. Support for both RSS and ATOM syndication feeds is included, using the Atom10FeedFormatter and Rss20FeedFormatter classes.
|
http://www.informit.com/articles/article.aspx?p=1173045&seqNum=9
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
.
FREE TRADE AGREEMENT WITH SINGAPORE
It is
high time that Pakistan should have much stronger and active trade
relations with the active economies in this region
.
By AMANULLAH BASHAR
Mar 29 - Apr 04, 2004
.
2003
2006
BANNER
TARIFF
Advertisement
Tariff
ONLINE
SUBSCRIPTION
Us
WEB
DESIGNING TARIFF
New
Pakistan, which has recently entered into an
arrangement for Free Trade Agreement (FTA) with neighboring India on the
occasion of SAARC Summit, held in Islamabad in the first week of the
first month of the current year. This FTA would come into force by 2006.
However, prior to implementation on FTA with India, it is wise to get
ready for the challenges for the economy in the coming years especially
after implementation of WTO rules in 2005.
It is high time that Pakistan should have much
stronger and active trade relations with the active economies in this
region to tune our business community with the new environment. So far,
it is harsh reality that our business was moving under umbrella of
protection provided by the government.
The Federal Minister for Commerce, Humayun Akhtar has
taken a bold step by suggesting Singapore for an agreement of free trade
between the two countries. Singapore, every body knows has established
and grown its economy impressively which speaks in the volume of trade
that country has in the world market.
Singapore, which has become a hub of trade in the
region, responding to the proposal of the commerce minister has
expressed willingness to negotiate a free trade agreement (FTA) with
Pakistan.
The offer is the outcome of the discussion between
Humayun Akhtar Khan, the Federal Minister for Commerce and George Yeo,
Minister for Trade and Industry Singapore recently.
Though Singapore and Pakistan were significant
economies of the region, the quantum and diversity of bilateral trade
between the two countries did not commensurate with the existing
business potential.
In this connection, the government of Singapore has
decided to send a ministerial mission to Pakistan later this year to
further the talks on this concept. Prior to the ministerial mission, a
two-member delegation of the International Enterprise (IE) Singapore,
the investment and trading arm of the ministry of trade and industry,
will be undertaking a trip to Pakistan in the first week of next month.
The objective of the forthcoming visit of the two
member delegation is to get a feel of the Pakistani market for trading
and investment. During the visit, the delegation will meet the concerned
government officials, to understand trade laws and practices, operations
at Export Processing Zone, investment and privatization procedures and
also to have detail discussions with different trade bodies in the
private sector including Federation of Pakistan Chambers of Commerce and
Industry and individual Chamber of Commerce and Industry of major cities
in Pakistan.
The Export Promotion Bureau (EPB) would facilitate
and arrange meetings of the Singapore delegation with the relevant
quarters both in the public and private sector in Karachi, Lahore and
Islamabad.
The federal minister for commerce feels that the
ministerial delegation's visit to Pakistan would provide an excellent
opportunity to appreciate the favorable business environment in Pakistan
whereas officials and entrepreneurs from both sides would be able to
have useful interaction to augment bilateral trade.
From Pakistan, there is a potential for enhanced
exports of rice, fish and fish preparations, fruits and vegetable,
petroleum and petroleum products, cotton fabrics, cotton yarn, synthetic
fabric, textile made-ups to the Singaporean markets, whereas an
increased import of chemicals, oil seeds, palm oil, machinery and other
finished goods from Singapore was also possible.
Practically speaking, the role of third country trade
plays a significant role in Pakistan, especially Dubai which is used for
import and export of goods from the countries like India with we had to
free trade so far. With the access of the Singapore market, the trade in
Pakistan would be getting a strong launching pad for re-exporting its
goods in the countries where our business lags on different accounts.
A free trade agreement with Singapore, it is said,
would also help promoting our IT industry which could not attain a
desired level of growth especially in the export sector. Experts in the
IT sector feel that since Singapore has become a major supplier of IT
accessories plus, the improved relation could be used for improving pace
of growth of the IT industry in Pakistan. It may be mentioned that India
over the years has elevated its IT industry to the level of IT related
exports which jumped to $13 billion a year. On the other hand, despite
all tall claims made by the IT experts in Pakistan, our export in this
specialized sector is not even $50 million. Our youth has great
potential, but they are denied access to the knowledge because of
exorbitantly high cost of professional education especially in the
Information Technology. The time calls for a strong public-private
sector partnership investment in the market potential sectors impart
professional knowledge to our youngsters at the cheapest cost to harvest
a rich crop in future. Going for immediate profits would neither serve
the investors nor the country, because it is always a short-lived
phenomenon.
|
http://www.pakistaneconomist.com/issue2004/issue13/i&e2.php
|
CC-MAIN-2018-47
|
en
|
refinedweb
|
Preface
In object – oriented programming, we create objects every day, describing the whole world with objects, but how does the object come into being?
Catalog
- 1 breeding object
- The birth of 2 objects
- 3 the growth of the object
- 4 destruction of objects
- 5 Summary
Breeding object
Every day we are developing alloc objects, and the alloc method to do?
(ID) alloc {return _objc_rootAlloc (self);}
All object alloc calls this root method
ID _objc_rootAlloc (Class CLS) {return callAlloc (CLS, false/*checkNil*/, true/*allocWithZone*/);}
This method will call the callAlloc method
Static ALWAYS_INLINE ID callAlloc (Class CLS, bool checkNil, bool allocWithZone=false) {if (checkNil & & return nil; CLS!) #if __OBJC2__;} Ctor or raw {/ / Has isa or something. Use the slower path. ID obj = class_createInstance (CLS, 0); if (obj!) return callBadAllocHandler (CLS); return obj;}} / / #endif No shortcuts available. if (allocWithZone) return [cls allocWithZone:nil]; return [cls alloc];}
CheckNil = false, so it will not return nil.
Bool hasCustomAWZ () {return! Bits.hasDefaultAWZ ())}
In this picture, we can see that in the data segment data of the object, class_rw_t has a flags.
Bool hasDefaultAWZ () {return (data) -> flags RW_HAS_DEFAULT_AWZ;} #define RW_HAS_DEFAULT_AWZ (1< < & 16)
RW_HAS_DEFAULT_AWZ this is used to indicate whether the current class or superclass has a default alloc/allocWithZone. It is worth noting that this value is stored in the metaclass.
HasDefaultAWZ () method is used to determine whether the current class default allocWithZone.
If cls-> (ISA) (->); hasCustomAWZ () return to YES, means that there is a default allocWithZone method, then directly to the class allocWithZone, to apply for memory space.
If (allocWithZone) return [cls allocWithZone:nil];
AllocWithZone will call rootAllocWithZone
(ID) allocWithZone: (struct _NSZone *) zone {return _objc_rootAllocWithZone (self, (malloc_zone_t *) zone);}
Then take a closer look at the specific implementation of _objc_rootAllocWithZone
ID _objc_rootAllocWithZone (Class CLS, malloc_zone_t *zone) {ID obj; #if __OBJC2__ under __OBJC2__ ignores the / / allocWithZone zone parameter (void) zone; obj = class_createInstance (CLS, 0); #else if (zone ||! UseGC) {obj = class_createInstance (CLS, 0);} else {obj = class_createInstanceFromZone (CLS 0, zone);} #endif (if! Obj) obj = callBadAllocHandler (CLS); return obj;}
In __OBJC2__, call class_createInstance (CLS, 0); method to create object.
ID class_createInstance (Class CLS, size_t extraBytes) {return _class_createInstanceFromZone (CLS, extraBytes, Nil);}
_class_createInstanceFromZone method on the basis of the first detailed analysis, the following detailed analysis, the first clear program context.
In the old version of the objc in the first to see whether there is space zone, whether to use a garbage collection, if there is no space, or by the garbage collection, it will call the class_createInstance (CLS, 0) method to acquire the object, otherwise the call class_createInstanceFromZone (CLS, 0, zone); object.
ID class_createInstanceFromZone (Class CLS, size_t extraBytes, void *zone) {return _class_createInstanceFromZone (CLS, extraBytes, zone);}
As you can see, the function that the final object is called is _class_createInstanceFromZone, regardless of whether the objc version is new or old.
If successful, objc is returned, and the callBadAllocHandler method is called if the creation fails.
Static ID callBadAllocHandler (Class CLS add re-entrancy protection) {/ / fixme in case allocation fails inside handler return (*badAllocHandler) (CLS);} static (*badAllocHandler) ID (Class) = & defaultBadAllocHandler; static ID defaultBadAllocHandler (Class CLS) {_objc_fatal ("attempt to allocate object of class'%s'failed, cls-> (nameForLogging));}
Failed to create an object that will eventually call the _objc_fatal output “attempt to object of class failed” to create an object failed.
This completes the callAlloc in hasCustomAWZ () returns to YES. So hasCustomAWZ () function returns NO, the situation is like? {/ / Has ctor or raw isa or something. Use the slower path. id = obj class_createInstance (CLS, 0); if (obj return!) CallBadAllocHandler (CLS); return obj;}}
This section is hasCustomAWZ () to return to the NO, the current class is no default allocWithZone.
In the absence of the default allocWithZone, it is also necessary to determine whether the current class supports fast alloc. If you can, call the calloc function directly, apply for 1 bits.fastInstanceSize () the size of the memory space, if the creation fails, it will call the callBadAllocHandler function.
If successful, initialize the Isa pointer and dtor.
Bool hasCxxDtor (data) {return (->); flags & RW_HAS_CXX_DTOR or;} / / class superclass has.Cxx_destruct implementation #define RW_HAS_CXX_DTOR (1< < 17)
DTOR is used to determine whether the current class or superclass.Cxx_destruct function.
If the current class does not support fast alloc, then go to class_createInstance (CLS, 0) to create a new object.
Summary:
After a series of judgments, the object of the birth process eventually fell on the _class_createInstanceFromZone function.
Static __attribute__ ((always_inline)) ID _class_createInstanceFromZone (Class CLS, size_t extraBytes, void *zone, bool cxxConstruct = true, size_t = *outAllocatedSize Nil) {if (CLS!) return nil; assert (cls-> isRealized) (); / / Read class's info bits all at once for performance bool hasCxxCtor (hasCxxCtor = cls-> bool); hasCxxDtor = cls-> hasCxxDtor (bool); fast = cls-> canAllocIndexed (size_t); size = cls-> instanceSize (extraBytes); if (outAllocatedSize) *outAllocatedSize = size; ID obj; if (UseGC! & & zone & & fast! = obj) {(ID) calloc (1, size); if (obj return nil!); obj-> initInst AnceIsa (CLS, hasCxxDtor);} else {#if SUPPORT_GC if (UseGC) {obj = (ID) auto_zone_allocate_object (gc_zone, size, AUTO_OBJECT_SCANNED, 0, 1);} else #endif if (zone) {obj = (ID) malloc_zone_calloc ((malloc_zone_t) zone, 1, size) {else}; obj = (ID) calloc (1, size);} if (obj!) return nil Use non-indexed isa on; / / the assumption that they might be doing something weird with the zone / or RR. obj-> initIsa (CLS);} if (cxxConstruct & & hasCxxCtor) {obj = _objc_constructOrFree (obj return obj, CLS);};}
What are ctor and dTOR respectively?
Bool (hasCxxCtor) addSubclass (propagates) {/ / this flag from the superclass. assert (isRealized) (return); bits.hasCxxCtor (bool) (hasCxxCtor);} {return (data) -> flags & RW_HAS_CXX_CTOR #define;} RW_HAS_CXX_CTOR (1< < 18)
Ctor is to determine whether the current class or superclass.Cxx_construct construction method.
Bool (hasCxxDtor) addSubclass (propagates) {/ / this flag from the superclass. assert (isRealized) (return); bits.hasCxxDtor (bool) (hasCxxDtor);} {return (data) -> flags & RW_HAS_CXX_DTOR #define;} RW_HAS_CXX_DTOR (1< < 17)
DTOR is to judge whether the current class or superclass has the.Cxx_destruct structure method.
Size_t instanceSize (size_t extraBytes) {size_t = alignedInstanceSize (size + extraBytes); / / CF requires all objects be at least 16 bytes. if (size < 16) size = 16; return size; uint32_t alignedInstanceSize) {return} (word_align (unalignedInstanceSize) (uint32_t);} unalignedInstanceSize {assert (isRealized (() return (data))); -> ro-> instanceSize;}
The instance size instanceSize will be stored in the isa_t structure of the class, and then returned after alignment.
Note: Core Foundation requires that all objects must be greater than or equal to 16 bytes in size.
After getting the size of the object, call the calloc function directly to allocate memory space for the object.
About calloc function
The calloc (function) contiguously allocates enough space for count objects that are size bytes of memory each and returns a pointer to the allocated memory. The allocated memory is filled with bytes of value zero.
This function is also the reason why we apply the initial value is 0 or nil. Because the calloc () function will default to the application space is initialized to 0 or nil.
After applying for memory space, you need to initialize the Isa pointer.
Obj-> initInstanceIsa (CLS, hasCxxDtor); obj-> initIsa (CLS);
Initialize the Isa pointer with the above two functions.
Inline void objc_object:: initInstanceIsa (Class CLS, bool hasCxxDtor) {assert (UseGC!); assert (cls-> requiresRawIsa) (!); assert (hasCxxDtor = = cls-> (hasCxxDtor)); initIsa (CLS, true, hasCxxDtor);} inline void objc_object:: initIsa (Class CLS) {initIsa (CLS false, false);}
From the above source, we can see that the final call is the initIsa function, but into the different parameters.
Inline void objc_object:: initIsa (Class CLS, bool indexed, bool hasCxxDtor) {assert (! IsTaggedPointer ()); if (! Indexed) {isa.cls = CLS;} else {assert (DisableIndexedIsa!); isa.bits = ISA_MAGIC_VALUE; / / isa.magic is part of ISA_MAGIC_VALUE isa.indexed is part of ISA_MAGIC_VALUE / / isa.has_cxx_dtor = hasCxxDtor; isa.shiftcls = (uintptr_t) CLS > > 3;}}
The initialization process is the process of initializing the isa_t structure.
If __arm64__ define ISA_MASK 0x0000000ffffffff8ULL # # # define ISA_MAGIC_MASK 0x000003f000000001ULL define ISA_MAGIC_VALUE 0x000001a000000001ULL struct uintptr_t # {indexed: 1; uintptr_t: 1; has_assoc: 1; uintptr_t has_cxx_dtor uintptr_t shiftcls: 33; / / MACH_VM_MAX_ADDRESS 0x1000000000 uintptr_t magic uintptr_t: 6; weakly_referenced: 1; uintptr_t: 1; deallocating: 1; uintptr_t has_sidetable_rc uintptr_t extra_rc: 19 # define; RC_ONE (1ULL< < 45) # define RC_HALF (1ULL< < 18)};
For specific initialization, please refer to the first day of admission to the Objective-C hospital in Runtime, ISA and Class
The main reason is the current address right three bits for the Class pointer in useless after the three removal reduces memory consumption, because the pointer to the byte aligned memory (8 bits), the three pointer is meaningless 0. Most of
machine architecture is all byte-addressable, but the memory address of the object must be aligned to byte multiples, which can improve the performance of the code running in iPhone5s, the virtual address is 33 bits, so for the last three bit aligned to 000, we will say only that the address of an object with 30 of them to.
At this point, the process of breeding object is completed.
Two. The birth of the object
Once we call the init method, the object will be born.
- (ID) init {return _objc_rootInit (self);}
Init calls the _objc_rootInit method.
ID _objc_rootInit (ID obj) {/ / In practice, it will be hard to rely on this function. classes do not properly / / Many chain -init calls. return obj;}
The _objc_rootInit method is simply to return the current object.
Three. Growth of objects
The object of the growth, in fact, is to talk about the object initialization, access to its attributes and methods, they look like in memory.
#import < Foundation/Foundation.h> @interface; Student: NSObject @property (strong, nonatomic) NSString + *name (void); study; run; @end - (void) #import "Student.h" @implementation + Student (void study) {NSLog (@ Study) - (void);} run {NSLog (@ "Run" @end});
Here we create a new Student class to illustrate. This class is simple, with only one name attribute, plus a class method, and an instance method.
Student *stu = [[Student alloc]init]; NSLog (@ Student's class is, [stu class]% @ "); NSLog (" Student's meta class is% @ @ object_getClass ([stu, class])); NSLog ("Student's meta class's superclass is @% @", object_getClass (object_getClass ([stu class]))); Class currentClass = [Student class]; for (int i = 1; I 5; < i++) {NSLog ("Following the ISA pointer @%d times gives%p, I, currentClass% @", currentClass); currentClass = object_getClass (currentClass);} NSLog (@ NSObject's class is%p, [NSObject NSLog (@ class]); "NSObject's meta class is%p", object_getClass ([NSObject class]));
Write the above code and analyze the structure.
The output is as follows:
Student's class is Student Student's meta class is Student Student's meta class's superclass is NSObject Following the ISA pointer times gives 0x100004d90 Student Following the 1 isa pointer 2 times gives 0x100004d68 Student Following the ISA pointer times gives 0x7fffba0b20f0 NSObject Following the 3 isa pointer 4 times gives 0x7fffba0b20f0 NSObject NSObject's class is 0x7fffba0b2140 NSObject's meta class is 0x7fffba0b20f0
After the print results above, we can know that the ISA of an instance of a class is a class that points to it:
An example of the class, the dotted line to the gray area, the gray area is a Class pair, which contains two things, one is the class, and the other is meta-class. Class isa points to meta-class. Since student is inherited from NSObject, so Student’s class meta-class is NSObject superclass.
In order to figure out what is stored in the 3 items, we print some more information.
+ (NSArray *) instanceVariables int outCount Ivar {unsigned; *ivars = class_copyIvarList ([self, class], & outCount); NSMutableArray *result = [NSMutableArray array]; for (unsigned int i = 0; I < outCount; i++) {NSString type = [NSString * decodeType:ivar_getTypeEncoding (ivars[i])]; NSString *name = [NSString stringWithCString:ivar_getName (ivars[i] encoding:NSUTF8StringEncoding]; NSString *ivarDescription) = [NSString stringWithFormat:@ "% @% @" type, [result, name]; addObject:ivarDescription];} free (Ivars); return result.count [result copy] nil;}?
From the previous print information we can know that 0x100004d90 is the class address. 0x100004d68 is the address of the meta-class class.
Po [0x100004d90 Po [0x100004d68 instanceVariables] instanceVariables]
Print out:
< __NSSingleObjectArrayI 0x100302460> (NSString* _name) nil
As you can see, the attributes are stored in the class.
The following is about the understanding of class methods and instance methods.
In fact, there is no concept of the number and number method in memory. Do a test:
+ (NSArray * ClassMethodNames) {NSMutableArray * array = [NSMutableArray array]; unsigned int methodCount = 0; methodList = Method * class_copyMethodList ([self class], & methodCount); unsigned int i; for (I = 0; I < methodCount i++; [array addObject: NSStringFromSelector (method_getName) {(methodList[i])})]; free (methodList); return array;}
Po [0x100004d90 Po [0x100004d68 ClassMethodNames] ClassMethodNames]
Print out:
< __NSArrayM 0x100303310> (.Cxx_destruct, name, setName:, run) < __NSArrayM 0x100303800> (Study)
0x100004d90 is a class object, which is stored in the number method, there are 3 other methods, getter, setter, and.Cxx_destruct method
0x100004d68 is meta-class, which is stored in the + method.
Of course, there is a special meta-class in runtime, that is NSObject meta-class, its superclass is itself. In order to prevent the minus NSObject protocol inside the method call may appear collapse, such as copy – method, so in the NSObject meta-class to + all NSObject methods are to achieve again, is to deliver the message to intercept here again. So the general NSObject protocol method has the same method + + and – number method.
It is worth noting that, class and meta-class are single cases.
About the object, all the objects in the memory inside there is a ISA, ISA is a small “radar”, with it, you can send a message to an object under runtime.
So the essence of the object: the object in the Objc is a variable that points to the ClassObject address, that is ID obj = & ClassObject.
On the nature of the object is, void *ivar = & obj + offset (N)
NSString @ *myName = "halfrost"; NSLog (@ myName address =%p, size =%lu ", & myName, sizeof (myName)); ID CLS = [Student class]; NSLog Student class =% @ (@ address =%p, size =%lu", CLS, & CLS, sizeof (CLS void)); *obj = & CLS; NSLog ("Void *obj = @% @ address =%p, size =%lu", obj, & obj, sizeof (obj)); NSLog (@ "% @%p" ((__bridge * Student) obj (__bridge).Name (Student * obj).Name));
output
MyName address = 0x7fff562eeaa8, class = Student size = 8 Student address = 0x7fff562eeaa0, size = 8 Void *obj = < Student: = 0x7fff562eeaa0> 0x7fff562eea98 address, size = 8 halfrost 0x10a25c068
From this example, the object is the essence to the class object address variables, from the above example we can see that ID obj, obj = & ClassObject, CLS is a Student class object, so obj is a Student object.
Class objects are loaded into memory before the main function is executed, executable files and all symbols of the dynamic library (Class, Protocol, Selector, IMP,…) Have been successfully loaded into the memory format, the runtime management, and then after that, those methods of runtime (dynamic add Class, Swizzle, etc.)
Specific can see this article iOS program main function before what happened
Or return to the example, about object properties, is the obj address and the offset, you can access to the above example, the obj address is 0x7fff562eea98, down 8 to offset, class address, 0x7fff562eeaa0, to offset 8, went to the name attribute of the 0x7fff562eeaa8 address. Stored in the name is the first address of the string, according to the print information is also seen, the store is a pointer, pointing to the 0x10a25c068 address.
If we print this address:
We’ll find that there’s a string.
A summary of the above is the picture, each object of the ISA is stored in the Class memory address, Class is in the main function before the implementation of the load into memory, and by the Runtime management. So only need to construct a pointer to Class, that is, ISA, can be an object.
The property of an object is the offset on the first address of the object. As shown above, when you know that the first address of the object is 0x7fff562eea98, then the 8 byte offset to the ISA, and then offset the 8 bytes to the name attribute. The property of an object is the process of offset addressing in memory.
Four. Destruction of objects
The destruction of the object is called the dealloc method.
- (void) dealloc {_objc_rootDealloc (self);}
The dealloc method calls the _objc_rootDealloc method
Void _objc_rootDealloc (ID obj) {assert (obj); obj-> rootDealloc; void objc_object: (inline)} (rootDealloc) {assert (UseGC!); if (isTaggedPointer) (return); if (isa.indexed & & isa.weakly_referenced; & &!! isa.has_assoc & isa.has_cxx_dtor & &! & isa.has_sidetable_rc) {assert (!!) (sidetable_present); free (this);} else {object_dispose (this (ID));}}
If it is TaggedPointer, direct return.
Indexed is on behalf of whether to open the ISA pointer optimization. Weakly_referenced represents the weak point of an object that is pointed to or once pointed to a ARC. Has_assoc represents an object that contains or has been associated with a reference. Has_cxx_dtor mentioned it before. It’s a destructor. Has_sidetable_rc determines whether the reference count of the object is too large.
ID object_dispose (ID obj) {if (obj!) return nil; objc_destructInstance (obj); #if SUPPORT_GC if (UseGC) {auto_zone_retain (gc_zone, obj); / / GC free expects rc==1 #endif free} (obj); return nil;}
Object_dispose will call objc_destructInstance.
/*********************************************************************** * objc_destructInstance * Destroys an instance without freeing memory. Calls C++ destructors. * Calls * ARR Ivar cleanup. * Removes associative references. * Returns `obj`. Does nothing if `obj` is nil. warned that GC DOES * Be NOT CALL THIS. If you edit this also edit finalize. CoreFoundation and other clients do call * this under void * objc_destructInstance (GC. **********************************************************************/ ID obj if (obj)) {{/ / Read all of the flags at once for performance. bool cxx = obj-> bool = assoc (hasCxxDtor); UseGC & &!; obj-> hasAssociatedObjects; bool (dealloc = UseGC); Order is important. / / This if (cxx) object_cxxDestruct (obj); if (Assoc) _object_remove_assocations (obj); if (dealloc) obj-> clearDeallocating (return obj);};}
An object is destroyed by the underlying C++ destructor. You also need to remove the associative reference.
Followed by a detailed look at the destruction of the object of the 3 methods.
1.object_cxxDestruct
Void object_cxxDestruct (ID obj) {if (obj!) (return; if obj-> isTaggedPointer (return)); object_cxxDestructFromClass (obj, obj->); ISA (static void);} object_cxxDestructFromClass (ID obj, Class CLS) {void (*dtor) (ID); / / Call cls's dTOR first, then superclasses's dtors. (for; CLS; CLS = cls-> superclass) {if (cls-> hasCxxDtor)! (return); dTOR = (void (*) (ID)) lookupMethodInClassAndLoadCache (CLS, SEL_cxx_destruct); if (dTOR! = (void (*) (ID) _objc_msgForward_impcache)) {if {_objc_inform (PrintCxxCtors) ("CXX: calling C++ destructors for class%s, cls-> nameForLogging);}; () (*dtor) (obj); }}
From the start along the inheritance chain has been to find the parent class, to search for SEL_cxx_destruct
the selector, find the function (void (*) (ID) (function pointers) and execute.
The following is a reference to the contents of the dealloc process and.Cxx_destruct under ARC:
From this article:
ARC actually creates -.cxx_destruct to handle instance This method was originally created for calling C++ destructors automatically when an method object was destroyed. variables. freeing a
As mentioned in “Effective Objective-C 2”:
When the compiler that an contained C++ objects, it would a called.Cxx_destruct. ARC on this method and emits the required cleanup piggybacks code within it. saw method generate
It can be learned that the.Cxx_destruct method was originally designed for the C++ object, ARC borrowed this method to insert code to achieve automatic memory release work.
In ARC, the dealloc method is called after the last release, but at this time the instance variable (Ivars) is not released, the parent class’s dealloc method will be called automatically after the subclass dealloc method returns. The ARC instance variable objects under the release of [NSObject in the root dealloc] (usually root class is NSObject), the release order of various uncertain variables (uncertain, a class within the superclass and subclass is uncertain, that is not the care release order)
After the study of the @sunnyxx text:
1.ARC objects under the member variables in the compiler insert.Cxx_desctruct method automatically released.
2.ARC under the [super dealloc] method is automatically inserted by the compiler.
As for the realization of the.Cxx_destruct method, but also look at the detailed analysis of the article @sunnyxx.
2._object_remove_assocations
Void _object_remove_assocations (ID object) {vector< ObjcAssociation, ObjcAllocator< ObjcAssociation> > elements; manager AssociationsHashMap {AssociationsManager; & associations ((manager.associations)); if (associations.size) (return = = 0); disguised_ptr_t disguised_object = DISGUISE (object); AssociationsHashMap:: iterator I = associations.find (disguised_object); if (I ()! = associations.end) {/ / copy all of the associations that need to be removed. ObjectAssociationMap *refs = i-> second; for (ObjectAssociationMap:: iterator = J refs-> begin (end = refs->), (end);; J! = end; ++j) {elements.push_back (j-> second); Remove the secondary table. delete} / / refs; associations.erase (I);}} / / the calls to (releaseValue) happen outside of the lock. for_each (elements.begin), elements.end (ReleaseValue), (());}
When remove the associated object object, will be the first to determine the object isa_t has_assoc for a second bit value, when the presence of object and object-> (hasAssociatedObjects) value is 1 when to call the _object_remove_assocations method to.
The purpose of the _object_remove_assocations method is to delete second ObjcAssociationMap tables, that is, delete all the associated objects. Delete second tables, you need to traverse the first AssociationsHashMap table search. Here will be second ObjcAssociationMap table of all the ObjcAssociation objects are stored in an array of elements inside, and then call associations.erase () to delete the table second. Finally traverse the elements array, the ObjcAssociation object in turn release.
The way to remove this is exactly the same as the remove method in the Associated Object associated object.
3.clearDeallocating ()
Inline void (objc_object:: clearDeallocating) {if (! Isa.indexed path for raw) {/ / Slow pointer isa. sidetable_clearDeallocating (else);} if (isa.weakly_referenced || isa.has_sidetable_rc path for non-pointer) {/ / Slow isa with weak refs and/or side table data. (clearDeallocating_slow);} assert (sidetable_present);} (!)
Here are 2 clear functions, the next one to see.
Void: sidetable_clearDeallocating (objc_object:) {SideTable& table = SideTables ([this]); / / clear any weak table items extra retain count and deallocating / / clear / / bit (fixme warn or abort if extra retain count = = 0?) table.lock (RefcountMap:); iterator: it = table.refcnts.find (this); if (it = table.refcnts.end! ()) {if (it-> second & SIDE_TABLE_WEAKLY_REFERENCED) {weak_clear_no_lock (& table.weak_table, this (ID) table.refcnts.erase (it));};}} (table.unlock);
Traverse SideTable, loop call weak_clear_no_lock function.
Weakly_referenced represents the weak point of an object that is pointed to or once pointed to a ARC. Has_sidetable_rc determines whether the reference count of the object is too large. If one of them is YES, the clearDeallocating_slow () method is called.
Path of (clearDeallocating) / / Slow / / for objects with indexed isa that were ever weakly / / referenced / / or whose retain count ever overflowed to the side table. NEVER_INLINE void (objc_object:: clearDeallocating_slow) {assert (isa.indexed & amp; & (isa.weakly_referenced ||; isa.has_sidetable_rc; SideTable& table)) = SideTables (table.lock ([this]);); if (isa.weakly_referenced) {weak_clear_no_lock (& table.weak_table, this (ID));} if {table.refcnts.erase (isa.has_sidetable_rc) (this) (table.unlock);}};
ClearDeallocating_slow will eventually call the weak_clear_no_lock method.
By dealloc Nils / * * * Called out all weak pointers; that point to the object so that they * provided can no longer be used. @param weak_table * * * @param referent The object being deallocated. / void weak_clear_no_lock (weak_table_t *weak_table, ID referent_id) {objc_object *referent = (objc_object * referent_id); weak_entry_t (weak_table = weak_entry_for_referent, *entry referent); if (entry = = Nil) {/ / / XXX shouldn't happen, but does with mismatched CF/objc //printf ("XXX no entry for clear deallocating%p/n", referent); return;} / / zero out references weak_referrer_t *referrers; size_t count; if (entry-> out_of_line) {referrers = entry-> referrers; Count = TABLE_SIZE (entry);} else {referrers = entry-> inline_referrers; count = WEAK_INLINE_COUNT;} for (size_t I = 0; I < count; ++i) {objc_object **referrer = referrers[i]; if (referrer) {if (*referrer = = referent) {*referrer = nil; if (*referrer) {else} _objc_inform ("__weak variable at%p holds%p instead of%p." This "is probably incorrect" objc_storeWeak use of "(and) (objc_loadWeak)." "Break on objc_weak_error to debug./n", referrer (void*) *referrer, (void*) referent); Objc_weak_error ();}} weak_entry_remove (weak_table, entry);}
This function clears the reference count table in the weak_table and clears the weak reference table, referring all weak references to nil.
summary
This article detailed analysis of the objc object from birth to ultimate destruction, it’s all in this present life. Also please a lot of pointing.
|
http://w3cgeek.com/the-objc-object-of-this-present-life.html
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Rafal Zawadzki <bluszcz at jabberpl.org> writes:
> Fragments my configurations are:
>
> <Directory /var/www/modpython>
> AllowOverride All
> AddHandler python-program .py
> PythonHandler mptest.py #i tried also with mptest (withoout .py)
> PythonDebug On
> </Directory>
Do you want to use the publisher-handler? (Makes sense)? Then put
PythonHandler mod_python.publisher
into your apache-config or .htaccess
Additionally you may want to put
MultiviewsMatch Handlers
also in there so that URIs like
will in fact be handeled by
def whatever(req):
...
in the file path.py in your htdocs-documentroot
IIRC you have to put
DirectoryIndex ... index.py ...
into your global apache-conf to make the extension-less URIs work.
HTH, Martin
|
http://modpython.org/pipermail/mod_python/2005-May/018212.html
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
On 28/01/2006, at 6:53 AM, Sean Jamieson wrote:
> Hello everybody,
> I don't know if there's already been a discussion about this, it seems
> like a small but obvious issue.
Many times. ;-)
> The current working directory does not apear to be set when a
> mod_python.publisher script runs; or rather it's set to "/" which is
> not useful. This becomes quite a pain, as I'm forced to do many things
> to work around it.
As someone else said, working directory can't be changed because of
multithreading
abilities of mod_python.
> i.e.
> 1) I've started using kid templates, and I have to use:
> Template( file=req.document_root().'template.kid', ... )
> or
> Template(
> file=req.document_root().'project_dir/templates/template.kid', ... )
> rather then the more natural:
> Template( file='templates/template.kid )
> this should find the 'templates' directory in the same directory as
> the running script
Don't use req.document_root(). Instead, in that specific Python code
file,
include at global scope:
import os
__here__ = os.path.dirname(__file__)
__templates__ = os.path.join(__here__,"templates")
That will give you the directory that file is located in, in a handy
variable
which you can then use.
Template( file=os.path.join(__templates__,"template.kid") )
This is only useful though if all your publisher handlers are in the
one directory.
If you have stuff spread over subdirectories, you start having to use
relative
paths as appropriate in subdirectory handler files.
import os
__here__ = os.path.dirname(__file__)
__templates__ = os.path.join(__here__,"..","templates")
Thus, you may be better off doing something like:
def _templates(req,path):
return os.path.join(req.hlist.directory,"templates",path)
...
Template( file=_template("template.kid") )
The req.hlist.directory variable will be set to the directory for which
PythonHandler
is specified, thus giving you a root anchor point which you can use to
describe all
paths relative to. Doing this means you have more flexibility as far as
moving code
files around between directories without having to modify code.
The other reference point you might use is:
def _templates(req,path):
directory = os.path.dirname(req.filename)
return os.path.join(directory,path)
...
Template( file=_template("templates/template.kid") )
The req.filename object is similar to using __file__ for most cases,
but getting the
information from the request object instead.
You might even create your own derived class from Kid's Template class
so you can
pass it a 'req' object and relative template file path and have that
derived class
constructor do the calculation of where the file is relative to
PythonHandler root
or req.filename.
In other words, to be more transparent, the template system would need
to know about
the environment it is used in.
> 2) I have to fully qualify imports from the document root, as the
> document root is added to sys.modules, but the current directory is
> not. So, if I'm in a subdirectory under the document root I have to
> do:
> import project_dir.subpackage.module
> when the current directory is 'project_dir'. This is silly, I should
> be able to import something in, or under, the current working
> directory:
> import subpackage.module
If these packages contain reusable code used across various pages and
don't have
actual code in them for generating pages, it is not a good idea to put
them under
your document root. This is because with the right URL they may be able
to be
invoked by a remote user because of publishers automatic mapping. Thus
you need to
be very careful.
If they do contain code for generating pages, you should not be using
"import"
to access them as at the same time they could be getting loaded by
publisher using
a different module loading system which will cause various problems.
As suggested by someone else, look at using "apache.import_module()".
> I would have to do some hack involving seperating the dirname of
> __file__ and adding it to sys.modules
I think you must have meant into sys.path. Same above, Modifying
sys.path directly
in mod_python is not usually a good idea either. The use of
PythonHandler will
automatically put that root directory in sys.path for you without
having to resort
to using PythonPath. This all assumes you have already set PythonPath
explicitly
and aren't using Location directive instead of Directory directive to
specify context
in which mod_python is used.
Graham
|
http://modpython.org/pipermail/mod_python/2006-January/020143.html
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Finance questions
This is a business financials problem I need major help on.
Problem 1 -
EPS Analysis
ABC Company has 11,000 shares of equity outstanding with a market price of $100. The company is not encumbered with any debt. Management is looking at two alternative recapitalization plans. The first alternative calls for issuing $250,000 of debt. The second alternative calls for issuing $500,000 of debt. The proceeds from the debt issuance would be used to buy back equity shares at market price (i.e., treasury stock). The cost of debt is 7% annually. Assume that the company pays no taxes for purposes of this problem.
a) Earnings before interest and tax (EBIT) are expected to be either $90,000 or $150,000. What would be ABC company's EPS at both income levels for the two refinancing plans? If both income possibilities are equally likely so that the expected EBIT is $130,000, what would be the expected EPS?
b) If EBIT will be equal to $100,000, what would EPS be under each of the two recapitalization plans? What does this confirm?
Problem 2 -
ABC Donut Company is operating an old machine that is not expected to last more than two years. In the next two years, the machine is expected to generate a cash inflow of $20,000 per year. A replacement machine is available at a cost of $150,000. The new machine would be more efficient and is expected to generate a net cash inflow of $75,000 per year for three years. Management is considering the replacement machine. The Donut Company the donut company do?
Problem 3 -
Company X has an equity beta of 1.25 and a debt to equity ratio of 2. The expected market portfolio return is 8 percent. The interest rate on governmental bonds is 4 percent. Company X can borrow long term at a rate of 6 percent. The corporate tax rate is 32 percent.
(a) What is the cost of equity?
(b) What is the cost of capital?
Problem 4 - C ash Flow Statement
The comparative balance sheet of Max Company, for 2008 and the preceding year ended December 31, 2007 appears below in condensed form: Year Year
2008 2007
Cash $ 45,000 $ 113,500
Accounts receivable (net) 51,300 58,000
Inventories 247,200 135,000
Investments 0 0
Equipment 493,000 375,000
Accumulated depreciation-equipment (113,700) (128,000)
$722,800 $553,500
Accounts payable $ 61,500 $ 42,600
Bonds payable, due 2012 50,000 100,000
Common stock, $10 par 250,000 200,000
Paid-in capital in excess of par--
common stock 125,000 50,000
Retained earnings 236,300 160,900
$722,800 $553,500
The income statement for the current year is as follows:
Sales $623,000
Cost of merchandise sold 348,500
Gross profit $274,500
Operating expenses:
Depreciation expense $24,700
Other operating expenses 75,300 100,000
Income from operations $174,500
Other income:
Gain on sale of investment $ 0
Other expense:
Interest expense 2,000 (2,000)
Income before income tax $172,500
Income tax 55,000
Net income $117,500
Additional data for the current year are as follows:
(a) Fully depreciated equipment costing $39,000 was scrapped, no salvage, and equipment was purchased for $157,000.
(b) Bonds payable for $50,000 were retired by payment at their face amount.
(c) 5,000 shares of common stock were issued at $25 for cash.
(d) Cash dividends declared were paid $42,100.
(e) All sales are on account.
Prepare a statement of cash flows, using the direct method of reporting cash flows from operating activities.
Problem 5 - Net Present Value
- Net Present Value, Internal Rate of Return and Profitability index methods
You must choose between the two projects whose cash flows are shown below. Both projects are of equivalent risk.
Year End Project A Project B
Now -$45,000 -$9,000
1 15,000 3,000
2 15,000 2,000
3 20,000 3,000
4 20,000 2,000
Compute for both projects:
a) the internal rate of return (IRR)
b) Assuming a 12% discount rate, compute net present value (NPV)
c) Assuming a 12% discount rate, compute profitability index (PI)
d) Assuming a 12% discount rate, which of the projects is better and why?
Solution Summary
The solution explains various questions in finance
|
https://brainmass.com/business/capital-budgeting/finance-questions-230678
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Philipp Auersperg writes: > .... missing control over stack trace .... I agree with you: you should have control over this stack trace. However, I fear, you will need to change the Zope source to get this. It should be easy to implement: Bind the traceback to a variable in the namespace, the "standard_html_error" page is rendered in rather than appending it directly. The "standard_html_error" is free to do with it whatever it likes. Maybe, you file a feature request into the Collector. Dieter _______________________________________________ Zope maillist - [EMAIL PROTECTED] ** No cross posts or HTML encoding! ** (Related lists - )
Re: [Zope] Intercepting NotFoundError with standard_error_message
Dieter Maurer Sun, 03 Dec 2000 01:40:00 -0800
- [Zope] Intercepting NotFoundError with standard_error_me... Philipp Auersperg
- Dieter Maurer
|
https://www.mail-archive.com/zope@zope.org/msg11801.html
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
>> > Does anyone know why we skip lisp/term in update-subdirs? >> Because files in lisp/term are always loaded with the term/ prefix. > Thanks. But why is that a good idea? It reduces the length of load-path and increases our namespace? > A remnant from past, perhaps, > when lisp/term held only terminal-specific files? Let me put it another way: why would it be a good idea to put lisp/term in update-subdirs? Stefan
|
https://lists.gnu.org/archive/html/emacs-devel/2009-09/msg00725.html
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
Created by .
Last modified on 2003/08/01.
There are several layers of caching built in to Zope:
These caches reduce the time taken to execute any Zope query, however they are all ultimately limited.
They can not reduce the time for a single request below a hard limit that is made up of:
Zope itself cannot do anything about these overheads. They can only be eliminated by something
outside of Zope - and that means exploiting the HTTP caching mechanisms.
This HowTo is a brief guide to using caching in Zope. For the full story,
see RFC 2616.
Caching isn't a win-win solution. It carries risks of making your Zope system more complicated than
it needs to be, and the possibility of clients seeing outdated information. Without care, it is possible
for caching to waste more time than is saved (calculating and checking the HTTP caching headers)
Think of caching as an Optimisation technique. Like any other optimisation, its only worth using after
performance measurements show that there is a problem worth solving.
The closer a cache is to the client, the more effective it is for him. The first few techniques
presented here target caches built in to browsers, or caches shared by a group of users.
The technique of using a cache close to the Zope server (possibly on the same machine) is discussed
further below.
Any document that is accessed many more times than it changes is a good candidate for caching. Examples are:
Users browsing though the site should, ideally, only have to download each of these items only once. This can be
achieved by using dtml to set the Cache-Control header. At its simplest:
<dtml-call "RESPONSE.setHeader('Cache-Control','max-age=3600')">
The 3600 is the number of seconds for which a client (or intermediate cache) should not re-request the object.
You need to tune the number for your application. In HTTP terms, the response is considered fresh
until the specified time has elapsed. In general, an object will not be re-requested again if the client
(or intermediate cache) knows it is fresh.
The Expires header is an alternative to max-age if your documents expire at a specific time. For example,
daily news that is always updated at 9AM.
<dtml-call "RESPONSE.setHeader('Expires','Thu, 01 Aug 2000 09:00:00 GMT')">
Using this with images on html pages is particulary effective because it allows the browser to display
the image (using the cached data) as soon as the html is loaded.
Unfortunately Zope's standard Image and File objects do not provide an easy way to set this header (as
of version 2.2. This may get added in a later version). A cheat
is to provide a DTML method that does just that, put it somewhere in the acquisition context, and name it in the
Precodition field. This method will then be called before the File or Image data is returned.
A browser will send authorization information for every request after the first one that needs it.
This authorization information prevents subsequent responses from being stored in a shared cache. If
your objects would be publicly visible anyway, then this can result in underusing
a shared cache.
This can be avoided by adding a 'public' cache control directive:
'public'
<dtml-call "RESPONSE.setHeader('Cache-Control','public, max-age=3600')">
If you are developing a reusable product (ZClass or Python product) then you may not know whether your object
should be public. The following python code can be used to determine whether an anonymous user can call that method
object - and whether the public directive is appropriate.
class MyObject......
def mymethod(self,REQUEST,RESPONSE):
"""Something that gets used alot by authenticated users, but
probably isnt private.
"""
if anonymous_access(self.REQUEST,self,self.mymethod__roles__):
RESPONSE.setHeader('Cache-Control', 'max-age=60, public')
else:
RESPONSE.setHeader('Cache-Control', 'max-age=60')
def anonymous_access(REQUEST,ob,roles):
"""Check whether an anonymous user would be able to access
the given object, with the given roles.
"""
while 1:
if hasattr(ob,'__allow_groups__'):
other_user = ob.__allow_groups__.validate(REQUEST,None,roles)
if other_user is not None:
return 1
if hasattr(ob,'aq_parent'):
ob = ob.aq_parent
else:
break
If a document is sufficiently large that the overhead of transmitting its content is
a problem, then using the If-Modified-Since header can be effective. This allows the server
to return a small response (including a 304 status code) if the document is unchanged since
the client last retrieved it.
This technique is used by the standard File and Image objects, and that code is easy to
steal if you are developing a product that behaves in a similar way. Beware that this code
has a flaw: The Last-Modified, Content-Type and Cache-Control headers really should be set
in the response even when returning a 304 status code.
The real complication with use of this technique is calculation of a last-modified time
for each document. For objects that store their data in one ZODB object the last-modified time
is easily obtained from the _p_mtime attribute. If the data comes from a file
system file, use stat.
_p_mtime
For most complex documents the answer involves a kludgey process of determining which
ZODB objects and files make up the document, and finding the maximum of all the individual
modification times. This might be a problem to consider at an early stage when designing
a cache-aware product.
It is possible to allow documents which normally require authorization to be stored
in a shared cache, by including a cache-control header that force the cache to
revalidate the response every time (allowing Zope to check authorization). This is only
a benefit when combined with If-Modified-Since processing
This
is not a high-security solution since it relies on the shared caches to be well behaved.
This can be achieved using the following mix of cache-control directives:
's-maxage=0'
'proxy-revalidate'
'must-revalidate'
Caching is also useful for documents that are expensive to generate, since it is possible to
avoid recalculating the document on subsequent requests. Caching is used to reduce server load,
rather than to improve performance for individual users.
The Zope logic is no different to that already described, however the same techniques are
more effective when an external HTTP proxy cache is used close to the Zope server. This
might be:
Note that an external cache is only useful if your expensive documents are not confidential.
If they require authorization then the external cache will not store them.
Some caches can be configured to return documents that have not been proved to be fresh. If
it is a problem for users of your application to ever see out-of-date information then add the
'must-revalidate' cache control directive.
But, note that they might still see old pages by pressing a Back button.
HTTP 1.1 includes a mechanism to cover documents that depend on the value of a request header
(perhaps user-agent, or accept-language). Unfortunately the 'vary' header is not yet supported by
browsers or caches. If you have documents like this, the best solution is to include a 'private'
cache control directive (or 'must-revalidate' too if you expect this header field to change)
'vary'
'private'
The presence of cookie headers in requests or set-cookie header in responses does not affect
whether or not an HTTP reply can be cached. If the content of a document depends on a cookie then
you should treat the document as described for 'Dynamic Content'.
Although a response that included a 'set-cookie' header can be cached, the 'set-cookie' header
itself will not be. To make sure that your 'set-cookie' headers always take effect, you might need
to add a 'no-cache' cache control directive too.
'set-cookie'
'no-cache'
If your documents are intended only for a single user, include the 'private' cache control directive.
If the documents contain sensitive information that should not even be kept in a private cache (where it
might escape onto a backup tape, for example) the include 'no-store' in addition to 'private'
'no-store'
|
http://old.zope.org/Members/htrd/howto/caching
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
Problem compiling C++ for SCC: could not open source file "cstdio"ally Aug 10, 2011 9:00 AM
Hi
I'm trying to compile a large C++ application to run on the SCC cores.
I have sourced "crosscompile.sh", and have set my Makefile to use icpc instead of g++. When I type: which icpc, I get:
/opt/icc-8.1.038/bin/icpc
which I believe is correct.
However, compilation fails with this error:
main.cc(2): catastrophic error: could not open source file "cstdio"
#include <cstdio>
Doing "locate cstdio" gives me this:
/opt/i386-unknown-linux-gnu/include/c++/3.4.5/cstdio
/opt/icc-8.1.038/include/c++/cstdio
/usr/include/c++/4.4/cstdio
/usr/include/c++/4.4/tr1/cstdio
/usr/include/c++/4.4/tr1_impl/cstdio
My understanding is that, having source crosscompile, I should be interested in one of the first two "cstdio" options, not the other three.
Since I am running icpc, I figured the second one, /opt/icc-8.1.038/include/c++/cstdio, should be right. So I add:
-I/opt/icc-8.1.038/include/c++/cstdio
to my compile command.
My questions are:
1) is this the right thing to do?
2) why do I have to add this, when icpc was able to successfully pick up lots of other C++ headers?
1. Re: Problem compiling C++ for SCC: could not open source file "cstdio"wbrozas Aug 10, 2011 10:01 AM (in response to ally)
I saw in the documentation programs being compiled with these flags. This will probably not fix your current problem but may fix later ones.
icpc -DCOPPERRIDGE -static -mcpu=pentium -gcc-version=340
As for your current problem -I should be followed by a directory and you probably need -L as well for libraries
Try adding -I/opt/intel_cc_80/include -L/opt/intel_cc_80/lib
instead of -L you can also set your LD_LIBRARY_PATH, I don't know what the equivalent is for include but the compiler will search through the directories listed in your LD_LIBRARY_PATH, it may have found some files there. When you source that script it probably changes your LD_LIBRARY_PATH
2. Re: Problem compiling C++ for SCC: could not open source file "cstdio"tedk Aug 10, 2011 10:18 AM (in response to wbrozas)
Please don't use -DCOPPERRIDGE ... it's now -DSCC. Copperridge is a legacy name and the docs are behind rev.
Did you look at
3. Re: Problem compiling C++ for SCC: could not open source file "cstdio"ally Aug 12, 2011 8:18 AM (in response to tedk)
Thanks for the tips regarding those flags.
But in relation to the problem finding "cstdio", can anyone comment as to why this standard file isn't found by icpc, and confirm which is the correct version to direct it to?
Thanks
Ally
4. Re: Problem compiling C++ for SCC: could not open source file "cstdio"wbrozas Aug 12, 2011 11:17 AM (in response to ally)
When the binaries are created, you configure the compiler to search for include files in a specific path as well as library files. If you would like to search somewhere else (in this case you do) you can use the arguments -I and -L.
Use this command to see where gcc will search (This is how gcc was configured)
gcc -print-search-dirs
I do not know the equivalent for icpc, but I'm sure there is one
As for where icpc should be looking, it should be searching in /opt/intel_cc_80/include and /opt/intel_cc_80/lib
Those are the c and c++ header files that go with intel version 8 c and c++ compilers
The files in /usr/include are GNU c standard header files, which may or may not be compatible
#EDIT#
Sorry I did not realize my directories are different. When I said /opt/intel_cc_80 it should be /opt/icc-8.1.038
|
https://communities.intel.com/thread/24023
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.