text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Details
- Type:
Bug
- Status: Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 10.1.2.1
-
- Component/s: Network Client
-
- Environment:Debian unstable, LInux 2.6.14.2, libc 2.3.5-6
- Urgency:Normal
- Issue & fix info:High Value Fix, Repro attached
- Bug behavior facts:Embedded/Client difference
Description
Trying to create a database with the following URL (note the Chinese character in the database name):
jdbc:derby://localhost:1527/\u4e10;create=true
throws the following exception:
----
%<----
Exception in thread "main" org.apache.derby.client.am.SqlException: Unicode string can't convert to Ebcdic string
at org.apache.derby.client.net.EbcdicCcsidManager.convertFromUCS2(Unknown Source)
at org.apache.derby.client.net.Request.writeScalarPaddedString(Unknown Source)
at org.apache.derby.client.net.NetConnectionRequest.buildRDBNAM(Unknown Source)
at org.apache.derby.client.net.NetConnectionRequest.buildACCSEC(Unknown Source)
at org.apache.derby.client.net.NetConnectionRequest.writeAccessSecurityONLconnect(Unknown Source)
at org.apache.derby.client.net.NetConnection.flowConnect(Unknown Source)
at org.apache.derby.client.net.NetConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:525)
at java.sql.DriverManager.getConnection(DriverManager.java:193)
at jdbctest.Main.main(Main.java:33)
----
%<----
It's possible, however, to create databases using the embedded driver, using an URL like:
jdbc:derby:\u4e10;create=true
Tested with both 10.1.1.0 and 10.1.2.1 with the same result.
Complete code to reproduce the bug:
----
%<----
public static void main(String[] args) throws Exception
----
%<----
Issue Links
- blocks
DERBY-4827 Modify the documentation for the 10.7 release regarding the UTF-8 CCSID manager
- Closed
- is depended upon by
DERBY-4805 Increase the length of the RDBNAM field in the DRDA implementation
- Resolved
- is part of
-
- is related to
DERBY-4584 Unable to connect to network server if client thread name has Japanese characters
- Closed
- relates to
DERBY-2251 When I Create a table with Chinese table name , ij report IO exception.
- Closed
DERBY-4799 IllegalArgumentException when generating error message on server
- Closed
Activity
- All
- Work Log
- History
- Activity
- Transitions
This is not related to Derby-708. This works in the embedded driver, but the path is encoded in EBCDIC (default DRDA encoding) between network client and server, and thus a character set equivalent to ISO-8859-1 is supported. This does not include chinese characters.
I ran into another occurrence of this while looking at the tests databasePermissions.java and databasePermissions_net.java. The 'embedded' version is made to run some subcases using Greek characters as username and password, networkserver/derbynetclient doesn't.
When you attempt to modify this so network server uses the user name and password strings with non-ascii (Greek, in this case) characters you bump into the same error (22005.S.3 / CANT_CONVERT_UNICODE_TO_EBCDIC) in org.apache.derby.client.net.EbcdicCcsidManager.convertFromUCS2.
Bernt said in this issue:
"... the path is encoded in EBCDIC (default DRDA encoding) between network client and server, and thus a character set equivalent to ISO-8859-1 is supported. This does not include chinese characters."
Are we locked into EBCDIC for this initial negotiation? I believe for data transfer etc, we use UTF-8. Could we change future versions to use UTF-8 for negotiating the databasename, user and password, or would that be in violation of the standard?
Thanks
Kathey
I did a quick prototype of Network server/client using a UTF8CcsidManager and was able to connect to the chinese database, but I don't see how we could implement this change and maintain compatibility with earlier versions. All of the exchange of server attributes is done in the CCSID manager encoding so we couldn't negotiate which CcsidManager to use. Are we just stuck until version 11 or does someone have an idea how to manage this?
I was wondering that until we have a long term solution in version 11, should we provide support for this in earlier versions by having a property which can be used to indiciate UTF8 rather than EBCDIC? Just a suggestion.
I know in general the community has avoided such properties, but perhaps it is justified in this case since there seems to be no other alternative. For client we would need to use a system property, since there is no derby.properties file for the client side. It seems a little messy to me, but the upside is that it would be a change that we could backport, so users could benefit immediately.
I noticed in the drda spec:
4.3.1.13 CCSID Manager
The CCSIDMGR allows the specification of a single-byte character set CCSID to be associated
with character typed parameters on DDM command and DDM reply messages. The CCSID
manager level of the application requester is sent on the EXCSAT command and specifies the
CCSID that the application requester will use when sending character command parameters.
So on the one hand it looks like there is the facility to specify a CCSID to use. I think it would be 1208 for UTF-8, but it explicitly says it should be a single-byte character set, so perhaps using UTF-8 is not in compliance with DRDA. But later in an example it mentions a server with CCSID 1208.
4.3.5.2 Examples
Below is a simple example of intermediate server processing. The example assumes that each
server has a different CCSID, indicated in the diagram generically as ebcdic, unicode, or ascii. In
the figure, the upstream requester has an EBCDIC CCSID (such as CCSID 37), the intermediate
server has a Unicode CCSID (such as CCSID 1208)...
So I am not totally sure whether it is legal or not.
Here's a possible workaround for this problem that bypasses DRDA compliance issues. It's not elegant but makes it possible to address this issue without changing the DRDA protocol. The idea is supporting database path aliases as a property. This may have other benefits / uses as well. Your thoughts please.
Idea:
I know that some databases [maybe even DB2? DB2 uses DRDA and does not encounter this problem] store location (host / port / path / name [or alias]) information in a file. Could we implement something similar (database names/aliases) using derby properties that can be read by Network server from the derby.properties file to resolve database names on the connection URL? For the server-side you would only, I think, need to specify the absolute or relative path to the database.
This seems innocuous enough a feature that we could backport to the older codelines to resolve this issue? It would only impact existing implementations that chose to set the property.
It struck me that something like what is done for the USER property might work well:
derby.dbalias.myDbAlias=<Yada-Path>/realDbName
And the connection URL would list only 'myDbAlias'?? I guess this would have to override derby.system.home and be overridded if the conneciton URL looked like a PATH? There are probably other issues I have not thought of..
Just one quick comment here. I once started looking at this issue and I i got some way towards a solution. My impression from looking at the DRDA spec is that it may not be THEORETICALLY possible (because of limitations such as those mentioned by Kathey), but in PRACTICE there should be possible to extend Derby's driver to use a different encoding and fall back to the old behavior when connected to an old server. It should be simple to make the server compatible with the new Derby client, old Derby client, DB2 client or the ODBC client.
I think I still have the work that I did on this lying around. I can try to make a patch of it, but I can't guarantee that the patch can be made against the latest trunk. That patch would by no means be a polished solution, but could perhaps be a starting point...
Here is a patch containing the work I had in my sandbox. It is made against
rev 660997. Updating to the current trunk produced one conflict in DRDAConnThread.java that dodn't look too bad but I'm not sure how to resolve it....
Hi Kathey,
my work on this issue should be in the patch. When working on it, I didn't really aim for a minimal solution, so it may be possible to achieve this with less work than what my patch suggests.
Based on what I can remember it seems like you are on the right track. Once the negotiating is working you just need to go through the code to find all the places where it is assumed that a given string length will fit in the same number of bytes. That isn't too bad as I recall, but there are some sticky points where a string, encoded in the negotiated charset, should be placed in DRDA fields which are specified with a fixed BYTE size, and should be padded to the correct size with space chars. This is simple as long as you can rely on the space character fitting in one byte, but when supporting encodings such as UCS-2 where space is two bytes, you can no longer use Arrays.fill() directly...
I also think there is a DRDA field where you are supposed to fill in the client's ip-address (or part of it) as a string in the negotiated charset, and that the number of bytes you can use is not enough to encode in UCS-2. But I think I concluded that this field is not used for anything important, so deviating from the spec here should not be a problem...
I have been talking with the local DRDA experts and found out that they are working on a new DRDA ACR for a UNICODEMGR which I think can help us with this issue. The short summary is this:
EXCSAT and ACCSEC are always sent EBCDIC. As part of the MGRLVL exchange, client sends UNICODEMGR 1208 which means that it is requesting all additional DDM parameters will be exchanged in code page 1208. The server responds with UNICODEMGR 1208 if it can accommodate the request. Otherwise it responds with UNICODEMGR 0 and all DDM parameters will continue to be exchanged in EBCDIC.
One problem with this approach is that ACCSEC currently has an RDBNAM parameter which we treat as required (the spec lists it as optional) and that has to be sent EBCDIC. So, my proposal is that we use the UNICODEMGR and we send RDBNAM on ACCSEC only if the EBCDIC conversion can be done. If the conversion can't be done, we send no RDBNAM on ACCSEC. Then we change the server to use the RDBNAM sent with the unicode SECCHK instead of the one sent on ACCSEC. (Currently we just verify that the SECCHK RDBNAM is the same as the one that was sent on ACCSEC.)
For an old client working with a new server, there will be no regression and the error message on sending a database name with international characters will be the same as currently listed in
DERBY-728.
For a new client working with a old server, this will mean that all the cases that currently pass will still pass, but if a nonconvertible database name is sent (e,g, one with Chinese
characters) , the server will send back a SYNTAXRM and the
server console will show:
= 2110; Error Code Value = e. Plaintext connection attempt
from an SSL enabled client?
org.apache.derby.impl.drda.DRDAProtocolException: Execution
failed because of a Distributed Protocol Error: DRDA_Proto_
SYNTAXRM; CODPNT arg = 2110; Error Code Value = e. Plaintext
connection attempt from an SSL enabled client?
at
org.apache.derby.impl.drda.DRDAConnThread.throwSyntaxrm(DRDAConn
Thread.java:513)
at
org.apache.derby.impl.drda.DRDAConnThread.missingCodePoint(DRDAC
onnThread.java:543)
at
org.apache.derby.impl.drda.DRDAConnThread.parseACCSEC(DRDAConnTh
read.java:1948)
at
org.apache.derby.impl.drda.DRDAConnThread.processCommands(DRDACo
nnThread.java:943)
at
org.apache.derby.impl.drda.DRDAConnThread.run(DRDAConnThread.jav
a:290)
The client could intercept the SYNTAXRM and knowing it was unable to convert the RDBNAM to EBCDIC could throw the same message it does now. The only regression would be that users attempting to send an invalid database name would now see the server side protocol error occur. I think it is an acceptable regression, since it won't cause any working cases to fail even with mixed revision server/client and it will enable us to move forward and have internationalized database name, user and password.
I prototyped the change and it all seemed to work ok. I'll attach the prototype patch.
I would like to implement as much as possible of this for 10.5, but since approval of the ACR by opengroup won't happen by the time we release 10.5, I propose to make the implementation dependent on a client system property derby.drda.unicodemgr=true. This would be false by default but could be switch to true in a maintenance release once opengroup approval occurs. Currently the hope is to have the ACR available publicly by the end of January. Then I would need Rick's help to try to push it through opengroup since he is our opengroup rep. I don't know how long that takes.
Attaching prototype of changes. This patch is not for commit. The prototype implements UNICODEMGR manager level to negotiate DDM parameter encoding. There are some places where performance degredation could occur which need to be addressed and some other issues in comments in the code. The prototype implementation adds a UTF8CcsidManager to client and server and switches the ccsidmgr in the DDMReader and DDMWriter based on the negotiated encoding. Probably that is not the clearest implementation since the new thing is called a UNICODEMGR not a CCSIDMANAGER, but this was the quickest way to implement the prototype. I haven't thought of a better way to do it yet but am open to suggestions.
The actual implementation will be in subtasks of this issue.
- Remove required RDBNAM from ACCSEC
- Client should only send RDBNAM on ACCSEC if EBCDIC conversion is possible.
- Accomidate length delimited DRDA strings where string length does not equal byte length.
- Implement UNICODEMGR support. Perhaps this can be broken up into subtasks but hopefully won't be too big ones the other three are done.
In the reproduction for this issue there is a Chinese character \u4e10. I'd like to know if anyone knows the meaning of this character before I put it in a bunch of tests.
Thanks
Kathey
According to it means "[Formal] a beggar", but I don't speak Chinese, so I really can't say.
I also found some web sites that indicate something like that, I think it's safe enough to use in tests.
Attached is ACR7007: a proposed change to the DRDA spec for UNICODEMGR, which will allow us to implement a fix for this issue. The ACR was developed within IBM with plans to present it to opengroup for approval. The authors said I could post it here so Derby could benefit and provide comments. Ultimately IBM will submit this to opengroup for incorporation in the spec.
Please take a look and post any comments to this issue. Rick may be especially interested as our representative at opengroup.
At the risk of pointing out the obvious, I tested this on the 10.5 RC1 using ij and the issue does not arise.
Interestingly enough, the folder that is created for the database seems to have the Unicode representation of the character and is just called: u4e10
I'm just wondering whether it isn't somehow assuming the u4e10 as a string literal rather than a Unicode character.
Tiago said:
>I'm just wondering whether it isn't somehow assuming the u4e10 as a string literal >rather than a Unicode character.
Yes, ij doesn't support escaped unicode characters. You have to use a java program, e.g.
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/\u4e10;create=true");
Hi Kathey,
Thanks for attaching the proposed change to Volume 1 of the DRDA spec. It got me thinking about SQL identifiers. It seems from the changes to chapters 6 and 7 on page 5 that DRDA still thinks that sql identifiers are limited to 255 bytes. I don't know where this limitation actually surfaces. It doesn't surface in the simple test I have attached (BigTableName) which pokes and peeks a table whose schema name and table name are each 128 unicode characters long, represented in utf-8 as 384 bytes apiece.
But it may prevent us from extending our DRDA or SQL support in the future. The maximum length of a SQL identifier is 128 unicode characters, according to part 2 of the 2008 SQL Standard, section 5.2 (<token> and <separator>), syntax rule (13). Derby supports this maximum length. At two bytes per Java character, this works out to 256 bytes, not 255. Since each unicode character can potentially expand to 4 bytes in UTF-8 encoding, the maximum length of a UTF-8 encoded identifier is 512 bytes. I believe that DRDA's sql identifiers should be at least 256 bytes long and probably 512 bytes.
Thanks.
Thank you Rick for looking at this.
I too am concerned about the DRDA 255 byte character string limit. I had thought of it especially in terms of this feature as users may have much longer paths for database name. I think this general limit extension needs to be addressed as a different ACR. I think we should open a separate issue for it and pursue it as a separate ACR with opengroup.
Unassigning this issue. I have not had time to focus on it and don't want to prevent someone else from picking it up.
I think the spec proposal is complete and the prototype is based on that and seems to work ok. The hardest part seems to be
DERBY-4009 to check the byte length limitations because we need to perform the check before we send and currently we do the byte conversion at a pretty low level during the send. The prototype doesn't have the checks.
Another issue regarding this change may whether to implement it before it officially gets into the spec. I was thinking maybe the initial implementation could be based on a property which would be made the default when the ACR is accepted,. On the other hand there are no user interfaces affected, so maybe it would be ok to go ahead and implement it. We have I think implemented some protocol extensions for setQueryTimeout and session caching that are Derby specific, but I may be wrong on that. This may also be a non-issue at the current rate of progress.
Anyway, please feel free to pick up on this issue. I will provide any assistance I can.
I marked this issue with labels mentor and gsoc. I would be willing to mentor a returning student in this project, but think it is probably not a good starting project for someone just joining derby.
I was recently discussing UNICODEMGR implementation with some engineers working on other database products. The topic of the encoding for embedded character data in PRDDTA and CRRTKN came up. The fields themselves are architected in DRDA as BYTSTRDR - Byte String, but do contain character data. The question was whether the character data should be UNICODE if UNICODEMGR was being used or should remain EBCDIC. I was asked how it will be in Derby's implemenation. I think it should be UNICODE. It just makes more sense (to me) and is how the current code will work, but should be limited to single byte characters. Let me know if you have a different opinion or better ideas.
I am probably garbling this, since I don't have the DRDA context in my head, but how would this help create database names with Chinese characters? AFAIK they are encoded in Unicode with 3 bytes (UTF-8), not single bytes..
@ Kathey:
I do agree with you, if the UNICODE format is chosen, it should be used to all subsequent exchanges of data. If DRDA specifies this field as byte string, then I suppose the encoding is left to the discretion of the implementation.
@ Dag:
In actual fact it wouldn't help the database names but I think for matters of coherence, if the UNICODE format is agreed upon between the parties, then it should be used for all cases.
Where does the single-byte character restriction come from? If the standard just says these objects contain byte strings, I'd assume we are allowed to encode multi-byte characters in them too.
I've had a talk with Kathey about how to approach this issue and here's a summary of what was discussed.
Essentially Kathey explained to me what she implemented in the derby-728_proto_diff.txt prototype. Based on this, we decided that I will first be addressing
DERBY-4009 which is a pre-requisite for DERBY-728. After that I will be implementing an UTF8CcsidManager on the server side and respective tests. Finally I will be adding the code for the manager level negotiation (UNICODEMGR introduces a new manager level) and for the switching between the two CcsidManagers.
This is my first patch for this issue.
Kathey, we talked about putting in place that setDatabaseName() method as one functional patch. However, that has already been checked-in.
As such, what this patch does is set the dbname and shortDbName fields to private. Being protected meant that there were classes that could bypass the setDatabaseName() and set the name directly to the attribute.
This is usually a bad idea so I encapsulated the fields with getters and setters to enforce the setDatabaseName() method.
I will be running regressions today.
I need to brainstorm a bit here regarding the Utf8CcsidManager class that I have.
There's one thing that I didn't implement because of a detail regarding the following method:
public String convertToUCS2(byte[] sourceBytes, int offset, int numToConvert) { }
So far we had this method on the EbcdicCcsidManager and then it's fine because EBCDIC only uses one byte per character at all times. So the offset parameter always works in a consistent way, that is to say that if offset is 5, we are not only getting 5 sourceBytes but also getting exactly 5 characters.
However, when we come to an Utf8CcsidManager, this offset might land straight in the middle of a character; then if we cut a character in half byte-wise, we will end with a totally different character.
Is it acceptable to consider offset as a number of characters rather than a number of bytes? It works both ways in EBCDIC but for UTF8 it would mean converting the sourceBytes to a String, offsetting it character-wise, and then convert the «offsetted» String to UCS2.
Any other ideas anyone might have?
I think from a practical perspective, at least for the server, the length passed is always going to be on a character border.
I only looked at the server code, but see the only place where it is ultimately called is from DDMReader.readString();
protected String readString () throws DRDAProtocolException{ return readString((int)ddmScalarLen); }
ddmScalarLen is what was sent from the client as the actual length of the ddm object, so the length should be good.
I think it would be good enough to document this assumption in the javadoc of the method.
We could not convert the sourceBytes because the buffer that is being passed is not all data, the rest of it (after offset ++ numToConvert bytes) is just the rest of the empty buffer.
Here is the list of changes checked in by patch #2:
- Utf8CcsidManager.java is rolled in for the server - This CCSID manager is not yet really used in practice. Instances are created but no real live code refers to it yet. I'm still unsure about this implementation and this code might change, but I needed to have a draft in place to proceed further.
- Both DDMWriter and DDMReader now have three CCSID manager attributes. These two classes have one instance of each of the available managers (UTF-8 and EBCDIC) and a reference to the current enabled one (already part of the existing implementation).
These two classes also no longer receive a CCSID manager in their constructor. Instead, they default to EBCDIC and whenever required we can setUtf8Ccsid() or revert to EBCDIC by doing setEbcdicCcsid().
- The DRDAConnThread.java class has also lost its own ccsidManager and will be using the one from its instance of DDMWriter. This class now initializes its DRDAStrings within the initialize() method, as it is only then that we have a DDMWriter available.
- Finally, the tests ProtocolTest and TestProto have also been changed to accommodate the constructor changes in DDMWriter and DDMReader.
–
I will be running regressions tonight. Provided that all goes well and there are no objections to this patch, it is ready for commit.
I forgot to mention but this patch aims at laying foundation for the dual CCSID manager possibility but the goal is to not break any of the current code. As I mentioned, the UTF-8 CCSID manager isn't yet being used by live code despite being in place and all going well, the EBCDIC will be the default even after the patch, without anything breaking.
The regressions ran with no failures or errors.
The regressions ran with no failures using both p2 patches.
Thanks Tiago for the patch, I think the naming of the methods is a bit confusing in the CCSidManger classes the method for example, public String convertToUCS2(byte[] sourceBytes) should probably just be convertToJavaString as as best I can tell that is what it is trying to do. So instead of:
String sourceString = new String(sourceBytes,"UTF-8");
return new String(sourceString.getBytes("UTF-16"),"UTF-16");
I think you could just return sourceString, unless I am missing something entirely.
I don't see that the CcsidManger numToCharRepresentation is being used anywhere. Could that just be removed?
Here are two refreshed patches after discussing the above issue with Kathey on IRC. We agreed that the convertToUCS2 method should actually be called convertToJavaString as we have no real requirement to have UCS2 Strings. As long as they are Java Strings, it should be fine as they won't be sent over the network (not in UCS2 anyway).
With this change, the conversion in the Utf8CcsidManager also changes slightly in this patch.
I've also removed a leftover comment that shouldn't have stayed there.
It needs to be said that the naming change should also happen in the client's CcsidManager classes, but I will keep this task for when I do the client changes.
I'll be running regressions again tonight and post the results in the morning.
The regressions failed for the last patch. Do NOT commit. The failure was as follows:
There was 1 failure:
1) testBootLock(org.apache.derbyTesting.functionTests.tests.store.BootLockTest)j
unit.framework.AssertionFailedError: Minion did not start or boot db in 60 secon
ds.
----Minion's stderr:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48) at java.lang.Integer.parseInt(Integer.java:470) at java.lang.Int
eger.valueOf(Integer.java:528) at java.lang.Integer.decode(Integer.java:958)at
org.apache.derbyTesting.functionTests.tests.store.BootLockMinion.main(BootLockMi
nion.java:42)
----Minion's stderr ended
at org.apache.derbyTesting.functionTests.tests.store.BootLockTest.waitFo
rMinionBoot(BootLockTest.java:217)
at org.apache.derbyTesting.functionTests.tests.store.BootLockTest.testBo
otLock(BootLockTest.java:130)
It is consistent by running the test by itself. I will be analysing the issue and submitting another patch soon.
It seems these errors come from Kathey's r956075 and are unrelated to my patches. Kathey can you confirm this please?
Hi Tiago. I think it would be good to change the convertFromUCS2 methods to convertFromJavaString and I wonder about this method which I think should be called
convertToChar
public char convertToUCS2Char(byte sourceByte){ return (char) sourceByte; }
For this one should the source byte be in UTF-8 , if so I think a straight cast might be a problem, depending on the default encoding. Is it needed? I don't see it in EbcdicCcsidManager..
The regressions ran without failures. I believe the patches are now ready to commit.
Hi Tiago,
I committed the patch, but then noticed the test names probably ought to be changed too.
testConvertFromUCS2 used 0 ms .
testConvertToUCS2 used 0 ms
Time: 0.593
You're right Kathey, I overlooked this. It should be safe to commit straight away, it's just a name change.
It looks like the new file (Utf8CcsidManager.java) is causing problems with insane builds. When using SanityManager routines you should always surround the call with a:
if (SanityManager.DEBUG)
SanityManager.THROWASSERT(...
This is so that when a release jar is built with sane=false no SanityManager code is included.
I'm attaching two patches to this issue.
The first, DERBY_728_p2_sanity.diff aims at fixing an issue with sanity. I was making calls to the SanityManager without a check to verify that the DEBUG was enabled. A question that remains open is: what do we do with the exception on a sane build? Is it ok to muffle it and only deal with it on insane mode?
The second patch, DERBY_728_p3.diff, should in principle enable UTF-8 support in the server. I'm not sure I've missed something but I'll post a short explanation of what I've done:
- CodePoint.java
Inserted the new code point for UNICODEMGR (0x1C08) as per the ACR and added it to the MGR_CODEPOINTS array.
–
- NetworkServerControlImpl.java
Set the minimum manager level for the UNICODEMGR in synch with the MGR_CODEPOINTS array.
–
- AppRequester.java
Set the minimum manager level for the UNICODEMGR in synch with the MGR_CODEPOINTS array.
Also added a convenience method that tells us whether the AppRequester depicted by this class supports or not UTF8. This relies on the manager level for UNICODEMGR being greater or equal to 1208. If the requester does not support UTF8, we won't get a UNICODEMGR manager level on the EXCSAT and as such UNICODEMGR will be set to 0 (which means this convenience method will return false).
–
- DRDAConnThread.java
When dealing with the ACCSEC code point and after we send the ACCSECRD reply we check whether the appRequester supports UTF8 and if it does, we enable it through the switchToUtf8() method [also part of the patch]. If it doesn't, make sure it goes back to EBCDIC, to make sure we aren't in UTF8 from the previous connection.
–
I'm not sure how I'd go about testing this as a client would have to support UTF-8 as well to be able to test it and this is still just the server side implementation. It will be a good test though to see if all regressions pass tonight; tomorrow, provided that this patch seems to be ok, I will do testing with older clients and see what the outcome is.
Regressions passed with no failures; I think it's safe to apply at least patch p2_sanity to fix the sanity issues.
Testing older clients today.
Hi Tiago,
The only comment I have on the code change is for AppRequester.supportsUtf8Ccsid(), I think == 1208 might be more appropriate than >= and perhaps a static constant would be good.
For testing, I think you can use the ProtocolTest to test if multi byte characters can be used in database name, userid and password, hopefully escaped unicode characters will work in protocol.tests.
I committed the sanity manager patch. I think it is fine to just ignore for insane builds, because we don't think it can happen and if it did the NPE that would result would be pretty easy to track.
It's great to see us so close on the server side!
Kathey
This feature has made it to the 10.7.1 release so unless bugs are found, I'm taking this issue as resolved and I'm closing it.
Quite likely, some common bug underlies this problem and Derby-708. | https://issues.apache.org/jira/browse/DERBY-728 | CC-MAIN-2016-30 | refinedweb | 5,399 | 55.03 |
I've been using some of these "opensource" tools for years now, there might be better tools so do comment below what your day to day tool is that helps you with work.
Screenshots: We take screenshots daily and share them on twitter, dev.to, slack and sometimes even in an email 👨💻. For that reason and easy to share I use Skitch. It is super easy to take a screenshot, make some pointers hit (copy) and (paste) and off to next task.
CheatSheet: This is one of those tools that I really love having on my Mac, sure I could be a Guru in some apps, but VI,VIM there is no Guru, there are Novice users and Advanced users. CheatSheet basically gives you supportive cheatsheet commands you can use with most tools like Sublime, VI, Mail, Chrome and many many more.
Alfred: I use Alfred quite a bit compare to Spotlight (I think this one is for Mac users only). Alfred basically helps me search my Mac in more advanced form + with the workflows you can add github, and many other helpful search functions.
Terminal on Steroids: Oh My Zsh! seriously since I started using it (last year) I fell in love it it so much.
Here is why...
I work on Kubernetes on daily basis and switch between namespaces, clusters quite a bit. That said, its really nice to have a visual representation which namespace and or cluster you are on while also giving you pointer that you are on blabla-patch1 branch in github. If you are on any type of terminal don't skip on Oh My Zsh!
What are some of your day to day must tools that did not come with your laptop installed?
Discussion | https://dev.to/joehobot/few-tools-i-use-to-help-me-with-day-to-day-work-3aei | CC-MAIN-2020-40 | refinedweb | 291 | 78.69 |
On 3/7/07, Ian Bicking <ianb at colorstudy.com> wrote: > Phillip J. Eby wrote: > > At 02:29 PM 3/6/2007 -0500, jason pellerin wrote: > >> I've been meaning to ask about this same issue, specifically with > >> respect to namespace packages, bdist_rpm and imp. I've had to patch > >> the spec files for all namespace packages that we build as RPMs, since > >> although the .pth file works when using import or __import__, imp > >> doesn't seem to recognize it, and that breaks Paste's app loading. > > > > Then Paste's app loading is broken, and wouldn't work with an egg either, > > if it's using "imp" and ignoring the package's __path__. > > I'm not sure which part of Paste is in question, but the only importing > that I can think of which it does is with pkg_resources or with __import__. I didn't save the output from trying to use the broken package load, unfortunately. I'll try to recreate it if I can. I may easily be putting the blame in the wrong place, though, since the failure was in paste.modpython -- it could be mod_python that's using imp in some egg-unfriendly way. If I can find some time today or in the next couple of days I'll re-break a namespace package and post the output from a failed load here. JP | https://mail.python.org/pipermail/distutils-sig/2007-March/007379.html | CC-MAIN-2018-05 | refinedweb | 229 | 79.3 |
Summary
Recently, at Devoxx, it was announced that Java would get lambda functions (a.k.a. anonymous functions or closures). There are many ways of implementing these on the JVM. This post proposes that reifying lambdas is a good choice.
Lambda functions are anonymous functions that can be defined using short syntax and in many cases offer a more concise alternative to inner classes. It was recently decided to add lambdas to Java () and a 'strawman' proposal was later given () for discussion on a discussion group ().
There are many ways to implement Lambdas on the JVM, one possibility is to erase their actual types and use signatures in class files (much like generics at present). Neal Gafter has given an example () that is difficult to do without erasing the types:
<T> #T() constant(T t) { return #() (t); }
The syntax used is from the referenced strawman:
The above 'constant' example will be used as a running example below.
Like generics the erasure option has problems, e.g.:
1. Can't, with some erasures proposals, have two methods of the same name only distinguished by lambda type, e.g. filter( #boolean(int) ) and filter( #boolean(float) ) illegal if both in same class
2. Can't have arrays of lambdas that are type safe, e.g. new #int()[n]; // Illegal
3. Can't have instanceof tests or class references, e.g. #int().class; // Illegal
This post proposes an alternative technique that doesn't erase type information except when used in conjunction with generics.
You could overcome the limitations of erasure given above in many cases if you had reified lambdas (i.e. lambdas that didn't erase the type). For example supose that:
#String() constant(String t) { return #() (t); }
Was translated to:
Callable$String constant(String t) { return new Callable$String() { @Override public String call() { return t; } }; }
Where:
public interface Callable$0<R> { R call(); } public interface Callable$String extends Callable$0<String> {}
The types Callable$... are created as needed by the class loader (they are not emitted by the compiler, but for typing purposes they are known internally to the compiler).
The case of primitives is more complicated because you want to avoid boxing, e.g:
#int() constant(int t) { return #() (t); }
Becomes:
Callable$int constant(int t) { return new Callable$int() { @Override public int call_int() { return t; } }; }
Where:
public interface Callable$Integer extends Callable$0<Integer> {} public abstract class Callable$int implements Callable$Integer { @Override public final Integer call() { return call_int(); } public abstract int call_int(); }
And in the generic's case (the original example) you would erase the type (because it is already erased):
<T> #T() constant(T t) { return #() (t); }
Is:
<T> Callable$0<T> constant(T t) { return new Callable$0<T>() { @Override public T call() { return t; } }; }
You would use the most specific type when a function type is given, e.g.:
class StringLambda extends #String() { ... } #String() stringLambda = ...;
Become:
class StringLambda extends Callable$String { ... } Callable$String stringLambda = ...;
Except when generics are used, in which case wild-cards and a Callable$*n* interface used:
#T(S) tSLambda = ...;
Becomes:
Callable$1<? extends T, ? super S> tSLambda = ...;
Where:
public interface Callable$1<R, A1> { R call(A1 a); }
The cases:
#Object(String) oS; #String(Object) sO = #String(Object o) (o.toString()); oS = sO; #Object(String)[] oSs = new #Object(String)[] {oS, sO}; #O(S) gOS = oS; // S = String, O = Object boolean test = gOS instanceof #Object(String) List<? extends #Object(String)> lOS; List<? extends #String(Object)> lSO = new ArrayList<#String(Object)>(); lOS = lSO; List<#int()> lI = new ArrayList<#int()>(); for (int ii = 0; ii < 3; ii++) { lI.add(constant(ii)); } #int() i = lI.get(0);
Are translate to:
Callable$Object$String oS; Callable$String$Object sO = new Callable$String$Object() { @Override public String call(final Object o) { return o.toString(); } }; oS = From$1$String$Object$$To$Object$String.cast(sO); Callable$Object$String[] oSs = new Callable$Object$String[] {oS, From$1$String$Object$$To$Object$String.cast(sO)}; Callable$1<Object,String> gOS = oS; boolean test = gOS instanceof Callable$Object$String; List<? extends Callable$1<? extends Object, ? super String>> lOS; List<? extends Callable$1<? extends String, ? super Object>> lSO = new ArrayList<Callable$1<? extends String, ? super Object>>(); lOS = lSO; List<Callable$0<? extends Integer>> lI = new ArrayList<Callable$0<? extends Integer>>(); for (int ii = 0; ii < 3; ii++) { lI.add(constant(ii)); } Callable$int i = From$0$Integer$$To$int.cast(lI.get(0));
Where:
public interface Callable$Object$String extends Callable$1<Object, String> {} public interface Wrapper { Object getWrapee(); } public static final class Wrappers { private Wrappers() {} public static Object unWrap(final Wrapper from) { Object wrapee = from.getWrapee(); while (wrapee instanceof Wrapper) { wrapee = ((Wrapper)wrapee).getWrapee(); } return wrapee; } public static boolean equals(final Wrapper self, final Object other) { if (self == other) { return true; } if (other == null) { return false; } final Object o = (other instanceof Wrapper) ? unWrap((Wrapper)other) : other; final Object s = unWrap(self); return o == s; } } public interface Wrapper$Object$String extends Callable$Object$String, Wrapper {} public interface Callable$String$Object extends Callable$1<String, Object> {} public final static class From$1$String$Object$$To$Object$String { private From$1$String$Object$$To$Object$String() {} public static Callable$Object$String cast(final Callable$1<? extends String, ? super Object> from) { return new Wrapper$Object$String() { @Override public Object call(final String s) { return from.call(s); } @Override public Object getWrapee() { return from; } @Override public boolean equals(final Object other) { return Wrappers.equals(this, other); } @Override public int hashCode() { return Wrappers.unWrap(this).hashCode(); } }; } } public static abstract class Wrapper$int extends Callable$int implements Wrapper {} public final static class From$0$Integer$$To$int { private From$0$Integer$$To$int() {} public static Callable$int cast(final Callable$0<? extends Integer> from) { if (from instanceof Callable$int) { return (Callable$int)from; } if (from instanceof Wrapper) { final Object wrapee = Wrappers.unWrap((Wrapper)from); if (wrapee instanceof Callable$int) { return (Callable$int)wrapee; } } return new Wrapper$int() { @Override public int call_int() { return from.call(); } @Override public Object getWrapee() { return from; } @Override public boolean equals(final Object other) { return Wrappers.equals(this, other); } @Override public int hashCode() { return Wrappers.unWrap(this).hashCode(); } }; } }
The cast methods create a new object; which is wasteful, but on the other hand they aren't needed often (see next section). The erasure schemes don't require 'cast' objects and therefore avoid this overhead, but on the other hand the erasure versions have similar limitations to erased generics. For the generic cases the use of wild-cards avoid the need for the cast methods (since the generics have already erased the types). The From$...$$To$... classes, like the Callable$... classes, are generated by the class loader on demand and not written by the compiler (but for typing purposes are known to the compiler).
The cast methods above are used 'mainly' for contravariant overriding. Most OO languages do not support contravariant overriding (except for generics), but for a moment suppose that Java did allow ontravariant overriding:
abstract class Base { abstract Object m(String s); } class Derived extends Base { @Override String m(Object o) { return o.toString(); } // Illegal arg should be String }
The above is type safe because the arguments to m vary contravariantly and the return types vary covariantly. The argument of m varies contravariantly in the derived class, Derived extends Base, but m's argument is Object and Object is the super type of String (which is m's argument type in Base). As m's enclosing classes go down the hierarchy, Base to Derived, its arguments go in the contra direction (up), from String to Object.
The above example shows that this can be useful, and that is the main purpose of providing 'cast' methods. However the above ability is not really missed in Java and is not provided by most of the common OO languages; therefore I infer that contravariance is not that common a requirement and hence the method suggested above is the best solution. In particular, since contravariance is not common, it makes sense to make that the expensive operation and make more common operations fast.
Reifying lambdas makes them easier to use them since they behave like normal Java objects, but on the other hand the implementation is harder. The implementation is harder because you essentially have an erased and a reified version.
How valuable is reifying lambdas?
(Updated 2 Jan 10 in response to comments from Neal Gafter and Zdenek Tronicek and updated 3 Jan 10 in response to comments from Zdenek Tronicek - Thanks.)
Have an opinion? Readers have already posted 10 comments about this weblog entry. Why not add yours?
If you'd like to be notified whenever Howard Lovatt adds a new entry to his weblog, subscribe to his RSS feed. | http://www.artima.com/weblogs/viewpost.jsp?thread=277879 | CC-MAIN-2017-22 | refinedweb | 1,444 | 54.32 |
Talk:Tag:historic=memorial
Contents
Thanks
Nice additional tag, thanks. As a newbie to OSM I expected such a tag and was surprised to find that it had only just been added.
For the UK it would be good if mappers could add the appropriate link to the UK National Inventory of War Memorials page for the memorial. Cheers -- John (Daytona2·Talk·Contribs) 09:27, 29 September 2008 (UTC)
inscriptions
I would suggest a tag inscription=* for reproducing any inscriptions on the memorial. Any comments? --abunai 17:32, 17 May 2009 (UTC)
- I like the idea. Perhaps even inscription:XX=* for different languages if that's the case. --Nighto 23:23, 22 February 2010 (UTC)
- Tagwatch shows inscription=* is used, however memorial:text=* is more widely used (1979 uses) --GabeH 18:03, 12 December 2010 (UTC)
By the way, do you think that this is the right tag for sculptures like busts? --Nighto 23:23, 22 February 2010 (UTC)
- If the bust is set up as a memorial over a person, why not? If the purpose of the bust is more decorative, than find something else. Isn't there any tags for sculptures in general? That could be needed for parks like Vigeland Parken in Oslo, Norway, which displays several sculptures by Gustav Vigeland. The entire park can be seen as a memorial over the artist, not each single sculpture. --Skippern 01:47, 23 February 2010 (UTC)
Very long inscriptions may be added to WikiSource, and tagged here with, say, inscription_url=*. Andy Mabbett (User:Pigsonthewing); Andy's talk; Andy's edits 11:33, 20 November 2011 (UTC)
- I'm using the URL tag for photos of the inscription too, I hope that's fine. Of course I store the photo on Commons. See --Nemo (talk) 23:16, 10 July 2016 (UTC)
- Seeing this now after many years. For the record, the established tags are inscription=* and inscription:url=*. --Dieterdreist (talk) 13:28, 24 February 2017 (UTC)
Commemorative trees
Please see discussion at Talk:Tag:natural=tree#Commemorative trees. Andy Mabbett (User:Pigsonthewing); Andy's talk; Andy's edits 11:29, 20 November 2011 (UTC)
Names
Some mappers at Germany are using memorial:name=* within the Stolpersteine-Project. name=* was not fitting, because a Stolperstein is only dedicated to a victim. This might also be applicable to some boards without names itself, but which are dedicated to a Person. I think this key-name is not a good choice, because it seems to be a duplicate to the name=*-Tag (another proposals for the same thing is person:name, which is not satisfying, too).
- It's worth looking at wikipedia=* and particularly the proposed wikipedia:subject=* for memorials to notable people (or events; there are also memorials to named animals) who are the subject of Wikipedia articles. Andy Mabbett (User:Pigsonthewing); Andy's talk; Andy's edits 12:08, 24 September 2013 (UTC)
- So the Wikipedia-Proposal implies a tagging like memorial:subject=*. As an alternative: I thought about memorial:designation=*, which might be not very specified. So +1 to memorial:subject=*.--Cracklinrain (talk) 14:09, 2 November 2013 (UTC)
- See also subject:wikidata=*.
- --Pyrog (talk) 12:26, 18 November 2019 (UTC)
- This is still an unresolved issue that has widespread effects. It is very common to misuse the name=* of memorials to indicate the subject of the memorial instead of its actual name. For example, it is very common to set the name of historic persons such as politicians or artists that are the subject of a plague or statue - especially if there is no clear true name of the memorial itself. memorial:subject=* has almost 700 uses in mid 2020 while memorial:name=* has twice as many (certainly many from Stolpersteine but it is used for other memorials as well). How shall we go forward: mention both on the wiki page (how? deprecating one?), start a vote, ...? --Stefanct (talk) 12:44, 11 August 2020 (UTC)
- subject:wikidata=* have the advantage of 1 subject = 1 unique identifier.
Also, IDs are shorter. It's useful for i.e. a war memorial with a lot of names.
- memorial:subject=* could have homonyms.
Paul Simon refer to
Paul Simon (politician),
Paul Simon (drummer),
Paul Simon (song writer)… ?
- --Pyrog (talk) 13:54, 11 August 2020 (UTC)
- I am not a big fan of relying on external databases for key functionalities. Also, IDs are not human-readable as is. The other (albeit related) disadvantage of solely using wikidata IDs is that there is little wiggle room if needed because of unclear/minor cases where no clear ID exists. You mention collections of subjects as for war memorials. In my country there are lots of war memorials dedicated to those fallen in WWI or WWII of individual small villages... adding and referring to them by a wikidata ID (that possibly does not even pass Wikidata's notability requirements) does not make a lot of sense. I acknowledge the big advantages of tagging the ID though (if available or useful otherwise)! Why not allow/promote both?
- --Stefanct (talk) 14:33, 11 August 2020 (UTC)
- > Also, IDs are not human-readable as is.
- Well, with iD or JOSM, you get automatically the label (even in your language)
- > where no clear ID exists
- Just create it :)
- > Why not allow/promote both ?
- Duplicate data mean more work ;)
- --Pyrog (talk) 16:43, 11 August 2020 (UTC)
- While it is perfectly fine to link to wikidata (additionally), I also agree with Stefanct that we should have and promote a proper OpenStreetMap tag for everything that we consider relevant (includes subjects of memorials and artwork). If the issue is duplication then I would prefer refraining from third party references. —-Dieterdreist (talk) 17:39, 11 August 2020 (UTC)
memorial:type
memorial=* has been massively changed to memorial:type=* by user malenki in Germany, thus taginfo usage statistics are 99% influenced by a single contributor. This variant is not the result of a general consensus, neither the usual tagging rules used in OSM (for instance, "building=school" is not "building:type=school", etc) and is therefore not recommended in the main documentation. --Pieren (talk) 16:17, 19 February 2014 (UTC)
- I agree. memorial=* seems more logical to me, and keys with ":type" or "_type" are prone to misspellings because it's difficult to memorize when to use colon (e.g. tower:type, maxspeed:type, seamark:type, mtb:type) and when to use underscore (e.g. artwork_type, map_type, reservoir_type, border_type). --Fkv (talk) 19:10, 12 August 2014 (UTC)
- As for "malenki removed memorial=stolperstein": Thats not the case. See for example , where malenki removed a wikipedia tag (and rightly so, because the wikipedia article is for the general project "Stolpersteine", and not for this individual stolperstein. Or see the one round the corner where he did exactly the same thing: . I think because memorial:type=* is widely accepted in germany at least for the stolperstein project, this use should be documented on the wiki accordingly. --Gormo (talk) 06:47, 1 October 2015 (UTC)
- @Pieren: you wrote:
- memorial=* has been massively changed to memorial:type=* by user malenki in Germany, thus taginfo usage statistics are 99% influenced by a single contributor. This variant is not the result of a general consensus,
- Please prove this wild speculation -- malenki 09:22, 1 October 2015 (UTC)
- @Malenki - surely it is for you to show that your changes have consensus? Andy Mabbett (User:Pigsonthewing); Andy's talk; Andy's edits 23:01, 15 November 2015 (UTC)
- @Andy: Consensus on what? -- malenki 12:27, 16 November 2015 (UTC)
- Please provide a link to a stolperstein node (or OSM IDs) where malenki has performed the action you critizise. You can - for example - use the deep history tool at to check which particular user changed what tags in what changeset for a specific object. I think you are misinterpreting OSM object histories. --Gormo (talk) 14:36, 16 November 2015 (UTC)
- Obviously neither Pieren nor Andy "Pigsonthewing" Mabbett are able to or want to substantiate their allegations/assumptions with facts. It seems the former has quite contributing to OSM altogether. -- malenki 11:12, 15 February 2016 (UTC)
- I think they are misinterpreting the object histories. I think this is an unfortunate misunderstanding on "their" part, it's not malice but incompetence/errors in understanding. I think this should not escalate. --Gormo (talk) 12:19, 15 February 2016 (UTC)
- I have looked at the tag history and the key memorial was at no time higher than memorial:type, rather the latter was used from the beginning and "memorial" only gained recently. Still there are significantly more memorial:type than memorial tags in the database as of now. --Dieterdreist (talk) 10:06, 11 January 2017 (UTC)
- Indeed, but most uses of memorial:type are with stolperstein, in Germany (18 395 out of 21 911 uses). So I guess that the Stolpersteine project has started using it and didn't change it. The RedBurn (talk) 08:36, 27 January 2017 (UTC)
artist_name
I would like to add artist_name to the page for tagging the artist like on tourism=artwork, can that be done without rolling out a proposal? :) Hakuch (talk) 21:04, 27 January 2016 (UTC)
Real persons and events only, right?
Am I right, that historic=memorial, being a tag within historic=* key, should always reflect objects, commemorating real people or events, including abstract ones (like, "Memorial of Unknown Soldier", which commemorates all real fallen soldiers, whose remains haven't been identified)? If yes, shouldn't it be explicitly told in tag description? There are sculptures of fictional characters or artworks, inspired by fictional events, which took place in non-documentary films or literature, and I think, these should always be mapped as artwork, not as memorials. --BushmanK (talk) 18:27, 4 June 2016 (UTC)
- I'd say yes. A "memorial" to Gandalf the Grey (from Lord of the Rings) or Lord Vetinari (from Discworld) would be an artwork, not a memorial. The historic-namespace should be reserved for historic events that, according to history, really took place. There might be grey areas (a memorial to something Jesus Christ did somewhere, according to the Bible), which I would see less strict (because there are historic interpretations of the Bible and other religions' texts). --Gormo (talk) 06:41, 6 June 2016 (UTC)
- Bible and its interpretations are not a part of evidence-based science, so I don't see why it's "grey area". However, memorial from your example isn't an artwork for tourists either, so it's another question, how to tag it properly. --BushmanK (talk) 14:51, 6 June 2016 (UTC)
- I have 2 memorials that are to animals. One to Mathew Flinders cat Trim the other to Australian horses in WW1, there are more of these WW1 horse memorials within Australia. So these real events, fictional events it is a possibility. Oh "dog on the tucker box" ... a 'legend' humm 'dedicated to the pioneers' Humm I am certain there will be a monument to some myth somewhere. Warin61 (talk) 20:50, 19 January 2017 (UTC)
memorial= values are orthogonal
Values of memorial= are mainly representing a physical form of a memorial, such as a statue, a plaque, and others. However, memorial=war_memorial indicates an event, which a memorial is dedicated to. Obviously, it creates the false dichotomy, when a mapper has to make a choice, what to indicate: a physical form or a dedication. This is totally wrong, and I suppose, that was a ground for introducing memorial:type= key. Currently, there is no other way to describe a war memorial and its form, except to use both memorial:type= and memorial=. --BushmanK (talk) 23:21, 7 January 2017 (UTC)
- You should take a look at the German page. There is a statistics table, which at least at Stolerstein has an overweight for
memorial:type=stolperstein. This can not be so easily changed with the rules of OSM. An have a look at Historical_Objects/Map_Properties. I would be happy if the things are arranged more clearly. --geozeisig (talk) 07:24, 8 January 2017 (UTC)
- First, I just wanted to mention this obvious issue of this scheme. Second, I don't think we should worry about being able or not being able to change anything by "rules". Changes are made by changing (clarifying) documentation and editor presets. Not immediately, but there is nothing happening immediately in OSM. --BushmanK (talk) 18:02, 8 January 2017 (UTC)
- +1 with BushmanK on both the scheme issue and the migration as a way of change. memorial:type=* is not very descriptive. Tagging could be something like memorial:event=* (war, WW2, WW1, death, rescue etc) and memorial:form= * (plaque, bench, statue, monolith etc). This is more descriptive than the over used and misunderstood 'type'. Warin61 (talk) 22:24, 18 January 2017 (UTC)
- There is now subject:wikidata=. --Shoepuppet (talk) 03:14, 16 July 2018 (UTC)
- >Currently, there is no other way to describe a war memorial and its form, except to use both memorial:type=* and memorial=*.
- You could use memorial=plaque;war_memorial
For information, in France a war memorial is a type of memorial usally called "Monument aux morts" and build after WWI.
- They ususally look like this:
Name vs. subject
Most memorials don't actually have names. But they generally commemorate a subject such as a person, an event, a place, an animal or a thing. The subject generally does (or did) have a name, or at least a description. So the name=* tag doesn't really make sense. I'm using subject=* instead. Objections? T99 (talk) 07:03, 24 September 2019 (UTC)
- See subject:wikidata=* above.
- --Pyrog (talk) 12:22, 18 November 2019 (UTC) | https://wiki.openstreetmap.org/wiki/Talk:Tag:historic%3Dmemorial | CC-MAIN-2020-45 | refinedweb | 2,277 | 62.07 |
Algorithm::Diff - Compute `intelligent' differences between two files / lists
require Algorithm::Diff; # This example produces traditional 'diff' output: my $diff = Algorithm::Diff->new( \@seq1, \@seq2 ); $diff->Base( 1 ); # Return line numbers, not indices while( $diff->Next() ) { next if $diff->Same(); my $sep = ''; if( ! $diff->Items(2) ) { printf "%d,%dd%d\n", $diff->Get(qw( Min1 Max1 Max2 )); } elsif( ! $diff->Items(1) ) { printf "%da%d,%d\n", $diff->Get(qw( Max1 Min2 Max2 )); } else { $ $_" for $diff->Items(2); } # Alternate interfaces: use Algorithm::Diff qw( LCS LCS_length LCSidx diff sdiff compact_diff traverse_sequences traverse_balanced ); @lcs = LCS( \@seq1, \@seq2 ); $lcsref = LCS( \@seq1, \@seq2 ); $count = LCS_length( \@seq1, \@seq2 ); ( $seq1idxref, $seq2idxref ) = LCSidx( \@seq1, \@seq2 ); # Complicated interfaces: @diffs = diff( \@seq1, \@seq2 ); @sdiffs = sdiff( \@seq1, \@seq2 ); @cdiffs = compact_diff( \@seq1, \@seq2 ); traverse_sequences( \@seq1, \@seq2, { MATCH => \&callback1, DISCARD_A => \&callback2, DISCARD_B => \&callback3, }, \&key_generator, @extra_args, ); traverse_balanced( \@seq1, \@seq2, { MATCH => \&callback1, DISCARD_A => \&callback2, DISCARD_B => \&callback3, CHANGE => \&callback4, }, \&key_generator, @extra_args, );
(by Mark-Jason Dominus)
I once read an article written by the authors of
diff; they said that they second
or
a x b y c z p d q a b c a x b y c z
(See also the README file and several example scripts include with this module.)
This module now provides an object-oriented interface that uses less memory and is easier to use than most of the previous procedural interfaces. It also still provides several exportable functions. We'll deal with these in ascending order of difficulty:
LCS,
LCS_length,
LCSidx, OO interface,
prepare,
diff,
sdiff,
traverse_sequences, and
traverse_balanced. "KEY GENERATION FUNCTIONS".
@lcs = LCS( \@seq1, \@seq2, \&keyGen, @args ); $lcsref = LCS( \@seq1, \@seq2, \&keyGen, @args );
Additional parameters, if any, will be passed to the key generation routine.
LCS_length
This is just like
LCS except it only returns the length of the longest common subsequence. This provides a performance gain of about 9% compared to
LCS.
LCSidx
Like
LCS except it returns references to two arrays. The first array contains the indices into @seq1 where the LCS items are located. The second array contains the indices into @seq2 where the LCS items are located.
Therefore, the following three lists will contain the same values:
my( $idx1, $idx2 ) = LCSidx( \@seq1, \@seq2 ); my @list1 = @seq1[ @$idx1 ]; my @list2 = @seq2[ @$idx2 ]; my @list3 = LCS( \@seq1, \@seq2 );
new
$diff = Algorithm::Diffs->new( \@seq1, \@seq2 ); $diff = Algorithm::Diffs->new( \@seq1, \@seq2, \%opts );
new computes the smallest set of additions and deletions necessary to turn the first sequence into the second and compactly records them in the object.
You use the object to iterate over hunks, where each hunk represents a contiguous section of items which should be added, deleted, replaced, or left unchanged.
The following summary of all of the methods looks a lot like Perl code but some of the symbols have different meanings:[ ] Encloses optional arguments : Is followed by the default value for an optional argument | Separates alternate return results
Method summary:$obj = Algorithm::Diff->new( \@seq1, \@seq2, [ \%opts ] ); $pos = $obj->Next( [ $count : 1 ] ); $revPos = $obj->Prev( [ $count : 1 ] ); $obj = $obj->Reset( [ $pos : 0 ] ); $copy = $obj->Copy( [ $pos, [ $newBase ] ] ); $oldBase = $obj->Base( [ $newBase ] );
Note that all of the following methods
dieif used on an object that is "reset" (not currently pointing at any hunk).$bits = $obj->Diff( ); @items|$cnt = $obj->Same( ); @items|$cnt = $obj->Items( $seqNum ); @idxs |$cnt = $obj->Range( $seqNum, [ $base ] ); $minIdx = $obj->Min( $seqNum, [ $base ] ); $maxIdx = $obj->Max( $seqNum, [ $base ] ); @values = $obj->Get( @names );
Passing in
undeffor an optional argument is always treated the same as if no argument were passed in.
Next$pos = $diff->Next(); # Move forward 1 hunk $pos = $diff->Next( 2 ); # Move forward 2 hunks $pos = $diff->Next(-5); # Move backward 5 hunks
Nextmoves the object to point at the next hunk. The object starts out "reset", which means it isn't pointing at any hunk. If the object is reset, then
Next()moves to the first hunk.
Nextreturns a true value iff the move didn't go past the last hunk. So
Next(0)will return true iff the object is not reset.
Actually,
Nextreturns the object's new position, which is a number between 1 and the number of hunks (inclusive), or returns a false value.
Prev
Prev($N)is almost identical to
Next(-$N); it moves to the $Nth previous hunk. On a 'reset' object,
Prev()[and
Next(-1)] move to the last hunk.
The position returned by
Previs relative to the end of the hunks; -1 for the last hunk, -2 for the second-to-last, etc.
Reset$diff->Reset(); # Reset the object's position $diff->Reset($pos); # Move to the specified hunk $diff->Reset(1); # Move to the first hunk $diff->Reset(-1); # Move to the last hunk
Resetreturns the object, so, for example, you could use
$diff->Reset()->Next(-1)to get the number of hunks.
Copy$copy = $diff->Copy( $newPos, $newBase );
Copyreturns a copy of the object. The copy and the original object share most of their data, so making copies takes very little memory. The copy maintains its own position (separate from the original), which is the main purpose of copies. It also maintains its own base.
By default, the copy's position starts out the same as the original object's position. But
Copytakes an optional first argument to set the new position, so the following three snippets are equivalent:$copy = $diff->Copy($pos); $copy = $diff->Copy(); $copy->Reset($pos); $copy = $diff->Copy()->Reset($pos);
Copytakes an optional second argument to set the base for the copy. If you wish to change the base of the copy but leave the position the same as in the original, here are two equivalent ways:$copy = $diff->Copy(); $copy->Base( 0 ); $copy = $diff->Copy(undef,0);
Here are two equivalent way to get a "reset" copy:$copy = $diff->Copy(0); $copy = $diff->Copy()->Reset();
Diff$bits = $obj->Diff();
Diffreturns a true value iff the current hunk contains items that are different between the two sequences. It actually returns one of the follow 4 values:
- 3
-
3==(1|2). This hunk contains items from @seq1 and the items from @seq2 that should replace them. Both sequence 1 and 2 contain changed items so both the 1 and 2 bits are set.
- 2
-
This hunk only contains items from @seq2 that should be inserted (not items from @seq1). Only sequence 2 contains changed items so only the 2 bit is set.
- 1
-
This hunk only contains items from @seq1 that should be deleted (not items from @seq2). Only sequence 1 contains changed items so only the 1 bit is set.
- 0
-
This means that the items in this hunk are the same in both sequences. Neither sequence 1 nor 2 contain changed items so neither the 1 nor the 2 bits are set.
Same
Samereturns a true value iff the current hunk contains items that are the same in both sequences. It actually returns the list of items if they are the same or an empty list if they aren't. In a scalar context, it returns the size of the list.
Items$count = $diff->Items(2); @items = $diff->Items($seqNum);
Itemsreturns the (number of) items from the specified sequence that are part of the current hunk.
If the current hunk contains only insertions, then
$diff->Items(1)will return an empty list (0 in a scalar context). If the current hunk contains only deletions, then
$diff->Items(2)will return an empty list (0 in a scalar context).
If the hunk contains replacements, then both
$diff->Items(1)and
$diff->Items(2)will return different, non-empty lists.
Otherwise, the hunk contains identical items and all of the following will return the same lists:@items = $diff->Items(1); @items = $diff->Items(2); @items = $diff->Same();
Range$count = $diff->Range( $seqNum ); @indices = $diff->Range( $seqNum ); @indices = $diff->Range( $seqNum, $base );
Rangeis like
Itemsexcept that it returns a list of indices to the items rather than the items themselves. By default, the index of the first item (in each sequence) is 0 but this can be changed by calling the
Basemethod. So, by default, the following two snippets return the same lists:@list = $diff->Items(2); @list = @seq2[ $diff->Range(2) ];
You can also specify the base to use as the second argument. So the following two snippets always return the same lists:@list = $diff->Items(1); @list = @seq1[ $diff->Range(1,0) ];
Base$curBase = $diff->Base(); $oldBase = $diff->Base($newBase);
Basesets and/or returns the current base (usually 0 or 1) that is used when you request range information. The base defaults to 0 so that range information is returned as array indices. You can set the base to 1 if you want to report traditional line numbers instead.
Min$min1 = $diff->Min(1); $min = $diff->Min( $seqNum, $base );
Minreturns the first value that
Rangewould return (given the same arguments) or returns
undefif
Rangewould return an empty list.
Max
Maxreturns the last value that
Rangewould return or
undef.
Get( $n, $x, $r ) = $diff->Get(qw( min1 max1 range1 )); @values = $diff->Get(qw( 0min2 1max2 range2 same base ));
Getreturns one or more scalar values. You pass in a list of the names of the values you want returned. Each name must match one of the following regexes:/^(-?\d+)?(min|max)[12]$/i /^(range[12]|same|diff|base)$/i
The 1 or 2 after a name says which sequence you want the information for (and where allowed, it is required). The optional number before "min" or "max" is the base to use. So the following equalities hold:$diff->Get('min1') == $diff->Min(1) $diff->Get('0min2') == $diff->Min(2,0)
Using
Getin a scalar context when you've passed in more than one name is a fatal error (
dieis called).
prepare
Given a reference to a list of items,
prepare returns a reference to a hash which can be used when comparing this sequence to other sequences with
LCS or
LCS_length.
$prep = prepare( \@seq1 ); for $i ( 0 .. 10_000 ) { @lcs = LCS( $prep, $seq[$i] ); # do something useful with @lcs }
prepare may be passed an optional third parameter; this is a CODE reference to a key generation function. See "KEY GENERATION FUNCTIONS".
$prep = prepare( \@seq1, \&keyGen ); for $i ( 0 .. 10_000 ) { @lcs = LCS( $seq[$i], $prep, \&keyGen ); # do something useful with @lcs }
Using
prepare provides a performance gain of about 50% when calling LCS many times compared with not preparing.. (Hunks containing unchanged items are not included.)
The return value of
diff is a list of hunks, or, in scalar context, a reference to such a list. If there are no differences, the list will be empty.
Here is an example. Calling
diff for the following two sequences:
a b c e h j l m n p b c d e f j k l m r s t
would produce the following list:
( [ [ '-',. And so on.
diff may be passed an optional third parameter; this is a CODE reference to a key generation function. See "KEY GENERATION FUNCTIONS".
Additional parameters, if any, will be passed to the key generation routine.
sdiff
@sdiffs = sdiff( \@seq1, \@seq2 ); $sdiffs_ref = sdiff( \@seq1, \@seq2 );
sdiff computes all necessary components to show two sequences and their minimized differences side by side, just like the Unix-utility sdiff does:
same same before | after old < - - > new
It returns a list of array refs, each pointing to an array of display instructions. In scalar context it returns a reference to such a list. If there are no differences, the list will have one entry per item, each indicating that the item was unchanged.
Display instructions consist of three elements: A modifier indicator (
+: Element added,
-: Element removed,
u: Element unmodified,
c: Element changed) and the value of the old and new elements, to be displayed side-by-side.
An
sdiff of the following two sequences:
a b c e h j l m n p b c d e f j k l m r s t
results in
( [ '-', 'a', '' ], [ 'u', 'b', 'b' ], [ 'u', 'c', 'c' ], [ '+', '', 'd' ], [ 'u', 'e', 'e' ], [ 'c', 'h', 'f' ], [ 'u', 'j', 'j' ], [ '+', '', 'k' ], [ 'u', 'l', 'l' ], [ 'u', 'm', 'm' ], [ 'c', 'n', 'r' ], [ 'c', 'p', 's' ], [ '+', '', 't' ], )
sdiff may be passed an optional third parameter; this is a CODE reference to a key generation function. See "KEY GENERATION FUNCTIONS".
Additional parameters, if any, will be passed to the key generation routine.
compact_diff
compact_diff is much like
sdiff except it returns a much more compact description consisting of just one flat list of indices. An example helps explain the format:
my @a = qw( a b c e h j l m n p ); my @b = qw( b c d e f j k l m r s t ); @cdiff = compact_diff( \@a, \@b ); # Returns: # @a @b @a @b # start start values values ( 0, 0, # = 0, 0, # a ! 1, 0, # b c = b c 3, 2, # ! d 3, 3, # e = e 4, 4, # f ! h 5, 5, # j = j 6, 6, # ! k 6, 7, # l m = l m 8, 9, # n p ! r s t 10, 12, # );
The 0th, 2nd, 4th, etc. entries are all indices into @seq1 (@a in the above example) indicating where a hunk begins. The 1st, 3rd, 5th, etc. entries are all indices into @seq2 (@b in the above example) indicating where the same hunk begins.
So each pair of indices (except the last pair) describes where a hunk begins (in each sequence). Since each hunk must end at the item just before the item that starts the next hunk, the next pair of indices can be used to determine where the hunk ends.
So, the first 4 entries (0..3) describe the first hunk. Entries 0 and 1 describe where the first hunk begins (and so are always both 0). Entries 2 and 3 describe where the next hunk begins, so subtracting 1 from each tells us where the first hunk ends. That is, the first hunk contains items
$diff[0] through
$diff[2] - 1 of the first sequence and contains items
$diff[1] through
$diff[3] - 1 of the second sequence.
In other words, the first hunk consists of the following two lists of items:
# 1st pair 2nd pair # of indices of indices @list1 = @a[ $cdiff[0] .. $cdiff[2]-1 ]; @list2 = @b[ $cdiff[1] .. $cdiff[3]-1 ]; # Hunk start Hunk end
Note that the hunks will always alternate between those that are part of the LCS (those that contain unchanged items) and those that contain changes. This means that all we need to be told is whether the first hunk is a 'same' or 'diff' hunk and we can determine which of the other hunks contain 'same' items or 'diff' items.
By convention, we always make the first hunk contain unchanged items. So the 1st, 3rd, 5th, etc. hunks (all odd-numbered hunks if you start counting from 1) all contain unchanged items. And the 2nd, 4th, 6th, etc. hunks (all even-numbered hunks if you start counting from 1) all contain changed items.
Since @a and @b don't begin with the same value, the first hunk in our example is empty (otherwise we'd violate the above convention). Note that the first 4 index values in our example are all zero. Plug these values into our previous code block and we get:
@hunk1a = @a[ 0 .. 0-1 ]; @hunk1b = @b[ 0 .. 0-1 ];
And
0..-1 returns the empty list.
Move down one pair of indices (2..5) and we get the offset ranges for the second hunk, which contains changed items.
Since
@diff[2..5] contains (0,0,1,0) in our example, the second hunk consists of these two lists of items:
@hunk2a = @a[ $cdiff[2] .. $cdiff[4]-1 ]; @hunk2b = @b[ $cdiff[3] .. $cdiff[5]-1 ]; # or @hunk2a = @a[ 0 .. 1-1 ]; @hunk2b = @b[ 0 .. 0-1 ]; # or @hunk2a = @a[ 0 .. 0 ]; @hunk2b = @b[ 0 .. -1 ]; # or @hunk2a = ( 'a' ); @hunk2b = ( );
That is, we would delete item 0 ('a') from @a.
Since
@diff[4..7] contains (1,0,3,2) in our example, the third hunk consists of these two lists of items:
@hunk3a = @a[ $cdiff[4] .. $cdiff[6]-1 ]; @hunk3a = @b[ $cdiff[5] .. $cdiff[7]-1 ]; # or @hunk3a = @a[ 1 .. 3-1 ]; @hunk3a = @b[ 0 .. 2-1 ]; # or @hunk3a = @a[ 1 .. 2 ]; @hunk3a = @b[ 0 .. 1 ]; # or @hunk3a = qw( b c ); @hunk3a = qw( b c );
Note that this third hunk contains unchanged items as our convention demands.
You can continue this process until you reach the last two indices, which will always be the number of items in each sequence. This is required so that subtracting one from each will give you the indices to the last items in each sequence.
traverse_sequences
traverse_sequences used to be the most general facility provided by this module (the new OO interface is more powerful and much easier to use). advance hash "KEY GENERATION FUNCTIONS".
Additional parameters, if any, will be passed to the key generation function.
If you want to pass additional parameters to your callbacks, but don't need a custom key generation function, you can get the default by passing undef:
traverse_sequences( \@seq1, \@seq2, { MATCH => $callback_1, DISCARD_A => $callback_2, DISCARD_B => $callback_3, }, undef, # default key-gen $myArgument1, $myArgument2, $myArgument3, );
traverse_sequences does not have a useful return value; you are expected to plug in the appropriate behavior with the callback functions.
traverse_balanced
traverse_balanced is an alternative to
traverse_sequences. It uses a different algorithm to iterate through the entries in the computed LCS. Instead of sticking to one side and showing element changes as insertions and deletions only, it will jump back and forth between the two sequences and report changes occurring as deletions on one side followed immediately by an insertion on the other side.
In addition to the
DISCARD_A,
DISCARD_B, and
MATCH callbacks supported by
traverse_sequences,
traverse_balanced supports a
CHANGE callback indicating that one element got
replaced by another:
traverse_balanced( \@seq1, \@seq2, { MATCH => $callback_1, DISCARD_A => $callback_2, DISCARD_B => $callback_3, CHANGE => $callback_4, } );
If no
CHANGE callback is specified,
traverse_balanced will map
CHANGE events to
DISCARD_A and
DISCARD_B actions, therefore resulting in a similar behaviour as
traverse_sequences with different order of events.
traverse_balanced might be a bit slower than
traverse_sequences, noticeable only while processing huge amounts of data.
The
sdiff function of this module is implemented as call to
traverse_balanced.
traverse_balanced does not have a useful return value; you are expected to plug in the appropriate behavior with the callback functions.
Most of the functions accept an optional extra.
If you pass these routines a non-reference and they expect a reference, they will die with a message.
This version released by Tye McQueen ().
Parts Copyright (c) 2000-2004 Ned Konz. All rights reserved. Parts by Tye McQueen.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl.
Mark-Jason still maintains a mailing list. To join a low-volume mailing list for announcements related to diff and Algorithm::Diff, send an empty mail message to mjd-perl-diff-request@plover.com.
Versions through 0.59 (and much of this documentation) were written by:
Mark-Jason Dominus, mjd-perl-diff@plover.com
This version borrows some documentation and routine names from Mark-Jason's, but Diff.pm's code was completely replaced.
This code was adapted from the Smalltalk code of Mario Wolczko <mario@wolczko.com>, which is available at
sdiff and
traverse_balanced were written by Mike Schilli <m@perlmeister.com>.
The algorithm is that described in A Fast Algorithm for Computing Longest Common Subsequences, CACM, vol.20, no.5, pp.350-353, May 1977, with a few minor improvements to improve the speed.
Much work was done by Ned Konz (perl@bike-nomad.com).
The OO interface and some other changes are by Tye McQueen. | http://search.cpan.org/dist/Algorithm-Diff/lib/Algorithm/Diff.pm | CC-MAIN-2016-40 | refinedweb | 3,271 | 61.56 |
.
cmn_err() displays a specified message on the console. cmn_err() can also panic the system. When the system panics, it attempts to save recent changes to data, display a “panic message” on the console, attempt to write a core file, and halt system processing. See the CE_PANIC level below.
level is a constant indicating the severity of the error condition. The four severity levels are:.
cmn_err() appends a \n to each format, except when level is CE_CONT.
vcmn_err() is identical to cmn_err() except that its last argument, ap, is a pointer to a variable list of arguments. ap contains the list of arguments used by the conversion specifications in format. ap.
None. However, if an unknown level is passed to cmn_err(), the following panic error message is displayed:
cmn_err() can be called from user, kernel, interrupt, or high-level interrupt context.
This first example shows how cmn_err() can record tracing and debugging information only in the system log (lines 17); display problems with a device only on the system console (line 23); or display problems with the device on both the system console and in the system log (line 28).
1 struct reg { 2 uchar_t data; 3 uchar_t csr; 4 }; 5 6 struct xxstate { 7 . . . 8 dev_info_t *dip; 9 struct reg *regp; 10 . . . 11 }; 12 13 dev_t dev; 14 struct xxstate *xsp; 15 . . . 16 #ifdef DEBUG /* in debugging mode, log function call */ 17 cmn_err(CE_CONT, "!%s%d: xxopen function called.", 18 ddi_binding_name(xsp->dip), getminor(dev)); 19 #endif /* end DEBUG */ 20 . . . 21 /* display device power failure on system console */ 22 if ((xsp->regp->csr & POWER) == OFF) 23 cmn_err(CE_NOTE, "‸OFF.", 24 ddi_binding_name(xsp->dip), getminor(dev)); 25 . . . 26 /* display warning if device has bad VTOC */ 27 if (xsp->regp->csr & BADVTOC) 28 cmn_err(CE_WARN, "%s%d: xxopen: Bad VTOC.", 29 ddi_binding_name(xsp->dip), getminor(dev));
This example shows how to use the %b conversion specification. Because of the leading '? ' character in the format string, this message will always be logged, but it will only be displayed when the kernel is booted in verbose mode.
When regval is set to (decimal) 13, the following message would be displayed:
The third example is an error reporting routine which accepts a variable number of arguments and displays a single line error message both in the system log and on the system console. Note the use of vsprintf() to construct the error message before calling cmn_err().
); }
dmesg(1M), kernel(1M), printf(3C), ddi_binding_name(9F), sprintf(9F), va_arg(9F), va_end(9F), va_start(9F), vsprintf(9F) | http://docs.oracle.com/cd/E19683-01/817-0702/6mgg163u0/index.html | CC-MAIN-2017-39 | refinedweb | 419 | 56.25 |
This site uses strictly necessary cookies. More Information
Hello Buddy, I have problem with Bloom effect in my project, I using bloom effect to my Game Object but not work properly. Even though, I have done to setting all correctly, but that Bloom not working. What is the wrong is it? please tell me the truth.
Using URP without any renderer pipeline asset chosen
0
Answers
How to make script remember a counter and display an ad every 5th time?
1
Answer
intellisense in Vis Studio still does not recognize or provide autocomplete for Unity namespace items.
0
Answers
Can someone please help me fix the script? in unity3D to move forwards and backwards by swiping to the screen,Rotate and move forward script not working
0
Answers
Universal renderer not working at all
0
Answers
EnterpriseSocial Q&A | https://answers.unity.com/questions/1829266/the-bloom-effect-doesnt-working-in-urpi-have-probl.html | CC-MAIN-2021-21 | refinedweb | 139 | 64.51 |
Sailor Professional Gear Kop Fountain Pen Nib/b Used Pre Owned Good
This item has been shown 0 times.
Sailor Professional Gear Kop Fountain Pen Nib/b Used Pre Owned Good:
$469
Item description
The pen point is B, and the list price is 64,800 yen. Both the box and the guarantee are attached. I purchased it as a fountain pen for a living thing, but the scene that mainly uses a fountain pen has become work only, and has been in a state of being stored for a long time. There are no scratches, etc., and it is in the state of beauty products. The pen tip is B along with the thick axis, so you can write comfortably. I think it is a fountain pen suitable for letters, diaries, address writing, etc.
Thank you for watching!
Our store policy is...1:Support your wonderful shopping!2:You GET 100% genuine merchandise from Japan.3:Fast & well packing delivery.YOU still wonder BUY it NOW?we offer...
Free shipping & 60 days Returns
If you have any question or request,PLEASE FEEL FREE to contact us anytime!-SHIPPING
we'd ship out by Japan post with tracking number and insurance.
standard shipping:Japan post EMS(a week)
economy shipping:Japan post e-packet(2-3 weeks)
-PAYMENTwe accept Paypal only,sorry.
we'd like to ask customers let us know the date if the payment would be delay.
-OTHER STORE INFO...
return item
if you want to return the item,please feel free to contact us from "Contact sellers"on .
for international buyers -Please note!
import duties,taxes and charges are not included in the item price or shipping charge.there charges are buyer's responsibility.
please check with your country's customs office to determine what these additional costs will be prior to offerding/buying.
these charges are normally collected by delivering freight(shipping) company or when you pick the item up - do not confuse them for additional shipping charges.
we do not mark merchandise values below value.US and?international government regulations prohibit such behavior.Sailor Professional Gear KOP Fountain Pen Nib/B Used Pre owned Good
Sailor Professional Gear Kop Fountain Pen Nib/b Used Pre Owned Good:
$469
Mabie Todd Combination, N°6 Nib.
Fountain Pens And Pen Parts
Platinum Century # 3776 Beckoning Cat Nib 14k Fine Fountain Pen With Box
Fountain Pens By Assorted Makers, Lot Of (5)
Platinum Vintage Sterling Silver Nib 18k Wg Fine Fountain Pen Japan Rare
Vintage Koh-i-noor Rapidograph Technical Fountain Pen 3 X 0 Made In Germany Nib
| http://www.holidays.net/store/Sailor-Professional-Gear-KOP-Fountain-Pen-Nib-B-Used-Pre-owned-Good_192892615365.html | CC-MAIN-2020-16 | refinedweb | 431 | 66.13 |
std::map::begin, std::map::cbegin
From cppreference.com
Returns an iterator to the first element of the container.
If the container is empty, the returned iterator will be equal to end().
[edit] Parameters
(none)
[edit] Return value
Iterator to the first element
[edit] Complexity
Constant
[edit] Example
Run this code
Output:
1, 1.09 4, 4.13 9, 9.24
Example using a custom comparison function
Run this code
#include <cmath> #include <iostream> #include <map> struct Point { double x, y; }; typedef Point * PointPtr; //Compare the x-coordinates of two Point pointers struct PointCmp { bool operator()(const PointPtr &lhs, const PointPtr &rhs) const { return lhs->x < rhs->x; } }; int main() { //Note that although the x-coordinates are out of order, the // map will be iterated through by increasing x-coordinates Point points[3] = { {2, 0}, {1, 0}, {3, 0} }; //mag is a map sending the address of node to its magnitude in the x-y plane //Although the keys are pointers-to-Point, we want to order the map by the // x-coordinates of the points and NOT by the addresses of the Points. This // is done by using the PointCmp class's comparison method. std::map<Point *, double, PointCmp> mag({ { points, 2 }, { points + 1, 1 }, { points + 2, 3 } }); //Change each y-coordinate from 0 to the magnitude for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; // pointer to Node cur->y = mag[cur]; // could also have used cur->y = iter->second; } //Update and print the magnitude of each node for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << iter->second << '\n'; } //Repeat the above with the range-based for loop for(auto i : mag) { auto cur = i.first; cur->y = i.second; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << mag[cur] << '\n'; //Note that in contrast to std::cout << iter->second << '\n'; above, // std::cout << i.second << '\n'; will NOT print the updated magnitude } }
Output:
The magnitude of (1, 2) is 2.23607 The magnitude of (2, 1) is 2.23607 The magnitude of (3, 3) is 4.24264 The magnitude of (1, 2.23607) is 2.44949 The magnitude of (2, 2.23607) is 3 The magnitude of (3, 4.24264) is 5.19615 | http://en.cppreference.com/w/cpp/container/map/begin | CC-MAIN-2017-22 | refinedweb | 407 | 63.7 |
sec_rgy_unix_getgrnam-Returns a UNIX style group entry for the account matching the specified group name
#include <dce/rgynbase.h> void sec_rgy_unix_getgrnam( sec_rgy_handle_t context, sec_rgy_name_t name, signed32 name_length, signed32 max_num_members,.
- name
A character string (of type sec_rgy_name_t) specifying the group name to be matched.
- name_length
A signed 32-bit integer specifying the length of name in characters.
- max_num_membersnam() routine returns the PGO item indicated by item_cursor, and advances the cursor to point to the next item in the database. When the end of the list of entries is reached, the routine returns sec_rgy_no_more_entries. Use sec_rgy_cursor_reset() to refresh the cursor.
Output
- group_entry
A UNIX style group entry structure returned with information about the account matching name.
-nam() routine looks up the next group entry in the registry that matches the input group name and returns the corresponding UNIX style group structure. The structure is in the following form:
The structure includes:The structure includes:typed. Note that the array contains only the names explicitly specified as members of the group. A principal that was made a member of the group because that group was assigned as the principal's primary group will not appear in the array.
This call is provided in source code form.
- /usr/include/dce/rgynbase.idl
The idl file from which dce/rgynbase.h was derived.
- error_status_ok
The call was successful.
- sec_rgy bad_data
The name supplied as input was too long.
- sec_rgy_no_more_entries
The cursor is at the end of the list of entries.
- sec_rgy_server_unavailable
The DCE Registry Server is unavailable. | http://pubs.opengroup.org/onlinepubs/9696989899/sec_rgy_unix_getgrnam.htm | CC-MAIN-2015-35 | refinedweb | 252 | 58.69 |
import "github.com/fsouza/gokabinet/kc"
Package kc provides types, methods and functions to interact with an Kyoto Cabinet database.
It's just a binding to the Kyoto Cabinet C library, so make sure you have installed Kyoto Cabinet in your system.
const ( READ WRITE )
type ApplyFunc func(key string, value interface{}, args ...interface{})
ApplyFunc, function used as parameter to the Apply and AsyncApply methods. The function receives three parameters:
key: the record key value: the record value args: extra arguments passed to Apply method
type ApplyResult struct { // contains filtered or unexported fields }
func NewApplyResult() *ApplyResult
func (r *ApplyResult) Wait()
type DB struct { // Path to the database file. Path string // contains filtered or unexported fields }
DB is the basic type for the gokabinet library. Holds an unexported instance of the database, for interactions.
func Open(dbfilepath string, mode int) (*DB, error)
Open opens a database.
There are constants for the modes: READ and WRITE.
READ indicates read-only access to the database, and WRITE indicates read and write access to the database (there is no write-only mode).
func (d *DB) Append(key, value string) error
Append appends a string to the end of the value of a string record. It can't append any value to a numeric record.
Returns a KCError instance when trying to append a string to a numeric record and when trying to append a string in read-only mode.
If the append is successful, the method returns nil.
func (d *DB) Apply(f ApplyFunc, args ...interface{})
Applies a function to all records in the database
The function is called with the key and the value as parameters. All extra arguments passed to Apply are used in the call to f
func (d *DB) AsyncApply(f ApplyFunc, args ...interface{}) Waiter
Similar to Apply, but asynchronous. Returns a Waiter object, so you can wait for the applying to finish
func (d *DB) BeginTransaction(hard bool) error
BeginTransaction begins a new transaction. It accepts a boolean flag that indicates whether the transaction should be hard or not. A hard transaction is a transaction that provides physical synchronization in the device, while a non-hard transaction provides logical synchronization with the file system.
func (d *DB) Clear() error
Clear removes all records from the database.
Returns a KCError in case of failure.
func (d *DB) Close()
Close closes the database, make sure you always call this method after using the database.
You can do it using the defer statement:
db := Open("my_db.kch", WRITE) defer db.Close()
func (d *DB) Commit() error
Commit commits the current transaction.
func (d *DB) CompareAndSwap(key, old, new string) error
CompareAndSwap performs a compare-and-swap operation, receiving three parameters: key, old and new.
If the value corresponding to key is equal to old, then it is set to new. If the operation fails, this method returns a non-nil error.
func (d *DB) Count() (int, error)
Count returns the number of records in the database.
func (d *DB) Get(key string) (string, error)
Get retrieves a record in the database by its key.
Returns the string value and nil in case of success, in case of errors, return a zero-valued string and an KCError instance (including when the key doesn't exist in the database).
func (d *DB) GetGob(key string, e interface{}) error
GetGob gets a record in the database by its key, decoding from gob format.
Returns nil in case of success. In case of errors, it returns a KCError instance explaining what happened.
func (d *DB) GetInt(key string) (int, error)
GetInt gets a numeric record from the database.
In case of errors (e.g.: when the given key refers to a non-numeric record), returns 0 and a KCError instance.
func (d *DB) Increment(key string, number int) (int, error)
Increment increments the value of a numeric record by a given number, and return the incremented value.
In case of errors, returns 0 and a KCError instance with detailed error message.
func (d *DB) LastError() error
LastError returns a KCError instance representing the last occurred error in the database.
func (d *DB) MatchPrefix(prefix string, max int64) ([]string, error)
MatchPrefix returns a list of keys that matches a prefix or an error in case of failure.
func (d *DB) MatchRegex(regex string, max int64) ([]string, error)
MatchRegex returns a list of keys that matches a regular expression string or an error in case of failure.
func (d *DB) Remove(key string) error
Remove removes a record from the database by its key.
Returns a KCError instance if there is no record for the given key, or in case of other errors. The error instance contains a message describing what happened
func (d *DB) Rollback() error
Rollback aborts the current transaction.
func (d *DB) Set(key, value string) error
Set adds a record to the database. Currently, it's able to store only string values.
Returns a KCError instance in case of errors, otherwise, returns nil.
func (d *DB) SetGob(key string, e interface{}) error
SetGob adds a record to the database, stored in gob format.
Returns a KCError instance in case of errors, otherwise, returns nil.
func (d *DB) SetInt(key string, number int) error
SetInt defines the value of an integer record, creating it when there is no record corresponding to the given key.
Returns an KCError in case of errors setting the value.
func (d *DB) Size() (int64, error)
Size returns the size of the database file.
type KCError string
KCError is used for errors using the gokabinet library. It implements the builtin error interface.
func (err KCError) Error() string
type Waiter interface { Wait() }
Waiter interface, provides the Wait method
This is the interface of the value returned by the AsyncApply method
Package kc imports 7 packages (graph) and is imported by 5 packages. Updated 2014-03-17. Refresh now. Tools for package owners. | http://godoc.org/github.com/fsouza/gokabinet/kc | CC-MAIN-2015-14 | refinedweb | 980 | 63.8 |
Hi Folks, I'd like to move on to the next term, "climbing". The spec defines it this way: Climbing: indicates that nodes returned by the construct are reached by navigating the parent, ancestor[-or-self], attribute, and/or namespace axes from the node at the current streaming position. When the context posture is climbing, use of certain axes such as parent and ancestor is permitted, but use of other axes such as child or descendant violates the streamability rules. Let's take an example. Let's suppose that an XSLT program is stream-processing this XML document: <Book xmlns=""> <Chapter id="abc"> <Title xml:Hello World</Title> </Chapter> </Book> Suppose that the context node is the <Title> element (that is, the current streaming position is the <Title> element). What nodes can a construct return in order for it to be considered a climbing construct? This XPath expression @* returns all the attributes of the context node, so @* is a climbing construct, correct? This XPath expression ancestor::* returns all the ancestors of the context node, so ancestor::* is a climbing construct, correct? This XPath expression for $i in ancestor::node() return $i also returns all the ancestors of the context node, so for $i in ancestor::node() return $i is a climbing construct, correct? This XPath expression ../@* returns all the attributes of the parent of the context node, so ../@* is a climbing construct, correct? This XPath expression ./namespace::* returns all the namespaces visible on the context node, so ./namespace::* is a climbing construct, correct? Notice that all the examples are XPath expressions. Can you give an example or two of a climbing construct that is not an XPath expression?? Is there anything else important to know about understanding what a climbing construct is? /Roger | http://www.oxygenxml.com/archives/xsl-list/201401/msg00166.html | CC-MAIN-2018-05 | refinedweb | 293 | 55.64 |
IRC log of svgig on 2008-11-20
Timestamps are in UTC.
15:51:32 [RRSAgent]
RRSAgent has joined #svgig
15:51:32 [RRSAgent]
logging to
15:51:34 [trackbot]
RRSAgent, make logs public
15:51:34 [Zakim]
Zakim has joined #svgig
15:51:36 [trackbot]
Zakim, this will be SVGIG
15:51:36 [Zakim]
ok, trackbot; I see GA_SVGIG()11:00AM scheduled to start in 9 minutes
15:51:37 [trackbot]
Meeting: SVG Interest Group Teleconference
15:51:37 [trackbot]
Date: 20 November 2008
15:53:43 [stelt]
stelt has joined #svgig
15:53:48 [Christophe]
Christophe has joined #svgig
15:53:50 [gwadej]
gwadej has joined #svgig
15:54:21 [JeffSchiller]
JeffSchiller has joined #svgig
15:54:54 [JeffSchiller]
shepazu
15:56:24 [darobin]
darobin has joined #svgig
15:57:29 [Zakim]
GA_SVGIG()11:00AM has now started
15:57:29 [Zakim]
+Shepazu
15:57:37 [Zakim]
+??P5
15:57:39 [Zakim]
-??P5
15:57:39 [Zakim]
+??P5
15:58:27 [Zakim]
+ +1.713.851.aaaa
15:58:30 [shepazu]
Christophe, it depends upon the WG
15:58:35 [Manuel]
Manuel has joined #svgig
15:58:44 [shepazu]
I think most of them are
15:58:52 [Zakim]
+ +1.312.540.aabb
16:00:14 [JeffSchiller]
Zakim, aabb is JeffSchiller
16:00:14 [Zakim]
+JeffSchiller; got it
16:00:15 [Zakim]
+Christophe_Strobbe
16:00:47 [Zakim]
+Rob_Russell
16:01:43 [Manuel]
i'm here, but, as mentioned, not in reach of a phone
16:02:21 [stelt]
me
16:02:34 [Christophe]
Previous minutes are at
16:03:16 [JeffSchiller]
JeffSchiller has joined #svgig
16:04:43 [Christophe]
Scribe: Christophe
16:04:48 [Christophe]
Meeting: SVG IG
16:05:04 [Christophe]
Agenda:
16:05:25 [Christophe]
Chair: Jeff, Doug
16:06:04 [Christophe]
Topic: SVG Spec
16:07:26 [Christophe]
DS: SVG 1.2 has entered PR phase (yesterday). Announcement:
16:08:10 [shepazu]
16:08:38 [Christophe]
DS: Notable change: URL is no longer 'SVGMobile' etc but 'SVGTiny':
16:09:10 [Christophe]
DS: Sort of important: clarify the message of SVG. Want to work on marketing.
16:09:32 [Christophe]
JS: I.e. the spec is not only aimed at the mobile space.
16:09:47 [shepazu]
16:09:49 [Rob_Russell]
Rob_Russell has joined #svgig
16:09:54 [stelt]
SVG counting in mobile space:
16:10:06 [Christophe]
DS: See also implementation report at
16:10:33 [Donald_Doherty]
Donald_Doherty has joined #svgig
16:10:35 [Christophe]
DS: New version of the test suite does not rely on XML ID.
16:11:14 [Christophe]
DS: Desktop browsers were not interested in implementing XML ID, and there were other issues related to XML ID.
16:11:21 [Zakim]
+Don_Doherty
16:11:32 [Christophe]
DS: Basically say: "only use XML ID if you are in a non-browser environment"
16:13:00 [Christophe]
DS: Only risk now would be if W3C member companies now said they don't want to publish it. (Not very likely.)
16:13:31 [Christophe]
DS: Companies interested in seeing SVG 1.2 published are asked to support it.
16:13:46 [Christophe]
DS: Possibly REC in mid December.
16:13:51 [stelt]
woot!!
16:14:54 [Christophe]
DS: SVG GI web site would be a good promotion tool. The book, too.
16:15:25 [Christophe]
rrsagent, make logs world
16:15:40 [Christophe]
DS: also ask more people to implement SVG
16:16:36 [Christophe]
DS: Convince people in Safari and Firefox to take SVG 1.2 as an implementation target by saying X is better defined in SVG 1.2; it's a better reference for resolving bugs.
16:17:02 [Christophe]
JS: Pushback microDOM?
16:17:18 [Christophe]
DS: That was one of the less populart parts in SVG, but it's very useful.
16:17:40 [Bruce_]
Bruce_ has joined #svgig
16:17:53 [Christophe]
JS: In terms of implementation, microdom is easier that full SVG 1.1 DOM. Another DOM might be expensive.
16:18:05 [Christophe]
DS: Much of it is convenience methods.
16:18:33 [Christophe]
DS: Anything that can be implemented as it stands: encourage vendors to implement.
16:19:08 [Christophe]
JS: Future? SVG 2.0 Core mentioned in places
16:19:20 [Christophe]
DS: Not yet 100% certain about path forward.
16:19:52 [Christophe]
DS: Current plan: build modules that describe specific pieces of functionality. you could plug them into SVG Tiny 1.2.
16:20:29 [Christophe]
DS: SVG 1.2 has most of the features of SVG 2.0; the modules ... Other modules would introduce new features.
16:21:07 [Christophe]
DS: SVG 2 would be a major rewrite of the spec but not necessarily much new functionality. tighthening up the spec and changes things to make it more adaptable. Integration with HTML content.
16:21:51 [Christophe]
DS: Make it a more stable platform. E.g. allowing non-namespaced href on outgonig links as well as ... etc.
16:23:18 [Manuel]
I'd like to see mentioning of text format handling in SVG 2.0via XHTML *or* XSL-FO, that would be great.
16:23:25 [Christophe]
DS: We resolved to work on modules. In the near future, there would be a path to follow before a single profile ...
16:23:52 [Christophe]
Topic: SVG IG Japan
16:24:59 [Christophe]
DS: Japanese chapter - Japanese market is not comfortable communicating through the same channels as rest of W3C. They're more comfortable discussing technical matters in japanese.
16:25:24 [Christophe]
DS: Try to see how they can promote SVG in Japan, find use cases and requirements and bring the back to the SVG IG.
16:25:35 [Christophe]
DS: Two main things going one:
16:26:35 [Christophe]
DS: (1) KDDI (service provider) is working on a "map module": module for mapping uses. Have a prototype. Not necessarily a general SVG viewer, but works on mobiles.
16:26:53 [stelt]
LOD
16:27:28 [Christophe]
DS: They're working on things like level of detail (e.g. when you zoom in, blocks resolve into individual buildings etc)
16:28:06 [Christophe]
DS: Range of zoom - e.g. from zoom level 5 - 10 show X, from 10 - 15 show X details etc
16:28:22 [Christophe]
JS: At the highest zoom level, you dont want all the details in your document.
16:28:56 [Christophe]
DS: See the 'discard' element; also need 'add' element: add something to the DOM when useful.
16:29:41 [Zakim]
+ +33.1.77.11.aacc
16:29:49 [Christophe]
DS: Also tile mechanism so you don't need whole map.
16:29:55 [darobin]
Zakim: aacc is me
16:30:05 [darobin]
Zakim, aacc is me
16:30:05 [Zakim]
+darobin; got it
16:30:42 [Christophe]
DS: (2) Also working on making SVG 1.2 Tiny ratify in JISC. Until it is a JISC standard, Japanese companies won't implement it.
16:31:13 [Christophe]
DS: More a formalization thing. If they decide that it is a good time to have this spec, they'll translate it.
16:31:40 [Christophe]
DS: They're also interested in making the mapping module a JISC standard.
16:31:53 [Christophe]
DS: Not aware of changes that they would want to make.
16:32:04 [darobin]
q+
16:32:24 [Christophe]
Topic: SVG Open 2009
16:32:42 [Christophe]
JS: Google no sponsor for SVG Open 2009
16:33:38 [Christophe]
RB: Liaison statement from ITU (?) to SVG about standardizing SVG for interactive TV.
16:34:53 [Christophe]
RB: The statement was sent by one of the ITU groups; a group that has to do with interactivity.
16:35:08 [Christophe]
DS: Discuss off-line.
16:36:04 [Christophe]
DS: JSR-287 : up for ratification as well.
16:36:32 [Christophe]
JS: One of the companies there is NVidia.
16:36:46 [Christophe]
Topic: SVG Open 2009
16:37:09 [Christophe]
XX: someone had good contacts with NVidia.
16:37:19 [darobin]
s/XX/RB/
16:37:30 [darobin]
s/someone/Nandini/
16:38:17 [stelt]
shows loads of parties to maybe contact
16:38:29 [Christophe]
JS: Conference: can work that out on the mailing list.
16:38:40 [Christophe]
JS: Robin Berjon: first time on IG call.
16:38:57 [Christophe]
RB: Independent consultant. Was member of SVG WG for a few years.
16:39:11 [shepazu]
16:39:14 [Christophe]
RB: Also editor on the community site.
16:39:37 [Christophe]
DS: Element traversal spec: really useful for SVG.
16:40:28 [Christophe]
DS: Was moved out of SVG and moved to Web Apps WG and is going to PR.
16:40:36 [shepazu]
16:40:50 [Christophe]
DS: There is an implementation report at
16:41:20 [Christophe]
RB: Same interface as in HTML 5?
16:41:20 [stelt]
SVG Open 2009: Enschede city has economical relation with Palo Alto city. Thin, but looking into it for leads
16:42:34 [Christophe]
DS: Already planning Element Traversal 2.0.
16:42:59 [Rob_Russell]
16:43:46 [Christophe]
DS: Element Traversal 2.0 already being implemented; could be published next year.
16:43:55 [Christophe]
Topic: SVG Community Website
16:44:10 [Christophe]
RR: Working on a theme.
16:44:54 [Christophe]
RR: Looks good graphically, but ... Will be uploaded to the site later; either default or optional.
16:45:49 [Christophe]
RR: Also turned on the update check .... Drupal updated.
16:46:15 [stelt]
the sooner to have something other than the default Drupal the better IMHO. We can perfect later
16:46:38 [shepazu]
q+ to ask about RSS feed for news
16:46:51 [Manuel]
i'm working on how the forums page could look, but it will last a bit (weekend?)
16:46:55 [stelt]
I've figured out how moderating works :-)
16:48:00 [JeffSchiller]
16:48:05 [Christophe]
RR: list items - new: need to get URL at bottom of the blurb.
16:48:15 [stelt]
make NEWS index ?
16:48:25 [Christophe]
s/new/news/
16:49:13 [Christophe]
RR: Need to work on news feed and global feed for articles (RSS or Atom)
16:50:10 [Christophe]
RS: currently site looks like nothing is happening.
16:50:46 [Christophe]
RR: (...) In the theme we can filter which types of content go into which boxes.
16:51:32 [Christophe]
JS: News and latest stories and articles should be major focus.
16:53:01 [Christophe]
RR: Manuel working on ... theme.
16:54:57 [Christophe]
DS: Worried about input and output. Would like this as source of info for SVG WG page. RSS feed for news available?
16:55:21 [Christophe]
RR: No feed for news yet. There will also be other feeds.
16:56:11 [stelt]
raw feed is what editors get
16:56:22 [Christophe]
DS: Also interested in raw feed with Google news alerts etc where SVG is mentioned .
16:56:49 [Christophe]
RR: The editors get that feed and approve things for publication.
16:57:16 [gwadej]
Apologies, but I have a meeting and have to go. Bye.
16:57:30 [Zakim]
- +1.713.851.aaaa
16:58:11 [Christophe]
Zakim, +1.713 was gwadej
16:58:11 [Zakim]
I don't understand '+1.713 was gwadej', Christophe
16:59:15 [Christophe]
DS: Would like to be notified. Would rather have a feed from SVG than one from Google.
16:59:28 [Christophe]
s/SVG/PlanetSVG/
17:00:25 [stelt]
to get "SVG Capital", StaVanGer, etc. filtered out
17:00:31 [Christophe]
DS: Forums: when building community site, they noticed that "old folks" like e-mail while "young folks" prefer forums.
17:01:21 [Christophe]
RR: We need a "Frankenstein's monster" for mail and forums.
17:01:45 [stelt]
Jon Cruz said he wanted to help on that
17:02:01 [Christophe]
RB: There are modules for sending mails to people when there's a new post on the forum etc.
17:02:28 [Christophe]
RB: You ca't reply via the e-mail, but there's a link to the forum.
17:02:46 [Christophe]
s/ca't/can't/
17:03:06 [Christophe]
DS: That would not be as good as replying to a thread via e-mail.
17:03:23 [Christophe]
RB: You would need to integrate with a mail module on the back end.
17:03:24 [Manuel]
have to leave, bye
17:03:45 [Christophe]
DS: If we get simply the notification, that would satisfy the "old fogeys".
17:05:13 [stelt]
i'll bill an extra hour then :-)
17:06:49 [Christophe]
DS: Would also like to see old news stories from SVG.org. Should be possible to get a dump of the news stories, maybe also the blogs.
17:06:58 [Christophe]
RR: Legal ramifications?
17:07:14 [Rob_Russell]
(that was js)
17:08:01 [stelt]
i'd like my diary from there as well
17:09:07 [Christophe]
DS: Get tutorials and/or fresh materials ("instant tricks" etc) on the site.
17:09:36 [Christophe]
JS: Would like to get one or two tutorials. Anyone else who can write something up?
17:10:18 [Christophe]
XX: We could get content from xml.com that is more than one year odl - see A. Quint's articles?
17:10:22 [stelt]
there are many inkscape tuts on Youtube
17:10:27 [darobin]
s/XX/RB/
17:12:20 [Christophe]
(...)
17:13:00 [Christophe]
DS: go through tutorials sites elsewhere. E.g. Photoshop tutorial -> how do the same thing in SVG.
17:13:49 [darobin]
17:14:05 [darobin]
17:14:06 [Christophe]
DS: Also simpler things e.g. what is the simplest way to do a gradient, markers, etc.
17:14:23 [stelt]
17:14:58 [Zakim]
-Don_Doherty
17:15:08 [Zakim]
-??P5
17:15:09 [Zakim]
-JeffSchiller
17:15:09 [Zakim]
-darobin
17:15:12 [Zakim]
-Rob_Russell
17:15:32 [Zakim]
-Christophe_Strobbe
17:15:34 [Zakim]
-Shepazu
17:15:35 [Zakim]
GA_SVGIG()11:00AM has ended
17:15:36 [Zakim]
Attendees were Shepazu, +1.713.851.aaaa, +1.312.540.aabb, JeffSchiller, Christophe_Strobbe, Rob_Russell, Don_Doherty, +33.1.77.11.aacc, darobin
17:16:34 [Christophe]
Present: Doug_Schepers, Jeff_Schiller, Bruce_Rindahl, Rob_Russel, Ruud_Steltenpool, Donald_Doherty, Robin_Berjon, Anthony_Grasso, Christophe_Strobbe
17:16:42 [Christophe]
rrsagent, generate minutes
17:16:42 [RRSAgent]
I have made the request to generate
Christophe
17:17:59 [Christophe]
regrets: David_Dailey, Dominic_DePasquale, David_Porter, Andreas_Neumann, Manuel_Strehl
17:18:13 [Christophe]
rrsagent, generate minutes
17:18:13 [RRSAgent]
I have made the request to generate
Christophe
17:18:49 [Christophe]
Agenda:
17:18:51 [Christophe]
rrsagent, generate minutes
17:18:51 [RRSAgent]
I have made the request to generate
Christophe
17:19:21 [Christophe]
zakim, bye
17:19:21 [Zakim]
Zakim has left #svgig
17:20:30 [Christophe]
Present: Doug_Schepers, Jeff_Schiller, Bruce_Rindahl, Rob_Russel, Ruud_Steltenpool, Donald_Doherty, Robin_Berjon, Anthony_Grasso, Christophe_Strobbe, G_WadeJohnson
17:20:32 [Christophe]
rrsagent, generate minutes
17:20:32 [RRSAgent]
I have made the request to generate
Christophe
17:20:42 [stelt]
stelt has left #svgig
17:21:00 [Christophe]
rrsagent, bye
17:21:00 [RRSAgent]
I see no action items | http://www.w3.org/2008/11/20-svgig-irc | CC-MAIN-2015-32 | refinedweb | 2,518 | 81.93 |
Michael Niedermayer wrote: > Hi > > On Thu, Jan 26, 2006 at 01:04:44AM -0500, Rich Felker wrote: >> On Thu, Jan 26, 2006 at 12:39:46AM +0100, Michael Niedermayer wrote: >>> Hi >>> >>> On Wed, Jan 25, 2006 at 01:30:44PM -1000, Steve Lhomme wrote: >>>> M. >> I don't have the authority to reject, just the authority to flame. :) > > :) > > >>> __align8(type, var) is ok, ill apply it if you send a patch with it >> I was against it because it's not even obvious that this is a variable >> declaration without reading the #define. >> >> Also, using __ prefix is illegal. __ is reserved for the >> implementation. For all you know, the C library/compiler might define >> __align8 for its own purposes. You should use align8 or something not >> in the reserved namespace at the very least. > >... -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: portable-align.patch URL: <> | http://ffmpeg.org/pipermail/ffmpeg-devel/2006-January/011490.html | CC-MAIN-2016-40 | refinedweb | 150 | 71.04 |
just another long tutorial to make mapping life easier.
ok well most people understand the world builder on a basic level.
if you don't stop. don't read more go away.
Now lets see everyone see the first screen of the world builder file menu choices ?
the red circled area is what we will be learning today.
lets start from the top as surely you will want to use an image of
something for your maps hieght data as this will look extremely cool.
Firstly you will need a picture to use : here's a tip: keep it simple .
so i'm going to use just a basic shape as you progress you can use almost
any image but to start with please keep it to a more general style
clip art rather then picture.
so what does one do with the clip art to make it import into world builder ?
well taking the image below as our example.
if we simply save this as 16 bit tga it may or may not import ...
however if we re size the canvass to be square it will work for sure.ok
so if you imported it nice and square like it will now look alot like
this which in case you havent noticed looks nothing like your image .
breath people there's some tricks to be used.
firstly re size the map as most likely it will be overly big and hard
to see if it imported even close to what was needed. *never judge it
until u re sized it smaller to look at it all.
when you re size select scale. make it .5 or something.
ok so this is odd its hugely spiky and the land dips too much how do we fix it ?
in world builder ??? yes if you have weeks and don't want to be smart
fix it in a image editor where you can adjust the contrast .
its a must to lower the contrast to smooth the map and make it easier to edit in world builder.
so now your tga file should look like below all nice and square and mostly black with a hint of your image.
so make a new map then import the tga file or it wont work.resize smaller to make it easy to view
ok so that the basic import tga tool.
now how to use it for a map which uses textures you like ...
go resize take note how big the map is 120x120 for instance..what we are going to do now is export height map.
save someplace you will be able to get it from.
now open up something with okay textures.(an ea official map for instance.)
re size it to that 120x120 without a border.
import height data and take notice your shape is in but all other height data is out...sorry.well that's it.
The Above method works for the following Games : Sage engine based command and conquer 3 and BFME II world builder.
amazing O_O.... could not have said it better myself :D
Thanks for that, i always have that spiky stuff. Now i know how to fix it.
if you see Generals/ZH WB actually have many hidden unimplemented features but left unfinished, and those features were implemented in BFME WB. >_>
I wonder if someone with haxorz skill can implement those in ZH WB.
Well with that spiky terrain you could have made a Tiberium Glacier Map with the right textures. It would fit perfectly. Many art masterpieces and inventions started out as mistakes. Which is the art of improvising. ;)
Hey thank you guys I appreciate the comments.
N5p29 I started out with gens and zh loved them great games both.
Sgt myers you got some cool ideas man. Glaciers hey ? nice though im currently busy mapping about 6 maps.
Oh yea got some left over ini in my blog for gens..
Also should note the flying VW buggy code in there one day.
Yeah this works for Generals/Zero Hour too.
Just got around to using this for the first time (I had tested it before, but now I'm working with a real mapping project) and it works perfect. Just wanted to drop by and say it's really not that much work, and you can even work with google earth images too, although it takes a bit more work because of so many color changes ;) | https://www.moddb.com/members/the-splat/tutorials/height-mapping-tutorial | CC-MAIN-2020-05 | refinedweb | 743 | 82.95 |
Hey,
today I accomplished the task to create Gradient Background without the use of an Image.
The task was to make it possible for the user to change the Background of the Views on Runtime! First I thought I could achive this with Images but on the long run it would have blown up the App-Size.
This is the best implementation I could come up with and the choosen Colors are persistent with the usage of the Settings Plugin form @JamesMontemagno that you can get here: Nuget
This code works for Android and iOS and you can drop it in if you want
So long Story short here's the code:
CustomRenderer in
PCL:
public class GradientContentPage : ContentPage { public static BindableProperty StartColorProperty = BindableProperty.Create<GradientContentPage, Color>(p => p.StartColor, Color.White); public static BindableProperty EndColorProperty = BindableProperty.Create<GradientContentPage, Color>(p => p.EndColor, Color.Gray); public Color StartColor { get { return (Color) GetValue(StartColorProperty); } set { SetValue(StartColorProperty, value); } } public Color EndColor { get { return (Color) GetValue(EndColorProperty); } set { SetValue(EndColorProperty, value); } } }
To make the Colors available all over my app I create two static variables in App.cs and since I can't put a
Color into the Settings I have to store them as
string
So here's the code for my
App.cs
public static Color StartColor; public static Color EndColor; public App() { StartColor = StringToColor(Helpers.Settings.StartColor.Split(' , '); EndColor = StringToColor(Helpers.Settings.EndColor.Split(' , '); MainPage = new NavigationPage(new DashboardView{ StartColor = App.StartColor, EndColor = App.EndColor }); }
As you may notice I've setting the Colors for the View on creation. Sadly you have to this, because Views that inherit from
ContentPage can't make us of
Implicit Styles right now because of this Bug 27659
So anyway let's take a look at
StringToColor
private static void StringToColor(IList<string> color) { for(var i = 0; i < color.Count(); i++) { //Regex to get the color code color[i] = Regex.Replace(color[i], @"^\d.\d+]", ""); } var a = double.Parse(color[0], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); var r = double.Parse(color[1], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); var g = double.Parse(color[2], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); var b = double.Parse(color[3], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); return Color.FromRgba(r, g, b, a); }
Ok, I admit I'm not happy with this function and if anyone has a better idea how to achive this, please let me know! Basically this function find the Color-Code.
Alright now let's get to the platform renderers:
CustomRenderer in
Android:
[assembly: ExportRenderer(typeof(GradientContentPage), typeof(GradientContentPageRenderer))] namespace YourApp.Droid { public class GradientContentPageRenderer : PageRenderer { protected override void OnVisibilityChanged(Android.Views.View changedView, ViewStates visibility) { base.OnVisibilityChanged(changedView, visibility); SetBackground(); } protected override void OnElementChanged(ElementChangedEventArgs<Page> page) { base.OnElementChanged(page); SetBackground(); } private void SetBackground() { var startColor = App.StartColor.ToAndroid(); var endColor = App.EndColor.ToAndroid(); var colors = new int[] { startColor, endColor }; Background = new GradientDrawable(GradientDrawable.Orientation.TopBottom, colors); } } }
You have to overwrite both Events to get every Background in the color you wan't. It's a bit odd but this is how Forms on Android reacts and there is no (at least I haven't found one) event that gets fired everytime you switch a Page;
CustomRenderer in
iOS:
[assembly: ExportRenderer(typeof(GradientContentPage), typeof(GradientContentPageRenderer))] namespace YourApp.iOS { public class GradientContentPageRenderer: PageRenderer { public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); var gradientLayer = new CAGradientLayer { Frame = View.Bounds, Colors = new [] { App.StartColor.ToCGColor(), App.EndColor.ToCGColor() }, StartPoint = new CGPoint(0, 0), EndPoint = new CGPoint(1, 1) } //This is needed to get every background redrawn if the color changes on runtime if(View.Layer.Sublayers[0].GetType() == typeof(CAGradientLayer)) { View.Layer.ReplaceSublayer(View.Layer.Sublayers[0], gradientLayer); } else { View.Layer.InsertSublayer(gradientLayer, 0); } } } }
For this one I have to thank @JohnBeans for his thread here on the forum: Click me
So for the Color Picking I created a view where the user can select a color and then it gets automatically drawn on runtime with the new color. But posting this would be to much for one thread. If someone is interested I can post it.
I have to update my post.
Since 1.4.4 -pre2 the rendering has changed on iOS. When
ViewWillAppearis called after the first page in your App the height of the NavigationBar is not in
View.Boundsanymore. This will lead to a white bar on the end of your background. So I have adjusted my App to counter this.#
On App.cs I had to Introduce 3 new variables.
then I changed the GradientContentPageRenderer like this
Thanks for this gradient code. Very informative.
Could this be applied to different elements (layouts, views) too?
Can the angle/direction of the gradient be configured?
If it is applied to a ContentPage, is the navigation bar included? Or can it be in a different way?
A few comments about your code:
If you only need App.Width, App.Height and App.OnAppStart in iOS, then you should keep those values in your iOS project and not outside. Maybe as static variables within your GradientContentPageRenderer.
However I don't see the reason why you read View.Bounds just once. - Apart from converting them to a string and back which you should also avoid. If you need those values somewhere else in your PCL project, then cast the nfloats to float, but do not convert them to strings.
Are you maybe looking for
UIScreen.MainScreen.Bounds?
Why did you add the StartColor and EndColor properties to your GradientContentPage?
I only see that you are using App.StartColor and App.EndColor, but you never use the properties of the GradientContentPage itself. You set them in
new DashboardView{ StartColor = App.StartColor, EndColor = App.EndColor }but you never use those values.
Unless you have a reason to store the colors as floats, you should consider storing them as hex strings instead "#FFFFCC00". Then you can simply use
Color.FromHex(string)and drop your
StringToColorwith which you are not happy anyway.
I try to avoid using
Regexwherever possible. It can be very expensive.
In the company I worked for, we used to validate the email address which the user entered with a very complicated Regex. After it worked for years without change, I stumbled upon a string which broke the validation completely. When the user entered that string, the JavaScript regex parser hang. Then I tried it in a simple C# program and that hang too. We also had some performance and memory issues on the server side which originated in bad usages of Regex.
I guess I sound a bit like a teacher now. Sorry about that. It was not my intention. I just wanted to mention what IMHO could be done better.
Hi,
Yes they should be applicable to
Layoutor
Viewsbut then you have to hook up in different Events. Mostly
OnElementChanged, I guess. Haven't tried that now.
On iOS you can handle the rotation for the gradient with
StartPointand
EndPointwhen you create the
CAGradientLayer. On Android you have the
GradientDrawable.Orientationin which are a few options.
No, the
NavigationBaris not included. It just the background for the
ContentPage. However, I guess you can change the NavigationBar Background inside of the
CustomRenderers. Just a thought, haven't tried it.
Oh my, didn't knew about
UIScreen.MainScreen.Bounds. That is working perfectly. Thanks I'll update the code here. Sadly I can't just edit it. Thank you for that.
Ha. Got me there
I don't know why I added the properties to the Pages. Thanks for pointing that out!
I actually have a reason. As on the end of my post I stated that I have a
ColorSelectionViewwhere the User can select the Colors for the background. I'm using own Colors and the
Build-In Colors. And there is no information what Hex-Code they have. Sadly. But after I'm releasing the App, I'm gonna take me some time to find out which Hex-Codes they have and do it with them. That seems alot easier.
I'm aware that
Regexcan be really expensive and this is the only time where I use a
Regexin the App. Thankfully the one I have here is fast enough and the Start time for the app is only 1-2 Seconds even with that function.
Actually you really helped me here, thank you. There's something to learn every day
This is the correct code for the iOS renderer.
I find this to be a good way to do gradients.
I actually just made a cross platform gradient with it for a user story right now. It was 3 lines of code.
[Edit] an example
This is a fully cross platform view - note how few lines of code are required for the gradient, which is just a content view that can be composed into any other layout:
For gradients I just use an SVG image. A simple rectangle drawn in Inkscape, where I can edit and preview all gradients colors, steps, orientation, etc. This is the svg file content:
Then I use the SVG plugin to display it and resize it to fit any iOS or Android app frame background:
In this way artists in my team can change all graphic elements and color themes without my intervention, just editing the SVG files in Inkscape.
I just saw that you should not use
UIScreen.MainScreen.Boundsanymore. In iOS 9 Apple copied from Microsoft for a change and introduced a split screen mode where two apps can run side by side. In that case the screen bounds are most likely not what you want anymore.
I saw voices which said that you should use
View.Window.Boundsinstead, but
View.Windowwas null in my case.
UIApplication.SharedApplication.KeyWindow.Boundsworks for me. From what I learned, this should be the recommended approach, but I don't know iOS well enough to be 100% sure.
@MichaelRumpler Thanks for that info. I'm gonna try it out and post my findings.
Using @GeorgeCook 's example with NGraphics 0.7.1, all the NGraphics.Model.AClass should be NGraphics.AClass
Not sure from which version this has changed though.
It's an old thread but please check out this library, I've rewritten it from swift gradient library.
PastelXamarinIos <- Search it on github
I have problem in IOS.
I am using CAGradientLayer,i wrote custom renderer for this, in XAml i have custom width this will change on runtime. when i am changing the width it's not updating.
You can achieve this with Skiasharp
Then just stretch the canvas over your grid etc | https://forums.xamarin.com/discussion/comment/349485/ | CC-MAIN-2021-25 | refinedweb | 1,761 | 51.04 |
quantize man page
Quantize — ImageMagick's color reduction algorithm.
Synopsis
#include <magick.h>
Description, pi, is defined by an ordered triple of red, green, and blue coordinates, (ri, gi, bi)., Reduction, and Assignment).:
- n1:
Number of pixels whose color is contained in the RGB cube which this node represents;
- n2:
Number of pixels whose color is not represented in a node at lower depth in the tree; initially, n2= 0 for all nodes except leaves of the tree.
- Sr, Sg, Sb:
Sums of the red, green, and blue component values for all pixels not classified at a lower depth. The combination of these sums and n2 will ultimately characterize the mean color of a set of pixels represented by this node.
- E:
The distance squared in RGB space between each pixel contained within a node and the nodes' center. This represents the quantization error for a node..
Measuring Color Reduction Error
Referenced By
ImageMagick(1). | https://www.mankier.com/5/quantize | CC-MAIN-2017-43 | refinedweb | 155 | 64.51 |
4 covers Models and Data Access.
So far, we’ve just been passing “dummy data” from our Controllers to our View templates. Now we’re ready to hook up a real database. In this tutorial we’ll be covering how to use SQL Server Compact Edition (often called SQL CE) as our database engine. SQL CE is a free, embedded, file based database that doesn’t require any installation or configuration, which makes it really convenient for local development.
Database access with Entity Framework Code-First
We’ll use the Entity Framework (EF) support that is included in ASP.NET MVC 3 projects to query and update the database. EF is a flexible object relational mapping (ORM) data API that enables developers to query and update data stored in a database in an object-oriented way.
Entity Framework version 4 supports a development paradigm called code-first. Code-first allows you to create model object by writing simple classes (also known as POCO from "plain-old" CLR objects), and can even create the database on the fly from your classes.
Changes to our Model Classes
We will be leveraging the database creation feature in Entity Framework in this tutorial. Before we do that, though, let’s make a few minor changes to our model classes to add in some things we’ll be using later on.
Adding the Artist Model Classes
Our Albums will be associated with Artists, so we’ll add a simple model class to describe an Artist. Add a new class to the Models folder named Artist.cs using the code shown below.
namespace MvcMusicStore.Models { public class Artist { public int ArtistId { get; set; } public string Name { get; set; } } }
Updating our Model Classes
Update the Album class as shown below.
namespace MvcMusicStore.Models { public class Album { public int AlbumId { get; set; } public int GenreId { get; set; } public int ArtistId { get; set; } public string Title { get; set; } public decimal Price { get; set; } public string AlbumArtUrl { get; set; } public Genre Genre { get; set; } public Artist Artist { get; set; } } }
Next, make the following updates to the Genre class.
using System.Collections.Generic; namespace MvcMusicStore.Models { public partial class Genre { public int GenreId { get; set; } public string Name { get; set; } public string Description { get; set; } public List<Album> Albums { get; set; } } }
Adding the App_Data folder
We’ll add an App_Data directory to our project to hold our SQL Server Express database files. App_Data is a special directory in ASP.NET which already has the correct security access permissions for database access. From the Project menu, select Add ASP.NET Folder, then App_Data.
Creating a Connection String in the web.config file
We will add a few lines to the website’s configuration file so that Entity Framework knows how to connect to our database. Double-click on the Web.config file located in the root of the project.
Scroll to the bottom of this file and add a <connectionStrings> section directly above the last line, as shown below.
<connectionStrings> <add name="MusicStoreEntities" connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf" providerName="System.Data.SqlServerCe.4.0"/> </connectionStrings> </configuration>
Adding a Context Class
Right-click the Models folder and add a new class named MusicStoreEntities.cs.
This class will represent the Entity Framework database context, and will handle our create, read, update, and delete operations for us. The code for this class is shown below.
using System.Data.Entity; namespace MvcMusicStore.Models { public class MusicStoreEntities : DbContext { public DbSet<Album> Albums { get; set; } public DbSet<Genre> Genres { get; set; } } }
That’s it - there’s no other configuration, special interfaces, etc. By extending the DbContext base class, our MusicStoreEntities class is able to handle our database operations for us. Now that we’ve got that hooked up, let’s add a few more properties to our model classes to take advantage of some of the additional information in our database.
Adding our store catalog data
We will take advantage of a feature in Entity Framework which adds “seed” data to a newly created database. This will pre-populate our store catalog with a list of Genres, Artists, and Albums. The MvcMusicStore-Assets.zip download - which included our site design files used earlier in this tutorial - has a class file with this seed data, located in a folder named Code.
Within the Code / Models folder, locate the SampleData.cs file and drop it into the Models folder in our project, as shown below.
Now we need to add one line of code to tell Entity Framework about that SampleData class. Double-click on the Global.asax file in the root of the project to open it and add the following line to the top the Application_Start method.
protected void Application_Start() { System.Data.Entity.Database.SetInitializer( new MvcMusicStore.Models.SampleData()); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); }
At this point, we’ve completed the work necessary to configure Entity Framework for our project.
Querying the Database
Now let’s update our StoreController so that instead of using “dummy data” it instead calls into our database to query all of its information. We’ll start by declaring a field on the StoreController to hold an instance of the MusicStoreEntities class, named storeDB:
public class StoreController : Controller { MusicStoreEntities storeDB = new MusicStoreEntities();
Updating the Store Index to query the database
The MusicStoreEntities class is maintained by the Entity Framework and exposes a collection property for each table in our database. Let’s update our StoreController’s Index action to retrieve all Genres in our database. Previously we did this by hard-coding string data. Now we can instead just use the Entity Framework context Generes collection:
public ActionResult Index() { var genres = storeDB.Genres.ToList(); return View(genres); }
No changes need to happen to our View template since we’re still returning the same StoreIndexViewModel we returned before - we’re just returning live data from our database now.
When we run the project again and visit the “/Store” URL, we’ll now see a list of all Genres in our database:
Updating Store Browse and Details to use live data
With the /Store/Browse?genre=[some-genre] action method, we’re searching for a Genre by name. We only expect one result, since we shouldn’t ever have two entries for the same Genre name, and so we can use the .Single() extension in LINQ to query for the appropriate Genre object like this (don’t type this yet):
var example = storeDB.Genres.Single(g => g.Name == “Disco”);
The Single method takes a Lambda expression as a parameter, which specifies that we want a single Genre object such that its name matches the value we’ve defined. In the case above, we are loading a single Genre object with a Name value matching Disco.
We’ll take advantage of an Entity Framework feature that allows us to indicate other related entities we want loaded as well when the Genre object is retrieved. This feature is called Query Result Shaping, and enables us to reduce the number of times we need to access the database to retrieve all of the information we need. We want to pre-fetch the Albums for Genre we retrieve, so we’ll update our query to include from Genres.Include(“Albums”) to indicate that we want related albums as well. This is more efficient, since it will retrieve both our Genre and Album data in a single database request.
With the explanations out of the way, here’s how our updated Browse controller action looks:
public ActionResult Browse(string genre) { // Retrieve Genre and its Associated Albums from database var genreModel = storeDB.Genres.Include("Albums") .Single(g => g.Name == genre); return View(genreModel); }
We can now update the Store Browse View to display the albums which are available in each Genre. Open the view template (found in /Views/Store/Browse.cshtml) and add a bulleted list of Albums as shown below.
@model MvcMusicStore.Models.Genre @{ ViewBag.Title = "Browse"; } <h2>Browsing Genre: @Model.Name</h2> <ul> @foreach (var album in Model.Albums) { <li> @album.Title </li> } </ul>
Running our application and browsing to /Store/Browse?genre=Jazz shows that our results are now being pulled from the database, displaying all albums in our selected Genre.
We’ll make the same change to our /Store/Details/[id] URL, and replace our dummy data with a database query which loads an Album whose ID matches the parameter value.
public ActionResult Details(int id) { var album = storeDB.Albums.Find(id); return View(album); }
Running our application and browsing to /Store/Details/1 shows that our results are now being pulled from the database.
Now that our Store Details page is set up to display an album by the Album ID, let’s update the Browse view to link to the Details view. We will use Html.ActionLink, exactly as we did to link from Store Index to Store Browse at the end of the previous section. The complete source for the Browse view appears below.
@model MvcMusicStore.Models.Genre @{ ViewBag.Title = "Browse"; } <h2>Browsing Genre: @Model.Name</h2> <ul> @foreach (var album in Model.Albums) { <li> @Html.ActionLink(album.Title, "Details", new { id = album.AlbumId }) </li> } </ul>
We’re now able to browse from our Store page to a Genre page, which lists the available albums, and by clicking on an album we can view details for that album.
Please use the Discussions at for any questions or comments.
This article was originally created on April 21, 2011 | http://www.asp.net/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-4 | CC-MAIN-2015-27 | refinedweb | 1,576 | 54.73 |
I'm making a Spree site that has links for changing the number of products per page including a link for All. The links for a number are easy because I can just pass a
:per_page
:per_page = 1000
Could you pass a querystring parameter and then filter it inside your controller action? For example:
def show @products = unless params[:show_all] Product.page(params[:page]).per(params[:per_page]) else Product.all end end
I know this doesn't give you a solution in either Spree or Kaminari but it might help to work around the issue. I'd love to know if there was another way built in to the library though. | https://codedump.io/share/pqGObTOidJiV/1/temporarily-disable-kaminari-pagination-in-spree | CC-MAIN-2016-44 | refinedweb | 111 | 71.44 |
Add depth of field in seconds -
Perfect focus pulls with moving cameras, objects - makes it all childs play.
Added this to my works pipeline, and all of a sudden everyones using D.O.F since the setups so easy and accurate.
Two setups -
One using the Mental Ray Bokeh lens shader.
And the second one, a real nice setup for post production with shader feedback inside of maya.
A must have tool for any serious artist!
For this tool and more, also check out
'''INSTALLATION:-
Unzip the AutoFocuser folder and choose from the folders the version that matches your version of Maya.
Place the stAF.pyc file in your Maya scripts directory eg..
C:\Users\'YOUR USER NAME'\Documents\maya\2014-x64\scripts
Then start maya...
TO USE AUTO FOCUSER SCRIPT:
add the below lines to your shelf or run in a python tab/command line
import stAF
stAF.zDepWin()
and you're ready to roll.
Enjoy one of my absolute favourite tools. | https://www.highend3d.com/maya/script/auto-focuser-for-maya | CC-MAIN-2018-39 | refinedweb | 163 | 76.72 |
The ready-set-go call has just resonated through the hallways at Microsoft, and we are now officially working on the next release of AX. What will the next release of AX look like? What features will it contain? What architectural changes will we make? What tools should we support? These are some of the many questions we will be working on during the upcoming months while we are defining the scope for the next release. I work in the Developer and Partner Tools team. This means I get to influence decisions like: “Should MorphX move into Visual Studio?”, “How many layers should AX 6.0 have?”, “Should X++ support eventing?”, “Do we need an Entity concept in the AOT?”, “How do we make our unit test cases available to partners?” – just to name a few. These are the questions that can get me out of bed in the morning – for a lot of good reasons, but primarily because I know my job makes a big difference to a lot of people.
If you want to join me shaping the future of AX at Microsoft Development Center Copenhagen, please visit:
Any one aware of AX 6.0 architecture? Whether standard AX client will be available or evrything will be web based?
The only thing I would like to see that I am not involved (I do enjoy our meeting with Microsoft Product Product Planners, Programe Managers & UE Team) in already is.. using all the power of Microsoft SQL 2000/2005/2008.
* Being able to control all the index options from the AOS
* Being able to write more complex X++ SQL
* Being able to use the fine tuning tools from MS SQL with AX
1) Object Id’s should be replaced with namespaces. GUIDS are a thing of the past! Maybe a central namespace registration service for partners would help avoiding conflicts.
2) Please do something about the report designer and runtitme. It hasn’t been updated for ages!
3) One should be able to retreive related table fields without coding explicit joins. The runtime should derive the joins from the relationships between the tables. This is something all ORM frameworks do.
4) Integrate the editor with the debugger.
5) Start decoupling and revisiting your designs. Everything in AX is bound together with "super-glue"! You have overused inheritance and failed to adhere to most of the modern object oriented design principles and best practices.
6) You should stop writing COBOL-like data access code. Its killing performance! I took a look at implementation of the new packing slip invoicing feature. It’s full of loops, in-memory joins and lookups. You should really join at the database level and minimize the roundtrips between application and database server.
Nice girl. Why do you call her 6.0?.. (no offence, just kidding 🙂
I guess, moving application objects to SQL database from file DB could be also a nice thing: performance, reliability, transactions, no need for file server, etc.
Well. Reporting is one gr8 tool on which DAX has been missing out lots with each new version. It seems like nothing is being done to upgrade the existing reporting architecture…..would definitely like to see the ballistic designing skills of .Net being incorporated into pre-historic DAX Reports.
Kudos to the future of ERPing!!!!
Sturla’s recommendation to replace Id’s with GUIDs would also greatly simplify the use of source control (no more "team server" handing out object IDs!) and distributed development.
Great Post! I would really be interested in learning about the more features which would be built into AX 6.0. Yes, Eventing is very much required where we can subscribe to events raised in .NET assemblies, And also Morphx (AOT integration) with Visual Studio IDE would be awesome. Thanks for the update and keep posting!
What about dropping the Id’s (tables, fields, indexes,…) as we know them and use GUID instead? That would make it more easy for partners to develop and deploy Dynamics Ax solutions.
The entity concept is something Dynamics Ax has been needing from day one. That is if you could use them as form data sources like we use tables today. That would make it possible to create good business logic layer between the tables and user interface. I sometimes see MorphX (and the tight bondage of forms and tables) as one of the strongest part of the system today, but also the biggest enemy.
Regards, Sturla.
With complete ignorance of AX internals, I write…
I’d certainly like to see MorphX look and feel more like Visual Studio, but actually move it to VS? Not unless there is some good technical reason for doing so. I’d hate to see MorphX compromised just to shoe-horn it into VS.
How many layers should AX 6.0 have? How about an undefined number of layers between the Microsoft layers and CUS, and the ability to order those layers as you choose?
Should AX support eventing? YES! YES! YES! Coming from the .NET and COM world this is absolutely the thing I miss most. This would reduce overlayering considerably because you wouldn’t need to place your own code in existing methods. You could have your own class with handlers for events raised by forms, reports, tables, etc. You know what would be REALLY cool? If .NET apps using the Business Connector could handle events triggered on the AOS. I’d love to be able to write a Windows Service in .NET that would sit and watch for things like insert, update, and delete events on certain tables.
twh
PingBack from | https://blogs.msdn.microsoft.com/mfp/2008/04/15/i-am-working-on-ax6-0-what-are-you-working-on/ | CC-MAIN-2017-22 | refinedweb | 936 | 75 |
I was experimenting with doing an enhanced podcast. It’s not really panning out and I have way better stuff to do, but I saw two important things along the way that I wanted to post, if only to get them into Google.
Enhanced What?
An “Enhanced Podcast” is Apple’s term for a podcast that offers some images and chapter marks. Back up: a podcast is basically audio files and an RSS feed, so you can subscribe with an RSS client and get informed when there’s a new audio file to pull down. In an enhanced podcast, this file adds images and chapters to the audio.
When played in iTunes, the images appear in the cover art viewer panel. On an iPod Photo, they appear on screen.
MAKE magazine’s blog has a great enhanced podcast how-to. If you look on iTunes, you can also see at least one recent show they did as an enhanced podcast (the one on making a charging cable for the Sony PSP). It combines the information provided with Apple’s “ChapterTool” (a beta tool for making enhanced podcasts) with their own experiences.
Key gotcha: the files have to be MPEG-4 containers, so the audio needs to be AAC. Among other downsides, QuickTime for Windows doesn’t export AAC audio (even if you buy QT Pro? I’m not sure), so only Macs can create these for now. FWIW, I don’t expect that to last — people won’t buy Macs just to create enhanced podcasts, but getting Windows-based authors to create enhanced podcasts would probably lead to more iPod-only enhanced podcasts, which would sell more iPods. And when Apple probably gets about the same margin off both iPods and consumer Macs….
What Does This Have To Do With QuickTime?
I figured I had you at “chapter track”… who else does chapter tracks but QuickTime? And a video track where the samples can have arbitrary durations, and is thus exceptionally well suited to slideshows? That’s very QuickTime-y.
In fact, if you look inside the m4b file with something like QuickTime Atomizer, or the QuickTime File Format parser I did for an ONJava article a few years ago, or even HexEdit (c’mon, be hardcore, you know you want to), you’ll see the insides look a lot more like QuickTime than like MPEG-4. There’s no MPEG-4 Initial Object Descriptor atom (iods), nor tracks for the object and scene descriptors (media of types odsm and sdsm).
What there is is an audio track, a video track, and two text tracks. Yet the video track allows for the samples to be regular JPEG’s or PNGs (look for their magic strings in the mdat atom), and I don’t think MPEG-4 even has a text track. The two text tracks are the chapter track (which is just a text track where the samples are the chapter names, with a track reference from the video track to the text track, see IceFlow #3 ), and an HREF track for links to the MAKE site (an HREF track is just a slightly special text track - see chapter 9 in QuickTime for Java: A Developer’s Notebook)
On the other hand, the strings are all null-terminated, which is very MPEG-4-ish. Usually, QuickTime strings use the Pascal-like convention of one byte of length followed by a run of characters.
So Why Not Just Export This As MPEG-4?
Because that turns the image samples into a real MPEG-4 video track, which I would be very surprised if the iPod Photo can play. Also, QuickTime doesn’t export the text tracks. And it doesn’t export audio on Windows.
So What’s This Code?
What I was trying was to build up the QuickTime equivalent to this enhanced podcast, and then see if I could hack it into an MPEG-4 by just switching the file extension or copying over the ftyp atom. That’s not completely implausible, since MPEG-4’s file format is extremely similar to QuickTime’s.
But that didn’t work, and I don’t want to mess around with it much longer.
Still, what I have is potentially useful as a slide show example. What it does is to copy over an MPEG-4 audio track from a selected file (you could take out the “check for MPEG-4″ stuff and it would work with any QT-friendly audio), copies it into a new movie, then takes three images from known locations (
images/chap1.png,
images/chap2.png, and
images/chap3.png) and makes a video track from them, putting them at times 0, duration*0.33, and duration*0.67 (ie, each covers a third of the movie, having a duration of audioDuration/3). Then it
flatten()s, so the sound and all the images are in the same file and you can mail it to all your QuickTime-loving friends.
import quicktime.*; import quicktime.std.*; import quicktime.std.image.*; import quicktime.std.movies.*; import quicktime.std.movies.media.*; import quicktime.io.*; import quicktime.util.*; import java.io.File; public class EPodcastTest extends Object { // 1-based count of "images/chapn.png" files, // where 1 <= n <= CHAPTER_COUNT public static final int CHAPTER_COUNT = 3; public static void main (String arrrImAPirate[] ) { try { QTSession.open(); // open a movie QTFile file = QTFile.standardGetFilePreview (QTFile.kStandardQTFileTypes); OpenMovieFile omFile = OpenMovieFile.asRead (file); Movie audioMovie = Movie.fromFile (omFile); // find audio track System.out.println (audioMovie.getTrackCount() + " tracks"); Track oldAudioTrack = audioMovie.getIndTrackType (1, StdQTConstants.audioMediaCharacteristic, StdQTConstants.movieTrackCharacteristic); if (oldAudioTrack == null) { System.out.println ("Didn't find audio track - bye"); System.exit (-1); } System.out.println ("found audio track"); if (oldAudioTrack.getMedia().getSampleDescription(1).getDataFormat() != QTUtils.toOSType ("mp4a")) { System.out.println ("Audio track is not mpeg-4 audio - bye"); System.exit (-1); } System.out.println ("Found MPEG-4 audio track"); // create new movie QTFile podMovieFile = new QTFile (new File ("podmovie.mov")); Movie podMovie = Movie.createMovieFile(podMovieFile, StdQTConstants.kMoviePlayer, StdQTConstants.createMovieFileDeleteCurFile | StdQTConstants.createMovieFileDontCreateResFile); // copy audio track Track podAudioTrack = podMovie.newTrack (0.0f, // width 0.0f, // height oldAudioTrack.getVolume()); // note how the data ref writes back to the podMovie SoundMedia newMedia = new SoundMedia (podAudioTrack, oldAudioTrack.getMedia().getTimeScale(), DataRef.fromMovie (podMovie)); podAudioTrack.getMedia().beginEdits(); oldAudioTrack.insertSegment (podAudioTrack, 0, oldAudioTrack.getDuration(), 0); podAudioTrack.getMedia().endEdits(); // add images as video track Track podVideoTrack = podMovie.newTrack (300.0f, 300.0f, 0f); VideoMedia podVideoMedia = new VideoMedia (podVideoTrack, podMovie.getTimeScale()); podVideoMedia.beginEdits(); File imagesDir = new File("images"); for (int i=1; i<=CHAPTER_COUNT; i++) { QTFile imageFile = new QTFile ( new File (imagesDir, "chap" + i + ".png")); System.out.println ("open " + imageFile.getPath()); GraphicsImporter gi = new GraphicsImporter (imageFile); ImageDescription id = gi.getImageDescription(); System.out.println ("ImageDescrption: " + id); // add a sample to the video track int sampleNumber = i - 1; int dataSize = gi.getDataSize(); System.out.println ("data size is " + dataSize); RawEncodedImage rei = new RawEncodedImage (dataSize, false); gi.readData (rei, 0, dataSize); System.out.println ("read image"); // argh, addSample wants QTHandleRef, but // RawEncodedImage is a QTPointer. copying the // bytes seems an unfortunate answer QTHandle imageHdl = new QTHandle (rei.getBytes()); int sampleFlags = 0; // don't set mediaSampleNotSync podVideoMedia.addSample (imageHdl, // data handle 0, // offset dataSize, // size podMovie.getDuration() / 3, // duration id, // sample description 1, // num samples sampleFlags ); // sampleFlags } podVideoMedia.endEdits(); podVideoTrack.insertMedia (0, // trackStart 0, // mediaTime podVideoMedia.getDuration(), // mediaDuration 1); // mediaRate System.out.println ("inserted media into video track"); System.out.println ("flattening"); podMovie.flatten(StdQTConstants.flattenAddMovieToDataFork | StdQTConstants.flattenForceMovieResourceBeforeMovieData, new QTFile (new File ("flatmovie.mov")), StdQTConstants.kMoviePlayer, IOConstants.smSystemScript, StdQTConstants.createMovieFileDeleteCurFile, StdQTConstants.movieInDataForkResID, null); // resName System.out.println ("Done"); } catch (QTException qte) { qte.printStackTrace(); } finally { QTSession.close(); System.exit(0); } } // main }
And The Useful Parts?
Two things would be interesting if you were trying to apply techniques from the book and got stuck — those examples generally deal with doing one thing at a time with a movie, and this is weird because it’s copying media with
Track.insertSegment(), and then adding samples with
Media.addSample().
Useful Part One: Using The Movie File As The DataRef For New Media
In the book, the “add a track” stuff deals with movies that already exist or are created with
new Movie(). For this slideshow maker, I created a movie with the
createMovieFile() method:
Movie podMovie = Movie.createMovieFile(podMovieFile, StdQTConstants.kMoviePlayer, StdQTConstants.createMovieFileDeleteCurFile | StdQTConstants.createMovieFileDontCreateResFile);
The gotcha is that I created the
SoundMedia in a way that fails when you flatten it. This is based on the approach of having a bogus in-memory
DataRef for storing the media (see Q&A: BeginMediaEdits -2050 badDataRefIndex error after calling NewMovie ):
SoundMedia newMedia = new SoundMedia (podAudioTrack, oldAudioTrack.getMedia().getTimeScale(), new DataRef (new QTHandle()));
Like I said, this sucks because you get
eofErr when you flatten. It works better to tell it “no, really, store the media in the movie file I just created”:
SoundMedia newMedia = new SoundMedia (podAudioTrack, oldAudioTrack.getMedia().getTimeScale(), DataRef.fromMovie (podMovie));
In fact, it’s simpler to omit the
DataRef altogether, unless you know you need it (eg, you used
new Movie() instead of
createMovieFile()). So this works too:
SoundMedia newMedia = new SoundMedia (podAudioTrack, oldAudioTrack.getMedia().getTimeScale());
Useful Part Two: Storing Slide Show Pictures In The Video Track
In the book, I show the more advanced way of laying down a video track with raw samples, using a
CSequence so you can pick up temporal compression. This puts original frames in a
GWorld and compresses each one. For a slide show, you wouldn’t want to re-compress your images if they’re already in a format like JPEG or PNG, you just want to add them straight into the
VideoMedia, which is possible.
So, book’s approach is:
- Import image with a
GraphicsImporter
- Set up a
CSequence. Get an
ImageDescriptionfrom this
- Draw some part of the imported image into a
GWorld
- Compress the
GWorldinto a frame.
addSample()with handle returned from the compress call and
ImageDescriptionfrom the
CSequence
To do slides, it’s simpler:
- Import image with
GraphicsImporter
- Get an
ImageDescriptionfrom the importer
- Make a
QTHandleby copying bytes from the importer
addSample()with this handle and description
BTW, step 3 sucks. There has to be a better way, but this is experimental hackery, so I’m just happy it works.
Speaking of hackery, it creates a useless reference movie file called “podmovie.mov” that it should probably delete. “flatmovie.mov” is the flattened movie with the slideshow.
Conclusion
Sheesh. This is long. I should have put it on O’Reilly as a blog or something… maybe I’ll do that too… Daddy needs to sell some ads… Anyways, I hope it helps someone at some point.
I’m officially done with trying to hack enhanced podcasts for now. Maybe Apple will give us a nice MovieExporter for doing them at some point, and then we could build a nice Java GUI for capturing and editing the sound, arranging the pictures, etc. | http://www.oreillynet.com/mac/blog/2005/08/qtj_failed_epodcast_experiment.html | crawl-002 | refinedweb | 1,806 | 56.66 |
If you get stuck, ask questions on Stack Overflow or Reddit. Good luck
Online resources, there are many. Too many sometimes. Grab anything from codecadeamy, codeschool, or Tree House. But remember that's not the only thing you need to know.
If you check my profile, we do remote programming courses where people work together with a real teacher for 6 weeks. We offer scholarships (100% free).
Remember:* Focus on learning programming. What's the scope of a variable? what's immutability? etc.* Practice a lot. Code as much as you can.* Look up for a group to work together.
Reasons to segregate:
1) The single biggest one is that it firewalls the liability of the businesses from each other. Whether this is important or not for you depends on what the businesses are doing: if it's Regular Internet Stuff then your E&O policy is probably good enough in terms of risk mitigation, but if 1+ of your products are in highly regulated spaces (hello HIPAA, finance, etc) then putting them in their own LLC isn't a crazy solution.
2) If you're religious about doing not just the paper ownership but the business accounts separately for each business, that makes eventually selling or otherwise disposing of them much, much easier. Otherwise you're looking at weeks of work and/or very fun professional services bills when you decide to do the division later.
3) If you have co-founders or investors, or the prospect of getting co-founders or investors, separate legal entities are going to be pretty much required. You don't want them to accidentally get ownership of your side projects; they don't want to own your side projects (ownership is a risk; they know the risks they're signing up for and don't want additional sources of uncontrolled unknown risk).
4) A minor factor, but there is non-zero social friction involved in "We've been talking about my trading name of $FOO but remember that the invoice/contract/etc will be from $BAR, LLC."
Reasons to not segregate:
1) It's a lot of extra work.
2) There's a running cost to keeping an LLC open, both the yearly fees and the operational complexity of maintaining separate books, accounts at various providers, and (if you're doing things in a complicated fashion) keeping up appearances with regards to the LLCs being formally separate from each other.
As an ex-consultant with some accidental knowledge of the payments space: I would be doing double-plus firewalling between any payments startup and anything I'd lose sleep about losing, and I would be happily writing a sizable check right about now to a lawyer rather than taking HN's advice about my compliance obligations and potential sources of risk.
I work at a small startup with a roughly 10-person eng team.
When we write docs we focus mainly on architecture and processes. The architecture docs often emerge from a "tech spec" that was written for the development of a feature that required a new service, or substantial changes to a new one. We keep everything in Github, in a README or other markdown files.
We also write API docs for HTTP endpoints. These are written with client developers and their concerns in mind. When doing this for a Rails app we use rspec_API_documentation, which is nice, but it can be annoying to have testing and documentation so tightly couples. We've talked about changing how we do this, but we always have more pressing things to do.
We never write docs for classes or modules within an app/service.
The rest of the systems are documented ad-hoc. Some readme files here and there, a large block of comments inside of confusing files, the occasional style guide, etc.
We also have an onboarding guide for new devs (just a PDF) which walks them through our systems, our tools, etc. Nothing fancy, about 10 pages.
I'm actually pretty proud of the search that I put together for this setup too, it's all done in the browser and the indexes are built at compile time which is then downloaded in full for a search, which sounds silly, but it works surprisingly well [4].
[1]
[2]
[3]
[4]
flatdoc is a small JavaScript file that fetches Markdown files and renders them as full pages:
Swagger UI is a dependency-free collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.
So we have a doc folder in the repo that is like staring into the maw of Cthulhu and takes up 90% of our build time on the CI server sucking that down mass of garbage for the checkout.
Saner systems have been proposed, but rejected because the powers that be are too averse to change...
Trying to get people onto Sphinx [0], and use it for some non-sanctioned documentation with good success, but unlikely to make it official.
I really think version control is important: what changed, who changed it, provisional changes through branches, and removing the bottleneck of "I updated the docs, please everyone check before release and send me your comments". It should be patches, and only patches.
[0]:
Besides the README.md to get started, the app defaults to a private portal with a component playground (for React), internal docs (for answering "how do I"), and tools for completely removing the need for doc pages at all.
I believe that documentation has to be part of the workflow, so component documentation should be visible while working on the component, tools for workflow should have introductions and helpful hints rather than being just forms and buttons, etc.
So far, this is proving fruitful.
(Side note: wikis are where docs go to die.)
- Easy editing (namely markdown files in folders)- Runs on "cheap" hosting/everywhere (built with PHP)- Supports multiple languages (so you can create docs in english, german, etc.)- Can have editable try-on-your-own demos embedded into the documentation- SEO friendly (clean URLs and navigation structure)- Themeable (themes are separated and run with the Twig templating engine)- Works on mobiles out of the box- Supports Plugins/Modules for custom content/behaviour- Formats reference pages for objects/classes/APIs in a nice way- Supports easy embedding of disqus for user feedback- Other stuff I forgot right now
The system powers the knowledge base of my recent app "InSite" for web developers:
You can see it also in action working - with a different theme - for my javascript UI library "modoJS":
That page is a bit more complex. It does _not_ use multiple languages there but it makes great use of the reference pages and has many many editable live-demos. It also has some custom modules like a live build script for the javascript library. At one point it even had a complete user-module with payments but I disabled that when modoJS went opensource.
Another instance of docEngine runs for my pet html5 game engine: one uses the default theme, has most pages in two languages and again incorporates a couple of live demos.
I host a little documentation about the engine itself here, but its not complete right now: can also find the github link to the project in the footer of every hosted documentation.
Have fun with it - I give it away for free. Critics and comments welcome!Everything I have linked was built by myself.
The important thing about docs is to keep in mind the audience. This is important because it lets you estimate their mental model and omit things that are redundant: for example, if it's internal documentation for a codebase, there is little need to explicitly list out Doxygen or JSDoc style information, because they have access to the damned source code. External audiences may need certain terms clarified, or some things explained more carefully because they can't just read the source.
I'd say that the biggest thing missing in the documentation efforts I've seen fail is the lack of explanation for the overarching vision/cohesive architecture of the work. This is sometimes because there isn't a single vision, or because the person who has the vision gets distracted snarfing on details that are not helpful without a preexisting schema to hang them on when learning. So, always always always have a high-level document that describes the general engineering problem the project solves, the main business constraints on that solution, and a rough sketch of how the problem is solved.
Ideally, the loss of the codebase should be less of a setback than the loss of the doc.
I will say that, as your documentation improves, you will hate your project more and more--this is the nature of the beast as you drag yourself through the broken shards of your teams engineering.
So whenever a new staffer comes along, I get asked to give them wiki access... but I'm the only one here that uses my edits (only ops staffer). Sure, have some wiki access, for all the good it will do you!
I really don't recommend our model :)
Anyway, this is an important point: documentation is not free. It takes time. Even shitty documentation takes time. If you want good documentation, you need to budget time away from other tasks. When I used to work in support, the field repair engineers would budget 30% of their hours for doing paperwork - not documentation specifically, but it clearly shows that 'writing stuff' is not something that springs as a natural/free parallel to other activity.
I believe that literate style of code writing has many benefits in any language.
Basically mix markdown with the codebase and export the documentation from the same file.
For a very well executed and interactive example check out
Which make it easy to create html, pdf, epub, latex formats, etc.
I like to create a user guide, developer guide, and ops guide for each large project.
1) Write to all of your target audience. For example if your product is targeted at both technical and non-technical people, then write the documentation in such a way that non-technical folks can understand it. Don't just write for the technical people.
2) If possible, write documentation around several 'how do I do XYZ task'? My experience has been that people tend to turn to documentation when they want to execute a specific task and they tend to search for those phrases
3) As much as is possible, include examples. This tends to remove ambiguities.
* MS doc(x) on a network folder with an excel spreadsheet to keep track of docs (and a lot of ugly macros).
* MS doc(x) in a badly organized subversion repository (side note here, docs comments and revision mode are heavily used in those contexts, which is really annoying)
* rst + sphinx documentation in a repository to generate various outputs (html, odt, pdf...) depending on the client.
In some cases we also use Mako (a python template engin) before sphinx to instantiate the documentation for a specific platform (ex: Windows, RedHat, Debian...), with just a few "if" conditions (sphinx could do it in theory, but it's quite buggy and limited).
I've also put in place a continuous build system (just an ugly shell script) rebuilding the sphinx html version every commit (it's our "badly implemented readthedocs.org", but it's good enough for our needs).
In other cases we use specification tools like PowerAMC or Eclipse/EMF/CDO based solutions, the specification tool in that case works on a model, and can generate various outputs (docx, pdf, rtf, html...).
At home, for my personal projects, I use rst + sphinx + readthedocs, or if the documentation is simple, just a simple README.md at the root of my repository.
As a personal opinion, I like to keep the documentation close to the code, but not too close.
For example, I find it really annoying when the sole documentation is doxygene (or equivalent), it's necessary to document each public methods/attributes individually, but it's not sufficient, you need to have a "bigger picture documentation" on how stuff works together (software and system architecture) in most cases.
On the other side, keeping the documentation away from the code (in a wiki or worst) doesn't work that well either, it's nearly a guaranty that documentation will be out of date soon, if it's not already the case.
I found having a doc directory in the source code repository a nice middle ground.
I found wikis annoying in most cases, rarely up to date, badly organized and difficult to version coherently and properly (ex: having version of the doc matching the software version).
We also have higher level documentation, which is meant to serve as a sort of conceptual overview of the framework, as well as to show what the framework comes with out of the box. This section is written mostly in kramdown, which gets parsed by jekyll before it's turned into HTML.
We generate the bulk of those manuals based on our object model, which is liberally sprinkled with (text only) descriptions. We've created a simple XML-based authoring framework which allows us to create pretty tidy documentation. Including images, tables, code examples etc.
We convert that XML to Apache FOP. At the end of the process, we're left with a bunch of tidy PDF manuals in a variety of languages.
This is the most important step. If you cannot remember it from a blank slate, then no one can. Keep doing that until you understand the code at first glance. Then your code will be easy for anyone to maintain.
Ideally, I'd love to find a mechanism that:
- provides the OO principles in documents; Encapsulations, Abstraction, Polymorphism, Inheritance . - Accessible & maintainable by non-techies. - Allows scripting (I toyed with PlantUML, but it was a bit rigid).
As for code, auto generated docs from jsdoc etc. headers are fine but I never use them honestly. I find unit tests to be the ultimate documentation in terms of code level docs.
I have a CVS repository of PDF and Word docs.
The business side uses docx format, so using markdown and generating docx is not really feasible. I have run into issues of people changing the filename and it creating a new entry in the version control. I have a idea I plan to implement to fix this.
What I would really like is some linux system that would make it easy to pull the text out of docx and make it searchable. I would want something that could run on the command line that does not have a ton of dependencies.
Obviously I think just locking your doors (if you don't already) is the smartest idea. And setup a camera outside, at least that way you can start to deter this behavior and possibly catch a glimpse if it does happen. I'd also bet if this is happening multiple times, it is someone you know, or a local teenager etc. That's what happened to me when I found my car getting egged etc repeatedly one summer, I setup a system to catch them which allowed me to have a little discussion with them to make it stop before it escalated.
A little fun too, if you only use the outside camera, put a sign in the car that says "don't look back" or something to that affect (to get them to look towards the camera). Most people when they read that immediately do the behavior you wrote to see why, and they'll look right at the camera. Only the real criminals will just bolt and not do it.
Rather than 64 bit and ECC RAM, you could have high redundancy on the module level. AFAIK Google do not use server grade systems, just lots of them in a failure tolerant configuration.
An important part of the goal is to get an as "closed computational environment" as possible, where risk for BIOS/firmware infection by hacker is minimal.
So just CPU, ECC RAM, ethernet, and microSD (or USB) to boot off..
"What do you mean more?" her husband says. "I can't afford more."
"I mean more better," the producer replies.
The problem isn't so much WHAT Mayer did, but how badly she did it. She wanted to boost Yahoo's video division, for example, so she (a) paid Katie Couric (someone my Mom really liked) more money than God, (b) licensed the streaming rights to SATURDAY NIGHT LIVE (which needs to be put out of its misery) and (c) decided to fund a season of COMMUNITY (which nobody ever watched). Now THERE'S a compelling product offering. WhoTF would watch that?
She redesigned the site to make it mobile-friendly-- which made it almost unreadable for desktop users. Apparently no one told her that browsers send information about what type of device is reading the site. I liked the tech news, but it became so painful that I just gave up.
(She also killed a lot of the personalization features, which is what had attracted people.)
She bought a lot of tiny companies, most of which made products that were never integrated-- and whose employees left as soon as their employment agreements expired.
She bought Tumblr... then had absolutely no idea what to do with it, and ended up not doing anything. Shut down their sales force to integrate it with the Yahoo sales force (which didn't want to sell Tumblr)-- and then realized they'd have to restart the Tumblr sales force to monetize at all.
She inherited an email system that was a hot mess and made it a different type of hot mess-- with enough glitches that people couldn't rely on it for their email.
A lot of the ideas were reasonable, but the execution was so horrific that there was never any value-add.
Why is Yahoo so politicized and who cares? I think Yahoo is no different from any other large corporation. It's just that the players are engaging and using the media a lot more for their stupid rich asshole power struggles that 99% of earth doesn't care about.
Thoughtbot's:
Realm's:
They got me on to monitoring EVERYTHING with statsd. Great stuff.
Edit: Too bad you can't use asterisks in HN comments...
Fellow longtime Gentoo and recent Alpine user here. I haven't encountered undue conflict burden from configuration file updates. Some projects do churn whitespace etc, in configuration defaults files, which is unfortunate but not specific to any distro.
If an application supports a conf.d style override, I use that, containing only settings which differ from default.
Is there something inherent about Alpine packaging that handles local config differently?
* Don't use queues. Use logs, such as Apache Kafka for example. It is unlikely to lose any data, and in case of some failure, the log with transactions is still there for some time. Also Kafka guarantees order of messages, which might be important (or not).
* Understand what is the nature of data and what are the queries that are made later. This is crucial for properly modeling the storage system.
* Be careful with the noSQL cool-aid. If mature databases, such as postgreSQL can't handle the load, choose some NoSQL, but be careful. I would suggest HBase, but your mileage may vary.
* NoSQL DBs typically limits queries that you might issue, so the modelling part is very important.
* Don't index data that you don't need to query later.
* If your schema is relational, consider de-normalization steps. Sometimes it is better to replicate some data, than to keep relational schema and make huge joins across tables.
* Don't use MongoDB
I hope it helps!
Most of the big data tools out there will work with data in this format -- BigQuery, Redshift, EMR. EMR can do batch processing against this data directly from s3 -- but may not be suitable for anything other than batch processing. BigQuery and/or Redshift are more targeted towards analytics workloads, but you could use them to saw the data into another system that you use for OLAP -- MySQL or Postgres probably.
BigQuery has a nice interface and it's a better hosted service than Redshift IMO. If you like that product, you can do streaming inserts in parallel to your gcs/s3 uploading process for more real-time access to the data. The web interface is not bad for casual exploration of terabytes of raw data. And the price isn't terrible either.
I've done some consulting in this space -- feel free to reach out if you'd like some free advice.
My advice is to step away from AWS (because of price as you noted). Bare metal servers are the best startup friend for large data in regards to performance and storage. This way you avoid virtualized CPU or distributed file systems that are more of a bottleneck than advantage.
Look for GorillaServers at
You get 40Tb storage with 8~16 cores per server, along with 30Tb of bandwidth included for roughly 200 USD/month.
This should remove the IOPS limitation and provide enough working space to transform the data. Hope this helps.
* Use a Queue. RabbitMQ is quite good. Instead of writing to files, generate data/tasks on the queue and have them consumed by more than one client. The clients should handle inserting the data to the database. You can control the pipe by the number of clients you have consuming tasks, and/or by rate limiting them. Break those queue consuming clients to small pieces. Its ok to queue item B on the queue while processing item A.
* If you data is more fluid and changing all the time, and/or if it comes in JSON serializable format, consider switching to postgresql ^9.4, and use the JSONB columns to store this data. You can index/query those columns and performance wise its on par (or surpasses) MongoDB.
* Avoid AWS at this stage. like commented by someone here - bare metal is a better friend to you. You'll also know exactly how much you're paying each month. no surprises. I can't recommend Softlayer enough.
* Don't over complicate things. If you can think of a simple solution to something - its preferable than the complicated solution you might have had before.
* If you're going the queue route suggested above, you can pre-process the data while you get it in. If its going to be placed into buckets, do it then, if its normalised - do it then. The tasks on the queue should be atomic and idempotent. You can use something like memcached if you need your clients to communicate between eachother (like checking if a queue item is not already processed by another consumer and thus is locked).
Have you looked at Google at all? Cloud Bigtable runs the whole of Google's Advertising Business and could scale per your requirements.
In my previous job we processed 100s of millions of row updates daily on a table with much contention and ~200G size and used a single PostgreSQL server with (now somewhat obsoleted by modern PCIe SSDs) TMS RamSAN storage, i.e. Fibre-Channel based Flash. We had some performance bottlenecks due to many indexes, triggers etc. but overall, live query performance was very good.
Realistically, this is what I would do (I work on something very similar but not really in adtech space):
1. Load data in text form (assuming it sits in S3) inside hadoop (EMR/Spark)
2. Generate reports you need based on your data and cache them in mysql RDS.
3. Serve the pre-generated reports to your user. You can get creative here and generate bucketed reports where user will fill its more "interactive". This approach will take you a long way and when you have time/money/people, maybe you can try getting fancier and better.
Getting fancy: If you truly want near-real time querying capabilities I would looks at apache kylin or linkedin pinot. But I would stay away from those for now.
Bigtable: As someone pointed out, bigtable is good solution (although I haven't used it) but since you are on AWS ecosystem, I would stick there.
(Hope that might be helpful! A bunch of us hang out on IRC at #cassandra if you're curious.)
If your data are event data, e.g. User activity, clicks, etc, these are non-volatile data which should preserve as-is and you want to enrich them later on for analysis.
You can store these flat files in S3 and use EMR (Hive, Spark) to process them and store it in Redshift. If your files are character delimited files, you can easily create a table definition with Hive/Spark and query it as if it is a RDBMS. You can process your files in EMR using spot instances and it can be as cheap as less than a dollar per hour.
This architecture will get you to massive, massive scale and is pretty resilient to spikes in traffic because of the Kafka buffer. I would avoid Mongo / mysql like the plague in this case, a lot of designs focus on the real time aspect for a lot of data like this, but if you take a hard look at what you really need, its batch map reduce on a massive scale and a dependable schedule with linear growth metrics. With an architecture like this deployed to AWS EMR (or even kinesis / s3 / EMR) you could grow for years. Forget about the trendy systems, and go for the dependable tool chains for big data.
And pay a little to read this book:-...
And this one:...
Nathan Marz brought Apache Storm to the world, and Martin Kleppmann is pretty well known for his work on Kafka.
Both are very good books on building scalable data processing systems.
The bottleneck is usually not I/O, but computing aggregates over data that continuously gets updated. This is quite CPU intensive even for smaller data sizes.
You might want to consider PostgreSQL, with Citus to shard tables and parallelise queries across many PostgreSQL servers. There's another big advertising platform that I helped move from MySQL to PostgreSQL+Citus recently and they're pretty happy with it. They ingest several TB of data per day and a dashboard runs group-by queries, with 99.5% of queries taking under 1 second. The data are also rolled up into daily aggregates inside the database.
There are inherent limitations to any distributed database. That's why there are so many. In Citus, not every SQL query works on distributed tables, but since every server is PostgreSQL 9.5, you do have a lot of possibilities.
Looking at your username, are you based in the Netherlands by any chance? :)
Some pointers:
- How CloudFlare uses Citus:...
- Overview of Citus:...
- Documentation:...
If you just want reports (and are okay getting them in the matter of minutes), then you can continue storing them in flat files and using apache HIVE/PIG-equivalent software (or whatever equivalent is hot right now, im out of date on this class of software).
If you want a really good out-of-box solution for storage + data processing, google cloud products might be a really good bet.
DO NOT write to txt files and read them again. This is unnecessary disk IO and you will run into a lot of problems later on. Instead, have an agent which writes into Kafka (like everyone mentioned), preferably using protobuff.
Then have an aggregator which does the data extraction and analysis and puts them in some sort of storage. You can browse this thread to look for and decide what sort of storage is suitable for you.
We looked at just about every open source and commercial platform that we might use as a backend, and decided that none were appropriate, for scale, maturity, or fairness / scheduling. So we ended up building, from scratch, something that looks a bit like Google's Dremel / BigQuery, but runs on our own bare metal infrastructure. And then we put postgres on top of that using Foreign Data Wrappers so we could write standard SQL queries against it.
Some blog posts about the nuts and bolts you might find interesting:
If we were starting today, we might consider Apache Drill, although I haven't looked at the maturity and stability of that project recently.
If you need to generate rich multi-dimension reports I recommend you create ETL pipeline into star-like sharded database (ala OLAP).
Dimensions normalization sometime dramatically reduce data volume, most of dimensions even can fit into RAM.
Actually 200Gb per day not so much in terms of throughput, you can manage it pretty well on PostgreSQL cluster (with help of pg_proxy). I think mySQL will also work OK.
Dedicated hardware will be cheaper then AWS RDS.
* Logs are written to S3 (either ELB does this automatically, or you put them there)
* S3 can put a message into an SQS queue when a log file is added
* A "worker" (written in language of your choice running on EC2 or Lambda) pops the message off the queue, downloads the log, and "reduces" it into grouped counts. In this case a large log file would be "reduced" to lines where each line is [date, referrer domain, action, count] (e.g. [['2016-02-24', 'news.ycombinator.com', 'impression', 500], ['2016-02-24', 'news.ycombinator.com', 'conversion', 20], ...]
* The reduction can either be persisted in a db that can handle further analysis or you reduce further first.
0:...
In a shell (modified for speed and ease of use) get, insert, update data in a simple way, without all the fat from other mainstream (Java) solutions.
Tip: focus on how to backup and restore first, the rest will be easy!
AWS also has Kinesis, which is deliberately intended to be a sort of event drain. Under the hood it uses S3 and they publish an API and an agent that handles all the retry / checkpoint logic for you.
If it's modelled in SQL, it's probably relational and normalized so you'll be joining together tables. This balloons the complexity of querying the data pretty fast. Denormalizing data simplifies the problem so see if you can get it into a K/V instead of or relational database. Not saying relational isn't a fine solution - even if you keep it in mysql, denormalizing will benefit the complexity of querying it.
Once you determine if you can denormalize, you can look at sharding the data so instead of having the data in one place, you have it in many places and the key of the record determines where to store and retrieve the data. Now you have the ability to scale your data horizontally across instances to divide the problem's complexity by n where n is the number of nodes.
Unfortunately the network is not reliable so you suddenly have to worry about CAP theorem and what happens when nodes become unavailable so you'll start looking at replication and consistency across nodes and need to figure out with your problem domain what you can tolerate. Eg bank accounts have different consistency requirements than social media data where a stale read isn't a big deal.
Aphyr's Call Me Maybe series has reviews of many datastores in pathological conditions so read about your choice there before you go all in (assuming you do want to look at different stores.) Dynamo style DB's like riak are what I think of immediately but read around - this guy is a wizard.
AWS has a notorious network so really think about those failure scenarios. Yes it's hard and the network isn't reliable. Dynamo DBs are cool though and fit the big problems you're looking at if you want to load and query it.
If you want to work with the data, the Apache Spark is worth looking at. You mention mapreduce for instance. Spark is quick.
It's sort of hard because there isn't a lot of information about the problem domain so I can only shoot in the dark. If you have strong consistency needs or need to worry more about concurrent state across data that's a different problem than processing one record at a time without a need for consistent view of the data as a whole. The latter you can just process the data via workers.
But think Sharding to divide the problem across nodes, Denormalization eg via Key/Value lookup for simple runtime complexity. But start where you are - look at your database and make sure it's very well tuned for the queries you're making.
Do you even need to load it into a db? You could distribute the load across clusters of workers if you have some source that you can stream the data from. Then you don't have to load and then query the data. Depends heavily on your domain problem. Good luck. I can email you to discuss if you want - I just don't want to post my email here. Data isn't so much where I hand out as much as processing lots of things concurrently in distributed systems is so others may have better ideas who have gone through similar items.
There are some cool papers like the Amazon Dynamo paper and I read the Google Spanner paper the other day (more globally oriented and around locking and consistency items). You can see how some of the big companies are formalizing thinking by reading some of the papers in that space. Then there are implementations you can actually use but you need to understand them a bit first I think....
Short answer: I think you're looking in the wrong direction, this problem isn't solved by a database but a full data processing system like Hadoop, Spark, Flink (my pick), or Google Cloud's dataflow. I don't know what kind of stack you guys are using (imo the solution to this problem is best made leveraging java) but I would say that you could benefit a lot from either using the hadoop ecosystem or using google cloud's ecosystem. Since you say that you are not experienced with that volume of data, I recommend you go with google cloud's ecosystem specifically look at google dataflow which supports autoscaling.
Long answer: To answer your question more directly, you have a bunch of data arriving that needs to be processed and stored every X minutes and needs to be available to be interactively analyzed or processed later in a report. This is a common task and is exactly why the hadoop ecosystem is so big right now.
The 'easy' way to solve this problem is by using google dataflow which is a stream processing abstraction over the google cloud that will let you set your X minute window (or more complex windowing) and automatically scale your compute servers (and pay only for what you use, not what you reserve). For interactive queries they offer google bigquery, a robust SQL based column database that lets you query your data in seconds and only charges you based on the columns you queried (if your data set is 1TB but the columns used in your query are only some short strings they might only charge you for querying 5GB). As a replacement for your mysql problems they also offer managed mysql instances and their own google bigtable which has many other useful features. Did I mention these services are integrated into an interactive ipython notebook style interface called Datalab and fully integrated with your dataflow code?
This is all might get a little expensive though (in terms of your cloud bill), the other solution is to do some harder work involving the hadoop ecosystem. The problem of processing data every X minutes is called windowing in stream processing. Your problems are solved by using Apache Flink, a relatively easy and fast stream processing system that makes it easy to set up clusters as you scale your data processing. Flink will help you with your report generation and make it easy to handle processing this streaming data in a fast, robust, and fault tolerant (that's a lot of buzz words) fashion.
Please take a look at the flink programming guide or the data-artisans training sessions on this topic. Note that the problem of doing SQL queries using flink is not solved (yet) this feature is planned to be released this year. However, flink will solve all your data processing problems in terms of the cross table reports and preprocessing for storage in a relational database or distributed filesystem.
For storing this data and making it available you need to use something fast but just as robust as mysql, the 'correct' solution at this time if you are not using all the columns of your table is using a columnar solution. From googles cloud you have bigquery, from the open source ecosystem you have drill, kudu, parquet, impala and many many more. You can also try using postgres or rethinkdb for a full relational solution or HDFS/QFS + ignite + flink from the hadoop ecosystem.
For the problem of interactively working with your data, try using Apache Zeppelin (free, scala required I think) or Databricks (paid but with lots of features, spark only i think). Or take the results of your query from flink or similar and interactively analyze those using jupyter/ipython(the solution I use).
The short answer is, dust off your old java textbooks. If you don't have a java dev on your team and aren't planning on hiring one, the google dataflow solution is way easier and cheaper in terms of engineering. If you help I do need an internship ;)
If you want to look at all the possible solutions from the hadoop ecosystem look at:
For google cloud ecosystem it's all there on their website.
Happy coding!
Oops, it seems I left out ingestion, I would use kafka or spring reactor.
P.S The flink mailing list is very friendly, try asking this question there.
Although it isn't fool proof, obviously better than not doing it.
What an incredible thought! Though, given the noise to signal ratio round here, one that I fear you may be alone in thinking.
Even non-meta questions can be rather lazy...I mean a couple of throw away sentences that don't provide much context suggest that it's probably not that important.
For example:
Versus:
While I don't think of "Ask HN" as StackOverflow, there's something to the response "What <code> have you tried?" and the idea that a two sentence question doesn't necessarily deserve a long detailed comprehensive answer.
so I guess what I"m saying is that I'm not particularly surprised by its speed, because a lot of the stories submitted to deserve to decline quickly
It's not exactly that but exists.
It's an incredibly sparse list though, given GitHub's popularity. Compare this Atlassian's marketplace...
which seems to include everybody, both big and small.
The most valuable thing Github has is the enormous portfolio of FOSS projects and all the free eyeballs that come with it. Yes, it's not paid, but because its public offerings are so popular, most developers are familiar with it and that gives it a trusted inlet to basically every software organization in existence. After all, in a non-dysfunctional organization, the guy who decides what products to buy to support their developers should give far more weight to what those developers want, than what is said by a vendor salesman whose job it is to convince them to buy a particular product.
Which means it's a mistake to neglect their FOSS users -- it seems self-evident that the biggest, best, most cost-effective way for Github to sell its paid features is word-of-mouth from its free users. It's very hard for a competitor to replicate their enormous network effect, which is also what makes it so effective. Their underwhelming response to the "dear github" letter suggests that their upper management is blind to this. I think there's a serious possibility that, in the next five to ten years, their position will be as marginalized as, say, Sourceforge is today -- long ago it was the "gold standard" in hosting services, but today it's only used by barely-maintained projects who can't even scrape together the resources needed to change their code hosting provider.
The idea was based on our experience that you spend too much time searching through code as a developer. Coati makes it much easier to see how the different parts of the software play together.
For example, I've seen many Scala programmers struggle with achieving maximal type safety due to getting bogged down in boilerplate. To attack this problem (as I see it anyway, but that's all which matters for now) I'm researching ways of utilizing Scala macros to cut down on such boilerplate while retaining type safety.
This has been huge for my own side work (which means the utility is definitely there), but I'm still uncertain as to the cost, i.e. what effects my approach might have on a "serious" commercial project. I'm just going to have to find out the old fashioned way.
A DIY sensor needs to either be some kind of test strip or a needle. Both are a lot easier to just get through insurance than to mimic.
I'm sure you could perform the chemical reactions yourself, but you'll probably find whatever you make will need to be replaced frequently. Meanwhile, the software, modified Android phones, etc. last a long longer, so that's where is the action.
The challenge for the homebrewer is to build something traceable. When you measure blood sugar today the same sample should yield the same number - not only today but also ten years from now. Yes, Theranos is fighting with traceability, too.
It's not necessarily a bad idea to play around with MOOCs to take a look at other skills while working at your job, but if a university course wasn't enough to make up your mind a MOOC won't be either.
(In general, a thesis or internship is a good way to look deeply into a specific niche. But if you're three months from graduating, I don't think that advice will help you...)
More schooling will teach more of the sort of things that are taught in school. A job will teach the sort of things that are taught on a job.
If the priority is learning more of the things that are taught in school, get a graduate degree. There is nothing to keep a person from spending time on MOOC's while working. A lot of people do.
Work is not like school, most new grads will learn a lot really fast because the learning is by doing alongside other people with more experience in a culture with a great deal of institutional experience in the thing that is being done.
To put it another way, if there's some really interesting MOOC, take it now.
Good luck.
The thing with doing MOOCs on your own is it seems easy to get lazy and end up wasting a lot of time with nothing to show on your resume.
Email them and say "I'd love to work at your company in a year, what can I do to prepare".
They'll tell you. You do want to get a job, be it contracting or something, so you have some professional experience.
But the main thing is you learn what you need to learn, you figure out if you need some github contributions, moocs, read a books, etc.
Your app would have to be great at non-secure notes AND have an option to add secure notes.
Evernote, btw, does support secure (encrypted) notes. They have a lousy UI for them but the option is there.
If you don't think that your app is better in at least some ways than existing note-taking apps, that having secure notes will not make a difference.
* Emacs (desktop / laptop editor)
* Orgzly (Android editor)
* org-mode (the note mechanism itself)
* Unison (for file sync)
* Ubuntu LTS + OpenSSH (on the file server)
Happy to provide more detail if you're interested.
Stord.io is a key/value store. This is often modelled as a hashmap or a dictionary in programming languages.
Under the hood, stord.io is powered by Redis, with a thin python application wrapper, based on Flask.Stord.io doesnt assume anything about your data, make whatever nested schema you want!
Full disclosure: if this wasn't already clear, it's my project. I would LOVE feedback/feature suggestions.
What are the key/value durability requirements? (OK to drop values now and then, or does it need to keep them until the end of time?). Need backups? Do values expire, or do you have to expire them manually? Since you can't enumerate or search, how do you delete things? Allowed sizes of keys and values, between bytes and terabytes? How far should it scale? Shared namespace, or namespace per user? Do you need a latency guarantee? How low? Are you gonna use it for something important and need an SLA on the availability of the service as a whole?
A couple of "nearby" points in the solution space:
Amazon S3 is a KV store where the keys look like filenames and the values look like files. High durability, good scaling, pretty high latency. You could also obviously paper a KV store on top of ElastiCache or DynamoDB, which are going to have different properties.
Going low-level and implementing your own in say, golang would probably be the most fun though :p
Hard to say if we could use a SAAS KV store at work without a lot more technical detail on the solution. I'm having a hard time thinking of an app where you'd want a KV store, but not need a database or NoSQL store which you could use instead.
Those short URLs are often being used in mass mailings, guestbooks, comment forms etc. and they'll get reported pretty quickly to URL blacklists. That gives you the chance to disable the shady short URls before too many people come across them.
Here is a list of URL blacklist providers that you should check each URL against, both before accepting it into your database and again before you deliver it to the user:
multi.surbl.org, uribl.swinog.ch, dbl.spamhaus.org, url.rbl.jp, uribl.spameatingmonkey.net, iadb.isipp.com, dnsbl.sorbs.net
You can find out more about this stuff on
Since I've implemented these checks I only receive complaint emails every other month and no contact from the authorities so far (in contrast to the disposable email services I run).
When you get a complaint about a URL, your software should allow you to disable all the URLs of the reported domain. There are times when the spammers have taken over a forum (or any site really) and created a large amount of spammy content.
Hope this helps.
My first thought is to wonder why someone would want to be in a space where an arms race against people devoted to child porn was both necessary and constant. Particularly when that space wasn't providing capital sufficient to retain a lawyer.
My gut tells me that as a matter of will, it's going to be hard to keep this class of activity from reoccurring regardless of how this incident works out and that scaling the service will scale the headaches of monitoring and policing user behavior along with it. Personally, I'd rather deal with users I liked. YMMV.
Good luck.
Take a look at the Center for Missing and Exploited children and perhaps call them. They operate a tip line to report this kind of activity. Sad that we need to think about these things.
In practice we paired when doing difficult stuff. It worked well.
Tips:
Don't pair at your desk. Use a pairing station.
Pair for a task, short if possible. If not, timebox.
Pair for short periods!
Train yourself to be productive while pairing. Don't relax. A short period of hard work.
Pick a consistent pairing time and make it a habit. Such as after standup, after lunch, whatever. Some times when you would not be productive solo, like after lunch, you can be productive in a pair. Experiment.
Failure modes:
Long, unproductive, exhausting pairing periods. People will quit.
That one guy that nobody wants to pair with. Happens, sorry.
Sitting there twiddling your thumbs while your pair partner writes an email. Only pair for coding / debugging / testing! Don't pair at your desk.
As a fast touch typer I preferred to be the one at the keyboard. I sometimes like to sketch things out first to test my initial idea.
I think pair programming can be extremely effective and fun when done in an ambitious work environment with open minded people who can work well with others. I much prefer doing pair programming than not since it's an opportunity to discuss requirements/design/solutions and also a kind of code review before the actual code review.
Coding on your own hides wrong assumptions, incorrect thinking, lack of teamwork/collaboration, misunderstandings and code quality issues which could likely to be found in pair programming sessions before a code review. It can be a great synergy when trying to solve complex problems where two people balance up different aspects of problem solving.
But all day pair programming would drive me crazy.
Pair programming glorifies the task of programming as overly difficult. Solving problems can be difficult, programming them shouldn't be. Solving a tough problem in a code editor is not a good idea, IMO.
For instance, the machine learning group (Yoshua Bengio, Ian Goodfellow, et al.) at the University of Montreal (the people behind open source software like Theano [2], Pylearn 2 [3], etc.) regularly makes papers available on arXiv, and is currently working on a book about Deep Learning, drafts of which are freely available [4].
[0]:[1]:[2]:[3]:[4: | http://hackerbra.in/ask/1456491902 | CC-MAIN-2018-51 | refinedweb | 8,469 | 70.13 |
I have successfully attached a BMP085 board to a Raspberry Pi and am logging pressure and temperature to cosm.com. This was fairly easy as I simply followed the instructions.
Then, I added a second I2C device a Honeywell HIH6131 which is a humidity and temperature sensor.
Finally, I wrote code (well maybe hacked is a better description) but it is not working correctly and would like some help.
First let me explain the HIH6131 which resides at the I2C address of 0x27. From the data sheet it does not have registers rather you simply read and write values. So the only write command is a "measurement request" command which causes the device to initiate a measurement. The command is shown in figure 1.
From the data sheet it is "a Measurement Request command consists of the Slave address plus the WRITE bit (0). Once the sensor responds with an acknowledge (ACK), the Master generates a stop condition."
Figure 1
Next I can either read two bytes for a humidity reading or four bytes for a humidity and temperature reading. For this question I will focus on a two byte humidity reading which is shown in figure 2.
Figure 2
From the data sheet "the Master generates a START condition and sends the sensor Slave address followed by a read bit (shown in Figure 2). After the sensor generates an acknowledge (ACK), it will transmit up to four bytes of data – the first two bytes containing the compensated temperature output and the second two bytes containing the optional compensated temperature output.
Now my testing. I am able to confirm that both devices are present as a sudo i2cdetect -y 0 command reveals both the BMP085 at 0x77 and the HIH6131 at 0x27.
Second, I am convinced the wiring of my new HIH6131 device is working because if I remove the clock wire to the HIH6131 I get "Error accessing 0x27: Check your I2C address" which of course is the correct device.
The problem is that I read back the same byte every time. So a two byte read is two bytes of the same value and a four byte read is four. However, they will change in value if I breath hot air on the sensor".
So, I think that tells me that I am issuing the measurement request since the byte is changing and therefore my problem is in reading the data back.
Now I will describe the part of my code where it goes wrong.
The first thing I did is added two commands to Adafruit_I2C.py:
Code: Select all
def write0(self): "Puts only device address on bus with write bit set" try: self.bus.write_quick(self.address) if (self.debug): print("I2C: Cannot access device") except IOError, err: print "Error accessing 0x%02X: Check your I2C address" % self.address return -1 def read0(self): "reads I2C bus" try: result = self.bus.read_byte(self.address) if (self.debug): print "I2C: Device 0x%02X error" % self.address return result except IOError, err: print "Error accessing 0x%02X: Check your I2C address" % self.address return -1
Then I created a new file called Adafruit_HIH6131.py and used the same format as Adafruit_BMP085.py.
I will focus on the two byte humidity read command:
Code: Select all
def readRawHumidity(self): # byte 1 = humidity msb, byte 2 = humidity lsb "Reads the raw (uncompensated) humidity from the sensor" self.i2c.write0() time.sleep(0.500) # allow time for the conversion msb = self.i2c.read0() lsb = self.i2c.read0() raw = (msb << 8) + lsb return raw
Can anyone help me?
Thank you. | https://www.raspberrypi.org/forums/viewtopic.php?p=261193 | CC-MAIN-2020-24 | refinedweb | 598 | 64 |
Agenda
See also: IRC log
->
Accepted.
->
Accepted.
Regrets from Paul.
Still no progress. Norm notes that the Charter expires before November.
Henry: I think saying "yes" now is important even if the answer is only maybe.
Norm: I'm going to say
"yes"
... We can decide if we really have critical mass, and an extended charter, a little closer and back out if necessary.
Norm: One other thing:
... Sonoa systems hasn't shown up in ages and can't be reached anymore, can we please declare them no longer in good standing?
Paul: You're supposed to contact the AC rep.
Henry: He is the AC rep.
<scribe> ACTION: Henry: mark Sonoa system as no longer in good standing. [recorded in]
->
Norm attempts to describe the thread
Richard: I haven't thought much
about this.
... Aren't namespaces supposed to handle this? We could use parameters in the XProc namespace and the fact that you couldn't pass those to the stylesheet appears negligible.
<Zakim> MSM, you wanted to ask how validation is trickier with just one GI; validation seems easier to me with distinct GIs
MSM: How is validation harder? We could do what Richard says and still pass them to the process. You just wouldn't be able to have different values for them.
<MSM> pipeline ::= (step | #any)*
<MSM> allows anything that matches the wildcard to be ignored.
<ht> Subst group is the XML Schema technology
Norm attempts to describe what he recalls at Murray's place. Mostly, I think we just didn't think about it hard enough.
Alex: The hardest part is that if you say your environment must validate before compiling a pipeline then the user will have to augment the schema if they add a new component type.
Norm: Yeah, but presumably that's a quality of implementation issue.
<MSM> <xsd:schema><xsd:element</xsd:schema>
Alex: Yes, but we're putting that one small barrier there.
<MSM> [A one-liner is really all you need. I agree with AM that we should consider it, but I think it's easy enough.]
Henry: I find this a difficult
call. I think the crucial difference is that you can do this
with schema languages using the relevant mechanisms.
... But in all three cases, if we go this route, you must do that or your document isn't valid if you've added new components.
<MSM> Henry, what role do you expect the notion of 'validity' to play?
Henry: Whereas if we go with the
status quo, then your document is valid. You don't have to do
anything, the published schemas will validate your
pipeline.
... That's just a fact, but I don't know if it matters. My inclination is to favor the change because if it means that people who utter extensions will have to get the framework right.
... If you have to use Widgets, Inc.'s schema in order to use their extensions, then that's a good consistency check.
... That tends to make me think that it's a good idea.
Alex: I'm really in favor of
this, but I still want to poke holes in it.
... We've said that we want our language to be open, so you can add documention, etc.
... That means that these things would be wildcards and that makes steps that are extensions would just be passed off as things that wouldn't be validated.
Henry: I don't want to go that route. I tend to think of it in terms of substitution groups. They only way you can do this is by identifying the abstract p:step as the substitution group head.
Alex: That means that we have to come up with some other mechanism to embed documentation.
Henry: Extension elements have no semantics. We said in the schema design that you can sprinkle elements and attributes to your hearts content but they have no impact on the validation semantics.
Richard: I think this is a complete red herring. No one's going to validate them, they're just going to run them through a pipeline processor and get better messages that way.
<Zakim> MSM, you wanted to ask what a pipeline processor should normally do with <p:pipeline><p:step .../><my:element .../></p:pipeline>
<alexmilowski> (yes... e.g. no one validates an XSLT transformation document)
Michael: Our current design is that given a pipeline as above, my:element will be ignored.
Norm: Yes.
Michael: In that case, I don't
think Henry quite answered Alex's question.
... If we're going to accept a pipeline like above, then I don't have to provide a substitution group to make the document valid.
Henry: You're right.
... If you've failed to do so then nothing will happen.
Michael: That depends purely on
whether or not the pipeline processor uses the substitution
group information.
... It's possible to write a processor such that it validates and then uses the PSVI information.
Richard: That's an interoperability nightmare.
Henry: We haven't tackled the question of how you make the syntax/semantics link for new steps.
Murray: This conversation is
coming at weird angles for me.
... We have a mechanism for declaring steps, right?
... I would have thought that's were we'd be talking about this.
<richard> i agree with murray: we tell the pipeline about steps by declaring them, not by a schema
Murray: If I want a my:foo then
I'd have to declare it. I would have thought that it would be
possible to read that and generate a bit of schema if you
wanted to satisfy the validation.
... And you could not bother with the validation if you just didn't care.
... The implementation is going to get it's information about the step from that declaration.
<MSM> If an extension step is <p:step type="my:newstep" ... />, we can still get a validity story (for those who want to have one): p:step/@type is typed union of p:built-ins, my:extensionsteps, xs:QName, xs:string; you can still use validation to tell whether your pipeline is going to be processed reliably.
<Zakim> ht, you wanted to disagree with richard
Henry: I think you're right, but
going a little further I'm still worried about the
interoperability story in the non-chameleon case.
... Consider Michael's pipeline: <p:xslt>...</p:xslt><my:step>...</my:step>
... Now consider two impls: one produced by the owner of the my: namespace with the step declaration built in.
... Now consider Norm's impl. It doesn't have any builtin step definition for my:step so it ignores the my:step.
<richard> is it allowed for implementations to have extra built-in step types? shouldn't you have to import a library to access them?
<MSM> Henry, what does the second implementation do with the declaration of my:step ?
<richard> bingo!
Henry: I think that means you
must declare every step that you use other than the ones in the
spec.
... I wanted to remark that I disagree with Richard about the utility of validating without running. I often use validation on things I can't run as a first order check.
<Zakim> MoZ, you wanted to give his two levels of disagreement on p:xslt
Mohamed: I think the requirement of validation is a strong requirement. Authoring tools must follow a schema or something like that. We need to have a strong way to declare what is in the XProc definition at the start.
<MSM> [I suspect it might be a good idea to make a point of recording design principles we discover, such as "if a pipeline is not interoperable, then we must design the spec so that processors which cannot support it (a) can detect the fact that they don't support it and (b) must say so. " If we have that written down, I don't know where. If we don't, and agree on it, we should get it written down.]
Mohamed: It must be clear.
Effectively, one person's user define step could be taken as a
special annotation. We can't have a fallback to not knowing
what the user meant by that user-defined namespace.
... With the p:step the declaration of the name was an indication.
... The content of the p:step was also defined. We knew what we would find in a step. In a my:component, I don't know what I'm going to find.
Richard: That raises a good point. Suppose you write a schema for a pipeline that allows extra things. Presumably that's not going to work.
<ht> I can summarise the observation that Murray's point led me to as "Conformant processors MUST NOT treat elements not defined as steps in this specification as steps unless there is an _explicit_ declare-step-type for it in the pipeline or in a library it includes"
Mohamed: That's why I'm opposed to p:xslt and prefer p:step.
Alex: In the email thread, I said that we should identify extension namespaces (like XSLT)
->
Alex: I'm not sure I want to require such an attribute, but it is a nice double check.
<MSM> [Alex, remember though that that feature in XSLT doesn't map to any existing schema language -- it requires some rather ad hoc checks.]
Norm and Alex discuss the declaration vs. namespace aspect.
<Zakim> MSM, you wanted to propose a strawman (? or real?) argument going the other way.
Michael: I wanted to observe that
if we want to have schema validity be a useful proxy for
interoperably processable, then that doesn't actually cut the
one direction.
... You can make a schema for p:step that would require extension steps to be declared, you could make one that allows them but recovers if they're not, etc.
... Specifically, if you wanted to be able to detect the presence of undeclared steps you could make the step's type attribute a union of the builtin names plus the names that get populated when the user writes an extension.
<Zakim> ht, you wanted to a) check what Richard/MoZ were saying and b) comment on AM's point
Henry: I'm not sure I understood
what Mohamed and Richard were saying.
... We don't have to require validation with a normative schema in order to use one to define the semantics and constraints.
ht, you got dropped!
Richard: In the current system, if you misspell a step name then you get an error.
<alexmilowski> yes
Richard: In the other system, if
you misspell a step name, isn't it just ignored?
... If that's true then this seems to be really bad for error detection.
<alexmilowski> ...that is why I wanted that "extension namespace" declaration...
Henry: I think that's a real issue.
Richard: If we were to go for this then I think we'd have to have an extension namespaces element to declare the things that could be ignored if they were unknonwn.
Henry: All I was trying to say
was that if we don't require validation, we might still choose
to use a schema to put conditions on acceptable input.
... If we do that then I think we can still say that every user defined step must have the following abstract content model.
... I don't think there's a vulnerability there to people smuggling in all sorts of nonsense.
... I had hoped that the requirement for every step to have a declaration would be sufficient to ensure interoperability. But Richard is correct that it's not as robust with respect to spelling mistakes.
<MSM> [N.B. To protect against smuggling in arbitrary nonsense, the normative schema would need to block declaration or substitution of extensions to the step type. Just using substitution groups doesn't give the protection HT was describing.]
Henry: It seems to me that there
are at least two ways to resolve that: one is to say that you
have to declare the type and note that the namespace is an
extension namespace.
... Another possibility which I think I might prefer is to say that you have to declare your ignore-me namespaces.
Norm: Yes, I like that a little better.
Alex: Henry's last comment is exactly what I was going to say.
Straw poll: Shall we use the status quo of p:step type="p:xxx" or the proposed change to use p:xxx as the name of the element for the step.
<MSM> question: how is the type attribute declared / to be declared?
<MSM> or does that matter? does the status quo specify?
Results: four in favor of the change, three for the status quo, one abstention. That's not consensus for a change.
Henry: The one thing I never said is that the change allows us to explore the use of attributes on these elements that would be a little odd otherwise.
Paul: I didn't feel strongly.
Richard: I didn't feel strongly either.
Henry: Come back to this a week later?
Alex: Maybe see some pipelines?
<MSM> give someone an action to summarize the question, the options, and the arguments each way
Richard: I think we've exposed a
lot of the issues talking about it today.
... There isn't really very much to choose between them.
Henry: I think we should take
Alex's offer up.
... I'll try to recast some examples too.
... And I'll rewrite my DTD.
... I think brevity is really important.
Norm: Ok, I'll leave it open one more week.
None.
Adjourned. | http://www.w3.org/XML/XProc/2007/02/15-minutes.html | CC-MAIN-2016-26 | refinedweb | 2,270 | 73.17 |
The drawback to the safety system’s process of copying data is that it also isolates the results of a job within each copy. To overcome this limitation you need to store the results in a type of shared memory called NativeContainer.
A
NativeContainer is a managed value type that provides a relatively safe C# wrapper for native memory. It contains a pointer to an unmanaged allocation. When used with the Unity C# Job System, a
NativeContainer allows a job to access data shared with the main thread rather than working with a copy.
Unity ships with a
NativeContainer called NativeArray. You can also manipulate a
NativeArray with NativeSlice to get a subset of the
NativeArray from a particular position to a certain length.
Note: The Entity Component System (ECS) package extends the
Unity.Collections namespace to include other types of
NativeContainer:
NativeList- a resizable
NativeArray.
NativeHashMap- key and value pairs.
NativeMultiHashMap- multiple values per key.
NativeQueue- a first in, first out (FIFO) queue.
The safety system is built into all
NativeContainer types. It tracks what is reading and writing to any
NativeContainer.
Note: All safety checks on
NativeContainer types (such as out of bounds checks, deallocation checks, and race condition checks) are only available in the Unity Editor and Play Mode.
Part of this safety system is the DisposeSentinel and AtomicSafetyHandle. The
DisposeSentinel detects memory leaks and gives you an error if you have not correctly freed your memory. Triggering the memory leak error happens long after the leak occurred.
Use the
AtomicSafetyHandle to transfer ownership of a
NativeContainer in code. For example, if two scheduled jobs are writing to the same
NativeArray, the safety system throws an exception with a clear error message that explains why and how to solve the problem. The safety system throws this exception when you schedule the offending job.
In this case, you can schedule a job with a dependency. The first job can write to the
NativeContainer, and once it has finished executing, the next job can then safely read and write to that same
NativeContainer. The read and write restrictions also apply when accessing data from the main thread. The safety system does allow multiple jobs to read from the same data in parallel.
By default, when a job has access to a
NativeContainer, it has both read and write access. This configuration can slow performance. The C# Job System does not allow you to schedule a job that has write access to a
NativeContainer at the same time as another job that is writing to it.
If a job does not need to write to a
NativeContainer, mark the
NativeContainer with the
[ReadOnly] attribute, like so:
[ReadOnly] public NativeArray<int> input;
In the above example, you can execute the job at the same time as other jobs that also have read-only access to the first
NativeArray.
Note: There is no protection against accessing static data from within a job. Accessing static data circumvents all safety systems and can crash Unity. For more information, see C# Job System tips and troubleshooting.
When creating a
NativeContainer, you must specify the type of memory allocation you need. The allocation type depends on the length of time the job runs. This way you can tailor the allocation to get the best performance possible in each situation.
There are three Allocator types for
NativeContainer memory allocation and release. You need to specify the appropriate one when instantiating your
NativeContainer.
NativeContainerallocations using
Tempto jobs. You also need to call the
Disposemethod before you return from the method call (such as MonoBehaviour.Update, or any other callback from native to managed code).
Tempbut is faster than
Persistent. It is for allocations within a lifespan of four frames and is thread-safe. If you don’t
Disposeof it within four frames, the console prints a warning, generated from the native code. Most small jobs use this
NativeContainerallocation type.
NativeContainerallocation type. You should not use
Persistentwhere performance is essential.
For example:
NativeArray<float> result = new NativeArray<float>(1, Allocator.TempJob);
Note: The number 1 in the example above indicates the size of the
NativeArray. In this case, it has only one array element (as it only stores one piece of data in
result).
2018–06–15 Page published
C# Job System exposed in 2018.1 NewIn20181
Did you find this page useful? Please give it a rating: | https://docs.unity3d.com/Manual/JobSystemNativeContainer.html | CC-MAIN-2020-16 | refinedweb | 729 | 57.27 |
I'm creating an Anagram Solver in Python 2.7.
The solver takes a user inputted anagram, converts each letter to a list item and then checks the list items against lines of a '.txt' file, appending any words that match the anagram's letters to a
possible_words
# Anagram_Solver.py
anagram = list(raw_input("Enter an Anagram: ").lower())
possible_words = []
with file('wordsEn.txt', 'r') as f:
for line in f:
if all(x in line + '\n' for x in anagram) and len(line) == len(anagram) + 1:
line = line.strip()
possible_words.append(line)
print "\n".join(possible_words)
Your code does as it's expected. You haven't actually made it check whether a letter appears twice (or 3+ times), it just checks
if 'l' in word twice, which will always be True for all words with at least one
l.
One method would be to count the letters of each word. If the letter counts are equal, then it is an anagram. This can be achieved easily with the collections.Counter class:
from collections import Counter anagram = raw_input("Enter an Anagram: ").lower() with file('wordsEn.txt', 'r') as f: for line in f: line = line.strip() if Counter(anagram) == Counter(line): possible_words.append(line) print "\n".join(possible_words)
Another method would be to use sorted() function, as suggested by Chris in the other answer's comments. This sorts the letters in both the anagram and line into alphabetical order, and then checks to see if they match. This process runs faster than the collections method.
anagram = raw_input("Enter an Anagram: ").lower() with file('wordsEn.txt', 'r') as f: for line in f: line = line.strip() if sorted(anagram) == sorted(line): possible_words.append(line) print "\n".join(possible_words) | https://codedump.io/share/gVwWEuHe7PX2/1/python---checking-if-all-and-only-the-letters-in-a-list-match-those-in-a-string | CC-MAIN-2017-04 | refinedweb | 285 | 69.99 |
Whether we put it in configure.in or inline, I've learned that we should be doing this (Note the use of int instead of ssize_t) and the definitions of PY_SSIZE_T_MAX and PY_SSIZE_T_MIN. There is a python article about preferred methods of maintaining backwards compatibility at #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #endif On 05/04/09 10:13 PM, "保坂範行" <address@hidden> wrote: > Hi, MichealP. > >> #ifndef Py_ssize_t >> typedef size_t Py_ssize_t; >> #endif >> #endif > It works. > But I do not believe this is right way to fix. > > Maybe configure scripts task? > When detecting python version, > if got <2.5, then define Py_ssize_t. > > Nori > > > | http://lists.gnu.org/archive/html/bug-gnubg/2009-04/msg00032.html | CC-MAIN-2016-40 | refinedweb | 110 | 68.47 |
Summary: Use Windows PowerShell to retrieve the power plan settings for your computer. The Microsoft Scripting Guys show you how.
Hey, Scripting Guy! I need to have a way to easily retrieve the power plan settings for the active power plan on my computer. I would like to have an easy to read display of the setting name, the allowable values, and the current value for when the computer is on battery power and for when it is on AC power. I know this seems like a lot to ask, but can Windows PowerShell retrieve this information for me?
— LC
Microsoft Scripting Guy Ed Wilson here. Today is Friday; at least it is if you live in Charlotte, North Carolina, and you are a Scripting Guy who is working on next week’s Hey, Scripting Guy! Blog posts. Better than the fact that it is Friday, it is actually Friday afternoon and as soon as this article is completed, I plan on securing for the day. Not that I will turn off my computer, or even that I will log out of the Redmond domain at work, but my writing mode will shut down and my play mode will kick in. I have a really complex WMI script I have been knocking around for the last two days, and I want to dig into it and figure out why it is not providing me the information I desire. As far as I can tell, no one has ever written a WMI script to do what I am working on, including the product group that wrote the WMI class I am messing around with. I did get a 1,500-line VBScript from one of the test engineers to exercise the class, but dude! I was hoping for something a bit clearer. I am going to fire up the WMI administrative tools, and dig into the various class associations to see if I can figure out the relationships. I am really looking forward to it.
Anyway, LC, I figure you are not interested in a 1,500-line VBScript, or even a 200-line Windows PowerShell script. So here you go–four lines of code. Admittedly, some it is a bit compact, but I will spend the next 2,000 words explaining it. The complete Get-ActivePowerPlanSettingsPwrCfg.ps1 script is shown here.
Get-ActivePowerPlanSettingsPwrCfg.ps1
$plan = Get-WmiObject -Class win32_powerplan -Namespace root\cimv2\power `
-Filter “isActive=’true'”
$regex = [regex]“{(.*?)}$”
$planGuid = $regex.Match($plan.instanceID.Tostring()).groups[1].value
powercfg -query $planGuid
I love using WMI to make command-line utilities more manageable. The PowerCfg.exe utility is a cool tool for interactively exploring and manipulating the power settings. One problem is the plethora of switches and the fact it relies on the power plan GUID for many operations. This means retrieving the GUID for the present power plan, and either copying it to the clipboard (assuming your current console has copy/paste enabled) or doing a lot of writing and typing. Or performing impressive memory feats.
In the Get-ActivePowerPlanSettingsPwrCfg.ps1 script, I basically “cheat.” I use WMI to retrieve the current power plan, use regular expressions to retrieve the GUID for the active power plan, and then pass the GUID for the active power plan to the powercfg.exe utility and tell it to retrieve the settings for the plan. There are essentially three steps:
WMI query
Regular expression to parse the GUID
Call to the Powercfg executable with the appropriate parameters and arguments
The Get-ActivePowerPlanSettingsPwrCfg.ps1 script consists of four logical lines (the first line, the WMI query, is broken into two lines because of limitations of displaying long lines of code on the blog platform. The backtick character (`) in Windows PowerShell is the line continuation character.
The query to the Win32_PowerPlan WMI class was discussed in yesterday’s Hey, Scripting Guy! Blog post.
The information that will be stored in the $plan variable is shown here:
PS C:\> Get-WmiObject -Class win32_powerplan -Namespace root\cimv2\power
-Filter “is Active=’true'”
PS C:\>
__GENUS : 2
__CLASS : Win32_PowerPlan
__SUPERCLASS : CIM_SettingData
__DYNASTY : CIM_ManagedElement
__RELPATH : Win32_PowerPlan.InstanceID=“Microsoft:PowerPlan\\{1bef50e5-557d-
4b3b-9b29-cdde74fcfd30}”
__PROPERTY_COUNT : 7
__DERIVATION : {CIM_SettingData, CIM_ManagedElement}
__SERVER : MRED1
__NAMESPACE : root\cimv2\power
__PATH : \\MRED1\root\cimv2\power:Win32_PowerPlan.InstanceID=“Microsoft:P
owerPlan\\{1bef50e5-557d-4b3b-9b29-cdde74fcfd30}”
Caption :
ChangeableType :
ConfigurationName :
Description :
ElementName : My Custom Plan 1
InstanceID : Microsoft:PowerPlan\{1bef50e5-557d-4b3b-9b29-cdde74fcfd30}
IsActive : True
There are only three properties that display any kind of interesting information: elementname, instanceID, and IsActive. Of those three properties, the only one we need for the Get-ActivePowerPlanSettingsPwrCfg.ps1 script is the InstanceID. Unfortunately, the InstanceID that is used by WMI is different than the GUID that is used by the PowerCfg.exe utility.
By comparing the results of a WMI Query that only returns the InstanceID with a list of power schemes retrieved by the PowerCfg utility, it becomes apparent that it is possible to manipulate the WMI data to retrieve the GUID. The output from WMI and from PowerCfg is shown here:
PS C:\> (Get-WmiObject -Class win32_powerplan -Namespace root\cimv2\power -Filter “is
Active=’true'”).InstanceID
Microsoft:PowerPlan\{1bef50e5-557d-4b3b-9b29-cdde74fcfd30}
PS C:\> powercfg -list
PS C:\>
Existing Power Schemes (* Active)
———————————–
Power Scheme GUID: 1bef50e5-557d-4b3b-9b29-cdde74fcfd30 (My Custom Plan 1) *)
It would be possible to use string manipulation to retrieve the GUID from the WMI information. By using the IndexOf method from the system.string .NET Framework class, and the substring method from the same class, the location of the “{“ and the “}” can be determined and the length of the characters determined. When the start position and the length are known, the substring method returns the GUID from the WMI InstanceID. This is shown here:
PS C:\> $guid = (Get-WmiObject -Class win32_powerplan -Namespace root\cimv2\power `
-Filter “isActive=’true'”).InstanceID.tostring()
PS C:\> $guid.IndexOf(“{“)
20
PS C:\> $guid.IndexOf(“}”)
57
PS C:\> $guid.Substring(21,36)
1bef50e5-557d-4b3b-9b29-cdde74fcfd30
PS C:\>
By the way, to figure out the length of the GUID, I did not count up the letters, numbers, and dashes. That is way too confusing. I used the Measure-Object cmdlet with the character parameter. The alias for the Measure-Object cmdlet is measure. Therefore, the command is shown here. (Windows PowerShell is smart enough to ignore the “” that are required to supply a string to the Windows PowerShell console. Therefore, the string actually has 36 characters in it. You do not have to subtract 2 from this number to use it with substring).
PS C:\> “1bef50e5-557d-4b3b-9b29-cdde74fcfd30” | measure -Character
Lines Words Characters Property
—– —– ———- ——–
36
PS C:\>
Before Windows PowerShell came along, I used Notepad to do my counting for me. Notice the cursor position indicator in the lower right corner of the following image. The number states that it is on line 1 and column 37 in Notepad; therefore, you need to always subtract one from the column number indicated because it is telling you where the first blank space resides.
The hardest part about using regular expressions is figuring out the pattern. We have several good Hey, Scripting Guy! Blog posts that talk about using regular expressions with VBScript as well as with Windows PowerShell. The VBScript regular expression articles are useful for Windows PowerShell scripters because they include information about the regular expression pattern. By the same token, the Windows PowerShell regular expression articles are of use to VBScript scripters.
The regular expression pattern that is used here is composed of eight characters that make up six different commands. The characters in the regex pattern are shown in Table 1.
Table 1
Because there is only one active power plan, it is possible to retrieve the InstanceID directly, and then convert it to a string. In the Get-ActivePowerPlanSettingsPwrCfg.ps1 script, I did not do this. Rather, I stored the entire object in the $plan variable. But for testing from the command line, this works out well. $guid will contain the following information:
PS C:\> $guid
Microsoft:PowerPlan\{1bef50e5-557d-4b3b-9b29-cdde74fcfd30}
PS C:\>
After the InstanceID has been converted to a string and stored in the $guid variable, the regex pattern is assigned to a variable called $regex. To create our regular expression pattern, we place the pattern inside a pair of quotation marks, and use the [regex] type accelerator to “cast” the string to a regex object. You can use the gettype method to check on the type object that has been created. This is shown here:
PS C:\> $regex.gettype()
PS C:\>
IsPublic IsSerial Name BaseType
——– ——– —- ——–
True True Regex System.Object
The match method from the regex object is used to perform the regular expression pattern match on the string that is supplied to the method call. The method returns a match object from the System.Text.RegularExpressions namespace. The match object has a number of methods and properties that are all listed here. GM is an alias for Get-Member and is used to show the members (methods and properties) of the match object:
PS C:\> $regex.Match($guid) | gmTypeName: …
Groups Property System.Text.RegularExpressions.GroupCollection Groups {get;}
Index Property System.Int32 Index {get;}
Length Property System.Int32 Length {get;}
Success Property System.Boolean Success {get;}
Value Property System.String Value {get;}
The cool thing about Windows PowerShell is that the match object that is returned by calling the match method from the regex class automatically expands to display the values of each of the properties. This sequence of commands is shown here, and illustrates how I went from the WMI object to retrieving the GUID:
PS C:\> $guid = (Get-WmiObject -Class win32_powerplan -Namespace root\cimv2\power `
-Filter “isActive=’true'”).InstanceID.tostring()
PS C:\> $regex = [regex]“{(.*?)}$”
PS C:\> $regex.Match($guid)}
The last thing we need to hone in on is the fact that the Groups property actually returns two different values. The first one is the GUID with the { } that were the delimiters for the regex pattern. The curly brackets will mess up the call to powercfg, and therefore it is necessary to remove them. This is where the subexpression came into play. If the regex pattern had been “{.*?}$” without the ( ) that were used in our actual pattern, the second group would not have been created. This is shown here:
PS C:\> $regex = [regex]“{.*}$”
PS C:\> $regex.Match($guid)
PS C:\>
Groups : {}
It would therefore be necessary to come back and remove the { } from the match value. Because our regex pattern {(.*?)}$ contains the sub-expression and therefore returns the second group match, we can index into the collection of groups and choose the second group, the one without the { } surrounding the GUID. When we have the specific group, the value can be directly retrieved. This is shown here. First, I use WMI to store the InstanceID as a string in the $guid variable. Next, I create the regex pattern and call the Match method. Next, I select only the second match group, and finally I display the value of that group:
PS C:\> $guid = (Get-WmiObject -Class win32_powerplan -Namespace root\cimv2\power -Fi
lter “isActive=’true'”).InstanceID.tostring()
PS C:\> $regex = [regex]“{(.*?)}$”
PS C:\> $regex.Match($guid)
Success : True
Captures : {1bef50e5-557d-4b3b-9b29-cdde74fcfd30}
Index : 21
Length : 36
Value : 1bef50e5-557d-4b3b-9b29-cdde74fcfd30 PS C:\> $regex.Match($guid).groups[1]}
PS C:\> $regex.Match($guid).groups[1].value
1bef50e5-557d-4b3b-9b29-cdde74fcfd30
PS C:\>
The last thing that is done is to use powercfg to perform a query for the particular power plan. This is a straightforward command as is shown here:
powercfg -query $planGuid
The results from running the Get-ActivePowerPlanSettingsPwrCfg.ps1 script are shown in the following image.
LC, that is all there is to using WMI and regular expressions to retrieve the active power plan GUID. WMI Week will continue tomorrow when we continue working with WMI power classes.
powercfg -list already shows you current plan marked with '*'. So you can use pipe to parse GUID.
(powercfg /l | ? { $_.Contains('*') -and $_.Contains('GUID')}).Split()[3]
Or more completely in one line:
powercfg /q ((powercfg /l | ? { $_.Contains('*') -and $_.Contains('GUID')}).Split()[3])
The only problem with this example is that it doesn't work! I would cut and paste and example of it failing but the crappy command shell you guys provided won't allow it. Fail and fail again! Good grief, Microsoft!
@Bill Westrup I just checked this example — on my Windows 8 laptop, and the example STILL works. Keep in mind this is a Windows PowerShell Script, so I pasted it into Windows PowerShell ISE. When I wrote it, I used Windows 7, Windows PowerShell 2.0 and the PowerShell ISE. I just ran it on Windows 8, with Windows PowerShell 3.0 and inside the ISE. Keep in mind, that when cutting and pasting from web pages, sometimes crap gets picked up. This was the case here, and after the ` (line continuation mark) in the script, there was a space I had to remove. As far as the PowerShell console, you CAN paste to it. You have two choices: copy the code to the clipboard and RIGHT Click with the mouse into the console. Or using Edit / Paste from the menu accessible by left clicking on the PowerShell icon. For most purposes the ISE is easier to use, and is why we created it. If you want to use the console, I just tested that as well. I copied the script from the web page, to Notepad, removed the line continuation, and pasted into the console. Hope this helps.
Cool! I just scripted sleep on my power laptop locked to my desk.
Now I can logon into it remotely 24×7.
Here is how it works:
C:WindowsSystem32powercfg.exe /SETACVALUEINDEX db310065-829b-4671-9647-2261c00e86ef SUB_SLEEP STANDBYIDLE 172860
Note, your active profile GUID may potentially be different.
Many thanks.
Please don’t treat it as a legal document. This is just a personal entry.
I do not have this WMI-class on my windows-systems.
As an alternative you can also use the code above with just a few modification
To know your current Windows Power Plan Settings using PowerShell:
Get-WmiObject -Class win32_powerplan -Namespace rootcimv2power -Filter "isActive=’true’" | Select ElementName
The Powercfg.exe tool used to have an option to /CREATE a powerscheme. Can this be done via script? My goal is to disable any & all options for sleep. | https://blogs.technet.microsoft.com/heyscriptingguy/2010/08/31/get-windows-power-plan-settings-on-your-computer-by-using-powershell/ | CC-MAIN-2017-26 | refinedweb | 2,415 | 65.12 |
0
def main(): #this program calculates the total price of a meal after inputting cost of food #tip and sales tax print ('Welcome to the Meal Calculator Program') print() #get the cost of food using the input function food_cost = input ("Please enter the price of your meal: ") food_cost = float (food_cost) #calculate tip tip_rate = input ("Tip rate used today is: ") tip_rate = float (tip_rate) #calulate sales tax tax_rate = input ("Tax rate used today is: ") tax_rate = float (tax_rate) #calculate total cost here, using inputted values total_cost = food_cost + (food_cost * tip_rate) + (food_cost * tax_rate) print ('The total cost based on', format(food_cost, '.2f'),\ 'food cost,', format(tip_rate, '.2f'),\ 'tip rate, and', format(tax_rate, '.2f'),\ 'tax rate is : $', format(total_cost, '.2f'),sep=' ') #calls main main()
Essentially, I would like to know how I would go about inputting a food cost, our example is 23.45, and in the output, getting $23.45 . Also, for tip rate, if I input .2, is there a way to get 20% in the output? Or input a percentage? | https://www.daniweb.com/programming/software-development/threads/463071/percentages-and-dollar-signs-in-output | CC-MAIN-2017-17 | refinedweb | 167 | 70.33 |
Revision history for Domain-PublicSuffix 0.15 2019-04-23 20:00 GMT - Refresh PublicSuffix list - Merged pull request from Gavin Carr to explicitly open a file with UTF-8 encoding - Bump Net::IDN::Encode requirement to 2.401 to avoid unicode issues - (#3) Provide a tld and suffix even with asking get_root_domain for a valid suffix that is not a valid domain. Will still report 'Domain not valid', but ->suffix and ->tld will resolve. - Make sure that the error condition from get_root_domain still throws when a root domain is already fired, but that it still returns. 0.14 2016-08-08 16:02 GMT - Release 0.13 2016-08-07 16:02 GMT - Test fixes 0.12 2016-08-05 16:02 GMT - Fix unicode parsing bug 0.11 2016-08-04 17:10 GMT - Remove Data::Validate::Domain dependency by simplifying the domain validity check to very basic sanity checks, with the assumption that egregious errors are either caught upstream, or result in a validity failure after checking the PublicSuffix match. - Update upstream PublicSuffix list 0.10 2014-10-15 01:35 GMT - Update upstream PublicSuffix list 0.09 2013-03-18 03:35 GMT - Include patch from Gavin Carr (GAVINC) to fix domains that evaluate to false 0.08 2013-01-31 15:00 GMT - Update upstream PublicSuffix list 0.07 2012-08-05 21:25 GMT - Typo fix. 0.06 2012-08-05 18:00 GMT - Minor documentation changes in Domain::PublicSuffix and get_root_domain - Switched to new upstream PublicSuffix list - Included patches from Daniel Kahn Gillmor (DKG): - Additional path to support Debian publicsuffix package - Non-zero exit from get_root_domain 0.05 2012-07-17 00:00 GMT - Ridiculously long wait, but at least we have Dist::Zilla and GitHub. - Updated default public suffix file - Included patches from Gavin Carr (GAVINC): - File::Spec fixes - Test file for problematic domains - non-TLD roots (like .co.im) are not getting flagged as RootEnable when they should be - Optionally allow underscores in domain 0.04 2008-10-09 11:30 GMT - Normalized code style - Updated default public suffix file to latest from Mozilla - Bug fixes, thanks to Jason Wieland -- - Documentation fixed to show that new requires a hashref - Path searching for the tld data file now searches from root - Improper code flow after finding a file causes module to break when a data file is defined. 0.03 2008-07-12 19:30 GMT Repackaging with MakeMaker, added basic test suite, updated Mozilla effective_tld data file. 0.02 2008-04-03 22:00 GMT Documentation and namespace fixes, so viewing in CPAN isn't a nightmare. 0.01 2008-03-31 20:00 First release, likely prone to bugs I haven't even thought of. | https://metacpan.org/changes/release/NMELNICK/Domain-PublicSuffix-0.15 | CC-MAIN-2019-26 | refinedweb | 455 | 62.38 |
This a tech tutorial on how to dynamically modify your view on Odoo. In Odoo, once a view record is defined, there is not much possibility of dynamically changing it according to the record(s) that it is showcasing. For example, in its XML definition, you can’t make the ‘string‘ attribute of a field to be the value of another field.
Most of the time, our needs can be solved using selection fields, notably state/type, if the changes we would like to impose are limited to a few variations. But it does not resolve the need to dynamically change the view according to model contents.
It is therefore needed that we override the fields_view_get function in the models.Model. Since apparently its documentation is “scarce” on line, we shall take a detailed tour around it.
This function, being inside the models.Model class, is called whenever odoo is rendering a view of the model. It gets the correct view given the context and returns the data of the field after essential logic treatments.
For example, suppose we have a pricelist model defined as:
class our_pricelist(models.Model):
_name=”our.pricelist”
And we have defined form view and tree view for it. We might even have defined 2 form views, one for default viewing and another to be used when called elsewhere, say, another model.
@api.model
def fields_view_get(self, view_id=None, view_type=’tree’, context=None, toolbar=False,submenu=False):
The fields_view_get will take as argument the view_id and view_type from the system, to do its rendering. These arguments depend on where and how it is called. For example if the menuitem action calls for view_mode=”tree,form”, then the view_type ‘tree’ is given when we click on the menu
Most of time (and in the entirety of this post), we shall not touch the toolbar and submenu here. Their presence is necessary, and we only use it once in calling the super:
result = super(our_pricelist,self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
Now we have done what the old fields_view_get does. However, we wouldn’t override this function if we were content with what it returns! As you have probably guessed, we are going to tinker around this result.
Suppose there are two fields in our_pricelist:
field_a = fields.Char(string=”Field A Char”)
field_b = fields.Date(string=”Field B Date”)
And we would like the label/string of field_a to be the value of field_b. Of course this example doesn’t make much practical sense, but it is an idea easily suited to other needs. We shall come to that later.
Before we hastily modifies the result returned by super’s fields_view_get, bear in mind that this function is called for whichever view under the model (i.e. our_pricelist). For the sake of avoiding making unwanted changes to views that we don’t want to touch, and moreover, prevent error as we might refer to fields that exist in target view but not necessarily in other views, we need to make restriction conditions to ensure that the view we are treating is indeed the target view.
If we have only defined one tree view and one form view, this can be easily done via an ‘if’:
if view_type == ‘form’:
However, if there are more than one form views defined, or there exists the prospect additional views to be added in future modules, it is better to verify the view_id. Both view_type and view_id are provided by system via the function call.
Having ensured that we are treating the right view, we can now set out to modify the string of field_a:
1) First, get the value of field_b via active_id:
active_id = self.env.context.get(‘active_id’, False)
new_string = self.env[‘our.pricelist’].browse(active_id).field_b
2) Add the following to import
from lxml import etree
3) Change the string attribute of field_a
doc = etree.XML(result[‘arch’])
if new_string:
for node in doc.xpath(“//field[@name=’field_a’]”):
node.set(‘string’, new_string)
4) Pack up your modifications and save it in the result string!
result[‘arch’] = etree.tostring(doc)
Done! Now in the our.pricelist’s form view, the label if field_a is always the value of field_b.
IMPORTANT: since the function fields_view_get is only called during the initial rendering, any change in the value of field_b is not reflected unless the view is reloaded. i.e. You have to refresh the page, manually or by python code, to update the string of field_a to field_b
Congratulations on reading till now! However, you might say where is the point of changing the field’s label by the value of another field? Indeed this seems an odd functionality, but it does open the door for dynamical modification of other stuff, like adding, rearranging the view according to your model data!
A useful implementation is the dynamical change of tree view column names!
Suppose the our.pricelist model has a one2many field called:
price_history_ids = fields.One2many(‘price.history’, ‘pricelist_id’)
And the pricelist keeps up to five columns of pricelist, each with a different date. Therefore it should also keep five date fields which probably need to be invisible in the XML form, but need to be the column header in the tree view of price_history_ids!
Do take note that the embedded tree view of price_history is NOT DEFINED in our.pricelist! Which means we need to override fields_view_get not in our.pricelist but in price.history now. The procedure is about the same, replace the string attribute of price.history’s tree view’s column fields and you are done.
Just remember to use this tree view in your our.pricelist form view by adding a context attribute to the field price_history_ids:
<field name=”price_history_ids” widget=”one2many” context=”{‘current_id’: active_id, ‘tree_view_ref’ : ‘your_module.your_tree_view’}”>
Below is the example of what can be achieved using that function: | https://www.alitec.sg/blog/technical-3/dynamically-modify-a-view-11 | CC-MAIN-2022-05 | refinedweb | 977 | 62.78 |
This post is going to focus on compiling C code with different options and seeing what the compiler does to the end result, by looking into objdump files of the compiled program.
The Program we will use is :
#include <stdio.h> int main() { printf("Hello World!\n"); }
Originally we will compile it using the following options :
-g # enable debugging information -O0 # do not optimize (that's a capital letter and then the digit zero) -fno-builtin # do not use builtin function optimizations
The 6 Options we will try and modify the process with are :
(1) Adding the compiler option
-static.
(2) Removing the compiler option
-fno-builtin.
(3) Removing the compiler option
-g.
(4) Adding additional arguments to the
printf() function in your program.
(5) Moving the
printf() call to a separate function named
output(), and call that function from
main().
(6) Removing
-O0 and add
-O3 to the gcc options.
Option 1.
Adding the -static options into our compiler options, has made the program size at least 900 times larger. When using objdump on the program we get to see all the libraries linked to C get directly compiled into our program. This does a number of things, one it makes the program larger as we no longer have the linker, all related functions must be inside the program itself. Two the program may run faster, because we have no need to go elsewhere to look for function and can just directly call functions from inside the program, the speed should increase, but it is hard to tell on a small program such as this. Overall we can say -static expands all related libraries and no longer has need for linker file.
Option 2.
Removing the compile option fno-builtin, from the looks at the objdump from removing this compiler options, it seems the compiler tries and finds a more direct function call for what it is trying to do, so instead of printf() it tries to find the underling function that it can call to improve the performance.
Option 3.
Removing the compile option -g gets rid of all extra code that is inserted by the compiler for debugging purposes, some of the notable items are line numbers and debugging statements. Useful in helping reduce the size of the compiled program.
Option 4.
Adding additional arguments to the printf() statements, adds extra registers to the program that are used to store the arguments, however after a certain count of arguments the program puts them onto a stack, this will start reducing the performance of the program, as the cpu will have to get them from memory.
Option 5.
Moving the printf() to a separate function and calling it from there, makes no real difference except for the fact that main now calls the created function first, and then calls the printf(), this has a small increase in compiled source code size.
Option 6.
Removing -o0 and adding -o3 tells the compiler to optimize the program, here is a small list of what each stage does :
0 – No optimization
1 – Do some optimization
2 – Do all the safe optimization
3 – Disregard safety do all possible optimizations
To finish up, just want to point out that the compiler does a lot of work, that we may not even know about. Giving compiler free reign can have it do drastic things to help optimize it for the machine to run. There are a lot of options, and in some cases those options can have a big performance update on your program, so playing around with them may be worth your time. | https://andreybykin.wordpress.com/2017/01/29/spo600-lab-4-compiling-c-code/ | CC-MAIN-2019-04 | refinedweb | 600 | 60.99 |
How Reshuffle Solves Common Fullstack Problems
Ryland G
・6 min read
Hi! For those of you who don’t know me, I’m Ryland, a fullstack dev/product manager/designer working for a SFbay-area startup. 4 months ago, I led an effort at my company to build a prototype tool that would simplify the process of creating fullstack apps. That idea has since transformed into an amazing product known as “Reshuffle”. Reshuffle eliminates the time-consuming, and headache inducing boilerplate traditionally associated with fullstack development and enable you to focus completely on your core value.
Here is a link to general launch announcement
Disclaimer: I try my best to be a transparent person, especially with my writing. My articles usually don’t have personal motivations but I want to make it clear when they do. I have vested interest as an employee of Reshuffle, but I really do believe it will revolutionize the way software is developed and shared. I’ve done my best to provide an honest (although still excited) outlook on what we’re offering.
Reshuffle TL;DR;
Reshuffle extends Create React App and adds a backend, integrating seamlessly into a traditional webpack/React workflow. Backends are written using “plain old JavaScript”, with React-inspired semantics. There is no need to manage or even create a database for apps, just use the resources you need, when you need them. Reshuffle offers FREE hosting of fullstack apps on the cloud.
Check out the site and remix an existing fullstack project for free!
How Reshuffle solves common fullstack problems
For a lot of us, the best way to start is with code (that’s why we’re all here right?). Here is a minimal fullstack example (including a database) built with the Reshuffle framework:
// src/App.js
import '@reshuffle/code-transform/macro' import React, { useState, useEffect } from 'react'; // import backend logic like any js function import { addAndGet } from '../backend/helloServer.js'; export default () => { const [num, setNum] = useState(undefined); useEffect(() => { addAndGet(0).then(setNum) }, []); return ( <div> <h1> Hello World from Reshuffle! </h1> <span> Number is: {num} </span> <button onClick={() => addAndGet(1).then(setNum)} > Increment me </button> </div> ); }
// backend/helloServer.js
// backend/helloServer.js import { update } from '@reshuffle/db'; /* @expose */ export async function addAndGet(num) { return update('num', (prevNumber) => { if (prevNumber) { return num + prevNumber; } return num; }); }
Hopefully that provides some context for the rest of this article!
Starting a new fullstack project can be daunting ♞
There have been tremendous improvements in fullstack development over the last 10-15 years. Frontend frameworks have never been more powerful, and paradigms like Serverless have made cloud infrastructure accessible to everyone. As someone who lives and breathes this world everyday, I couldn’t be happier to see how far we’ve come. Although things have gotten a lot better, there are still some pretty rough edges:
- Starting a new fullstack project has serious overhead and requires boilerplate every time
- Even with the best framework/packages, you never start from exactly where you want
- Even if frontend tool X and backend tool Y are perfect, you still have to integrate them
- It seems like the easier the backend platform is, the more you have to entrench yourself with its semantics
Reshuffle solves these problems and more:
Creating a new fullstack project has serious overhead and boilerplate every time
With Reshuffle, you start new projects by remixing (here is a link to a doc explaining that) old ones. Avoid recreating the same boilerplate over and over again and immediately start with the project setup right for you.
Even with the best framework/packages, you never start from exactly where you want
With all of our open-source templates, it’s nearly always possible to start from exactly where you want to. Remix the template that closest matches your needs and avoid implementing features which don’t bring your app value.
Even if frontend tool X and backend tool Y are perfect, you still have to integrate them
Reshuffle takes a more opinionated approach than other offerings and merges backend/frontend into a single unit. By taking advantage of the wildly successful Create React App framework, we can provide a uniform and cohesive environment for fullstack development. Reshuffle handles all the tedious integration work leaving you to do the important stuff 😉
It seems like the easier the backend platform is, the more you have to entrench yourself with its semantics
Reshuffle integrates seamlessly into the existing React developer experience. Our hope is that existing React developers will need to learn as few new concepts as possible to extend their apps to the cloud.
We hope to fundamentally reduce the cost of transforming a great idea into a great application.
Source code isn’t the whole story 📖
Github transformed the development ecosystem and open-source landscape. Although there was open-source in the past, Github brought it to the masses. Services like npm further contributed to this transformation, making it easier to share code than ever before. In more recent times, offerings such as Netlify and Github pages have made hosting and sharing static sites a convenient and enjoyable process. But throughout this transformation, fullstack applications have been neglected. There are a million solutions for sharing code and static sites, but once a backend comes into the picture, sharing becomes tricky…
Reshuffle enables sharing live fullstack apps, not just source code and rendered HTML. By providing every app a zero-config, zero-cost backend and data layer, we hope to transform fullstack app sharing, just as npm and Github did with source code. Wouldn’t it be cool if every npm module came with a live preview, running on a real backend? Reshuffle allows any open-source template to be “remixed” free of cost. Remixing instantly creates a copy of the app (including code, compute, and data) to your account. Imagine a world where you always know if an npm module fits your needs, without having to create a local project to test it out. This is the world we are striving to build.
Here is a video that explains everything concisely:
Developing locally isn’t developing remotely
One of the most frustrating aspects of fullstack, is the need to constantly be aware of minute differences between your local environment and the cloud. Even small differences in behavior can have catastrophic effects on production systems. Containerization and virtualization technologies have definitely improved things, but there is still a ton of room for error when developing in a split environment.
Reshuffle unifies the fullstack development process, permanently blurring the line between running locally and on the cloud. We believe that running your app on the cloud should simply be a choice you make, similar to an on/off switch. You no longer have to worry about maintaining different configs for your local and remote environment, just flip the switch when you’re ready to go live.
Managing cloud resources is a burden
Using the cloud has never been easier. Especially compared to the not-so-distant past, where managing infrastructure meant literally managing physical servers, it’s a completely different world. Serverless and the emergence of Devops has made the cloud infinitely more accessible. Unfortunately, serverless !== hassle-less. Physical/virtual infrastructure management has seemingly been replaced with an endless slew of YML config files. Even with the best Serverless offerings, you’re required to be aware of and responsible for details that aren’t helping you deliver value to your users.
Reshuffle manages the full burden of the cloud, so you don’t have to. Never visit YML-land again, as there are no tedious config files or cloud configuration options. Our system is intelligent and responsive, auto-scaling to fit your needs, without your intervention.
Conclusion
Reshuffle will transform the application landscape, significantly reducing the barrier of entry required for fullstack development. We're starting with React and are hard at work adding support for other frameworks and mobile apps. We’ve reduced the number of moving parts required to create a new cloud application, making it possible to focus on your core value, instead of maintaining servers.
Open source software and the amazing developer community (like the one here on Dev.to) is our foundation, and nothing makes us happier than providing value back to developers. If this article even got you 1/10 as excited as I am, I’ll count that as a success.
Reshuffle is available today. Create, copy and deploy fullstack applications at absolutely 0 cost (free as in beer and as in speech, although we wouldn’t recommend doing both at the same time)!
Feel free to ask me ask anything in the comments, or join us on our Discord.
Great write up, Ryland. I've been lucky enough to get my feet wet with reshuffle, and as a relatively new developer it's really cool to see how easy reshuffle has made creating fullstack apps.
I think with the advent of no-code tools, I think reshuffle has positioned itself nicely as a way to get custom and fluid ideas out quick while still being able to manage data.
Excited to see how reshuffle grows and how the platform expands! 🚀
Hey Heath. First off, thank you so much for your invaluable support and feedback over the last months. I'm really glad you like what we've made, a lot of blood, sweat and tears went into it.
Couldn't agree more. Reshuffle is a product for myself just as much as it is for others. Everyone has that threshold where they can't stand doing a repetitive task anymore. Fullstack development had reached that point for me, and I really think Reshuffle takes a huge amount of the heavy lifting off the user.
Thanks again for the awesome insights and comments! | https://dev.to/taillogs/how-reshuffle-solves-common-fullstack-problems-4h17 | CC-MAIN-2019-47 | refinedweb | 1,630 | 51.78 |
I'm trying to avoid having to use "nearly" the same code twice. I have the following template function, which searches for the provided value in a
QVector and returns the index to the element.
template<class tVec,class tVal> int upperBoundIndex(const QVector<tVec> &vec,int first,int last,tVal value) { //code here }
Searching for example a vector of the following type works fine:
QVector<int>, however I'd like to also be able to search a vector of the type
QVector<int*>, so I wrote another template function.
template<class tVec,class tVal> int upperBoundIndex(const QVector<tVec*> &vec,int first,int last,tVal value) { //similar code here, but the dereferencing }
This also works fine, but I've been wondering, is there a way I can use the same code for both functions? Because I nearly copy and pasted the code from one function to the other, and so far whenever I changed something in one function I, jumped right to the other and applied the same changes, is there a more optimal solution?
p.s. I'm not looking for alternative search functions, I know there are search functions for example in the std namespace. I'd like to know if there's a way to optimize my approach. | http://www.howtobuildsoftware.com/index.php/how-do/jy4/c-qt-templates-pointers-c-template-using-pointer-and-non-pointer-arguments-in-a-qvector | CC-MAIN-2018-43 | refinedweb | 212 | 52.53 |
In Django, we can easily create our database tables by defining some model classes. Here, we define different types of model fields also known as attributes. Within this framework, we have Django Queryset that we can use to access the attributes of different models.
In Django QuerySet, we have different types of model queries that we can use for accessing data of all models, specific model, or specific objects of each model. I’m going to explain all these different types of Django queries in brief.
Django Queries – Different QuerySet Explained
Before we’re going to explore different types of queries in Django, Let me first show you some models.py code. In this models.py code, I’ve defined some model objects that we’ll query in this article…
from django.db import models class Customer(models.Model): name = models.CharField(max_length=100, null=True) phone = models.CharField(max_length=100, null=True) email = models.EmailField(null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('Outdoor', 'Outdoor') ) name = models.CharField(max_length=100) price = models.FloatField(null=True) category = models.CharField(max_length=100, choices=CATEGORY) description = models.TextField(max_length=200, null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out For Delivery', 'Out For Delivery'), ('Delieverd', 'Delieverd') ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=100, choices=STATUS)
Let me explain you this above models.py code, what I did here. I’ve created 3 different models – Customer, Product, Orders…
So, I’ve added 4 different attributes in this Customer model – name, phone, email, and date_created. In Product model, I’ve added 5 different attributes – name, price, category, description, and created field.
In Order Model, we have connected customer and product attribute by using Foreign Key. Which means Order objects of individual customer will be linked to only that Customer object. Same as product field will be connected with the object of product model with the help of foreign key. There are different types of Django queries that we can use to access all objects of models or all attributes of a specific object within a model by the help of id.
Accessing All Objects of Specific Model in Django
Now let start with accessing all objects of a specific model. Here, we’re going to extract the attributes of all objects within a Customer Model. we know that each object will be consist of 4 different attributes – name, email, phone, date_created. In customer model, I have already created 4 different objects “PK Karn, Sohail, Mahure, Ritesh”. If I want to access all attributes of these 4 objects then django query will be:
customers = Customer.objects.all()
In the above Customer.objects.all() – our Customer is a model and all() function is used to access all objects within the Customer model. Then we’ve stored these data within our customers variable. Because we have different objects here, therefore, our data has stored within the list. To access these data in our templates, we have to iterate “customers” variable in “for loop“.
{% for customer in customers %} <p>{{customer.name}}</p> <p>{{customer.phone}}</p> <p>{{customer.email}}</p> <p>{{customer.date_created}}</p> {% endfor %}
Now It will loop all data of all different objects one by one.
Accessing Specific Object Of Model(by using get method):
Accessing all objects of a model can be easy with .all() method. But what if you just want to access data of specific object within a model. In such case, you can use get() method to access a specific object. Here, I want to access only “PK Karn” objects of Customer model. So, here we will use get() method.
But To access specific object with get(), you need to pass at least one attribute within get() function e.g get(name=”PK Karn”). But there is a problem, what if two different objects will have same name?, In such case, it will throw an error. So, instead of using any attribute, we use “id” attribute. Because id attribute of object will be always unique. this “id” attribute will be created automatically, whenever you will create any new object.
customer = Customer.objects.get(id=1)
Here, you don’t need to use for loop. Because our customer variable contains only information related about one object. You can access this data within your template e.g:
<p>{{customer.name}}</p> <p>{{customer.phone}}</p> <p>{{customer.email}}</p> <p>{{customer.date_created}}</p>
Accessing Objects By using Django filter Query
You can also access all objects of a model with certain conditions or filters. Django has filter() function to access objects within a model with some conditions. Here, I’m going to access objects of Product model, But I only want to access objects with “Indoor” categories. Here, we can use .filter() method to do this.
products = Product.objects.filter(category="Indoor")
Because here we’re not accessing any single object. We’re accessing Product objects with filter of Indoor Category. Therefore, .filter() function has returned set consist of different objects. To access these data within the templates, you need to use for loop.
{% for product in products %} <p>{{product.name}}</p> <p>{{product.price}}</p> <p>{{product.category}}</p> <p>{{product.description}}</p> {% endfor %}
Other Important Django Queries in QuerySet
There are some other important Django queries that I’m going to explain you in short.
1. To Access first Or Last Object of Model
firstCustomer = Customer.objects.first() Or lastCustomer = Customer.objects.last()
2. To Return Or Access all objects related to Particular Foreign Model Object
Suppose you want to access all objects of Order model but only related to specific Customer. Here you can use
customer = Customer.objects.get(id=1) (PK Karn) Object. Now following query is used to access all Order of (PK karn)Customer Object.
pkorder = customer.order_set.all()
3. Queries to Sorting Objects in Ascending Or Descending
ascending = Product.objects.all().order_by('id') or descending = Product.objects.all().order_by('-id')
You need to use order_by(‘attributes’) following .all() method to sorting.
Read Also: Create Restful API’s with Django rest framework – Serializers, CRUD
These were some main Django queries that you can use to access objects or data out of our Models or Django database. I hope you will like this.
Please don’t forget to bookmark our blog, If you want such kind of articles. Because we always post such kind of programming related article on this blog.
Thank’s to read… | https://www.codechit.com/django-queryset-model-queries/ | CC-MAIN-2021-31 | refinedweb | 1,113 | 52.05 |
Using JNDI with J2EE RI
As far as this book is concerned the role of JNDI is to support access to the different components of your application. Your J2EE vendor will provide a name service that you can use with each component technology (EJBs, servlets, JSPs and application clients).
This section will concentrate on registering and using named objects within a J2EE application. Later sections will discuss using JNDI as a Java technology outside of a J2EE server.
In simple terms JNDI has two roles within a J2EE server:
To bind distributed objects such as EJBs, JDBC datasources, URLs, JMS resources, and so on.
To look up and use bound objects.
The following sections provide a simple introduction to these two roles.
Binding J2EE Components
The binding of J2EE components is done by the J2EE container either as part of the process of deploying a component or as a separate operation. You will not normally use the JNDI API to bind any objects.
Tomorrow you will look at the deployment process for registering an EJB against a JNDI name. Today you will consider the Agency case study database you created as part of yesterday's exercise (Day 2, "The J2EE Platform and Roles"). On Day 2 you used a simple Java program to define and populate the database schema. At the same time you also used the J2EE RI asadmin command to bind a javax.sql.DataSource to a JNDI name for accessing the database from within the applications you will develop in subsequent days of this book. You either used the supplied asant build files and entered the command
asant create-jdbc
or you entered the asadmin command yourself. Either way the executed command was:
asadmin create-jdbc-resource --connectionpoolid PointBasePool
--enabled=true jdbc/Agency--enabled=true jdbc/Agency
What you did with this command was bind a DataSource object against the JNDI name jdbc/Agency.
The asadmin command is specific to the J2EE RI server but other J2EE servers will have similar utilities for registering JDBC datasources. The J2EE RI also provides a Web-based interface for administration as discussed on Day 2. You can verify that your jdbc/Agency object is bound correctly by starting up the J2EE RI server and then browsing to (MS Windows users can use the Start, Sun Microsystems, J2EE 1.4 SDK, Admin Console menu item). You will need to provide your administrative username and password, which will be admin and password if you followed the instructions on Day 2.
In the Admin Console Web Application select JDBC Resources and then jdbc/Agency in the left hand window and you will see the view shown in Figure 3.2.
Figure
3.2 Case Study jdbc/Agency DataSource.
J2EE RI implements a datasource by associating it with a connection pool object, and it is this object that contains the connection information for the database. Other J2EE servers may encode the database connection information with the datasource itself.
In the J2EE RI Admin Console select the jdbc/PointBasePool entry in the left window and scroll the right window down to the Properties section at the bottom of the page as shown in Figure 3.3.
From the Connection Pool properties you can see the Connection URL for the PointBase database used for the case study tables (jdbc:pointbase:server://localhost:9092/sun-appserv-samples) and the username and password used to access the database (pbPublic in both cases). You don't need to be aware of the details of the database connection information as this is now encapsulated behind a DataSource object.
All you have to do to use the database is know the name the datasource has been registered against, and then look up the DataSource object.
Figure
3.3 J2EE RI Point Base Pool Connection.
Lookup of J2EE Components
Using JNDI to look up a J2EE component is a simple two-step process:
Obtain a JNDI InitialContext object.
Use this context to look up the required object.
The first step in using the JNDI name service is to get a context in which to add or find names. The context that represents the entire namespace is called the Initial Context This Initial Context is represented by a class called javax.naming.InitialContext, which is a sub-class of the javax.naming.Context class.
A Context object represents a context that you can use to look up objects or add new objects to the namespace. You can also interrogate the context to get a list of objects bound to that context.
The following code creates a context using the default name service within the J2EE container:
Context ctx = new InitialContext();
If something goes wrong when creating the context, a NamingException is thrown. You are unlikely to come across problems creating the InitialContext within a J2EE server (other possible problems are discussed later in the section "Initial Context Naming Exceptions").
Once you have a Context object you can use the lookup() method to obtain your required component. The following code obtains the jdbc/Agency DataSource:
DataSource dataSource = (DataSource)ctx.lookup("jdbc/Agency");
Note that lookup() returns a java.lang.Object and this must be cast into a javax.sql.DataSource.
There are two common problems at this stage:
You mistyped the name, or the object isn't bound to the name service, in which case a javax.naming.NameNotFound exception is thrown.
The object you retrieved was not what you expected and a ClassCastException will be thrown.
That's it. You can now use the DataSource to access the database. Listing 3.1 shows a simple application that will list the contents of the database tables passed as command line parameters.
Listing 3.1 Full Text of AgencyTable.java
import javax.naming.* ; import java.sql.*; import javax.sql.*; public class AgencyTable { public static void main(String args[]) { try { AgencyTable at = new AgencyTable(); for (int i=0; i<args.length; i++) at.printTable(args[i]); } catch (NamingException ex) { System.out.println ("Error connecting to jdbc/Agency: "+ex); } catch (SQLException ex) { System.out.println ("Error getting table rows: "+ex); } } private DataSource dataSource; public AgencyTable () throws NamingException { InitialContext ic = new InitialContext(); dataSource = (DataSource)ic.lookup("jdbc/Agency"); } public void printTable(String table) throws SQLException { Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; try { con = dataSource.getConnection(); stmt = con.prepareStatement("SELECT * FROM "+table); rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int numCols = rsmd.getColumnCount(); // get column header info for (int i=1; i <= numCols; i++) { System.out.print (rsmd.getColumnLabel(i)); if (i > 1) System.out.print (','); } System.out.println (); while (rs.next()) { for (int i=1; i <= numCols; i++) { System.out.print (rs.getString(i)); if (i > 1) System.out.print (','); } System.out.println (); } } finally { try {rs.close();} catch (Exception ex) {} try {stmt.close();} catch (Exception ex) {} try {con.close();} catch (Exception ex) {} } } }
Before you can run this example you must have started the J2EE RI default domain and be running the PointBase database server as discussed on Day 2.
Run this application using the supplied asant build files entering the following command from within the Day03/examples directory:
asant AgencyTable
You will be prompted to provide a space-separated list of tables to examine; choose any of the tables shown in yesterdays ERD (such as Applicant, Customer, Location).
NOTE
You must use the supplied asant build files to run today's examples. The name service provided with the J2EE RI must be used by a J2EE component such as a Client Application and cannot be used by a normal command line program. The asant build files wrap up the program as a J2EE Application Client and set up the correct CLASSPATH before running the program. Application Clients are discussed in detail tomorrow and in the section "Using JNDI Functionality" later today.
Hopefully you can see the benefits of using both JNDI and DataSource objects within your enterprise application. Compare the code in Listing 3.1 with the code used to connect to the database in CreateAgency.java program used yesterday (Day02/exercise/src/CreateAgency.java), shown in the following excerpt:
Class.forName("com.pointbase.jdbc.jdbcUniversalDriver"); Connection con = DriverManager.getConnection( "jdbc:pointbase:server://localhost/sun-appserv-samples,new", "pbPublic","pbPublic");
In this excerpt the database details are hard coded into the application making it awkward to migrate the application to a new database. If you look at the code for the CreateAgency.java program on the Web site, you will see commented out definitions for the database connection details for the Cloudscape database that was shipped with J2EE RI 1.3. The example in Listing 3.1 has not changed between J2EE RI 1.3 and J2EE RI 1.4 despite the change of database provider.
Other Distributed J2EE Components
Throughout many of the days of this course you will use JNDI to look up many different types of objects:
EJBson most days from 4 through to 14
The javax.transaction.UserTransaction object on Day 8, "Transactions and Persistence"
JMS resources on Day 9, "Java Message Service" and Day 10, "Message-Driven Beans"
Resource Adapters and RMI-IIOP servants on Day 19, "Integrating with External Resources"
For each of these objects, except EJBs, you will use the J2EE RI asadmin command to define the required resources. For EJBs you will use the deploytool application (discussed tomorrow) to define the JNDI name as part of the deployment process for the EJB.
There is one minor twist to using EJBs and RMI-IIOP objects with JNDI and this is the type of object that is stored in the name service.
EJBs use RMI-IIOP and when a JNDI lookup is used to obtain an EJB (or any RMI-IIOP object) you obtain an RMI-IIOP remote object stub and not the actual object you expect. You must downcast the CORBA object into the actual object you require using the PortableRemoteObject.narrow() method.
Looking ahead momentarily to tomorrow's work on EJBs, the following code fragment shows how to look up an EJB:
InitialContext ctx = new InitialContext(); Object lookup = ctx.lookup("ejb/Agency"); AgencyHome home = (AgencyHome)PortableRemoteObject.narrow( lookup, AgencyHome.class);
In this case the EJB is bound against the name ejb/Agency and is of type agency.AgencyHome. This example has been slightly simplified from the real code which is shown in the next section, "J2EE Java Component Environment."
The narrow() method takes as parameters the RMI-IIOP remote stub object and the Class object representing the target class for the downcast. This method will throw a ClassCastException if the remote stub does not represent the correct class.
J2EE Java Component Environment
One extra issue concerning J2EE components that should be considered now, while you are looking at JNDI within the J2EE server framework, is that of the Java Component Environment.
To explain this concept consider the case where two developers independently design and develop EJBs both of whom use the name jdbc/Database as the name of the DataSource object used to access the database. An application assembler wants to use both EJBs in a single application but each EJB was designed to use a different database schema. Such a situation may arise if the assembler is "buying in" EJBs developed by external organizations.
The Java Component Environment is designed to resolve the possibility of JNDI resource name conflicts by providing each component with its own private namespace. Every J2EE component has a context within its namespace called java:comp/env that is used to store references to resources required by that component. The component's deployment descriptor defines the resources referenced by the component that will need to be defined within the Java Component Environment.
Resources that can be referenced by a J2EE component include:
Enterprise JavaBeansdiscussed primarily on Day 5, "Session EJBs," and Day 6, "Entity EJBs."
Environment Entriesdiscussed on Day 5.
Message Destination Referencesdiscussed on Day 10.
Resource Referencesdiscussed today (DataSource) and on Day 10 (ConnectionFactory).
Web Service Referencesdiscussed on Day 20, "Using RPC-Style Web Services with J2EE."
Returning to the example from the previous section, where the sample code for an EJB lookup was shown without the complication of the Java Component Environment, the actual EJB lookup code is
InitialContext ctx = new InitialContext(); Object lookup = ctx.lookup("java:comp/env/ejb/Agency"); AgencyHome home = (AgencyHome)PortableRemoteObject.narrow( lookup, AgencyHome.class);
The ejb/Agency name is defined as an EJB Reference within the Java Component Environment. As part of the deployment process the EJB Reference will be mapped onto the actual JNDI name used by the EJB (if you are a little lost at this point, don't worry, all will be made clear on Days 4 and 5). | http://www.informit.com/articles/article.aspx?p=170886&seqNum=2 | CC-MAIN-2019-51 | refinedweb | 2,107 | 54.63 |
code does not compile when i attempt to call the static method OpenParentApplication on the WKInterfaceController class. returns CS0117 error (...does not contain a definition for...).
# Expected behavior
I expect to be able to call the static method ;)
# Actual behavior
failure to compile
# Supplemental info (logs, images, videos)
sample code:
using System;
using WatchKit;
using Foundation;
namespace ClockKing.RoutinelyExtension
{
public partial class InterfaceController : WKInterfaceController
{
public override void WillActivate()
{
// This method is called when the watch view controller is about to be visible to the user.
Console.WriteLine("{0} will activate", this);
WKInterfaceController.OpenParentApplication(new NSDictionary(), (replyInfo, error) =>
{
if (error != null)
{
Console.WriteLine(error);
return;
}
Console.WriteLine("parent app responded");
// do something with replyInfo[] dictionary
});
}
# Test environment (full version information)
alpha channel.
That API exists but it's only available from iOS (if you run on the phone), i.e. not on watchOS (if you run on the watch).
That's controlled by the WK_AVAILABLE_IOS_ONLY macro, e.g.
from iOS SDK
+ (BOOL)openParentApplication:(NSDictionary *)userInfo reply:(nullable void(^)(NSDictionary * replyInfo, NSError * __nullable error)) reply WK_AVAILABLE_IOS_ONLY(8.2); // launches containing iOS application on
and watchOS SDK
+ (BOOL)openParentApplication:(NSDictionary *)userInfo reply:(nullable void(^)(NSDictionary * replyInfo, NSError * __nullable error)) reply WK_AVAILABLE_IOS_ONLY(8.2); // launches containing iOS application on the phone. userInfo must be non-nil
It looks like you should be using the WatchConnectivity namespace for this.
Thank you for your quick response. I Understand how the availability is being set; however, the examples in the xamarin guides suggest using this method from the watchkit extension:
is this a deprecated behavior from watchkit 1.0?
It's not a deprecation, this is still available in WatchKit, as part of iOS but it does not exists in watchOS.
Apple made it a bit confusing but watchOS 1.x only support WatchKit _extensions_ (on phone). There's no such things as WatchKit 1.0 or 2.0, WatchKit is a framework that exists on both OS.
Also the linked guide is about WatchKit _extensions_, i.e. running on iOS (phone) and not watchOS 2.x (native apps on the watch device). As such it's normal (and correct) to use this API in this context.
ah, ok, that makes (slightly?) more sense. I'll look into WatchConnectivity, and i'll keep an eye out for an updated guide for using WatchKit on watchOS 2.x. | https://bugzilla.xamarin.com/42/42405/bug.html | CC-MAIN-2021-25 | refinedweb | 390 | 51.14 |
.
// C++ program to represent undirected and weighted graph // using STL. The program basically prints adjacency list // representation of graph #include <bits/stdc++.h> using namespace std; // To add an edge void addEdge(vector <pair<int, int> > adj[], int u, int v, int wt) { adj[u].push_back(make_pair(v, wt)); adj[v].push_back(make_pair(u, wt)); } // Print adjacency list representaion ot graph void printGraph(vector<pair<int,int> > adj[], int V) { int v, w; for (int u = 0; u < V; u++) { cout << "Node " << u << " makes an edge with \n"; for (auto it = adj[u].begin(); it!=adj[u].end(); it++) { v = it->first; w = it->second; cout << "\tNode " << v << " with edge weight =" << w << "\n"; } cout << "\n"; } } // Driver code int main() { int V = 5; vector<pair<int, ints> > adj[V]; addEdge(adj, 0, 1, 10); addEdge(adj, 0, 4, 20); addEdge(adj, 1, 2, 30); addEdge(adj, 1, 3, 40); addEdge(adj, 1, 4, 50); addEdge(adj, 2, 3, 60); addEdge(adj, 3, 4, 70); printGraph(adj, V); return 0; }. | http://www.geeksforgeeks.org/graph-implementation-using-stl-for-competitive-programming-set-2-weighted-graph/ | CC-MAIN-2017-17 | refinedweb | 168 | 65.76 |
Hi everybody,
I’m trying to get the grove 433Mhz work on my arduino uno without success for 2 weeks now…
My projet is to use attiny85 chips to receive a command from the rf link to make a led blink.
I’ve try to use manchester on it (see github.com/mchr3k/arduino-libs-manchester for more details).
So i have connected the rx and tx on my arduino just for the test, and i receive nothing!
Do you think it’s possible to get it work on the same board to be sure it can work?
Does someone even build something with an attiny85?
This is the code for testing on arduino uno:
#include <MANCHESTER.h>
#define TxPin 2 //the digital pin to use to transmit data
#define RxPin 12
unsigned int Tdata = 0; //the 16 bits to send
void setup()
{
MANCHESTER.SetTxPin(TxPin); // sets the digital pin as output default 4
MANCHESTER.SetRxPin(RxPin); //user sets rx pin default 4
MANCHESTER.SetTimeOut(1000); //user sets timeout default blocks
Serial.begin(9600); // Debugging only
}//end of setup
void loop()
{
Tdata +=1;
MANCHESTER.Transmit(Tdata);
unsigned int data = MANCHESTER.Receive();
Serial.println(data);
delay(100);
}//end of loop
Thanks!! | https://forum.seeedstudio.com/t/grove-433-mhz-on-attiny85-via-arduino-uno/16010 | CC-MAIN-2020-29 | refinedweb | 200 | 67.15 |
#include <gromacs/analysisdata/modules/histogram.h>
Data module for per-frame histograms.
Output data contains the same number of frames and data sets as the input data. Each frame contains the histogram(s) for the points in that frame. Each input data set is processed independently into the corresponding output data set. Missing values are ignored. All input columns for a data set are averaged into the same histogram. The number of columns for all data sets equals the number of bins in the histogram.
The histograms are accumulated as 64-bit integers within a frame and summed in double precision across frames, even if the output data is in single precision.
Adds a module that processes only a subset of the columns.
Throws in the same situations as addModule().
Currently, all data sets are filtered using the same column mask.
Adds a module to process the data.
If data has already been added to the data, the new module immediately processes all existing data. APIError is thrown if all data is not available through getDataFrame().
The caller can keep a copy of the module pointer if it requires later access to the module.
If the method throws, the state of the data object is not changed. The state of the data module is indeterminate.
Applies a module to process data that is ready.
This function works as addModule(), except that it does not keep a reference to
module within the data object after it returns. Also, it can only be called after the data is ready, and only if getDataFrame() gives access to all of the data. It is provided for additional flexibility in postprocessing in-memory data.
modulerequests storage (addModule() has the same problem if called after data is started).
Returns the average histogram over all frames.
Can be called already before the histogram is calculated to customize the way the average histogram is calculated.
Returns the number of columns in a data set.
If the number of columns is not yet known, returns 0. The returned value does not change after modules have been notified of data start, but may change multiple times before that, depending on the actual data class. Derived classes should set the number of columns with setColumnCount(), within the above limitations.
Does not throw.
Returns the number of columns in the data.
This is a convenience method for data objects with a single data set. Can only be called if dataSetCount() == 1.
Does not throw.
Called (once) when no more data is available.
Implements gmx::AnalysisDataModuleParallel.
Returns the number of data sets in the data object.
If the number is not yet known, returns 0. The returned value does not change after modules have been notified of data start, but may change multiple times before that, depending on the actual data class. Derived classes should set the number of columns with setDataSetCount(), within the above limitations.
Does not throw.uleParallel.
Returns the total number of frames in the data.
This function returns the number of frames that the object has produced. If requestStorage() has been successfully called, tryGetDataframe() or getDataFrame() can be used to access some or all of these frames.
Does not throw.
Derived classes should implement this to return the number of frames. The frame count should not be incremented before tryGetDataFrameInternal() can return the new frame. The frame count must be incremented before AnalysisDataModuleManager::notifyFrameFinish() is called.
Implements gmx::AbstractAnalysisData.
Called when a data frame is finished.
Implements gmx::AnalysisDataModuleParallel.
Called in sequential order for each frame after they are finished.
This method is called after frameFinished(), but with an additional constraint that it is always called in serial and with an increasing
frameIndex. Parallel data modules need this to serialize their data for downstream serial modules; AnalysisDataModuleSerial provides an empty implementation, as there frameFinished() can be used for the same purpose.
Implements gmx::AnalysisDataModuleParallel.
Called at the start of each data frame.
Implements gmx::AnalysisDataModuleParallel.
Access stored data.
index.
If the data is not certainly available, use tryGetDataFrame().
Whether the data can have multiple points in the same column in the same frame.
trueif multiple points in the same column are allowed within a single frame.
This kind of data can appear in many histogramming applications (e.g., RDFs), where each trajectory frame has several data points (possibly a different number for each frame). The current interface doesn't support storing such data, but this should rarely be necessary.
The returned value does not change after modules have been notified of data start. Derived classes can change the type by calling setMultipoint() subject to the above restriction. If this is not done, the function always returns false.
Does not throw.
Called (once) for parallel data when the data has been set up.
This method is called instead of dataStarted() if the input data has the capability to present data in non-sequential order. If the method returns true, then the module accepts this and frame notification methods may be called in that non-sequential order. If the method returns false, then the frame notification methods are called in sequential order, as if dataStarted() had been called.
See dataStarted() for general information on initializing the data. That applies to this method as well, with the exception that calling AbstractAnalysisData::requestStorage() is currently not very well supported (or rather, accessing the requested storage doesn't work).
Implements gmx::AnalysisDataModuleParallel.uleParallel.
Request storage of frames.
If called multiple times, the largest request is honored.
Does not throw. Failure to honor the request is indicated through the return value.
Sets the number of columns for a data set.
Must be called at least once for each data set before AnalysisDataModuleManager::notifyDataStart(). Can be called only before AnalysisDataModuleManager::notifyDataStart(). Multiple calls are allowed before that point; the last call takes effect.
Strong exception safety.
Sets the number of data sets.
It not called, the data object has a single data set. Can be called only before AnalysisDataModuleManager::notifyDataStart(). Multiple calls are allowed before that point; the last call takes effect.
Strong exception safety.
Sets whether the data has multiple points per column in a frame.
If not called, only a single point per column is allowed. Can be called only before AnalysisDataModuleManager::notifyDataStart(). Multiple calls are allowed before that point; the last call takes effect.
Strong exception safety.
Access stored data.
index, or an invalid reference if no such frame is available.
Does not throw. Failure to access a frame with the given index is indicated through the return value. Negative
index is allowed, and will always result in an invalid reference being returned. | https://manual.gromacs.org/current/doxygen/html-lib/classgmx_1_1AnalysisDataSimpleHistogramModule.xhtml | CC-MAIN-2021-17 | refinedweb | 1,100 | 51.14 |
cbc.block : block_symmetric_assemble & boundary conditions
Hello !
Here is my problem. I need to use the cbc.block package for my python code (I need block-structure matrix), but I don't know how to apply my boundary condition (Dirichlet boundary conditions, basically non-slip conditions). Let me explain:
I downloaded the last version of cbc.block from: https:/
Traceback (most recent call last):
File "mixedpoisson.py", line 97, in <module>
[a21, 0 ]], bcs=bcs)
File "/usr/local/
symm[i,j], asymm[i,j] = _symmetric_
File "/usr/local/
from dolfin import symmetric_assemble
ImportError: cannot import name symmetric_assemble
Is this a problem with the versions of FEniCS/cbc.block ? I understood that "symmetric_
Consequently, I tried to first assemble my blocks and then build my block matrix with: A = block_mat([...]) and the RHS: b = block_vec([...]). To apply my boundary condition I used: bc = block_bc([...]) (with inside my boundary conditions defined with DirichletBC) and bc.apply(A, b). However, "block_bc" is apparently not defined. I obtain this error:
NameError: name 'block_bc' is not defined
So now, I'm confused ! Anyone can help me with that ?
Thanks in advance for your time,
Coraline
PS: I install FEniCS via dorsal, so I have dolfin-1.2.0
Python 2.7.3
Question information
- Language:
- English Edit question
- Status:
- Answered
- For:
- DOLFIN Edit question
- Assignee:
- No assignee Edit question
- Last query:
- 2013-08-08
- Last reply:
- 2013-08-09
FEniCS no longer uses Launchpad for Questions & Answers. Please consult the documentation on the FEniCS web page for where and how to (re)post your question: http://
fenicsproject. org/support/ | https://answers.launchpad.net/dolfin/+question/233718 | CC-MAIN-2021-21 | refinedweb | 263 | 58.38 |
TURN ON
TUNE IN
THE WEEKENDER’S PICKS FOR FALL TELEVISION
WeeKender , Wednesday,september 25, 2013
2
page
What new fall TV show do you think will fail?
Te ll @wkdr what new fa ll show you think will fail
Contributors Ralphie Aversa, Justin Brown, Kait Burrier, Caeriel Crestin, Pete Croatto, Nick Delorenzo, Tim Hlivia, Melissa Highes, Michael Irwin, Amy Longsdorf, Matt Morgis, Ryan O’Malley, Kacy Muir, Jason Riedmiller, Erin Rovin, Ned Russin, Chuck Shepherd, Jen Stevens,Alan K. Stout, Mike Sullivan, Bill Thomas, Mark Uricheck, Robbie Vanderveken, Noelle Vetrosky, Bobby Walsh, Derek Warren Interns Holly Dastalfo, Bill Rigotti Address 90 E. Market St., Wilkes-Barre, PA 18703 Fax 570.831.7375 E-mail Weekender@theweekender.com Online theweekender.com • facebook.com/theweekender • follow us on Twitter: @wkdr Circulation The Weekender is available at more than 1,000 locations throughout Northeastern Pennsylvania. For distribution problems call 570.829.5000 • To suggest a new location call 570.831.7349 • To place a classified ad call 570.829.7130 Editorial policy The Weekender is published weekly from offices at 90 E. Market St., Wilkes-Barre, PA 18703. The opinions of independent contributors of the Weekender do not necessarily reflect those of the editor or staff. Rating system WWWWW = superb WWWW = excellent WWW = good WW = average W = listenable/watchable * Scarborough Research
As I write this letter, I am still coming to grips with the passing of my grandmother, but one memory I still hold onto fondly was when we first bonded. I moved into her home as a teenager, and one thing she loved was her television. She would stay up late every night to watch Nick at Nite and or any other reruns of sitcoms playing at that hour. We both loved “Seinfeld,” so we would watch the show together and laugh about it for weeks afterward – it was the one thing we both “got” despite our many differences. That’s the power of good entertain- ment, and this fall, there seems to be plenty of it. Each member of our staff summarized our picks for the fall season on pages 28 and 29, which range from comedies to dramas to sci-fi tales to horror stories. It’s a lot to take in, but that’s what DVRs are for. We didn’t have one of those when I watched TV with grandma, but we both enjoyed staying up late anyway, so we didn’t really need one. Find your favorite new show in our guide and then get someone special to watch it with you. TV programming comes and goes, but the right show can stick with you forever – especially with the right company. -Rich Howells, Weekender Editor
Josh Groban@joshgroban
Online comment of the week.
“In honor of the #emmys I will now watch the tv IN my GTA5 game.”
The Weekender has 12,656
Facebook fans. Find us now at Facebook.com/theweekender
Wednesday, sePtember 25, 2013
Page 3
WEDNESDAY, SEPTEMBER 25, 2013
PAGE
5
Down in Mexico…err, Scranton
SARA POKORNY
Weekender Staff Writer
It’s no secret that The Great Party is an incredibly unique band – its Ameri-Pop style is one not often heard (if ever, outside of the band itself) in this area. The group, who has already released a video for the song “Theresa” off the self-titled EP, has put together quite the spectacle in produc- ing a video for another song off the EP, “Hecho En Mexico.” The Great Party, in conjunc- tion with The Vintage, is host- ing a release show for the video Sept. 28 at TwentyFiveEight Studios (703 N. Washington Ave., Rear, behind Cooper’s). There is an aura of dark humor surrounding the video, in which band mem- bers Mike Eastman, Rosaleen Eastman, Matt Mang, Michael Nordberg, and Matthew Thomas suit up in their best Day of the Dead attire. The Day of the Dead is a hol- iday that takes place on Nov. 1 and 2 of mainly Mexican heri- tage that focuses on gatherings of family and friends to pray for and remember those who have passed on. Fitting, given the basis of the song. “The song is about a guy who’s got a thing for a dead girl,” Rosaleen said, before laughted broke out and her husband Mike chimed in with, “Honestly, I did not even know that until right now.” The group’s playfulness and sense of humor shines through in the video. “There is some grave dig- ging,” Mike Eastman said, “but there’s also a fun twist. We’re having a traditional party on a grave site but, instead, we’re digging some- one up.” The shoot took place over two days in June, directed by Zac Stuart-Pontier, with a crew coming in from New York. A bevy of extras helped make up the party scene.
This project was supported by a Lackawanna County Arts And Culture Grant through the Lackawanna County Commissioners and Council On Arts Culture and Education. The release show will serves as a Day of the Dead party all its own. There will be free Day of the Dead face paint- ing, which earns those that hit up The Bog in Scranton afterwards an extended happy hour. Not only will The Great Party be performing but there will also be free face painting, custom crafts from Alchemy Home Company including a Sugar Skull scent created just for the occasion, food by Eden- A-Vegan Cafe, an educational piece on the Day Of The Dead holiday, and an opening set of music by A Fire With Friends. The Great Party would like to thank Stuart-Pontier, David Jacobsen, John Ferguson, The Lackawanna County Arts & Culture Department, Donna and Matty Thomas, Suzie Frisch, Beth Thomas, and the rest of the crew and all the extras for making the filming of “Hecho En Mexico” such a great experience. The party will not only be the first time local audiences are being treated to the video, but also the first time the band itself will see it in full. “We’ve seen about 90 per- cent up until this time,” Mike Eastman said, before bursting into laughter. “I mean, it can be an animated feature for all we know.”
W
The Great Party “Hecho En Mexico” viewing party: Sept. 28, doors 6:30 p.m., TwentyFiveEight Studios (703 N. Washington Ave., Rear, behind Cooper’s).
…does it take to spend an evening seeing some hot fall fashions while enjoying cocktails, all for a good cause? Stop by at Sapphire Goes Pink, A Making Strides Against Breast Cancer charity event put on by The Sapphire Salon & Destination Spa in conjunction with the American Cancer Society. On Sept . 29 from 5 to 7 p.m. The Sapphire Salon in Pittston will hold a fall fashion show, an event that will also have door prizes, cocktails and hors d’oeuvres. All proceeds generated, including the $20 ticket price, will be donated to Making Strides Against Breast Cancer, a local organization . Tickets can be purchased in advance through Sapphire. Call 570.602.7700. There will also be an after party from 7:30 to 10 p.m. at Cooper ’s Seafood House, with a percentage of those pro- ceeds going to the American Cancer Society.
…are local businesses teaming up on Oct. 8 to raise money? Kayla Nakonechni is a local girl, a senior at Penn State University who was recently diagnosed with glioblastoma, a form of brain cancer. Local businesses Pieroguys Pierogies, What the Fork Food Truck, and Burnt Carbon are holding an event on Carbondale Area High School’s campus to raise money for Kayla and her family. The event will feature lunch and dinner service from What the Fork food truck, the launch of Pieroguy ’s Pierogies new flavor, face painting by the Carbondale Area cheerleaders, an acoustic performance by Graces Downfall, and many surprises. For more information on the event, to make a donation, or if you’re interested in becoming a sponsor please contact joseph.caviston@gmail.com or 570.947.7799.
…can you catch a balloon ride this weekend? The Fork and the Cork festival is back on Sept. 28 from 2 to 6 p.m. at Mount Airy Casino Resort. Now in its seventh year, Fork and Cork is Northeastern Pennsylvania’s premier food & wine-tasting event. The grand tasting session tickets cost $55 per person, $100 per couple. For more info or to purchase tickets for the event, visit forkandthecork.com. Hot air balloon rides will be on the resort grounds from 4 to 7 p.m., allowing guests to enjoy breathtaking and panoramic views of the picturesque Pocono Mountains amidst beautiful fall foliage. “Once again, we are thrilled to host an afternoon of unparalleled selections of wines, beers and spirits that will be expertly paired with artisan cheese and regional foods,” said John Culetsu, Executive Vice President and General Manager of Mount Airy Casino Resort.
WeeKender , Wednesday,september 25, 2013
6
page
COVER STORY
Fall televisiOn … 28-29
LISTINGS
the W … 5 cOncerts … 10 theater … 19 mind& bOdy … 19 speaK & see … 21 live entertainment … 22 agenda … 36, 50 Fitness … 47
MUSIC
the great party … 5 album revieWs … 16 charts … 16 music On the menu … 27 Farm aid … 43
STAGE & SCREEN
mOvie revieW … 23 the english teacher … 24 ralphie repOrt … 27 starstrucK … 27
ARTS
nOvel apprOach … 21 inFinite imprObabilty … 30
LIFESTYLE
First and ted … 7 shOW us sOme sKin … 25 Just FOr the health OF it … 32 nOt yOur mama’s Kitchen … 32 maKeup rules … 37 securely FashiOned … 37 man OF the WeeK … 53 mOdel OF the WeeK … 54
HUMOR & FUN
pet OF the WeeK … 27 inFect scrantOn … 34-35 puzzle … 36 sOrry mOm and dad … 38 neWs OF the Weird … 38 snipstamp #spaceWalK … 39 i’d tap that … 40 berWicK breWing cOmpany … 40 sign language … 52
GAMES & TECH
get yOur game On … 42 mOtOrhead … 42
ON THE COVER
design by amanda dittmar vOlume 20 issue 46
Wednesday, sePtember 25, 2013
Your guide to fantasY football Te d Black | Special to the We ekender
Gordon good to go, shy away from Holmes, and more for Week 4
Another week of football gone by - how did you fare? Hopefully, things went well and, if not, you’ve got a fresh start coming up tomorrow night. Toss ‘em, keep ‘em, make some tough decisions - hopefully this week’s guide will put you on the path to big wins in Week 4. Adds:
Josh Gordon: Many managers shied away from Gordon during their draft because of the two-game suspension looming from his off-the-field issues. He has WR1 talent on a team that has been desperately trying to stretch the field for the first few weeks of the sea- son. Brian Hoyer targeted Gordon NINETEEN times in Week 3, and you can expect that number to hold steady as the season contin- ues. It is also worth mention- ing that the Cleveland fire sale might lead to Gordon being shipped off to a con- tender in need of WR help (New England and San Francisco come to mind). Bilal Powell: Powell was slated as the number two, back behind Chris Ivory during the preseason, but Ivory’s ineffectiveness and injuries have vaulted Powell into the role of every down back for the Jets. He might not be as elusive as Ivory, but his 29 touches in Week 3 prove that the Jets’ are eager to run the ball and take the pressure of rookie QB Geno Smith. His talent is limited, but that can easily be offset by the lack of able-bodied running backs on the Jets’ depth chart. Any amount of modest success can land him the feature back duties, even once Ivory returns from his hamstring injury. Brandon Bolden: Steven Ridley has fallen out of favor in the New England backfield and Shane Vereen will be on
Josh Gordon
the injured reserve list until at least Week 11. Bolden didn’t see as many carries as Ridley or even LeGarrette Blount, but he did play on 26 of 72 snaps (more than Blount and equal to Ridley). Bolden is emerging as a pass catching threat out of the backfield and will likely be playing most passing downs. The Patriots’ offense is hurt- ing for pass catchers right now and Bolden will have no problem being a check-down option for Tom Brady. His value will clearly be elevated in any PPR leagues. Pass:
Santonio Holmes: Many fantasy team owners rushed to the waiver wire to place a claim on the Jets’ WR after his big game this past week against Buffalo. Holmes reeled in five catches for 154 yards and one touchdown.
Does this mean Santonio is back? Absolutely not. People aren’t realizing that the Buffalo secondary has been absolutely decimated by injuries. Many of the defen- sive backs playing against New York this past week have no business trying to cover NFL receivers, even if said receiver is a former star who is fading quicker with each passing day. Isaiah Pead: With the injury to Daryl Richardson, Pead had an opportunity to showcase his talent and attempt to earn at least a timeshare in the Rams’ back- field. With that opportunity Pead trudged to the line of scrimmage on numerous car- ries and rarely made defend- ers miss. It is possible that he could find value in the Rams’ hot-and-cold passing attack though. St. Louis has
been playing catch up a lot so far this season, so Pead might be able to snag a few passes from Sam Bradford,
but don’t expect to see dras- tically better numbers than what Daryl Richardson (who shouldn’t miss more than another week) has put up so far this season. Ted Ginn: Ginn had himself a field day against
a Giants’ defense that has
been struggling to find its identity early in the season. There has never been any question about Ginn’s speed. He’s been torching defensive backs since his years at Ohio State. Ginn’s problems begin with his hands and end with his inability to run routes
effectively. It’s awe-inspiring
to see someone so fast have
the inability to create sepa- ration from defensive backs on the professional level.
Tiered power rank ings for We ek 4
RB:
tier 1: a.Peterson, m.Forte, J.Charles tier 2: L.mcCoy, d.martin, d.murray, m.Lynch tier 3: r. bush (if healty), a.morris, b.Pierce, t.richardson, C.J. spiller (if healthy), d.mcFadden tier #: d. sproles, m.Jones-drew, K.moreno, C.Johnson, a.Foster
WR:
tier 1: C. Johnson, J. Jones, b.marshall tier 2: d.bryant , d.thomas, W.Welker, a.J.green, d. Jackson tier 3: W.Welker, V.Cruz, r.Wayne, L.Fitzgerald, r.White, J.gordon tier 4: e.decker, a.Johnson, P.garcon, .y.Hilton, a.brown, V. Jackson, t.smith, a.boldin, m.Colston
QB:
tier 1: P.manning, t.romo, d.brees, a. Luck, r.griffin II tier 2: m.ryan, m.Vick, C.Kaepernick tier 3: m.stafford, t. brady, r .tannehill, r.Wi lson
TE:
tier 1: J. graham tier 2: r.gronkowski (if healthy), J.thomas, J. Cameron tier 3: t.gonzalez, J.Wi tten, m.bennett , C.Fleener, V.davis (if healthy), a.gates tier 4: J.Cook, b.myers, H.miller, O.daniels
by Alex Smith. Bowe has
elite receiver talent, but he’s merely a decoy in an offense whose number one priority
is run the ball followed by:
check down to tight end, run the ball, check down to
slot receiver, run the ball, punt. Alex Smith has done
a great job leading this
Kansas City team through three weeks, it’s just diffi- cult to see Smith and Bowe finding any sort of mutual success with one another. - Ted is a Miami fan through and through, and
he will pull himself out of has been fumbling and stum-
bling his way through fan-
the slump this week against Oakland. Feel free to start him without hesitation this
week - I know I will. Sit this week: Dwayne Bowe. Bowe just simply isn’t a fit for an offense lead
W
Robert Griffin III. RG3 has struggled mightily through the first three weeks. He has
Ginn might be able to real in a 40 to 50 yard bomb from Cam Newton here or there, but keep in mind those plays are few and far between in Carolina’s run-heavy offense. Hot start of the week:
looked better as each game progressed (but I guess that’s not too difficult, con- sidering he was barely even on the scoreboard at halftime of each game). He’s clearly not 100 percent healthy, but
tasy leagues for 9 years now. Shoot him a message with questions or suggestions at tedblack1@gmail.com.
8
page
Wednesday, sePtember 25, 2013
Page 9
WeeKender , Wednesday,september 25, 2013
page 10
ALICE C. WILTSIE PERFORMING ARTS CENTER (700 n. Wyoming st., Hazleton)
570.861.0510, wiltsiecenter.org
• Big Bad Voodoo Daddy: Oct. 18, 8 p.m. THE COOPERAGE PROJECT (1030 Main St., Honesdale)
570.253.2020,
thecooperageproject.org
• Patrick Fitzsimmons: Oct. 20
(Donations accepted and appreciated at the door at all events.) F.M. KIRBY CENTER
(71 Public Square, Wilkes-Barre) 570.826.1100, kirbycenter.org
• Dinosaur Train Live!: Oct. 17, 2:30 p.m., 6:30 p.m. $15-$25.
• Alice Cooper: Oct. 18, 8 p.m. $39,
$49, $59, $75 (limited pit seating).
• Cyndi Lauper: Oct 22, 8 p.m. $32, $47, $57..
• Joe Nardone’s Christmas Doo
Wop Spectacular: Dec. 14, 7 p.m. $29.50, $39.50, $49.50 HAWLEY SILK MILL (8 Silk Mill Dr., Hawley. 570.588.8077, silkmillharmony. com) JimmyThackery and the Drivers:
Sept. 26, 8 p.m., $20.
• Bill Kirchen and Texicali: Sept. 27, 8:30 p.m. $23.
• The.
• Eaglemanis: Oct. 11, 8:30 p.m.,
$23.
• Cast of Beatlemania: Oct. 12, 8:30 p.m., $27.
• Childhood’s End: Oct. 18, 8:30
p.m., $23.
• Robben Ford Band: Oct. 24, 8:30
p.m. $27.
• The Badlees: Oct. 25, 8:30 p.m.,
$19.
MEETING OF THE MINDS VI
• Sept. 27-29, Meshoppen, featuring Tea Leaf Green, Orgone, Cabinet, The Heavy Pets, Flux Capacitor,
more. $65, presale; $90, day of show. Info: jibberjazz.com..
• Rob Base: Dec. 28, 10 p.m., $20 cover charge.
• Burlesque Show: Dec. 29, 8 p.m.,
$15.
• Comedy on the Edge: Dec. 30, 8
p.m., $20-$30. PENN’S PEAK (325 Maury Rd., Jim Thorpe) 866.605.7325, pennspeak.com
Josh Turner: Sept. 26, 8 p.m.
•
•
8
•.
Hinder & Candleboxwith Devour
Nitty Gritty Dirt Band: Sept. 27,
p.m.
• King Henry and the Showmen:
Oct. 15-17, 1 p.m.
• Back to the Eighties Showwith
8
•
21, 8 p.m.
• Rhonda Vincent and The Rage:
march 22, 8 p.m. RIVER STREET JAZZ CAFE (667 n. river st., plains)
570.822.2992, riverstreetjazzcafe.
com5
• Pigeons Play Ping Pong: Sept. 26,
10 p.m. $5/$8.
Christmas with The Cars: Dec. 14,
p.m.
An Evening With Vince Gill: Feb.
• Clarence Spady Band with Tony
Carfora on SAX: Sept. 27, 8 p.m.,
$5-$8.
• Wham Bam Bowie Band, Tribute
to David Bowie: Sept. 28, 10 p.m.
$8/$10.
• Mike Mizwinski: Oct. 3, 8 p.m.,
$8-$10.
• Joe Louis Walker: Oct. 4, 9 p.m.
$10/$15.
• The Manhattan Project with
Horizon Wireless: Oct. 5, 10 p.m.
$8/$10.
• George Wesley’s Band: Oct. 11, 8
p.m., $5-$8.
• Strawberry Jam: Oct. 12, 8 p.m.,
$5-$8.
• The Magic Beans: Oct. 17, 8 p.m.,
$5-:
If you’re a David Bowie fan you don’t want to miss out on the Wham
Bam Bowie Band, a tribute to the musical super star. The group will
play Sept. 28 at 10 p.m. at the River Street Jazz Cafe (667 N. River St., Plains Township). For more info or tickets call 570.822.2992 or visit riverstreetjazzcafe.com5.
Sept. 28, 8 p.m., $16. SHERMAN THEATER
(524 Main St., Stroudsburg)
570.420.2808, shermantheater.
com
• moe./Sister Sparrow and the Dirty
Birds: Sept. 29, 7 p.m., $28.
•
7
cage zone seating.
• SOJA: Oct. 10, 8 p.m., $17.50-$20.
• Taking Back Sunday/Polar Bear
Club/Transit: Oct. 14, 8 p.m., $25-
$28.
• Conspirator: Oct. 19, 9 p.m.,
$17-$20.
•
p.m., $22.50-$25.
•
Soul: Oct. 24, 8 p.m., $25-$30.
•
The Ugly/The Big Empty/Badtown
Rude/The Curse of Sorrow: Oct. 25,
7 p.m., $16-$18.
• The Rocky Horror Picture Show:
Oct. 26, 10 p.m. $5 film, $12 pre- party and film.
•
$35-$45.
• Lotus: Nov. 7, 9 p.m., $20-$22.
• In This Moment/Motionless In
White/Kyng/All Hail The Yeti: Nov. 8,
7 p.m., $20-$22.
• Jake Miller: Nov. 19, 8 p.m., $20-
$22.
Twelve-Twenty Four: Dec. 12, 7:30 p.m., $22.
•
Sherman Cage Rage MMA: Oct. 5,
p.m. $35 general admission, $50
Coheed and Cambria: Oct. 20, 7
Umphrey’s McGee/The London
The Misfits/The Attack/Take Away
Gregg Allman: Oct. 29, 8 p.m.,
PHILADELPHIA ELECTRIC FACTORY
(3421 Willow St., Philadelphia)
215.LOVE.222, electricfactory.info
• Neko Case: Sept. 25, 8:30 p.m.
• Korn: Sept. 26, 8:30 p.m.
• Local Natives/Wild Nothing: Sept.
28, 8:30 p.m.
•
Stevenson: Sept. 29, 8:30 p.m.
•
Green Lantern/Branchez: Oct. 3, 8:30 p.m.
•
Birds: Oct. 4, 8:30 p.m.
• Digitour: Oct. 5, 8:30 p.m.
Moe./Sister Sparrow * The Dirty
The Waterboys/Freddie
Zeds Dead/Paper Diamond/ Wolfgang Gartner & TommyTrash:
Oct. 20, 8 p.m.
• Steve Aoki: Oct. 24,
Chunk! No, Captain Chunk!/The
Color Morale/Dangerkids: Oct. 30,
7 p.m.
We Came As Romans/Silverstein/
• Infected Mushroom/Zomboy: Oct. 31, 8:30 p.m.
• Fitz and the Tantrums/Captial
Cities/Beat Club: Nov. 1, 8:30 p.m.
• Matt Nathanson/Joshua Radin:
nov. 2, 8 p.m.
•
May Fire/Breathe Carolina/Issues:
Nov. 4, 7 p.m.
My Bloody Valentine: Nov. 9, 8:30 p.m.
•
nov. 13, 8 p.m.
•
8
Hoodie Allen/OCD: Moosh &
Twist/Mod Sun/D-Why: Nov. 23, 8:30 p.m.
•
•
•
Sleeping with Sirens/Memphis
Alkaline Trio/Newfound Glory:
Reel Big Fish/Goldfinger: Nov. 15,
p.m..
Get The Led Out: Dec. 14, 8:30 p.m.
•
•
•
MGMT: Dec. 3, 8 p.m.
Dark Star Orchestra: Dec. 29, 8:30
p.m.
•
THE FILLMORE AT THE TLA (334 South St., Philadelphia)
215.922.1011, tlaphilly.com
•
7
• Oh Land: Sept. 26, 9 p.m.
• Danny Brown & Action Bronson 2
High 2 Die Tour: Sept. 27, 9 p.m.
• Mike Stud: Sept. 28, 8 p.m.
• Immortal Technique/Brother Ali:
Sept. 29, 8 p.m.
•
p.m.
Streetlight Manifesto: Oct. 2, 7 p.m.
KESWICK THEATRE
(291 North Keswick Ave., Glenside) 215.572.7650, keswicktheatre.com
• Jonny Lang: Sept. 27, 8 p.m.
• Jimmy Cliff: Sept. 29, 8 p.m.
• Blondie: Oct. 3, 8 p.m.
• Robert Hunter: Oct. 4, 8 p.m.
• Kashmir: Oct. 5, 8 p.m.
•
Lotus: Dec. 30, 31, 9 p.m.
Katatonia/Cult of Luna: Sept. 25,
p.m.
Trivium/Devildriver: Sept. 30, 7
•
•
8
•
•
•
• Steven Wright: Nov. 3, 8 p.m. NORTH STAR BAR 27th & Poplar St., Philadelphia
215.684.0808
• Oct. 2: Calabrese
• Oct. 3: The Toasters/Voodoo Glow Skulls
• Oct. 5: Mephiskapheles/Inspector 7, post sun times TROCADERO THEATRE (1003 Arch St., Philadelphia) 215.336.2000, thetroc.com
• The 2013 Philly Zombie Prom:
sept. 28, 8 p.m.
•
•
•
•
7
•
•
Stephen “Ragga” Marley: Oct. 25,
Switchfoot: Oct. 6, 7:30 p.m.
Reverend Al Sharpton: Oct. 10,
p.m.
Steve Hackett: Oct. 11, 12, 8 p.m.
Colin Hay: Oct. 13, 8 p.m.
Fifth Harmony: Nov. 1, 8 p.m.
Andrea Gibson: Oct. 16, 8 p.m.
The Chariot: Oct. 17, 6:30 p.m.
Broadway Idiot: Oct. 20, 3 p.m.
p.m.
The Legwarmers: Nov. 2, 9 p.m.
Less Than Jake/Anti-Flag/Masked
Intruder/Get Dead: Nov. 8, 7:30 p.m.
•
•
7
SUSQUEHANNA BANK CENTER
(1 Harbour Blvd., Camden, N.J.) 609.365.1300, livenation.com/
venues/14115
• Thirty Seconds to Mars: Sept. 29,
7:30 p.m.
• The Weekend: Oct. 4, 8 p.m.
• Pretty Lights: Nov. 1, 8 p.m.
• Paramore: Nov. 8, 7 p.m.
• Slayer: Nov. 29, 7:30 p.m.
The Fresh Beat Band: Dec. 6, 6:30 p.m.
•
WELLS FARGO CENTER
(3601 South Broad St.,
Philadelphia)
215.336.3600,
wellsfargocenterphilly.com
• Selena Gomez: Oct. 18, 8 p.m.
• Drake: Oct. 19, 7 p.m.
• Pearl Jam: Oct. 21, 7:30 p.m.
• Josh Groban: Nov. 3, 7:30 p.m.
• Bon Jovi: Nov. 5, 7:30 p.m.
• Justin Timberlake: Nov. 10, 8 p.m.
• Elton John: Nov. 27, 8 p.m.
• P!nk: Dec. 6, 8 p.m.
• Rod Stewart: Dec. 11, 8 p.m.
• Trans-Siberian Orchestra: Dec. 21,
p.m., 8 p.m. ELSEWHERE IN PA
BRYCE JORDAN CENTER
(127 University Dr., State College)
814.865.5500, bjc.psu.edu
• OneRepublic: Oct. 3
• Bassnectar: Oct. 10, 7 p.m.
• B.B. King: Oct. 13, 7:30 p.m.
• Rod Stewart: Oct. 14, 7 p.m.
• nine inch nails: Oct. 19, 8 p.m.
• Jeff Dunham: Nov. 6, 7:30 p.m.
Macklemore & Ryan Lewis: Nov. 7, 7:30 p.m.
CROCODILE ROCK
(520 West Hamilton st,allentown) 610.434.460, crocodilerockcafe.
com
• The Browning: Oct. 1, 5 p.m.
• A Skylit Drive: Oct. 4, 5 p.m.
• Teddy Geiger: Oct. 16, 5:30 p.m.
• Reverse Order: Oct. 26, 5 p.m.
• Ice Nine Kills: Nov. 14.
• The Word Alive: Nov. 16, 5 p.m.
• Veil of Maya: Dec. 6.
GIANT CENTER
(950 Hersheypark Dr., Hershey)
717.534.3911, giantcenter.com
• Selena Gomez: Oct. 22, 7 p.m.
•
3
Robin Thicke: Feb. 25, 7:45 p.m.
•
Pam Ann: Nov. 14, 8 p.m.
The Devil Wears Prada: Dec. 14,
p.m.
•
p.m.
•
p.m., 7:30 p.m.
SANDS BETHLEHEM EVENT
CENTER
(77 Sands Blvd., Bethlehem) 610.2977414, sandseventcenter.
com
• Steely Dan: Sep. 27, 7 p.m.
• Silvertide: Sept. 29, 6 p.m.
• Daryl Hall/John Oates: Sept. 30, 7:30 p.m.
• Brian Wilson/Jeff Beck: Oct. 6, 7:30.
• Sammy Hagar: Oct. 26, 8 p.m.
• The Black Crowes: Oct. 30, 8 p.m.
• Frankie Valli: Nov. 9, 8 p.m.
• Paramore: Nov. 11, 7:30 p.m.
• Trace Adkins: Nov. 29, 8 p.m.
SOVEREIGN CENTER
(700 Penn St., Reading) 610.898.7299, sovereigncenter.com
• Jason Bishop: Nov. 2, 7:30 p.m.
• Fab Four: Nov. 9, 8 p.m.
• Ina Garten: Nov. 13, 7:30 p.m.
• Drew Carey: Nov. 23, 7:30 p.m. WHITAKER CENTER (222 Market St., Harrisburg)
717.214.ARTS,whitakercenter.org
• Bo Bice: Oct. 10, 7:30 p.m.
NEWYORK / NEWJERSEY
BEACON THEATRE
(2124 Broadway, NewYork, N.Y.)
212.465.6500, beacontheatre.com
•
An Evening with Ian Anderson: Oct. 11, 8 p.m.
•
Zappa Plays Zappa: Oct. 31, 8 p.m. IRVING PLAZA (17 Irving Place, New York, N.Y.) 212.777.6800, irvingplaza.com
•
•
•
Trans-Siberian Orchestra: Dec. 8, 3
The Fresh Beat Band: Dec. 4, 7
Joe Satriani: Sept. 26, 8 p.m.
The Fab Faux: Oct. 26, 8 p.m.
Hinder and Candlebox: Sept. 26,
7
•
p.m.
• Marky Ramone’s Blitzkrieg w/
Andrew W.K. on vocals: Oct. 3, 7
p.m.
•
6
IZOD CENTER
(50 State Rt. 120, East Rutherford,
N.J.) 201.935.3900, meadowlands.com
Justin Timberlake: Nov. 9, 8 p.m. MADISON SQUARE GARDEN (7th Ave., New York, N.Y.)
•
3oh!3/The Summer Set: Oct. 21,
p.m.
Streetlight Manifesto: Oct. 1, 7
p.m.
212.465.6741, thegarden.com
•
1, 8 p.m.
• Paramore: Nov. 13, 7:30 p.m.
• Rod Stewart: Dec. 9, 8 p.m.
RADIO CITY MUSIC HALL
(1260 6th Ave., New York, N.Y.) 212.247.4777, radiocity. Expanded listings at theweekender.com.
W
Ed Sheeran: Oct. 29, 8 p.m. Nov.
WED
BEST OPEN MIC IN N.E.P.A
Doors @ 8pm • Starts @ 9pm • NO COVER
THURS
PRE CITY BISCO SHOW
PIGEONS PLAYING PING PONG OPENING ACT REGGIE WATSON
high-energy mix of funk, rock, electronica & jazz Doors @ 8pm Music @ 10pm
FRI
CLARENCE SPADY BAND W/ TONY CARFORA ON SAX
“Great original Blues by one of the Hottest guitar players in the country” Music @ 10pm Open @ 6pm
SAT
WHAM BAM BOWIE BAND
FT. MEMBERS OF PROJECT OBJECT
National touring David Bowie tribute band “DOING THE COMPLETE ZIGGY STARDUST ALBUM” Doors @ 8pm Music @ 10 pm
NEW SPECIALS
RIVERSTREETJAZZCAFE.com
FACEBOOK.COM/RIVERSTREETJAZZCAFE
@ RSJC667NRIVERST
The Beaumont Inn
MUSIC ON THE PATIO • DALLAS PA. FRI- 8-11PM STRAWBERRY JAM DUO SUN- 5-8 PM FREEMAN WHITE
SenunaS’
Bar &
Grill
133 n. Main St., W-B - (Right across from King’s College)
Voted Best College Bar in Weekender 2013 Readers Choice
Happy HouR SpeCialS
$1.50
Bud, lager, Miller, Coors - pints
$2.00 Cherry/Grape Tic Tac Bombs
$3.00
$2.00
$2.25
$4.00
JaGeRBoMBS
Miller, Coors, Bud or lager - Bottles
import Drafts
14oz long islands
Welcome Back King’s alumni
Thursday Night 10-12 $1 Well Vodka - Rum Drinks - Dom. Drafts $2.25 Fireball Shots
Thursd ay
DJ O’Shea
Friday
DJ O’Shea
saTurday
DJ Hersh
No Cover
Happy HOur:
Mon-Wed 9-11 Thurs-Sat 10-12 Friday - 5-7 & 10-12
$ 5
Combo
HH
Any Shot
+
Any Draft
is $5
Wednesday
MUSICIAN’S
SHOWCASE
WITH JOHNNY NOVA STARTING @ 9:30
Pizza & Mac n’ Chz Night Patsy’s Homemade Pizza 6 or 12 cuts Bud Lt Drafts $2 All Night & LIT Pitchers $4.50
Thursday
TRIVIA
Burger Night
NOW OPEN SUNDAYS @ 4PM
Hours: Mon-Sat 4pm-Close Sunday - 4-Close
Friday
Monday
WINGS
&
YUENGS
Tuesday
MEXICAN
FOOD
NIGHT
ON THE OTHER SIDE
W/ MOCK SUN & DJ PETE NOWAK
Saturday
THE OTHER SIDE
I AM BUFFALO
INSIDE BAR
GENE BURK
AND
FRIENDS
119 S. Main St, WB • 570-970-9570 • bartandurby.com
WEEKENDER, WEDNESDAY, SEPTEMBER 25, 2013
PAGE 14
Wednesday, sePtember 25, 2013
Page 15
we
have
the
ticket
Come
watch
the
games
at
these
NEPA
establishments
279 BAR & GRILL AVANTI PIZZERIA & SPORTS BAR BEER BOYS BOTTLENECKS SALOON & EATERY BREWS BROTHERS, LUZERNE & PITTSTON CAREY’S PUB CHARLIE B’S GROTTO PIZZA HUN’S WEST SIDE CAFE HUN’S CAFE 99 KING’S PIZZERIA MY LOWER END STAN’S CAFE TOMMYBOY’S
WeeKender , Wednesday,september 25, 2013
Collabs fuel celebration of Hagar’s longtime career
albums like these are a hit-or-miss proposition; the cover-heavy, famous
friend tagalong collaborations. such attempts have yielded monstrous victories, like Johnny Cash’s “american” series, or abysmal misfires like the recent metallica/ Lou reed “Lulu” trainwreck. Vocal goliath sammy Hagar tries his hand at this concept with “sammy Hagar
& Friends,” an album that brings
along for the ride bandmates like Hagar’s Chickenfoot pals drummer Chad smith and michael anthony (Hagar’s co-Van Halen holdover), along with notable buddies like Kid rock and Journey’s neal schon. the result is pleasing – no patchwork
quilt of assembled one-offs here; it’s
a classic sammy Hagar buckshot
through and through. perhaps most noticeable is the continued staying power of Hagar’s bombastic, upper-register vocals.
at the age of 65, Hagar continues to defy Father time with his soul-
phrased, agitated vocal candor. this
is evident on tracks like “not going
down,” a bluesy, idle-drive rocker featuring bassist bill Church and drummer denny Carmassi of Hagar’s
seminal early 1970’s hard rock act, montrose. Covers like depeche mode’s “personal Jesus” are given
a playful roadhouse treatment, the
cut sounding like a lost chicken- grea se d out ta ke from ZZ to p’s “tre s Hombres” album, schon’s strings sizzling a bubbling blues. “Knockdown dragout” is probably the most typical Hagar hard-partying, tequila-torrent rock ‘n roll scrape. Hagar and Kid rock trade lead
vocals amid a rhythmic blowout reminiscent of Hagar’s 1997 radio hit, “Little White Lie.” the only real clinker of the bunch may be a cover of Jimmy buffett’s “margaritaville,”
with to by Ke ith on shared le ad vocal – the track’s lackluster waft a bit too karaoke to properly conform
to Hagar’s dynamic personality. a lower-key cut that does work is “all We need Is an Island,” co-written by Heart’s nancy Wilson, with a world- music flair by way of grateful dead drummer mickey Hart’s percussion and ta hitian Uk ulele sea so ned sa lt .
a lighthearted, yet musically potent powerhouse celebration of Hagar’s 40 years in music, this collaboration smacks every inch of Hagar’s fun-in- the-sun, untroubled charisma, and proves the red rocker hasn’t lost a single shade of his musical color.
- Mark Uricheck, Weekender Correspondent
W WWWW
Sammy Hagar ‘Sammy hagar & Friends’
Deer Tick’s latest one of eclectic sounds
by McCauley. Like many albums of 2013, horn sections have snuck into several songs. A blast of brass opens “Trash,” courtesy of Austin collective Grupo Fantasma. Deer Tick’s love song to the open road then mellows into a twangy melody, cresting with a chorus of crash- ing drums and flirtatious horns. “Where’s all the romance that I used to know/I wanna fall in love again with the open road,” McCauley croons, gravelly and swaying with playful nos- talgia, “Checking out past noon, bill me if you want/It’s my disposition as a wasteful savant.” “Thyme” is an enchantingly sinister rock waltz that’ll appeal to fans of And the Moneynotes and Dr. Dog. The presence of ‘70s style ballads peppered throughout “Negativity” echo those in other recent albums, like Band of Horses’ “Mirage Rock.” Vaness a Carlton joins McCauley on the un- romantic realities of relationships on country duet “In Our Time.” “Mirror Wa lls” st ands out with a steady beat, keys that brighten and descend, and a guitar solo wailing for a few bars of speedy sorrow. “Pot of Gold” thrashes with the well- worn energy of early Deer Tick, layering vocals
Deer Tick’s albums have always slinked over persistant drumbeats, tearing the listener past the confines of genre, and their fifth from the countrified doldrums and showcasing
McCauley ’s Cobainesque whine—well-suited for their Nirvana covers side project, Deervana. While the down-and-out sentiments remain throughout “Negativity,” Deer Tick’s coltish
varying from alt-country to sweet folk to spirit, catchy melodies, and accessible lyrics
riled rock.
allow for some mainstream sunshine to peek
full-length album is no exception. The title carries weight through the thread of senti- ment across the 12 tracks, but “Negativity” doesn’t wallow — the sound dips and rises,
The Rhode Island quintet - guitar- out from behind the clouds.
ist John McCauley, bassist Christopher Dale Ryan, drummer Dennis Ryan, gui- tarist Ian O’Neil, and Rob Crowell on keys and sax - all contribute vocals, led
- Kait Burrier, Weekender Correspondent W
he loves. With characteris- tic laid-back charm, Jackson applies his sweet baritone to the hot acoustic pick- ing and soaring harmonies that characterize bluegrass. What Jackson brings to the table is outstanding song- writing — an area where contemporary bluegrass can be lacking. The 54-year-old contributes eight original songs, including the stand- outs “Blacktop” and “Let’s Get Ba ck To Me And Yo u,” as we ll as two by his nephew Adam Wright , who co -produced the collection with Jackson’s longtime studio collaborator, Keith Stegall. Jackson tips his hat to blue- grass history by covering Bill Monroe’s “Blue Moon Of Kentucky” and the Dillards’ great “There Is A Time,” and he runs John Anderson’s “Wild And Blue” through a mountain gap without losing its soulful strength. To Ja ckson ’s credit , he
singers of his generation. Most of his doesn’t aim any of these songs
Ve teran country st ar Alan Ja ckson ranks among the most tradition-based
Alan Jackson adds new facet to sound
influences are on the surface: honky- to fit country radio’s format. tonk, swing, blues and songs both Instead, he concentrates on romantic and social that draw on details making a solid string-band
from his personal life.
album for the ages — and suc- Bluegrass ceeds.
- Michael McCall,
Album,” much like his two collections
of gospel hymns, brings out another Associated Press W
form of American roots music that
Jackson’s
new
“The
To p 8 at 8 with Ra lphie Aversa
8.
Macklemore/R ya n Le wis/Mar y Lambert: Same Love
6.
Need Your Love
7.
Lorde: Royals
Calvin Harris/Ellie Goulding: I
Capital Cities: Safe and Sound Katy Perry: Roar Avicii: Wake Me Up Lana Del Ray: Summertime
5.
4.
3.
2.
Sadness
1. Lady Gaga: Applause
To p 10 Albums at Galler y of So und
1. Jack Johnson: ‘From Here To Now To You’
2. Elvis Costello & The Roots: ‘Wise Up
Ghost’
3. Justin Moore: ‘Off The Beaten Path’
4. Rick Ross Presents: ‘Self Made 3’
5. MGMT: ‘MGMT’
6. Avenged Sevenfold: ‘Hail To The King’
7. Gwar: ‘Battle Maximus’
8. 2 Chainz: ‘B.O.A.T.S. II #Metime’
9. Five Finger Death Punch: ‘Wrong Side
Of Heaven & Righteous Side Of Hell V.1’
10. Grateful Dead: ‘Sunshine Daydream’
Wednesday, sePtember 25, 2013
Ono’s Bar&Grill
Open Sunday at 12:00 Noon
NFL Sunday Ticket
8:00 pm - 10 pm
Dollar mugs
With Jill
236 Zerby Ave. Kings ton, PA 283-2511
Wednesday, sePtember 25, 2013
Page 19
2,. com)
• Mon., Wed., Fri., 9-10 a.m. Private
training on Cadillac,reformer and Wunda Chair, along with Pilates mat
classes, stability ball core classes, more. Check website for updates.
• Mon., Wed.: Nia Technique, 5:30 p.m. American Wicca Study Group ()
• “The Pagan PowWow:” third
saturday of every month, 7 p.m., the garb Wench, 13 n. main
St., Ashley. • Tarot readings by Jamie dana by appointment,
570.235.0741.
Arts YOUniverse
(47 n. Franklin st., Wilkes-barre, 570.970.2787,. com),. com, info@bellasyoga.com) All workshops $15, pre-registration suggested.
• Sun. Class: 10-11:15 a.m. Features
alternating Vinyasa style yoga w/ yoga fusion. Candy’s Place (190 Welles st., Forty Fort.
570.714.8800)
$35 a month for all classes, $7 per
class. First class is free for everyone.
• One on One Personal Training and
Yoga for breast cancer survivors:
Requirements include a breast cancer diagnosis, a doctor’s note for participation, and all forms to be
filled out prior to participation. Free.
• Gentle Yoga: Tuesdays and Thursdays, 5:30-6:30 p.m.
Introduction to the benefits of
learning to relax and energize with yoga specially designed for people with or without cancer.
• Meditation and Deep Breathing:
Wednesdays, 5:30-6:30 p.m.
• Strength and Balance: Mondays,
5:30-6:30 p.m.; Wednesdays, 4:15- 5:15 p.m. Several forms of exercise,
such as yoga, Pilates, and weights to help increase strength and improve balance
• Standing Strong: Mondays, 10:15-
11:30 a.m.; Wednesdays10:15-11:30 a.m.; Thursdays,10:15-11:30 a.m.; Fridays,10:15-11:30 a.m. Incorporates cardio exercise with
a dance flavor and includes an infusion of weights. Club Fit (1 West broad st., Hazleton,
570.497.4700,.
com)
• Boxing classes w/ Rich Pastorella (pastorella.net26.net). mon., 7-8 p.m. $40/month. Goddess Creations Shop & Gallery (214 depot st., Clarks summit, 570.575.8649, info@ goddesscreations.net)
• Tarot Card Readings by
appointment.., 6:30- p.m., Body Language
studios (239 schuyler ave, Kingston)
• Tues., 7:00 p.m., Jaya Yoga (320
south state street, Clarks summit)
• Wed., 6 p.m., Holistic Health
Center (route 6, tunkhannock) Harris Conservatory for the Arts
(545 Charles st. Luzerne, 718.0673)
setting/stress reduction, more. Call for info/reservation.., Weds.: 9 a.m., 5:30 p.m. (90
minutes), 7:30 p.m. (one hour)
• Tues.: 9 a.m. (Hot Power Fusion),
4 p.m. (one hour), 5:30 p.m. (90 minutes)
• Weds.: 9 a.m., 5:30 p.m. (90
minutes), 7:30 p.m. (one hour)
• Hoop Fitness Techniques: Mon.,
7:30-8:30 p.m. $5/class. Call for info. Hapkido Taekwondo Institute (210 division st., Kingston. 570.287.4290,, masterpete@htkdi.com) Learn self-defense, get in shape and reduce stress today at the
Hapkido Taekwondo Institute in Kingston. new student special of $99 for 3 months includes uniform. take a free trial class and check us out - you’ll be glad you did! Special
children’s and women’s self-defense classes are offered as is weapons training.
Inner HarmonyWellness Center (mercy Hospital general services Bldg., 743 Jefferson Ave., scranton, 570.346.4621, www. innerharmonywellness.com, peteramato@aol.com)
• Meditation Technique Workshops:
Wed., 6:30 p.m. $15/session. Goal
class)
• Fri.: 9 a.m. (90 minutes), 5:30 p.m. (Hot Power Fusion)
• Sat., Sun.: 9 a.m. (90 minutes), 11 a.m. (Hot Power Fusion), 3 p.m. (90 minutes) Odyssey Fitness (401 Coal st., Wilkes- barre, 570.829.2661, odysseyfitnesscenter.com)
• Yo ga Clas ses : Sun., 12:30 p. m.;
Mon., 7: 15 a.m.; Tu es. ,. info.
Expanded listings at
theweekender.com. W
Actors Circle at Providence Playhouse (1256 Providence Rd, Scranton, reservations:
30, $30 after that date.
• USO-style show to
honor local veterans at Veterans’ Day: Nov. 9. $35
Sept. 13-14, 8 p.m.; Sept.
15, 2 p.m. $18, adults; $15, seniors; $10, children 12 and under.- playwrights@live,
plays; $20, musicals; $86, summer pass, first five shows; $120, season pass. All shows are BYOB and
feature cabaret seating. • “The Mousetrap:” Sept. 13, 14, 19-21, 8 p.m.; Sept. 15, 22, 3 p.m.
• “Sweeney Todd: The
Demon Barber of Fleet. Little Theatre of Wilkes-Barre ( 537 North Main
StreetWilkes-Barre.
570.823.1875.)
• “National Pastime”:
September 2013 The Moose Exchange (203 W. Main St ., Bloomsburg)
• “Lucy, I’m Dead!”: Nov.
2, 7:30 p.m. $25 until Sept.
7-13, 6:30 p.m. - 7:30 p.m.
Adults, 7:30 p.m. - 9:30 p.m.
• A Chirstmas Carol-
The Musical: Dec. 5-8, 12-15, 19-22
The Phoenix Performing Arts Centre (409-411 Main St.,
Duryea, 570.457.3589, phoenixpac.vpweb.com,
phoenixpac08@aol.com)
• Phoenix Kids present
“Willy Wonka the Musical”:
Sept. 13-29, 7 p.m. Fridays and Saturdays, 2 p.m.
Sundays. $10. din- ner, beverages during din- ner, the show, and tax. Shawnee Playhouse (570.421.5093, theshaw-
neeplayhouse.com)
• “Roses in December:”
(84 W. So uth St , Wi l.
• “The No-Frills Revue”:
Feb. 14-15, 21-22, 8 p.m., Feb. 16, 23, 2 p.m.
An Evening of One Act Plays by Anton Pavlovich Chekov: April 3-5, 8 p.m., April 6, 2 p.m. Expanded listings at theweekender.com..
WEEKENDER, WEDNESDAY, SEPTEMBER 25, 2013
PAGE 20
at
KKKIIINNNNNNG’SG’SG’SGGG’’’SSS
Saturday September 28th
(on deck) Revolution 3 Beatles Tribute and Classic Rock
49 S. Mountain Blvd., Mountaintop 570-474-5464
#MARCSTATTOOING
PIERCING OF THE WEEK
Saturday Iron Cowboy
NFL TICKE T
Sun - open @ 12 Mon- open @ 7
stomtat2
/customtat2
Wednesday, sePtember 25, 2013
Page 21
Book reviews and literary insight
Kacy Muir | Weekender Correspondent
Somebody to love
One of the most important gifts of life is love. Many of us spend our lives falling in and out of love with the world. We learn about ourselves, for better or for worse. After all that soul searching, we look for somebody to love, hoping that one day we will we eventually find that someone. Enter protagonist, Marie Commeford, of Alice McDermott’s latest novel, “Someone”. Marie takes readers on a non-linear jour- ney through life, love and loss. McDermott, who was pre- viously awarded the National Book Prize for her novel “Charming Billy,” has gone on to win various awards in addition to being thrice nom- inated for the Pulitzer Prize. As a result, the continued maturity, poise and brilliance that McDermott has created with “Someone” may prove to be her most pivotal work yet. Readers are introduced to Marie at a young age. We soon find that she is suffer- ing from severe myopia, an eye disorder that eventually destroys her ability to see clearly. However, the condi- tion never once denies her the ability to see the wonder and beauty around her:
“Slipping out of that first darkness, into the dusty, city light of these rooms, I met the blurred faces of the parents I’d been given — given through no merit of my own — faces that even to my defective eyes, ill-formed, you might say, in the hours of that first darkness, were astonished by love.” Marie’s family gathers much of the readers’ emotion within the novel, particu- larly her brother Gabe, who, while religious, decides to
‘someone’ By alice Mcdermott rating: W W W W W
leave the priesthood. While the reasons are unknown, McDermott allows readers to come to their own con- clusions. Nevertheless, even in Gabe’s ambiguity, readers grow to admire and care for him as a man who is both genuine and noble. Narrating the book as a senior, Marie bridges one of her first memories — wait- ing for her father on the steps of their Brooklyn home to everything in between — to love, marriage, motherhood, faith and death. Even consid- ering McDermott does not heed to chronological order, there remains a great balance
to the work. The descrip- tions are vivid and mesmer- izing, transporting readers to each given scene with preci- sion. The pages move like a perfected pirouette, whirling with ease and grace. The novel showcases that there is more than one per- son with the ability to love us; they are those who can take us in without judgment, even knowing our darkest secrets and deepest flaws. In the end, Marie’s life becomes a culmination of events recap- tured not through her dimin- ishing sight, but through a clear lens of wisdom. W
BooKs rele ased the WeeK of sept. 30:
• ‘David and Goliath: Underdogs, Misfits, and the Art of Battling Giants’ by Malcolm
Gladwell
• ‘One Summer: America, 1927’ by Bill Bryson
• ‘The Signature of All Things’ (Signed Edition) by Elizabeth Gilbert
• ‘Golden Malicious’ (Orchard Mystery Series #7) by Sheila Connolly
• ‘Brea k Ou t!: 5 Keys to Go Beyo nd Yo ur Ba rriers and Live an Ex traordinar y Life’ (Signed Edition) by Joel Osteen
poetIC Egyptian Lecture Series:
• “Egypt Before the Pyramids:” Sept.
27, 2 p.m., Plymouth Public Library (107 W. Main St., Plymouth).
• “CSI: Ancient Egypt:” Oct. 18, 2
p.m., Mill Memorial Library (495 E. Main St., Nanticoke).
• “Death on the Nile:” Oct. 19, 11:30
a.m., Osterhout Free Library Central Branch (71 S. Franklin St.,Wilkes- Barre).
• “I Want My Mummy:” Oct. 24, 6
p.m., West Pittston Library at Trinity Episcopal Church (220 Montgomery Ave.,West Pittston).
• “X-Raying the Pharaohs:” Nov.
7, 5:30 p.m., Hoyt Library (284 Wyoming Ave., Kingston).
• “Food in Ancient Egypt:” Nov. 8, 3
p.m., Osterhout Free Library North
Branch (28 Oliver St., Wilkes-Barre).
• “Mummies Through Time:” Nov. 9,
11:30 a.m., Pittston Area Memorial Library (47 Broad St., Pittston).
• “Everywhere the Glint of Gold:”
Nov. 14, 6:30 p.m., Back Mountain Memorial Library (96 Huntsville Road, Dallas).
• “Show me the Mummy:” Nov. 15,
2 p.m., Hazleton Area Public Library (55 N. Church St., Hazleton).
• “Searching for Cleopatra:” Nov. 16, noon, Wyoming Free Library (358 Wyoming Ave.,Wyoming). forty fort Meeting house
(across from the Forty Fort Borough Building on River St. Forty Fort) Lecture Series
• “Early Travelers, Traders, &
Residents of Wyoming Valley” with
Clark Switzer: Sept. 15, 3:30 p.m.
• “Wyoming Valley’s First Jews:
The German Connection”with Dr.
Sheldon Spear: Sept. 22, 3:30 p.m.
• Vesper Service with Rabbi Kaplan
of Temple Israel: Sept. 29, 5 p.m. friends of the scranton public library (520 Vine St., Scranton,
570.348.3000)
• Used Book Sale at Library Express
in the Mall at Steamtown: Sept.17-22..
• Gold Room, Administration
Building; Oct. 30, 7 p.m., Gold Room, Administration Building.
• Campion Literary Society Writing
Workshops: Oct. 17, 4 p.m., Sheehy- Farmer Campus Center.
• Reading by Amy Bloom: Oct. 22, 7:30 p.m., Burke Auditorium. the osterhout free library
(71 S. Franklin St., Wilkes-Barre, www. osterhout.info, 570.821.1959)
• Socrates Café Discussion Group:
Sept. 12, 6:30-8 p.m.
• Knit & Crochet Group: Sept. 14, 28, 10:30 a.m.-noon.
• Franklin St. Sleuths Book
Discussion: Sept. 19, 6:30 p.m.
“Murder in Little Italy,” by Victoria Thompson.
• Personal Power Brown Bag Lunch:
Sept. 23, 12:15-1 p.m.
• Personal Power Evening Program:
Sept. 23, 6-7:30 p.m.
• Fall Gala: Oct. 4, 6-11.
Westmoreland Club (59 S. Franklin St., Wilkes-Barre).
pittston Memorial library
(47 Broad St., 570.654.9565, pitmemlib@comcast.net)
• Taste of Greater Pittston: Sept. 8,
2-5 p.m. $30.
• Library expansion committee
meeting: Sept. 11, 6:30 p.m.
• Teen Advisory Group (TAG)
meeting: Sept. 12, noon.
• The Greater Pittston CharityTrain
Ride: Sept. 15, 9 a.m., to Jim Thorpe.
$65.
(225 Center St. Bloomsburg.
570.204.7847)
Gallery Hours: Tuesday-Thursday,
9 a.m.-4 p.m.; Friday, 9 a.m.-8 p.m.; Saturday, 10 a.m.-2 p.m.)
• Anthony Ferro /NewWorks 2013/
Oil Pastel on Paper: Oct. 1-26.
Opening reception Oct. 5, 3-6 p.m. Converge Gallery
(140 W. Fourth St., Williamsport,
570.435.7080, convergegallery.com)
• Beyond The Surface: Sept. 5, Oct.
31. Opening reception and artist talk by Jason Bryant Sept. 5, 6-9 p.m.
• Movie night: Sept. 26, 5:45 p.m.
• Intro to Financial Aid and
Scholarships Workshop: Sept. 26, 6
p.m. Free for parents and students presented by NEPA Career and College Counseling Associates. No registration is required. scranton storyslam:
Scranton StorySlam, Jessup: ATaleYears of Painting, Carol
Oldenburg and Earl Lehman: Sept.
5-28.
• “Gates to Infinity”: Sept. 5-28.
• Choose Freedom, drop-in
meditation classes: Through Sept. 19,
7-8:30 p.m. $10 per class.
• “This Show Is For The Birds”: Oct.
4-29..
Center street Café and Gallery
(1901 Mulberry St., Scranton,
PA, 570.346.7186,- museum.org) Admission $5 adults; $3 students/ seniors; $2 children 6-12; members free.
• Sidewalk Surfing: The Art & Culture
of Skateboarding: Through Dec. 30. exhibit of diane Grant Czajkowski, “Nature and pet portraits”:
Sept. 12-25, Citizens Bank (Kingston Corners, 196 S. Wyoming Ave, Kingston). Open during bank hours:
Monday through Thursday, 9 a.m.-5 p.m.; Friday, 9 a.m.- 6 p.m. hazleton art league (225 E. Broad
St., Hazleton, hazletonartleague.org)
• DylanFest: Seot. 22, 1 p.m.
hope horn Gallery (Hyland Hall, Universityof.
the linder Gallery at Keystone College
(570.945.8335, keystone.edu/ lindergallery)
• “James Harmon: Planned. | https://it.scribd.com/document/170837935/The-Weekender-09-25-2013 | CC-MAIN-2020-34 | refinedweb | 8,549 | 78.04 |
Defying Classification topic feed: software/django Tredinnickmalcolm@pointy-stick> Preparing For The Next Django Sprint 2008-02-15T23:59:02ZMalcolm Tredinnickmalcolm@pointy-stick.com <p>In a little over four weeks (17 March in the US), Django will have another one of our code sprints. The 'main event' will be in Chicago, USA, where a <a href="">bunch of people</a> will be taking advantage of the post-PyCon sprint sessions for three days. However, as always, remote participation is possible and encouraged. </p> <p>Somebody recently asked on <a href="">django-users</a> what they could to prepare for the sprint, since this was going to be their first time. Jacob has <a href="">promised</a> to give an introductory tutorial on the day in Chicago, which will help those present in person. For others, here are my thoughts on how to prepare (and why now isn't too early to start if you want to get some real work done). </p> <h2> What Not To Do</h2> <p>From IRC during the September Django sprint: </p> <pre><code </code></pre><p>Too much sharing right there. Enough said. </p> <h2> Choose Your Own Adventure</h2> <p). </p> ). </p> <p> <strong>(Non-)Suggestion #1:</strong>. </p> <p> <strong>Suggestion #2:</strong> Have a look at the <a href="">full list</a>. </p> <p. </p> <p). </p> <p. </p> . </p> <p> <strong>Suggestion #3:</strong> Make sure your laptop or desktop machine is ready for work beforehand. If you're going to be writing patches for Django, you're going to have to be able to test them. This means being able to run the test suite. Read the unit-testing section in <a href="">contributing.txt</a> because people forget to create settings files and the like. </p> <p. </p> <p"? </p> <p <a href="">Buildbot</a>, which includes Python 2.3 + SQLite amongst it's clients. Ironically, as I write this, I notice there's a 2.3 failure from something I checked in a while back (not sure why it's failing, though). Kind of proves my point in an embarrassing fashion. </p> <p. </p> <p> <strong>Suggestion #4:</strong>. </p> <p). </p> <p> <strong>Suggestion #5 (something easier):</strong>. </p> <p> <strong>Suggestion #6 (also fairly easy):</strong> Go through tickets in the "unknown" component and try to find a better component for them. That will help people working on suggestion #2, for a start. </p> <p> <strong>Suggestion #7 (be a tester):</strong>. </p> <p>Also, you'll sometimes find help requests in the ticket tracker (although we usually catch those). They can be quietly closed with a note pointing the person to django-users for support help. </p> <p> <strong>Suggestion #8 (for foreign language speakers):</strong>. </p> <p. </p> Django Tip: Application-level context processors 2008-02-12T14:53:05ZMalcolm Tredinnickmalcolm@pointy-stick.com <p>Whilst going through my feed reading this morning, I read the application-level context processors <a href="">were not possible</a>. This came as a bit of a shock, since I've been using them for a while now. :-) </p> <p>It's not hard and there's an interesting conclusion to be drawn about the power of scoping rules (plus a reprise on my thoughts on why putting everything under the sun into a framework isn't a great idea). </p> <h2> Some Context</h2> <p>This post is essentially a reply to <a href="">a reply </a> to <a href="">a post</a>. </p> <h2> Context Processors</h2> <p> <a href="">Context processors</a> in Django are functions that run just before a template is rendered. A template is given a bag of data (the <em>context</em>) and context processors can add to that bag of data. A context processor is <em>only</em> given the <a href="">request object</a>;. </p> <p>Django also provides the ability to provide extra context processors directly to the <a href="">RequestContext</a> object. Sometimes this is used to run a particular context processor for a single view or a small subset of views. The drawback (unless you step back for a minute) is that you have to specify these extra processors each time. </p> <p>Well, no. You don't. </p> <h2> Writing a replacement RequestHandler</h2> <p <em>want</em>. </p> <p>Drop this into a file somewhere: </p> <pre><code>from django import template def make_request_context(extra_processors): class MyRequestContext(template.RequestContext): def __init__(*args, **kwargs): processors = list(kwargs.pop('processors', ()) super(MyRequest, self).__init__(processors=extra_processors + processors, *args, **kwargs) return MyRequestContext </code></pre><p>Now, whenever you want a RequestContext-like class that always runs a specific set of context processors, you call <em>make_request_context()</em>, passing it a list of the extra processors. </p> <p>For example, if you have one file with all your views in it, you could put this at the top: </p> <pre><code>MY_CONTEXT_PROCESSORS = ( super.secret.special.processor.stuff, ... ) RequestContext = make_request_context(MY_CONTEXT_PROCESSORS) </code></pre><p>and your code will work transparently (that's why I called it <em>RequestContext</em> here, so that existing code won't require any change. Slightly contradicts the above advice and I wouldn't personally do this, but it's your call to make). </p> <p. </p> <h3> Aside: Why Not Use a Metaclass?</h3> <p>Now, it's possible to write <em>make_request_context()</em> using a metaclass and a <em>__new__()</em> method. But why bother?? That just adds extra complexity because you have to remember the signature for <em>__new__()</em> <em>__new__()</em> method in the Python docs: it was originally created so that it was possible to subclass built-in types like <em>int</em> and <em>str</em>. Everything else was already possible. </p> <p>Again, sometimes a metaclass makes things a little neater. Sometimes it's a line ball. Often, it's just showing off. </p> <h2> Conclusion: Put It In Django Core?!</h2> <p>[Pure personal opinion here. I do not have my Django maintainers hat on, outside of the first sentence of the next paragraph.] </p> <p. </p> <p. </p> <p). </p> <p. </p> Django Tip: Complex Forms 2008-01-06T13:39:10ZMalcolm Tredinnickmalcolm@pointy-stick.com <p>On the Django mailing list, we periodically see requests for help by somebody trying to create a semi-complex form of some description. Often, getting a second perspective is a good choice because the original poster was overlooking a possibly easier alternate approach. </p> <p>Today, I want to fill in one of the gaps. Something that is really easy once you know the machinery and possibly not so obvious until you sweat it out once: putting multiple repetitive sections into a single form. </p> <h2> The Problem</h2> <p>Let's consider a fairly typical example. You are presenting a selection of multiple choice questions. A <em>Quiz</em> model contains a number of <em>Questions</em>, with each question having a number of <em>Answers</em> associated with it, one of which is the correct answer. I knocked together the following models: </p> <pre><code) </code></pre><p>All of this code is available for <a href="">download</a>. The admin user is <em>admin</em> and password is <em>abc123</em>. As you'll see in the download, I've simplified things slightly for conciseness here; leaving out the <em>Admin</em> classes and the like.. </p> <p>Given a quiz id, I want to display the associated questions and their answers in a single HTML form. </p> <h2> Designing The Forms</h2> <p>I'll be using Django's <em>newforms</em> package here, since <em>oldforms</em> is... well... old (and deprecated for good reasons. Don't use it in new code). </p> <p>This is the step where many people get tripped up because it looks like displaying many questions, each with many answers doesn't fit naturally into the layout of the form classes. The trick is to remember that a <em>newforms.Form</em> class corresponds to an HTML form fragment — not the entire HTML form. This is why you need to supply the outer <form>...</form> tags yourself, for example. You can happily use multiple form classes (at the Python level) to produce one form at the HTML level. </p> <p. </p> <p>The form class might look something like this:: </p> <pre><code) </code></pre><p <em>correct_answer</em> on the <em>Question</em> model creates a hidden attribute <em>correct_answer_id</em>, which is the primary key value of the related entry. So I can get away with comparing primary key values to check for the correct answer. </p> <p>Finally, I added a convenience method, <em>is_correct()</em>, (<em>self.correct</em>) to a string before comparing with the form submission. Forgetting something like that can add a few minutes to the debugging process, although after you do it once or twice, you tend to remember forever. </p> <p <em>prefix</em> attribute accepted by the <em>Form</em> class. The <em>prefix</em> is attached to the front of any elements produced by that form instance. So we can display multiple questions by giving each one a different prefix. </p> <p: </p> <pre><code </code></pre><p>This function creates one form for each question and returns the list of form instances, as required. The <em>data</em> parameter to the function is used when a form submission is made (it will be the <em>request.POST</em> dictionary) Initialising a form with <em>data=None</em> creates an unbound form, which is why I've chosen that default. </p> <h2> The Views and Templates</h2> <p>We have a function to create forms for a given quiz. Now let's pull it together in a view. </p> <pre><code}) </code></pre><p. </p> <p. </p> <p>Attentive readers will notice that I'm using <em>urlresolvers.reverse()</em>. </p> <p>Display the result of this view in a template is done with something like this: </p> <pre><code> <form action="." method="post"> <ol> {% for form in forms %} <li> <p>{{ form.problem }}</p> {{ form.as_p }} </li> {% endfor %} </ol> <input type="submit"> </form> </code></pre><p>Of course, in practice, you'll probably do a lot more here with CSS classes and perhaps a custom display method instead of <em>as_p()</em>, but that's fairly standard stuff and would take us too far afield for our current purposes. </p> <p>I haven't given the results display view here, but you can find it in the <a href="">source code</a>, along with the URL definitions. You can fire up the development server (<em>./manage.py runserver</em>) and point your browser to to see the example in action. </p> Django Tips: Source Code Filenames 2007-11-14T22:58:24ZMalcolm Tredinnickmalcolm@pointy-stick.com <p>Following on from <a href="">last week's post</a> about writing code that isn't tied to a project structure in Django, here are a couple of other quick thoughts about file naming and layout. </p> <p>(Apologies to the half dozen or so people who read this blog for the "anything but Django" content. I've been spending all my free time in the last week working on Django, so it's buzzing around in my head at the moment.) </p> <h2> The Executive Summary</h2> <p>I mentioned last week that your settings file doesn't have to be called <code>settings.py</code> and your root URL configuration (or any other URL configuration) file doesn't have to be called <code>urls.py</code>. In a similar vein, it's worth remembering that almost nothing <em>has</em> to be called by a particular name or put in a particular place. The number of required files are few enough we can list all of them: </p> <ol> <li> Django <em>applications</em>, which are listed in the <code>INSTALLED_APPLICATIONS</code> list <code>from app_name import ...</code> for any <code>app_name</code> in your application list. </li> <li> If your application contains any models, they must be in a <code>models</code> namespace in the application directory. This means either <code>models.py</code> or a directory called <code>models/</code>, containing all you models. We'll talk about this a bit more below. </li> <li> Any template tags you write must live under a directory called <code>templatetags</code> in your application directory. You can have subdirectories underneath the <code>templatetags/</code> directory, but that must be the root of the hierarchy. </li> </ol> <p>Everything else is unrestricted (constrained only by Python's syntax and semantics). </p> <h2> The Restrictions</h2> <h3> Models</h3> <p>If you only have a few models, a single <code>models.py</code> <code>model</code> namespace by writing things like this in <code>models/__init__.py</code>: </p> <pre><code>from file1 import ModelA, ModelB from subdir.file2 import ModelC </code></pre><p>Secondly, each model needs to set the <code>Meta.app_label</code> attribute to the name of the application is you're using this directory method. In this fashion, you can happily use as many files and subdirectories as you like under <code>models/</code> </p> <p>At the moment, this is a little messy — needing to specify <code>app_label</code> and import each model explicitly. Fortunately, I have a feeling it's probably not too hard to fix when we get down to it (although lot of attempted fixes keep overlooking things like nested directories and files that only contain utility functions or model managers). <a href="">Adrian</a> has a plan that would seem to fix a few of these related problems, which he explained to me at one point, although I'm not completely clear on all the details. So I would expect this slight wart to go away in the near future. </p> <h3> Template Tags</h3> <p>Although custom template tags are required to live under a <code>templatetags/</code> hierarchy, that's as far as the restriction goes. You can use whatever file names you want (subject to Python's rules again). You can also use sub-modules (sub-directories, each containing an <code>__init__.py</code> file). So if you have <code>app_name/templatetags/foo/bar/baz.py</code>, you can write </p> <pre><code>{% load foo.bar.baz %} </code></pre><p>in a template and it load your template tags from <code>baz.py</code>. </p> <h2> The Non-Restrictions</h2> <p>All other file and directory names are completely unrestricted. This freedom is apparently a source of confusion because of the tendency to use common names (<code>views.py</code>, <code>urls.py</code>, <code>settings.py</code>). </p> <p>Some quick notes on a few of the cases that cause confusion for those who still aren't believers... </p> <h3> VIews</h3> <p>A Django <em>view</em> is just a Python callable that accepts at least one argument (the <em>HttpRequest</em> object as the first positional argument) and returns an <em>HttpResponse</em>. Any function that meets that interface is sufficient. You can store it anywhere. You can load it however you like. It doesn't even have to be a function (a class with a <code>__call__</code> method is used in some cases in the Django source, for example). </p> <p. </p> <h3> Templates</h3> <p>Almost certainly by this point, somebody thinks I've made a mistake because templates must go in the <code>templates/</code> directory of your application so they can be loaded, right? Wrong! That is only true if you decide to use the <code>app_directories</code> template loader. This is a handy loader in a lot of cases, since you can don't need to make any extra configuration changes when you add new templates and it's a loader that is available in the default configuration. But don't confuse <em>possible</em> with <em>compulsory</em>. </p> <p>For all its benefits, be aware that the <code>app_directories</code> loader does have some drawbacks: it collapses all of your <code>templates/</code> directories (for each application) into one, in effect. So name collisions are possible and not always easy to avoid if you're lazy and pick really common names (like <code>index.html</code>). This has led to the practice of people always putting a sub-directory under their <code>app_name/templates/</code> directory, also called <code>app_name</code>, so that each application's templates are loaded as <code>app_name/index.html</code>,. </p> <p>What is possibly not widely realised is that the first template loader Django tries to use is the <code>filesystem</code> loader. This looks in the template directories listed in the <code>TEMPLATE_DIRS</code> setting for templates to load. It's used a lot to create site-wide templates, but can also be handily used for loading application templates: just append your application's root template directory into <code>TEMPLATE_DIRS</code>. This also means that even if somebody writing a third-party app has forgotten you might not be using the <code>app_directories</code> loader, you can still put <code>app_name/templates/</code> into <code>TEMPLATE_DIRS</code> and have the <code>filesystem</code> loader do the work. </p> <p. </p> <h2> Conclusion</h2> <p. </p> Django Tip: External Database Backends 2007-11-11T20:26:00ZMalcolm Tredinnickmalcolm@pointy-stick.com <p>I was going to write a longer Django entry today about WSGI, but I've been spending time working on Django code instead, so a here's something shorter and possibly less useful that deserves some attention from Django users. </p> <p>Every now and again, somebody has a need to change the behaviour in Django's existing database backends. Or they want to develop a new backed for, say, <a href="">Firebird</a> or Microsoft's SQL-Server or something. A couple of months ago (in <a href="">revision 6316</a>), George Vilches contributed a patch that gave Django the ability to import external database backends. </p> <p>This means you can set the <code>DATABASE_ENGINE</code> setting to any importable Python module that acts like a Django database backend. You need to have the same main files as in the Django backed (<code>base.py</code>, <code>creation.py</code>, etc), but you can also add extra files, reuse some of the existing code, or pretty much do whatever you like. </p> <p>It's even <a href="">documented</a>, which means people are encouraged to use it. </p> <p>The net result of all this is that anybody wanting to add an extra backend to Django can happily develop it and provide support as a third-party module. This cuts down on the inconvenience for those developers and also makes the Django maintainers' life easier, because existing support and a history of maintenance is required for anything we're likely to include in core. </p> <p>Most people aren't going to need this functionality. Every now and again, though, somebody, somewhere will want to change the default character column type for Oracle to something different from what Django uses. Or will want to add support for their favourite underused database server. This is now possible and doesn't require making changes to the core code. Hooks like this, that are unobtrusive and don't have any real performance impact (we check it once at import time) are really the way to go for extensible frameworks (where extensions are justified; not everything has to be customisable). </p> | http://www.pointy-stick.com/blog/feeds/topics/software/django/atom.xml | crawl-001 | refinedweb | 3,279 | 54.93 |
How I’m hacking my way into Ruby on Rails web development
Everyone can learn to code, and they won’t be a nothing anymore. Yes, sure. Everyone has a computer. There are tons of online resources. But where to start? How not to give up? How to get a certification when you are self-taught? Is there really still a shortage of programmers? How do I compete against the college kids? When am I ready to apply for my first job as a developer? What programming language should I learn? Are online courses and MOOCs worth anything, or should I wait to save money for a “real” training, IRL, with professionals?
For all these questions, there are also lots of online resources. And you can ask online communities, and many coders are happy to help. But there are too many answers, and the more information you gather, the more you realize that “just learning to code” won’t be as easy and straightforward as you thought, especially if your aim is to become a professional coder.
Learn C the hard way
Several times I tried to learn alone : different flavors of Basic, a bit of Javascript, I even once decided to tackle a tutorial called “Learn C the hard way”, because I was ambitious and I had heard that many students in prestigious schools (like école 42 in Paris) had to start with C (low level programming). I crashed and burnt not quite long after compiling a “hello world” program… Hell, I even did “hello world” in Assembly! Not sure how that would impress a recruiter in a webdev job interview though. Then, thanks to my background in education, I started googling the phrase “learn by doing”, because I was tired of the same old online courses with chapters on what’s a variable, what’s a loop, what’s an array, etc. I eventually found a learn-by-doing Python tutorial called Learn cryptography with Python. This was fun and motivating because I like crypto, I held on for maybe eleven lessons, until I reached the famous (simple) Caesar cypher, which I passed. As I was pretty proud, I started googling for job opportunities in cryptography to have an idea of an aim. Well, the only offer I found was a promising government “junior” position. I read the long text eagerly, it was quite exciting, they especially wanted passionate people with a strong taste for code, Python being a plus. All good… Until I started reading the minimum curriculum requirements, and that was a PhD in maths. Bummer.
Classic, expensive training
Then I got lucky with the job centre and government decisions in France : I was offered a 4 months training in web development, with a one month internship at the end. I found it hard to say “yes” because it was not Python (now I had a clear idea of what was in fashion and in demand), it was not cryptography or blockchain or big data analysis or all these fancy stuff. Just a classic web development training in a no-name school, fullstack but with a focus on the front end (Photoshop, Animate, Illustrator, CSS…). Hell, I said yes, and proceeded with the codecademy courses that were required as minimum level for admittance. It was nice to have someone pick the courses for me and to have a deadline. Then I started the training with 7 hours a day of classes in HTML5, CSS3, CSS preprocessors, PHP7, Javascript, jQuery, Photoshop, one week of object-oriented PHP, and eventually one week of introduction to the most popular PHP framework in France, Symfony. It was nice but the “learn by doing” aspect was completely absent. Many students had a background as illustrators or web designers, but most people had never done programming, so our teachers struggled to dumb everything down so that even the slowest student could follow. Which means that most classes consisted in a teacher writing code on his virtual blackboard, and us copying everything word for word on the computers in class. Then the panicked teacher, always behind schedule, would pass in the rows to debug everyone’s code, to find the missing semi colon or the fatal typo. When all the typos were eventually found and the program worked as on the virtual blackboard, it was a big “hurray!”, as if programming skills had just been sucessfully passed on to everyone.
By the end we were building nice web apps with a nice PHP backend (SQL database queried through PHP’s PDO (an object representing the database), complete CRUD (database read/write…), administrator dashboard, fancy object oriented PHP, with private, public and protected methods, setters and getters…) and a nice dynamic frontend (wireframing, Photoshop mockups, Illustrator logo, jQuery carousel, dynamic CSS with SCSS (sass, bootstrap…)), and we even had three days of SEO classes, to learn a few analytics tools and natural referencing principles. It was all nice and fun, except that by the time we had to look for a one month internship, we realized we had to start from zero and try to understand all that we had typed on our keyboards for four months, like drones. It didn’t help that most recruiters weren’t interested in hiring interns from no-name schools only for a month (even for no money at all, and we legally couldn’t propose more than a month), when they had candidates from college or renowned schools applying for 6 months internships. I finally found an internship through friends, but there was noone there to teach me anything related to coding, and after a month I wasn’t able to deliver the simple javascript quizz game I had promised, with a PHP backend to write and save the questions. I realized I was actually a grand beginner and that I never had a chance to train on simple coding tasks before starting a complete project on my own. I actually got lost trying to build on an open source quizz code I had found on github. I had tried to pick the most simple javascript code, but after days of headache I realized it was based on a Javascript framework (knockout.js) that I didn’t understand, and I didn’t have the time to learn it from scratch. I was desperate for a little bit of guidance, and I didn’t have any.
So then it was almost back to zero, I didn’t feel ready at all to apply for webdev jobs after a catastrophic intern experience. I thought it was back to online courses, codecademy and all, to level up. But again, I was not sure where to go, I was wondering what was the point of going on learning stuff that any freelancer with simple Wordpress knowledge could do in a day, frontend and backend. Anyway, I still needed to learn by doing, and I had realized that learning in a real school was the other extreme of learning totally alone : too much guidance gave us the illusion we had become fullstack web developers, while we had just copied code on the teacher’s screen and hunted for typos in “our” code.
The Hacking Project
So I went on looking for the Graal of how to learn coding outside of expensive schools or engineering programs, and that’s when someone told me about The Hacking Project (aka THP), whose teaching method relies mostly on practice. Again, it was not Python or cryptanalysis or big data computing, but it was free of charge (with a deposit) and it looked new and mysterious (the tagline was along the lines of “learn to code for the web from scratch, in Ruby, without teachers but in peer-programming with other learners from your town”). So I tried to start their “week 0”, supposedly for complete beginners, a week you have to pass and finish if you want to be accepted in the program. Consistant with the “hacker” spirit of the program, we were told to drop the Windows environment and switch to the Linux (or Mac) command line. I already knew Linux and as I was not really a beginner in web development, I thought week 0 would be easy. It was at the beginning, but the last day (and night) was a big challenge, namely when I had to make a Ruby program to draw a pyramid in the Terminal, letting the user choose the number of stairs of the pyramid. This time, no teacher writing the code on his screen and explaining the code, and I couldn’t even find the solution online : I’ve had to… think. What happens in the case of one stair? 2 stairs? 3 stairs? n+1 stairs? Finally it worked and I was like whooha, eurêka! I had done it myself!
First day
So I left my 300€ deposit and I was in. Big day a monday this October, like a first day of school, The Hacking Project had rented a large meeting room for an exceptional live-in presentation (we knew that afterwards we’d have to fend for ourselves, but with a small team (and a tutor from a previous session)). I didn’t know anyone, so I appreciated that the managing team didn’t let us choose our team : we had had to talk about our background and aims in our applications, and they took charge of building the teams for us. Everyone was younger than me, but I appreciated that my teammates weren’t total geeks, and we quickly found common interests besides web development. After that first morning of team-building games (in a relaxed, californian-like spirit, I found), we were left with our tutor, who told us to find a place (library, or whatever bar or coworking space) to start week 1, day one.
After lunch, we ended up in a Starbucks, having to clone the frontend of the Google homepage in html/css, on a common github repository for the team, by pairs. Thanks to the THP Slack channels (online chats for all the teams in France, that was about 250 people, plus previous sessions’ “alumni” stil hanging around), we soon found better places to work together everyday, from morning (sort of…) to late in the evening. The typical day was reading resources in the morning, then coding one or more projects as a team. The typical week was a couple free projects (one per day), two validating projects, and two mornings of peer reviewing (or grading) by phone (required), where the Hacking Project would give us two persons to grade, and two persons to be graded by, usually from another town or city in France. Well, just when I thought coding was nice for introverts, I had to shoot the shit with total strangers twice a week, and grade them, or be graded by them… I found this particularly difficult, but as with everything you fear, doing it anyway gives you a great feeling of achievement. Basically, you’re not alone : you realize that other beginners (total beginners or not) have struggled on the same projects, often made the exact same mistakes, had the same bugs, had the same impression that everything in coding was harder than it seemed at first.
First quitters…
As a non-total beginner, I appreciated that the learning curve was quite steep (in fact, one guy in our team gave up the second week, and another near the end : the program is not for the faint of heart). Only a day for basic html/css, then little ruby projects (including the famous Caesar cypher that I mentioned above, I had already done it in Python), then object-oriented Ruby, then simple web applications running on a local server using the Sinatra gem (“gems” are the name of the Ruby optional libraries), then the first steps on the Ruby on Rails framework (a fullstack webdev framework, where we were told to choose SQLite as the database engine, then PostgreSQL), before ending on a near professional environment : Ruby on Rails webapps hosted on heroku.com (the switch to a production environment being much more tricky than it seems, as always).
Fitting in a team
I noticed several things while working with other coding beginners, and by comparing the learning method with my previous training :
- I’m not stupid, but I’m more scared than most people. I remember in my classic training that I was fascinated by complex (relational) databases, as explained by a very good teacher from the renowned CNAM in Paris. But we weren’t forced to practice until the final project (which I never finished), so I chickened out and remained afraid of the inner joins, left joins and “n, n” relationships between database entities. With the Hacking Project, we had carry out simple projects, run simple queries in SQLite console, before tackling bigger Ruby on Rails projects, with “simple” relational databases and then not so simple “polymorphic” data tables, like when you want to let your web app user comment on comments below an article. I tend to like theory so much, that left alone I’d read and read and stay fascinated and always procrastinate before the moment to really design the damn database, and see in console through simple queries if it works or not (like, does the database return the correct answer when you want all of shakespeare.books, or all comments on Johnny’s comments). Left alone, I thought relational databases were very complex things that only great minds could design correctly, but when I realized that more adventurous beginners could make it work rather quickly with repeated trial and error, I felt challenged, and I realized that reading all the history of databases was a waste of time, a simple fear to try and play with the damn thing. I tackled the damn thing and conquered my fear of relational databases and SQL joins.
- A second difference with my more classic webdev training with teachers, was the heavy team working with github, a skill that apparently makes all the difference in the eyes of a recruiter between someone with no work experience, and someone with experience. Learning to handle merge failures with friends is already difficult (hey pal, you just erased all I had done…), I don’t imagine learning it as an intern trying to add a bit of code in a professional project, handled by people who actually make a living with the code you’re not too sure what you’re doing with, when you try to git push, git merge or git rebase… In the hacking project, we learnt everything by doing, as a team, synchronized on github for all the big projects (those projects would be git cloned locally by other students in charge of grading us as peers).
- Another difference with classic learning is how fast we went from simple html/css to a full on web development framework. In my classic training, after 4 months, only a handful of students were selected for the class on the Symfony framework. Still, the teacher took us by the hand (the ubiquitous principle of mostly copying the code explained by the teacher on his screen, on a Vagrant virtual machine he had prepared for us), and writing a route for the Model / View / Controller architecture seemed like wizardry. By the end of the week we had coded a Twitter-like application, but the teacher had done almost everything. Of course that experience later helped me grasp the Ruby on Rails MVC architecture, but other students at the Hacking Project have had to learn all of this on the fly : how and why make routes, how to send dynamic data from the Postgres database to the dynamic views through a dedicated controller (all in object Ruby…). Noone was there to tell us “it’s highly advanced” or “it’s only for the best, advanced students”, or “you’ll see that next year”. Nope, we had a deadline, usually for the same day at midnight, with a high motivation knowing the morning after someone from another part of France would grade us, and we could lose a life (a joker) if the project didn’t work well enough. (you start with 3 lives, and you can only recover them with community work (work for the Hacking Project community, living on Slack, a big supportive family, sort of)).
- The Rabbit and the Turtle. Again on the aspect of team work, I found an occasion to discover my assets and flaws in a context of programming. I thought programming was purely intellectual : it works or it doesn’t. But I realized that personality, even in coding, plays a large part in team work. You have to find your place, be able to help (but not too much, lest someone wonders by the end of the day what the hell you did on your own part…), deal with conflicts, drop an idea, push another that really seems woth it… Sometimes you’re at the center, sometimes you feel stupid, left out, or guilty for leading everyone astray, or for a nefarious git reset --hard that had seemed like a great idea in face of deadline emergency... I realized I tend to help a lot, but I count too much on myself (and stack overflow) when I’m stuck. I’m never out of ideas to try, but the hours pass, and the beginners who had the courage or humility to ask Ruby seniors for help, have moved on long ago, while I was still there sweating on my code and hiding where I was, rationalizing that it was more important to understand things by myself. At other times, I was coding an exercize project at the speed of a turtle, while everyone in my team was far ahead. But when they got stuck with messy code, unable to get help on Slack or Stack O, I would sometimes catch up, having read all the theory, with a very neat organized code following most of the good practices (ahem), and I’d be able to put them back on track, as sometimes my great respect for complexity and fear to make bad coding choices would turn out to be an asset, while more adventurous coders would sometimes rage at code that should have worked, but didn’t, for some mysterious reason. Sometimes the guy who says “wait, it’s more complex than you think” was right. Sometimes he’s slow and a chicken. Depends. Another aspect of my calm, rational, cautious, repectful and organized personality that proved precious in coding is when I managed to teach my fellows some debugging basics, like, don’t try to desperately make all the code work at once, break it down into parts, comment out all the complex stuff and let’s start by seeing if the most simple stuff does work, then let’s build on it. But to be honest, I ended up taking a lot of inspiration from them : try and fail, try and fail, and ask for help, a lot. I eventually asked some more advanced coders for help so much that they ended up sometimes saying “no, sorry, I’m too busy with my own code”, and well, my pride didn’t die. I asked someone else, or used good ol’ Stack O, or found another way.
Thriller
One thing I especially liked at the Hacking Project, that I just finished, was the frequent impression to be in a movie, namely a thriller. Two deadlines per week at midnight, a team of beginners, struggling with github, struggling with the switch to the production environment necessary to deploy our projects to heroku… High stress, high tension, despair, then little miracles, or just sheer holding on and working our asses off to have the damn thing work. And eventually, it works at the last minute after a 12 hours day of work, and the (free of charge) co-working place we were occupying still sells beer by midnight, and it’s magic.
Wo- wo- working together,
as Gonzales would have it. Also the pleasure to know that the morning after, you’d grade someone from another city and there would be a good chance you would be able to lift his or her deep depression, by finding what was the damn thing that didn’t work in his team’s project, and tell him this is not the end of the world, and one way or another, we both learnt something. And even if you lose a life, you can still recover one by doing extra work for the community.
Final Project
For the last 2 weeks, this time we had to choose our project and our team (but by now we knew all the sailors in town (a sailor at THP being a beginner, as opposed to alumni known as “corsairs” (lawful pirates, following the hacker namespace principles))). I was actually picked by a sailor from my own team (it was one of the guys who wouldn’t give up and work late until the deadline, with the aforementioned thrilling moments of victory). Long story short, we made a (mobile first) web app to help parisian night owls find cheap booze at night, allowing shopowners to make an account and add their shop. We called it alim-alo. We passed the jury, who was not as harsh as expected (still a bit) but gave us precious advice for the future. By the way, the motto I remember from developing on Ruby on Rails is
“CoC!”
(convention over configuration : stay in the rails and it will be easy). Then we were selected to present our site to all our peers (in a conference hall offered for the night by high up employees of famous french unicorn Xavier Niel (huge portrait in the hall), famous for “Free” web and cloud hosting and “Iliad” etc)
In the end I don’t have a degree (not possible for them for now) but I have the invaluable experience of working in a team of programmers, on concrete projects. We might rage sometimes when we feel that a Wordpress freelancer managed (apparently) to do better than us with only 3 days of Wordpress, but the ability to code a dynamic website in Ruby, backed by a Postgres database means you have almost total freedom to tailor the web app to your needs or the client’s needs. As for the Ruby on Rails framework, it’s pretty complex when you have to learn it so quickly, but most difficulties are linked to security enforcement. In today’s web development, either you don’t code and you do Wordpress (Wix, Drupal…), or you do code but unless you’re a security expert, you have to use a modern framework, that enforces security for you. The clients wants that.
And above all, The Hacking Project pushed me to focus on finishing tasks and pushed me to conquer my fears. Now I don’t feel like just a student with a degree, but like a problem solver who knows his limits and knows what he can bring to a team. I liked the community spirit of this school and writing this article is actually the last mission I picked as a mere “sailor”, soon to become an alumni aka “corsair”, with the other duties that go with it, like tutoring young sailors. Next step for me, as someone motivated to soon find a junior position in web development, is try the experimental “THP Next” curriculum, where the focus will be to become really proficient in Ruby on Rails, ready for employment as a web developer. For someone with not a lot of time or money, and high levels of anxiety and self-doubt, this looks, for now, like a damn good hack of the classic curriculum, a damn good hack into web development. | https://medium.com/@libertegalitefraternite13579/how-im-hacking-my-way-into-ruby-on-rails-web-development-7548960ab57c | CC-MAIN-2020-16 | refinedweb | 3,995 | 57.64 |
The program consists of 5 classes: SavingsAccount class, RspAccount class, Client class, Bank class and Machine class.
Im done with the SavingsAccount class and the RspAccount class and the class im having trouble with is the Client class.
The client class models a client, who can have at most one savings account and one Rsp account. (our program consists of only one client, since we havent covered arrays yet) Our class should have the following public constructor: Client (String name, int id, int pin) and it should have the following public methods:
String get_name() which gets the name of the client
int get_id() which gets the ID of the client
void set_id(int id) which sets the ID of the client
int get_pin() which gets the PIN of the client
void set_pin(int pin) which sets the PIN of the client
SavingsAccount get _savings() which gets savings account of the client & returns null if he hasnt one
void set_savings(SavingsAccount sa) which sets the savings account of the client
RspAccount get_rsp() which gets Rsp account of a client & returns null if he hasnt one
void set_rsp(RspAccount ra) which sets Rsp account of the client
boolean has_savings() which returns true if client has savings account, false if he hasnt
boolean has_rsp() which returns true if client has rsp account, false if he hasnt
double total_asset() returns the client's total assets in existing accounts
SO.. here is my client class (What ive done so far, which i know isnt enough, but im suck and i absolutely need help.. im not looking for code answer, just hints anything, i cant apply classes methods, i dont know how to call objects, to get my client class working, etc..Thank you so much in advance, to whoever will be the one helping me..thanks a lot)
import java.util.Scanner; public static void main (String [] args){ Scanner scanner = new Scanner (System.in); } public class Client { String clientName = ""; int clientID; int clientPIN; public Client (String name, int id, int pin){ // this is the constructor (same name as class) clientName = name; clientID = id; clientPIN = pin; } public String get_name(){ // gets the client's name System.out.println("Please enter your name:"); name = scan.next() + " " + scan.next(); return name; } public int get_id (){ // gets the client's ID System.out.println("Please enter your ID"); id = scan.nextInt(); return id; } public void set_id (int id){ // sets client's ID // what do we put here? } public int get_pin (){ // gets client's PIN System.out.println("Please enter your PIN code"); pin = scan.nextInt(); return pin; } public void set_pin (int pin){ // sets client's PIN // what do we put here? } public SavingsAccount get_savings (){ // gets SavingsAccount (the object which represents the client's savings account) of client if he has one, if // not, returns Null (how do u do that?) } public void set_savings (SavingsAccount sa){ // what do we put here? it sets the savingsaccount of client, if he has one. The set_savings() method does // the opposite. It sets the client's savings // account to the oject that is the parameter of the method. It was not specified what the method should do // if the client already has a savings account. You can do whatever you think is appropriate in that case } public void set_rsp (RspAccount ra){ // what do we put here? } public boolean has_savings (){ // returns true if client has savingsaccount, false if not. How do we do that? } public boolean has_rsp (){ // returns true if client has rsp account, false if not. How do we do that? } public double total_asset (){ // returns client's total asset in existing accounts. How do we do that? } }
thank you so much once again, to whoever will help.. | http://www.dreamincode.net/forums/topic/25452-client-class-how-to-create-objects-call-methods-etc/ | CC-MAIN-2016-07 | refinedweb | 611 | 69.41 |
.
Thanksgiving day is over but the madness begins... Some of you are out shopping for Black Friday deals with your significant other, the die-hard's are in the office today because no one else will be around to bother them, and some are home resting. I, on the other hand, spent most of the day adding new content to my web site (). I finally got to writing the reviews for some of the books I have read in the last few months.
So with the end of the year budget funds coming available that need to be spend (in most cases), this would be a good time to pick some books to expand your knowledge.
The feed for book reviews can be found at. I am planning on adding 1 every two weeks or so.
The URL for the book review section is.
Enjoy.
Now that Visual Studio 2008 is available to MSDN subscribers you might want a few tips to make you more productive. I found this Weblog which provides tips for working in the Visual Studio IDE (both 2005 and 2008).
Check it out
First.
1: <microsoft.web.preview>
2: <searchSiteMap enabled="true">
3: <providers>
4: <add name="Navigation" type="Microsoft.Web.Preview.Search.AspNetSiteMapSearchSiteMapProvider, Microsoft.Web.Preview"/>
5: <add name="Articles" type="JosephGuadagno.Web.BLL.SiteMap.ArticleSiteMapData, JosephGuadagno.Web.BLL"
6: targetUrl=""
7: targetUrlseparator="/"
8: queryStringDataFormatString="{0}"
9:
10: <add name="Books" type="JosephGuadagno.Web.BLL.SiteMap.BookSiteMapData, JosephGuadagno.Web.BLL"
11: targetUrl=""
12: targetUrlseparator="/"
13: queryStringDataFormatString="{0}"
14:
15: <add name="News" type="JosephGuadagno.Web.BLL.SiteMap.NewsSiteMapData, JosephGuadagno.Web.BLL"
16: targetUrl=""
17: targetUrlseparator="/"
18: queryStringDataFormatString="{0}"
19:
20: </providers>
21: </searchSiteMap>
22: </microsoft.web.preview>
1: <httpHandlers>
2: <add verb="*" path="SearchSiteMaps.axd" type="Microsoft.Web.Preview.Search.SearchSiteMapHandler" validate="true"/>
3: </httpHandlers>
A call to will produce something like this.
1: <sitemapindex>
2: <sitemap>
3: <loc>
4:
5: </loc>
6: <lastmod>2007-11-13T04:53:21.371Z</lastmod>
7: </sitemap>
8: <sitemap>
9: <loc>
10:
11: </loc>
12: <lastmod>2007-11-13T04:53:21.371Z</lastmod>
13: </sitemap>
14: <sitemap>
15: <loc>
16:
17: </loc>
18: <lastmod>2007-11-13T04:53:21.371Z</lastmod>
19: </sitemap>
20: <sitemap>
21: <loc>
22:
23: </loc>
24: <lastmod>2007-11-13T04:53:21.371Z</lastmod>
25: </sitemap>
26: </sitemapindex> are that one of them is for the fixed navigation tied to the site map file, the other three use the dynamic site map provider, one for each type since the classes and data retrieval are different.
This provider is the easiest to use and only requires a valid Asp.Net site map file. Adding the following line to the searchSiteMap section of the web config file will instruct the provider to load the default asp.net site map.
1: <add name="Navigation"
2: providers section, I use three different custom providers, Articles, Books and News. These providers inherit from the DynamicDataSearchSiteMapProvider class which requires that you implement the DataQuery method which returns a IEnumerable interface. I choose to return a List<SiteEntry> objects.
The SiteEntry class supports the following properties (taken straight from the Asp.Net futures site):
targetUrl
targetUrlseparator
?
#
/
queryStringDataFormatString
String.Format
queryStringDataFields
targetUrlFormatString
DataQuery
lastModifiedDataField
changeFrequencyDataField
priorityDataField
pathInfoFormat
true
These properties are used in conjunction with your properties that you want to display in the site map. For my search site map.
The ArticleSiteMapData provider looks like this
1: /// <summary>
2: /// A SiteMap provider for the Article page.
3: /// </summary>
4: public class ArticleSiteMapData: DynamicDataSearchSiteMapProvider
5: {
6: public ArticleSiteMapData() {}
7:
8: public override IEnumerable DataQuery()
9: {
10: // Holds a list of the ArticleEntry's
11: List<SiteEntry> list = new List<SiteEntry>();
12: TList<Article> articles = new TList<Article>();
13:
14: articles = DataRepository.ArticleProvider.GetAll();
15:
16: foreach (Article article in articles)
17: {
18: string url = BLL.URLRewrite.GetArticleRewrite(article);
19: SiteEntry siteEntry = new SiteEntry(url, article.AddedOn, SiteEntry.ChangeFrequency.Daily, "0.5");
20: list.Add(siteEntry);
21: }
22:
23: articles = null;
24: return list.ToArray();
25: }
26: }.
That's about it. I was a lot to read and digest but hopefully useful. I you have any questions, please feel free to contact me or leave a comment or you can discuss the Sitemap provider in the ASP.net forums.
Here some search engine urls where you can submit you site maps.
Google:
Yahoo:
This past weekend I took on what I thought would be a simple task. I wanted to convert my Visual Studio 2005 "File Based" web site () to a Web Application Project. I Googled for a while to see if there were any how to's or articles on pitfalls and such. I came across ScottGu's post at so I decided to follow it step by step. Unfortunately it took about 2 days to get everything working.
So after I followed all of the steps I "built" the solution. About 300 some odd compile time errors showed up. I was thinking to myself, "What did I do wrong? The site has been working in the development environment for two weeks". After doing some digging I realized why there were so many errors. Most of the web pages where done with the "Copy, Paste, Modify" method. I got the page to work with one object, then I copied, pasted the file to another page and modified it for the new object. While this approached worked in the file based web site it did not for the Web Application Project. And here is why, a lot of the class names were the same.
Example:
default.aspx, details.aspx, etc.
Most of these pages / classes were repeated because the same functionality was needed for the different objects. Now if you think about it, the Web Application Project creates an assembly of objects. Each of the objects represents a Code-Behind module for your page (and some other objects). Therefore, you can not have more than one object with the same name in the assembly. Hence the reason for over 300 hundred errors.
The best way to look at the conversion is that now you are creating an Assembly with multiple objects. When you convert the application, just like in any assembly, you must have unique names. Since all of my content on the web site is organized in folders based on the function of the page I decided to wrap all of the pages in namespaces based on the folder.
For example
The class structure will look something like this.
This way ensures that all of the classes are unique. Now you need to modify the files.
You are going to have to modify the *.aspx pages Inherits attribute to look similar to this.
1: Inherits="JosephGuadagno.Web.Website.Articles.ArticleDetail"
The code behind file *.aspx.cs should have a namespace wrapped around it.
1: namespace JosephGuadagno.Web.Website.Articles
2: {
3: public partial class ArticleDetail :JosephGuadagno.Web.BLL.BasePage
4: {
5: }
6: }
The *.aspx.designer.cs sometime gets updated by itself. If not, wrap it around the same namespace as in the code behind.
I hope this helps you out. | http://weblogs.asp.net/jguadagno/archive/2007/11.aspx | crawl-003 | refinedweb | 1,178 | 66.54 |
I'm going to restart this application from scratch because it doesn't have much of a domain model. I started developing it mostly to work with the TreeTableView, as discussed in the day before yesterday's blog entry. But, now that it's clear that it's pretty easy to get quite far with the de.ueberdosis.mp3info library, I'm going to start again and prepare the ground properly. So, consider this a prototype!
One of the strengths of the NetBeans Platform is definitely the ease with which you can integrate third party libraries (such as, in this case, the de.ueberdosis.mp3info library). There's a template that bundles such a library in two or three clicks into your application. And then you can use the library just as you would use any library provided by the JDK. Code completion and all the rest is seamlessly available for third party libraries. And, in answer to Opsi's question (in the comments at the end of the most recent blog entry) about how to use this particular library from Java, here is a basic example:
RandomAccessFile ra = null;
try {
ra = new RandomAccessFile(getCurrentFile(), "rw");
myTag = myReader.readExtendedTag(ra);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
String Artist = myTag.getArtist();
String Album = myTag.getAlbum();
String Title = myTag.getTitle();
In fact, that's the only part of the API that I've used thus far. Look at the second line within the try block. It uses a method called readExtendedTag(RandomAccessFile). When you use that method, you can retrieve all of the following information (or a subset thereof):
The rest of the application, apart from the snippet above, is nothing more than standard JDK classes and a handful of the NetBeans APIs. Note that, for the above snippet, you'd need the following import statements:
import de.ueberdosis.mp3info.ID3Reader;
import de.ueberdosis.mp3info.ID3Tag;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
It is a pretty cool library and, once I've designed a domain model, I hope to leverage a lot more of its functionality.
In other news. Check out this great technical writing blog, by Microsoft's Harry Miller, which includes a podcast for each blog entry, with interviews and interesting food for thought on subjects such as "Author's Voice" and "Thinking Visually". Check it out and enjoy.
thanks!, now I understand why I didn't find the java bindings. Using the packages you gave I found that the lib you are using should be mp3info (but there was a link in the post to id3lib which is a C++ lib), isn't it?
Regards | https://blogs.oracle.com/geertjan/mp3-manager-on-netbeans-platform | CC-MAIN-2019-04 | refinedweb | 446 | 66.23 |
Ken McDonell wrote:
The dynamic pmns stuff is quite a bit trickier than I originally
postulated (why, in retrospect, is that not a surprise?).
so how did the pmID pad field out in the end?
Any way I have it working for the DSO PMDA case (daemon case is a
straightforward, if tedious, extension).
Max Matveev observed yesterday that he'd like to be able to have one
PMDA use the dynamic PMNS features to return a PMID within its own
domain sometime, but at other times (depending on some global
configuration set up) have the same metric name translated into a PMID
that belongs to another PMDA.
This is (a) odd, and (b) even more amazing that he has a legitimate need
for this!
Some uses I can think of that we've struggled with in the past:
1. deprecate a PMDA, but keep some of it's namespace in the replacement
2. conditional support for certain metrics, e.g. standard or
premium value-plus varieties
3. conditionally enabled metrics or instance domains e.g. via pmie rules, etc
4. alternative instance domains and/or semantics, e.g. redirect parts of
the standard namespace to the cluster PMDA
5. multiple domains in the one PMDA (urk)
I'm getting carried away a bit ...
Cheers
-- Mark
Well, after a short discussion, we postulated that it should "just
work" (tm) ... so I tried it.
$ pminfo -m | grep 2.4.1
pmcd.agent.status PMID: 2.4.1
sampledso.secret.foo.bar.max.redirect PMID: 2.4.1
sampledso.secret is a subtree of dynamic metric names known only to the
sample PMDA, but sampledso.secret.foo.bar.max.redirect maps to the PMID
of a metric exported from the pmcd PMDA.
So, ...
$ pminfo -f sampledso.secret.foo.bar.max.redirect
sampledso.secret.foo.bar.max.redirect
inst [2 or "pmcd"] value 0
inst [10 or "trace"] value 0
inst [15 or "sendmail"] value 0
inst [29 or "sample"] value 0
inst [30 or "sampledso"] value 0
inst [60 or "linux"] value 0
inst [250 or "trivial"] value 4
inst [253 or "simple"] value 0
8^)>
_______________________________________________
pcp mailing list
pcp@xxxxxxxxxxx | http://oss.sgi.com/archives/pcp/2009-08/msg00005.html | CC-MAIN-2015-22 | refinedweb | 360 | 57.27 |
Geertjan's Blog (Comments) 2015-03-26T15:49:16+00:00 Apache Roller Re: Trip Report: NetBeans Day Germany 2015 (Part 1) Peter Hidalgo 2015-03-26T02:05:24+00:00 2015-03-26T02:05:24+00:00 <p>Awesome day in munich.</p> <p>Thanks for sharing Geertjan!!! I hope you continue sharing as much Netbeans days as you can.</p> Re: How to Deploy NetBeans Platform Applications to GlassFish Geertjan 2015-03-25T22:37:08+00:00 2015-03-25T22:37:08+00:00 <p?</p> Re: How to Deploy NetBeans Platform Applications to GlassFish dave 2015-03-25T22:34:15+00:00 2015-03-25T22:34:15+00:00 <p<br/> BUILD FAILD (total time 0 seconds) please how can I fixed this. What could be the problem <br/> please help me </p> Re: 29th May: (Free) NetBeans Day UK! Geertjan 2015-03-23T11:02:54+00:00 2015-03-23T11:02:54+00:00 <p>There will be a NetBeans Day in Ireland if you want there to be a NetBeans Day in Ireland! Drop me a mail at geertjan dot wielenga at oracle dot com and we'll work together to make it happen.</p> Re: 29th May: (Free) NetBeans Day UK! guest 2015-03-23T10:37:32+00:00 2015-03-23T10:37:32+00:00 <p>Hi Geertjan, do you know if there is a Netbeans day in the works for Ireland? Is there a schedule of planned days somewhere? </p> <p>Thanks,<br/> Phil</p> Re: YouTube: Yeoman in NetBeans IDE webdavce 2015-03-23T05:16:49+00:00 2015-03-23T05:16:49+00:00 <p>How to import this plugin?<br/> I tryed the normalö way, but no success.</p> <p>Regards Dave</p> Re: Asset Management on NetBeans Emilian Bold 2015-03-21T17:15:51+00:00 2015-03-21T17:15:51+00:00 <p>Many companies view their technological stack a *competitive advantage* and are quite unwilling to disclose it to the world.</p> <p>So, although the Platform is used for a lot of important things, the companies using it are quite comfortable with it being a bit off the radar.</p> <p>Actually, if Oracle were to *discontinue* the Platform, a few unexpected entities could emerge to stop that.</p> <p>But even more would say *nothing* because they will just keep an internal fork in-house. There is a lot of expertise out there for the most unexpected things.</p> Re: Microservices, Java EE, and Adam Bien at Blue4IT Peter 2015-03-21T02:28:47+00:00 2015-03-21T02:28:47+00:00 <p>Play Framework is far better than Java EE in my opinion cause its simplicity and stateless way of doing things. Stateless apps scales better than JavaEE.</p> Re: The Unicorn / The Rhinoceros guest 2015-03-21T01:39:56+00:00 2015-03-21T01:39:56+00:00 <p>Unicorn is in fact the scientific name for a single horned rhinoceros. Use this old webster's dictionary from 1828 and type in the word rhinoceros.</p> <p><a href="" rel="nofollow"></a></p> <p>This is why the old King James version of the bible also uses the word unicorn to refer to a rhinoceros with one horn.</p> Re: YouTube: EJDK, Raspberry Pi, and NetBeans IDE 8 guest 2015-03-20T20:41:44+00:00 2015-03-20T20:41:44+00:00 <p>First of all, thanks for the excellent explanation of "Raspberry Pi, and NetBeans IDE 8" as seen, so done, It works oke!<br/> Unfortunately it was intended my created GUI application to work on the Raspberry Pi, but it don't works.<br/> I get the errors (error: JFrame is not available in profile 'compact3'<br/> public class scrHfd extends javax.swing.JFrame) and so on for other Jframe items<br/> What can I change , or is it not possible to use the GUI with a JRE platform ?</p> Re: Grunting in NetBeans IDE azPHPguru 2015-03-20T16:04:45+00:00 2015-03-20T16:04:45+00:00 <p>Thanks to your help - we identified it was broken in the latest nightly build. Grunt integration works fine in NetBeans 8.0.2 on Yosemite. </p> Re: Python in NetBeans IDE 8.0.2 guest 2015-03-20T12:18:09+00:00 2015-03-20T12:18:09+00:00 <p>hi, how can i add a mysqli module to python in netbeans</p> Re: Why I Am Excited About JDK 8 Update 40 guest 2015-03-20T11:56:51+00:00 2015-03-20T11:56:51+00:00 <p>Is there a planned release for the epub-plugin? <br/> It looks like a very promising project - especially since Sigil is not supported and developed anymore.</p> Re: Grunting in NetBeans IDE Geertjan 2015-03-19T21:40:42+00:00 2015-03-19T21:40:42+00:00 <p>Contact me on Skype to discuss this, will save some time. My username there: geertjanwielenga</p> Re: Grunting in NetBeans IDE guest 2015-03-19T21:38:59+00:00 2015-03-19T21:38:59+00:00 .</p> Re: Microservices, Java EE, and Adam Bien at Blue4IT alex 2015-03-19T13:03:08+00:00 2015-03-19T13:03:08+00:00 <p>I have always found it hard to argue with Adam's reasoning. Probably because he's always talking about simplicity.</p> Re: Why I Am Excited About JDK 8 Update 40 Geertjan 2015-03-18T17:05:27+00:00 2015-03-18T17:05:27+00:00 <p>Based on your "problem description"? No log files, nothing, nothing at all to reproduce anything, no files to help in any way? Nope, no clue whatsoever, Skip.</p> Re: Why I Am Excited About JDK 8 Update 40 guest 2015-03-18T17:03:20+00:00 2015-03-18T17:03:20+00:00 <p>Hi Geertjan,</p> <p>It's interesting. We are not at all excited with what has happened to our application with update 40. </p> <p>The exact opposite has occurred for our webstart Swing application. With Java 8 update 40, performance of our Swing GUI has been severely degraded. I haven't been able to discern what was in the update between 31 and 40, but the clicking around in our app is now very sluggish compared to 31. </p> <p>Any ideas what in update 40 might have caused a Swing app launched via Webstart to be so sluggish vs. the exact same application running on Java 8 update 31?</p> <p>Thanks,<br/> Skip Walker</p> Re: Bower and Node.js in NetBeans IDE guest 2015-03-18T00:55:14+00:00 2015-03-18T00:55:14+00:00 <p>Thanks for adding and pointing out the features that simplify the use of Angular in the HTML-5 project in NB. NB is turning out to be an excellent development environment for JavaScript</p> Re: Trip Report: NetBeans Day Germany 2015 (Part 1) Jiří Kovalský 2015-03-17T17:08:35+00:00 2015-03-17T17:08:35+00:00 <p>What a wonderful event that NetBeans Day is! Thanks for sharing Geertjan.</p> Re: How to Implement Yeoman in NetBeans IDE guest 2015-03-16T18:00:45+00:00 2015-03-16T18:00:45+00:00 <p>How to add Yeoman plug-in into IDE. There is no steps mention anywhere. Please help me out.</p> <p>Please note I am very much new in NetBeans.</p> Re: [ERROR] Two declarations cause a collision in the ObjectFactory class. guest 2015-03-15T22:00:43+00:00 2015-03-15T22:00:43+00:00 <p>Very nice and very clear.</p> <p>So.... how does one go about creating the schema binding?? I can't use yours for my wsdl? Tutorial anywhere?</p> Re: Handy HyperlinkProvider Jirka Chmiel 2015-03-15T17:15:45+00:00 2015-03-15T17:15:45+00:00 <p>Hello, </p> <p>Thank you for your post. It is useful. So and what are we doing when there are more file candidates. Is there anyway how to display a context menu (or something like that) with all file candidates so that user could choose one of them and then that file open in editor? Thanks.</p> Re: Two Hidden NetBeans Keyboard Shortcuts for Opening & Toggling between Views Bob Thompson 2015-03-15T10:37:24+00:00 2015-03-15T10:37:24+00:00 <p>Is there a shortcut to toggle between the code and design window? Similar to "F7" in Visual Studio and "F12" in Delphi?</p> Re: Ctrl-G = Go to Line | Go to Bookmark Chris Nahr 2015-03-14T09:34:37+00:00 2015-03-14T09:34:37+00:00 <p>That looks useful but also rather cumbersome to use. Suggestion for future NetBeans versions: assign keys to new bookmarks automatically, and show bookmark keys right in the Go To dialog without having to hit Ctrl+G again.</p> Re: org.netbeans.spi.project.ui.ProjectOpenedHook guest 2015-03-14T09:04:03+00:00 2015-03-14T09:04:03+00:00 <p>FYI: Added this information to <a href="" rel="nofollow"></a></p> Re: Learn Java, For Real, Thoroughly, With Huw and NetBeans IDE guest 2015-03-13T18:57:05+00:00 2015-03-13T18:57:05+00:00 <p>Dang it! Missed the discount.</p> Re: Fixed: MessageBodyReader not found for media type TimF 2015-03-13T16:30:15+00:00 2015-03-13T16:30:15+00:00 <p>I'm new to Java and stuff like this drives me nuts. :) Thanks so much for posting it, it's helped me keep moving.</p> Re: Python in NetBeans IDE 8.0.2 Artur Barseghyan 2015-03-13T09:14:09+00:00 2015-03-13T09:14:09+00:00 <p>Thank you!</p> Re: Integrating Cloud Providers into NetBeans IDE (Part 6) guest 2015-03-12T17:11:01+00:00 2015-03-12T17:11:01+00:00 <p>Hi Geertjan<br/> Thank you for this netbeans extension.<br/> We have deployed a "local" openshift solution within our network in my company.<br/> Is it possible to point the extension to our server instead of OpenShift by Red Hat cloud service with some hacks ?</p> | https://blogs.oracle.com/geertjan/feed/comments/atom | CC-MAIN-2015-14 | refinedweb | 1,714 | 72.26 |
Macrosfilter in the macro body;
varargsvariable as a list of values.):
{% import "forms.html" as forms %}
The above
import call imports the "forms.html" file (which can contain only macros, or a template and some macros), and import the functions as items of the
forms variable.
The macro can then be called at will:
<p>{{ forms.input('username') }}</p> <p>{{ forms.input('password', null, 'password') }}</p>
If macros are defined and used in the same template, you can use the special
_self variable to import them:
{% import _self as forms %} <p>{{ forms.input('username') }}</p>:
{% macro input(name, value, type, size) %} <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" /> {% endmacro %} {% macro wrapped_input(name, value, type, size) %} {% import _self as forms %} <div class="field"> {{ forms.input(name, value, type, size) }} </div> {% endmacro %}
Twig allows you to put the name of the macro after the end tag for better readability:
{% macro input() %} ... {% endmacro input %}
Of course, the name after the
endmacro word must match the macro name.
© 2009–2017 by the Twig Team
Licensed under the three clause BSD license.
The Twig logo is © 2010–2017 SensioLabs | http://docs.w3cub.com/twig~1/tags/macro/ | CC-MAIN-2018-43 | refinedweb | 191 | 72.66 |
There are times when you want to prevent inheritance. Perhaps there is no need the extensibility for various reasons. If you know this for sure, there are advantages to declaring the final keyword precisely that.
Java has a special keyword called final that can use for creating final methods, final classes, and final variables. The final modifier is void, which simply means that no value is returned.The final modifier indicates that the value of this member cannot change. We get a compile-time error if our program tries to change its contents. Each of these is explained in more detail next.
Final methods are methods whose implementations cannot be changed. When a method declared as final, it cannot be overridden by a subclass method. In private methods is equal to final, but in variables, it is not. For example, consider a class E that contains a final method called computeSquare that computes the square of its argument:
public class E {
public final int computeSquare(int x) {
return x*x;
}
}
By declaring computeSquare as fina1, we ensure that it not be overridden in a subclass. Thus, if subclass F attempts to override computeSquare, it causes a compilation error:
public class F extends E {
// error: cannot override the final method computeSquare in E
public int computeSquare(int x) {
// some code goes here
}
}
There are times when you want to prevent inheritance. Perhaps there is no need to extend the class, for instance. If you know this for sure, there are advantages to declaring this class final.
Just like final methods, a class can also be declared final. A final class is a class that cannot use as a superclass (i.e., a Class cannot extend final class). To declare the class as final, precede the class header with the final keyword. So the class header looks like below.
final class ClassName {
..............
}
When you declare a class to be final, all methods of this class are implicitly final. It is because another class cannot extend the final class so no class can be in a position to override any of the methods in the final class. For example, String and StringBuffer classes are examples of final classes.
public final class HourlyEmployee extends Employee {
// class definition
}
A class can declare as final for either of the following two reasons:
1. None of the methods in the class should override.
2. The class should not extend further.
The two main advantages of declaring final classes are higher efficiency and safety. The dynamic binding inherent in virtual methods is harder on the compiler, resulting in slower execution. By declaring a class final, virtual methods are replaced by the compiler with in-line code, speeding up the process. Final classes are also safer, in that they avoid ambiguous situations where a message sent may end up at an object that returns the wrong data.
Examples of final classes in the Java API are:
• An array is a collection of similar elements. The array is a predefined class present in java.lang package. It is a final class which can't be inherited.
• In java String is a predefined class present in java.lang package. A string is a final class, and it is immutable.
• Each of the numeric type-wrapper classes - Byte, Short, Integer, Long, Float, and Double extends class Number. Also, the type-wrapper classes are final classes, so you cannot extend them.
• The System class provides a system-independent programming interface for accessing such resources outside the Java environment. The System class should not instantiate. It is a final class, and all its variables and methods are static.
• The java.sql.Numeric class adds the capability of representing SQL fixed point NUMERIC and DECIMAL values to the java.lang.Number class. The Numeric class is a final class and, therefore, cannot be redefined.
Final variables are declared using the final keyword. A final variable can be assigned a value only once. A variable that is declared as final and not initialized is called a final blank variable. A final blank variable forces the constructors to initialize it. Java local classes can only reference local variables and parameters that declared as final. It declares a variable called ANGLE:
final int ANGLE = 10;
Reassigning to ANGLE again results in an error:
ANGLE = 20; // error, ANGLE has been already assigned.
Final variables are useful in local and anonymous classes.
How do final variables differ from constants? Constants are class variables because they declared with the static modifier. It means that a single copy of this variable shared among all instances of a class. Final variables, on the other hand, are instance variables.
A distinct advantage of declaring a java variable as static final is the compiled java class results in faster performance.
‘final’ should not call as constants. Because when an array declared as final, the state of the object stored in the array can be modified. You need to make it immutable in order not to allow modifications. In a general context, constants do not allow modifying. In C++, an array declared as const not allow the above scenario, but java allows. So java’s final is not the general constant used across in computer languages.
A variable that is declared static final is closer to constants in general software terminology. You must instantiate the variable when you declare it static | https://ecomputernotes.com/java/what-is-java-language/what-is-final-keyword-in-java | CC-MAIN-2019-35 | refinedweb | 895 | 57.37 |
Viewed++.--Andrew Orlowski
Cnet's reporting that Microsoft is about to release (or perhaps just announce) its long-awaited Java-Killer, to be named C# (pronounced "C sharp"). This is a C++ derivative with a lot of Java-like features. It will have garbage collection and maybe security. (Not that Microsoft knows the first thing about security; If ActiveX didn't prove that, ILoveYou sure did.) It will probably be Windows only, at least until the FSF gets their hands on it.
The name's cute, but otherwise this strikes me as a yawn.
If Microsoft wanted to really challenge Java, they should have gone with
Python. I just don't believe it's possible for any major advances in language design
to be made while restricting oneself to the mistakes
Kernighan and Ritchie made 30 years ago. Many of Java's flaws are the
results of needlessly maintaining compatibility with C. Much of Java's simplicity
comes from places where it broke with C and C++. (
switch statements come immediately to
mind.) IMHO, a simpler, easier-to-use
language than Java can only come about if you move further away from C and C++, not closer.
Discussion on slashdot.
Date: Wed, 28 Jun 2000 11:59:32 -0700
To: Elliotte Rusty Harold
From: Greg Guerin <glguerin@amug.org>
Subject: flamage-reduced comments on C#
It's difficult to effectively criticize a language spec that's so incomplete. There's really no way to know what's missing because it's not been documented yet, vs. what's missing because it's not a language feature. Of the language features hinted at or mentioned in passing but not described, any critique would be wasted because you'd simply be critiquing YOUR ASSUMPTION of how the feature will behave. I'm actually looking forward to a spec that's good enough to be worth criticizing.
The download of the language reference spec:
leaves plenty out. It starts by being a Windows-specific download (self-extracting ZIP of a Word document). Getting past those format and security hurdles, I made a PDF for future use [[which I can email you if you want (~500KB), but see rant, which you can omit if you post this]].
There's also this gem:.
So I guess I have to get written permission just to download it, eh?
Some of the more obvious things missing:
Despite having more in common with Java than it has differences, C# seems altogether a "looser" language and not as tight or clean as Java. Where Java eschews some feature altogether (pre-processor, 'goto' statement), or provides exactly one way to accomplish something, C# often provides multiple intrinsic language mechanisms. It's not clear to me that this is an advantage, except in marketing bullet-lists.
Wherever possible, it seems that C# has chosen a different key-word than Java:
sealedinstead of
final
baseinstead of
super
namespaceinstead of
package
lockinstead of
synchronized
The C# syntax is also more C++-like than Java is. Where Java (wisely,
IMHO) chose to use keywords like
extends, C# uses punctuation. C# looks
much more like C++ than Java does.
Stylistically, C# seems to like initial-caps on method-names, identical to the style of naming classes:
class Foo { public void SomeMethod() { ... } }
Personally, I find this needlessly confusing, but I suspect it's a style that will be emulated by hordes of programmers. Blecch!!
C# has a pre-processor. It has:
#define name
but it's unclear to me if it also has:
#define name text
or:
#define name(...) macro(...)
The examples illustrate
#define's simply being true/false controls for
conditional compilation with the typical
#if/
#else/
#elif/
#endif directives.
C# does not seem to have doc-comments, but I can't tell whether it's an undocumented feature or not a language feature at all.
C# has goto and labels, just like C. And you can goto case statements, too.
C# distinguishes the 'struct' type from the 'class' type. The spec says:
Structs differ from classes in several important ways, however: structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored either "on the stack" or "in-line".
The apparent difference is that there can't ever be pointers/references to structs, though there can be arrays of them. This is probably faster than class-instances in some cases, but bigger and slower in others.
C# has delegates as full-fledged language constructs. It's sort of like a lightweight version of an 'interface' method (implementation-agnostic as long as method-signature matches). Useful in some cases, I'm sure, but I suspect it will largely be abused as an excuse to avoid having to do better software design.
C# has enums as full-fledged language constructs. These look pretty much
like the C/C++ enums, just by glancing at them. Of course, there's the
obligatory jab at Java:
"The use of enums is superior to the use of integer constants - as is
common in languages without enums - because the use of enums makes the code
more readable and self-documenting."
(Editor's note: and the use of typesafe enums
is superior to the use of integer enums, and in fact completely obviates the need for an
enum keyword
C# has namespaces instead of "packages". Pretty much the same effect, though.
C# has attributes and properties (named attributes) in the language. I'm not sure what these really do for you, other than act as cruft-collectors (IMHO).
C# has events as full-fledged language constructs. It's not clear to me exactly what benefits this provides over simply defining events and handlers using classes or other existing language constructs.
There appears to be support for some kind of versioning (i.e. control over binary compatibility). Unfortunately, the feature is not described in detail, and the example in the language overview is trivial.
C# requires that overrides of super-class methods be declared as such using
the key-word
override. The C++ keyword
virtual is also apparently
required, implying to me that virtual method-invocation is NOT the norm.
Unfortunately, the distinction is not actually explained anywhere in the
doc, so maybe it's vestigial, or maybe it's not.
C# also has a 'foreach' statement that iterates over every element of a
collection. Java does the same thing using
Enumeration objects. A
'foreach' statement is more convenient, but the concurrency issues are
subtle yet nowhere explained. I can see advantages and disadvantages to
each scheme, depending on what you need to do, so I don't think there's an
unequivocal "winner" for this feature.
In my earlier comments on C#, I noted the absence of a class library (well, the documentation of one). The above URL says:
>The Framework is a common set of classes and libraries that provide the >basis for the .Net building blocks that Microsoft is building to deliver on >its software as a service .Net platform.
Given this mention of "The Framework" and some brief comments in the C# documentation, I strongly suspect that there may not be a distinct "C# class library" as such. Rather, C# will probably use "The Framework" classes, perhaps supplemented by some glue or other run-time support. So the obvious questions now are "What's in The Framework?" and "Where is The Framework specification?"
Conspicuous by its absence was any additional information on a security-model for C# or The Framework.
Ironically for a company that touts "innovation" as its shield against lawsuits, this first-new-language since Visual Basic debuted almost precisely a decade ago shows a remarkable lack of courage. Compared to Apple, whose new Aqua interface is based on the premise that loyalty to the Mac is not about specific widgets but about productivity gains, Microsoft looks precisely like the legacy dinosaurs that it so effectively slew in the middle 80s.
C#, in summary, looks like the product of a two-hour brainstorming session between the creators of Visual Basic, Visual C++, and Turbo Pascal. Aside from minor syntactical issues ("using" vs. "import", ":" vs. "extends"), the major differences in the language appear to be formalization of delegates (callbacks) and attributes, as well as a couple minor things, like structs and enums.
Then there's a huge language change: versioning. They call it that, but actually, it's optional polymorphism. A base class can add a method with the same signature as an existing sub-class method without causing a compilation problem. (class Base ships, class Derived extends it and adds a foo() method. Next version of Base ships and adds a method foo() -- programs using Derived remain compatible.) When a derived class is compiled, it can specify the use of polymorphism:
class Base{ public void foo(){ System.Console.WriteLine("Base.Foo"); } public void bar(){ System.Console.WriteLine("Base.Bar"); } } class Derived{ public override void foo(){ System.Console.WriteLine("Derived.Foo"); } public new void bar(){ System.Console.WriteLine("Derived.Bar"); } static void Main(){ Derived d = new Derived(); d.foo(); d.bar(); Base b = new Derived(); b.foo(); b.bar(); } }
will print "Derived.Foo Derived.Bar Derived.Foo Base.Bar"
While I can see the advantage of versioning for framework writers, I think it is, on balance, quite dangerous when taken in the context of real object-oriented programs. Understanding an inheritance tree is difficult enough; branches that suddenly change dispatching philosophy based on a keyword are going to be prone to error.
Other than versioning, C# contains no readily apparent innovations. The concept of a shared runtime library based on a common object model is a fine one, but hardly proof that Microsoft has the best intentions of the programmers in mind: You will learn the Microsoft-written libraries and then you may use all Microsoft programming languages.
The popularity of programming languages have traditionally followed a 5-7 year cycle, triggered by the early adopters embracing a programming language that addresses the perceived "biggest challenge." We are currently nearing the end of Java's cycle and within two years, mark my words, all the cool kids will be programming something new. It won't be C#.
Date: Fri, 30 Jun 2000 15:46:14 -1000
From: Robin Meade <rmeade@outreach.hawaii.edu>
Subject: C# allows Strings in switch statement
C# allows Strings in switch statement
Actually, I think this is a nice feature that I long wished Java had.
Web (and network) programming is string intensive (processing html form submissions, for example). This feature makes it easier to work with strings.
Compare
String action = request.getParameter("action"); if (action.equals("next")) { if (validate(request)) sendNextPage(); else showErrorMessage(); } else if (action.equals("back")) { sendPrevousPage(); } else { handleUnkownAction(); }
to
String action = request.getParameter("action"); switch (action) { case "next": if (validate(request)) sendNextPage(); else showErrorMessage(); break; case "back": sendPrevousPage(); break; case default: handleUnkownAction(); }
I think the latter (C# way) is easier to read and understand. Switchability on string values seems to me quite appropriate for a general purpose programming language with a bias towards web and network programming, as Java is.
- Robin Meade
Date: Wed, 28 Jun 2000 14:34:51 -0700
From: Greg Guerin <glguerin@amug.org>
Subject: more flamage-reduced comments on C#
Oops, I forgot to mention that every C# object is automagically a COM object (there's a chapter called "Interoperability" that goes into some detail about this). However, I am sufficiently ignorant of COM that I have no real practical idea of how useful this is, or what the speed/memory costs of it are, or its security implications. It does seem to be something that Windows programmers get excited about, though.
One other thing I've seen in web articles about C# is that it executes on a "virtual processor" (a virtual machine to the rest of the world). However, this is not mentioned at all in the language spec, and I found no further information on it.
Date: Sat, 1 Jul 2000 15:25:08 -0700
From: Greg Guerin <glguerin@amug.org>
Subject: more comments on C#
I found the details on C#'s 'virtual ' keyword. It's pretty much what I expected: you MUST use it on any method which you wish to be overridable. A non-virtual method is resolved at compile-time, using the compile-time type of the object. A virtual method is resolved at run-time, using the run-time type of the object. Like Java, static methods are always non-virtual. Unlike Java, it appears that non-static methods can also be non-virtual, and indeed are by default if not explicitly declared virtual. I see little practical advantage and much needless complexity arising from this feature.
I didn't notice it before, but C# provides operator overloading <sigh>:
The overloadable unary operators are:
+ - ! ~ ++ -- true false
The overloadable binary operators are:
+ - * / % & | ^ << >> == != > < >= <=
Only the operators listed above can be overloaded. In particular, it is not possible to overload member access, method invocation, or the =, &&, ||, ?:, new, typeof, sizeof, and is operators.
All the listed operators can be overloaded and/or defined on class or struct types <groan>. There are also hints that enum's and some other types can have operators defined or overloaded.
I also missed this astonishing "feature" of the 'switch' statement:
Unlike C and C++, execution of a switch section is not permitted to "fall through" to the next switch section... The "no fall through" rule prevents a common class of bugs that occur in C and C++ when break statements are accidentally omitted.
Thus, the following (as it would appear in C) is a C# error:
switch ( a ) { case 1: perform(); case 2: something(); case 3: more(); }
and requires this structure instead:
switch ( a ) { case 1: perform(); goto case 2; case 2: something(); goto case 3; case 3: more(); }
You CAN have multiple labels on the same case-section, so this is legal:
switch ( a ) { case 1: case 2: something(); break; case 3: otherwise(); }
If you wish the cases to be mutually exclusive, you use the 'break' statement in The Canonical Way.
As a consolation prize, you can use the string type in switches:
void dosify( string cmd ) { switch ( cmd.ToLowerCase() ) { case "ls": doDir(); break; case "rm": doDel(); break; case "cp": doCopy(); break; default: doNothing(); break; } }
There is no information on how the compiled code performs this, except that the "string equality" operator (equivalent to Java's String.equals() semantics) governs the comparison. So maybe it's a hash-table or maybe it's an if/else chain.! | http://www.cafeaulait.org/reports/cdull.html | crawl-002 | refinedweb | 2,420 | 54.42 |
I want post json request like that
{"jsonrpc": "2.0", "method": "testApi", "params": {
"message": "abc"
}
, "id": 1}
I read posts:
How to POST raw whole JSON in the body of a Retrofit request?
but i can'not found class TypedInput, TypedByteArray, TypedString in my retrofit2 package. Where is?
To POST a body in
Retrofit, you create an object that represents this body, a class that includes
String jsonrpc,
String method, etc. Then, pass this object to the method that you define in your service interface and has a param with
@Body annotation.
Here is an example for POST body object:
public class PostBody{ String jsonprc; String method; Param param; public PostBody(...){ //IMPLEMENT THIS } ... class Param{ //IMPLEMENT THIS } } | https://codedump.io/share/XBVewsCbtJa1/1/post-raw-json-in-body-retrofit2 | CC-MAIN-2018-26 | refinedweb | 117 | 71.75 |
Components and supplies
Apps and online services
About this project
We all know that being without that special person in your life can be difficult, but what if you could send love and affection remotely over the Internet by just hugging a pillow?
Now, we can't really send hugs... but what we can send is a sweet emoji through a messaging app, triggered by you giving a pillow a hug.
When you hug the I Love You Pillow you will hear the sound of a heartbeat coming from the buzzer inside. Depending on the length of your hug, a different emoji will be sent from a Telegram Bot to whatever chat you choose.
Stay in touch with your loved one with this huggable device!
In a Nutshell
In this experiment, we will use aluminium foil to create a DIY capacitive sensor that will be used to detect hugs.
In order to create our hug-sending-device we will need the following components:
- Buzzer
- Aluminium foil
- 1 resistor 5M ohm
- Breadboard
- Wires
Learning Goals
- Introducing Telegram Bots
- Managing capacitive sensors
- Telegram Bots and group chats #ProTips
- WiFi best practices #ProTips
Pro Tips are useful but not strictly necessary steps that add a layer of complexity to the project.
Want to Know More?
This tutorial is part of a series of experiments that familiarise you with the MKR1000 and IoT. All experiments can be built using the components contained in the MKR IoT Bundle.
- I Love You Pillow
Introducing Telegram Bots
Telegram is a popular messaging app for both mobile and desktop. Besides letting us chat with our friends it also allows us to create handy and powerful chat-bots!
A chat-bot is nothing but a contact you can chat with, but instead a person behind it, there is a machine that replies accordingly to the code you wrote.
The TelegramBot library for Arduino gives us an easy way to implement the logic behind the chat-bot.
Create Your Bot
Creating a Bot is so easy!
Just follow these few simple steps or take a look at the documentation here.
Set Up the Board
First off make sure we have all the needed libraries.
Here's the list of all the libraries we will need:
- WiFi101
- TelegramBot
- ArduinoJson
- CapacitiveSensor
You can easily install them following this simple guide.
In order to use Telegram's API we first need to upload the certificates on the MKR1000. This applies to most of online services and APIs!
Upload the Firmware Updater example from the WiFi101 library and add api.telegram.org to the domains.
> examples > WiFi101 > FirmwareUpdater
If you are using the Arduino Web Editor this feature is not yet implemented and you need to do this through the Arduino Desktop Application.
Let the magic happen!
Open the EchoBot example from the TelegramBot library, fill in your WiFi credentials and the API token you received from the BotFather and upload!
> example > TelegramBot > EchoBot
You just created a bot that echoes all your messages.
EchoBot and Emoji
Emojis are everywhere! We will use them to send our love and hugs. Using the EchoBot example is an easy way to see how the bots read your emoji.
Unfortunately the way the bot receives the emoji is not the same used to send them. In order to send an Emoji we will need to use UNICODE characters.
For instance to send an heart emoji we will use:
\U00002764
You can see the full list of unicode emoji codes here. In order to create a bot that replies to an heart emoji with another heart emoji we will use a code like this:
void loop() { message m = bot.getUpdates(); // Read new messages if ( m.chat_id != 0 ){ // Check if there are some updates Serial.println(m.text); // print the message received if(m.text == "u2764ufe0f"){ //check if it received an heart emoji bot.sendMessage(m.chat_id, "\U00002764"); // Reply to the same chat with the heart emoji } } }
The result will be:
Capacitive Sensor
Enough with Telegram, let's start building our DIY capacitive sensor!
The capacitiveSensor library turns two or more Arduino pins into a capacitive sensor, which can sense the electrical capacitance of the human body. All the sensor setup requires is a medium to high value resistor and a piece of aluminum foil.
At its most sensitive, the sensor will start to sense a hand or body inches away from the sensor and through different kind of materials. We will hide our sensor inside the pillow!
Upload the example sketch, connect the wires and see the result on the console:
#include <CapacitiveSensor.h> CapacitiveSensor foil = CapacitiveSensor(5,4); // 10M resistor between pins 5 & 4, pin 4 is sensor pin, add a wire and or foil void setup() { foil.set_CS_AutocaL_Millis(0xFFFFFFFF); // turn off autocalibrate Serial.begin(9600); } void loop() { long start = millis(); long sensor_value = foil.capacitiveSensor(30); Serial.print(millis() - start); // check on performance in milliseconds Serial.print("\t"); // tab character for debug windown spacing Serial.print(sensor_value); // print sensor output Serial.println("\t"); // print sensor output 3 delay(500); // arbitrary delay to limit data to serial port }
Wiring and results
We will use
sensor_value as a threshold to detect hugs!
The Heartbeat
The longer you hug, the more heartbeats you hear. The more the heart beats the more love you send (and different emoji, as well).
We will emulate the sound of a heartbeat using a buzzer and a few simple lines of code.
int Buzzer = 8; // Pin attached to the buzzer void setup(){} void loop(){ HeartBeat(); delay(1000); } void HeartBeat(){ tone(Buzzer, 31, 200); // tone(Pin, Note, Duration); delay(200); tone(Buzzer, 31, 400); delay(200); noTone(Buzzer); delay(1000); }
For a more complex use of the buzzer and the Tone function take a look at the dropdown menu examples and look for
Digital > ToneMelody
#ProTip: Chat-id and Group-chat
In order to send messages, a bot needs a chat-id.
The chat id is the unique identifier of a chat between someone and a bot. In order to get the bot to send messages to a specific person you first need that person to text the bot and save the chat-id of that specific chat.
In this project the Bot will reply only to the very last person who text it no matter who that was.
The Bots are public, everyone can text a Bot!
If you want to include the bot in a group chat you need to disable the privacy mode allowing the bot to read all the messages, otherwise it would only be able to detect commands that start with
/:
#ProTip: WiFi Best Practices
WiFi can be tricky. Sometimes it just turns off for few seconds with apparently no reason at all. This could be a problem for your Arduino since most of the time we run the WiFi connection function only at the beginning of the sketch.
Online services can be tricky as well, When the Arduino sends a request to a server (Telegram in this case) it waits for a reply. For hundreds of reasons a reply can fail to arrive, keeping the Arduino in an infinite loop.
To make your project more stable you can add a watchdog.
A watchdog is a timer that has to be periodically updated, otherwise it will reboot the board.
You can use these two libraries to add a watchdog to your project:
- Adafruit ASF Core // has to be downloaded and installed manually from Github
The EchoBot example will then look like this:
#include <WiFi101.h> #include <SPI.h> #include <TelegramBot.h> #include <Adafruit_SleepyDog.h> // Initialize Wifi connection to the router char ssid[] = "xxxx"; // your network SSID (name) char pass[] = "yyyy"; // your network key // Initialize Telegram BOT const char BotToken[] = "xxxx"; WiFiSSLClient client; TelegramBot bot (BotToken, client); void setup() { Serial.begin(115200); while (!Serial) {} delay(3000); // attempt to connect to Wifi network: Serial.print("Connecting Wifi: "); Serial.println(ssid); while (WiFi.begin(ssid, pass) != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(""); Serial.println("WiFi connected"); bot.begin(); Watchdog.enable(10000); // set the timer to 10 sec } void loop() { Watchdog.reset(); // if this function is not called within 10 seconds the board will reset itself message m = bot.getUpdates(); // Read new messages if ( m.chat_id != 0 ){ // Checks if there are some updates Serial.println(m.text); bot.sendMessage(m.chat_id, m.text); // Reply to the same chat with the same text } else { Serial.println("no new message"); } }
Code
Complete sketch
Schematics
Team Arduino
Arduino_Genuino
- 43 projects
- 2,020 followers
Published onDecember 5, 2017
Members who respect this project
you might like | https://create.arduino.cc/projecthub/arduino/love-you-pillow-f08931?ref=platform&ref_id=424_trending___&offset=3 | CC-MAIN-2018-30 | refinedweb | 1,428 | 63.09 |
Hashing algorithms are mathematical functions that converts data into a fixed length hash values, hash codes, or hashes. The output hash value is literally a summary of the original value. The most important thing about these hash values is that it is impossible to retrieve the original input data just from hash values.
Now, you may be thinking, then what's the benefit of using hashing algorithms ? Why just use encryption ? Well, even though encryption is important for protecting data (data confidentiality), sometimes it is important to be able to prove that no one has modified the data you're sending. Using hashing values, you'll be able to tell if some file isn't modified since creation (data integrity).
That's not it, there are many examples of their use, some examples include: digital signatures, public-key encryption, message authentication, password protection and many other cryptographic protocols. In fact, whether you're storing your files on a cloud storage system, using Git version control system, connecting to an HTTPS website, connecting to a remote machine using SSH, or even sending a message on your mobile phone, there's hash function somewhere under the hood.
Read also: How to Transfer Files in the Network using Sockets in Python.
In this tutorial, we will be using hashlib built-in module to use different hash algorithms in Python, let's get started:
import hashlib # encode it to bytes using UTF-8 encoding message = "Some text to hash".encode()
We gonna use different hash algorithms on this message string, starting with MD5:
# hash with MD5 (not recommended) print("MD5:", hashlib.md5(message).hexdigest())
Output:
MD5: 3eecc85e6440899b28a9ea6d8369f01c
MD5 is pretty obsolete now, and you should never use it, as it isn't collision resistant, let's try SHA-2:
# hash with SHA-2 (SHA-256 & SHA-512) print("SHA-256:", hashlib.sha256(message).hexdigest()) print("SHA-512:", hashlib.sha512(message).hexdigest())
Output:
SHA-256: 7a86e0e93e6aa6cf49f19368ca7242e24640a988ac8e5508dfcede39fa53faa2 SHA-512: 96fa772f72678c85bbd5d23b66d51d50f8f9824a0aba0ded624ab61fe8b602bf4e3611075fe13595d3e74c63c59f7d79241acc97888e9a7a5c791159c85c3ccd
SHA-2 is a family of 4 hash functions: SHA-224, SHA-256, SHA-384 and SHA-512, you can also use hashlib.sha224() and hashlib.sha-384(). However, SHA-256 and SHA-512 are mostly used.
The reason it's called SHA-2 (Secure Hash Algorithm 2), is because SHA-2 is the successor of SHA-1 which is outdated and easy to break, the motivation of SHA-2 was to generate longer hashes which leads to higher security levels than SHA-1.
Although SHA-2 is still used nowadays, many believe that attacks on SHA-2 are just a matter of time, researchers are concerned about its long term security due to its similarity to SHA-1.
As a result, SHA-3 is introduced by NIST as a backup plan, which is a sponge function that is completely different from SHA-2 and SHA-1, let's see it in Python:
# hash with SHA-3 print("SHA-3-256:", hashlib.sha3_256(message).hexdigest()) print("SHA-3-512:", hashlib.sha3_512(message).hexdigest())
Output:
SHA-3-256: d7007c1cd52f8168f22fa25ef011a5b3644bcb437efa46de34761d3340187609 SHA-3-512: de6b4c8f7d4fd608987c123122bcc63081372d09b4bc14955bfc828335dec1246b5c6633c5b1c87d2ad2b777d713d7777819263e7ad675a3743bf2a35bc699d0
SHA-3 is unlikely to be broken any time soon. In fact, hundreds of skilled cryptanalysts have failed to break SHA-3.
What do we mean by secure in hashing algorithms ? Hashing functions have many safety characteristics, including collision resistance, which is provided by algorithms that make it extremely hard for an attacker to find two completely different messages that hashes to the same hash value.
Pre-image resistance is also a key factor for a hash algorithm security, an algorithm that is pre-image resistant makes it hard and time-consuming for an attacker to find the original message given the hash value.
There are few incentives to upgrade to SHA-3, since SHA-2 is still secure, and because speed is also a concern, SHA-3 isn't faster than SHA-2.
What if we want to use a faster hash function more secure than SHA-2 and at least as secure as SHA-3 ? The answer lies on BLAKE2:
# hash with BLAKE2 # 256-bit BLAKE2 (or BLAKE2s) print("BLAKE2c:", hashlib.blake2s(message).hexdigest()) # 512-bit BLAKE2 (or BLAKE2b) print("BLAKE2b:", hashlib.blake2b(message).hexdigest())
Output:
BLAKE2c: 6889074426b5454d751547cd33ca4c64cd693f86ce69be5c951223f3af845786 BLAKE2b: 13e2ca8f6a282f27b2022dde683490b1085b3e16a98ee77b44b25bc84a0366afe8d70a4aa47dd10e064f1f772573513d64d56e5ef646fb935c040b32f67e5ab2
BLAKE2 hashes are faster than SHA-1, SHA-2, SHA-3 and even MD5, and even more secure than SHA-2. It is suited for use on modern CPUs that supports parallel computing on multicore systems.
BLAKE2 is widely used and has been integrated into major cryptography libraries such as OpenSSL and Sodium and more.
You can also easily hash an entire file, just by reading all the file content and then passing the file bytes to any function we covered. Check the corresponding code here.
To wrap up, for further readings, you need to read the official Python documentation for hashlib module. Also, If you're interested in cryptography, Serious Cryptography book helped me a lot learning crypto, I hope you do too !
Related: How to Encrypt and Decrypt Files in Python.
Happy Hashing ♥View Full Code | https://www.thepythoncode.com/article/hashing-functions-in-python-using-hashlib | CC-MAIN-2020-05 | refinedweb | 836 | 52.39 |
If our Lighttpd runs on a multi-processor machine, it can take advantage of that by spawning multiple versions of itself. Also, most Lighttpd installations will not have a machine to themselves; therefore, we should not only measure the speed but also its resource usage.
Optimizing Compilers: gcc with the usual settings (-O2) already does quite a good job of creating a fast Lighttpd executable. However, -O3 may nudge the speed up a tiny little bit (or slow it down, depending on our system) at the cost of a bigger executable system. If there are optimizing compilers for our platform (for example, Intel and Sun Microsystems each have compilers that optimize for their CPUs), they might even give another tiny speed boost.
If we do not want to invest money in commercial compilers, but maximize on what gcc has to offer, we can use Acovea, which is an open source project that employs genetic algorithms and trial-and-error to find the best individual settings for gcc on our platform. Get it from
Finally, optimization should stop where security (or, to a lesser extent, maintainability) is compromised. A slower web server that does what we want is way better than a fast web server obeying the commands of a script kiddie.
Before we optimize away blindly, we better have a way to measure the "speed". A useful measure most administrators will agree with is "served requests per second". http_load is a tool to measure the requests per second. We can get it from.
http_load is very simple. Give it a site to request, and it will flood the site with requests, measuring how many are served in a given amount of time. This allows a very simplistic approach to optimizing Lighttpd: Tweak some settings, run http_load with a sufficient realistic scenario, and see if our Lighttpd handles more or less requests than before.
We do not yet know where to spend time optimizing. For this, we need to make use of timing log instrumentation that has been included with Lighttpd 1.5.0 or even use a profiler to see where the most time is spent. However, there are some "big knobs" to turn that can increase performance, where http_load will help us find a good setting.
Installing http_load
http_load can be downloaded as a source .tar file (which was named .tar.gz for me, though it is not gzipped). The version as of this writing is 12Mar2006. Unpack it to /usr/src (or another path by changing the /usr/src) with:
$ cd /usr/src && tar xf /path/to/http_load-12Mar2006.tar.gz
$ cd http_load-12Mar2006
We can optionally add SSL support. We may skip this if we do not need it.
To add SSL support we need to find out where the SSL libs and includes are. I assume they are in /usr/lib and /usr/include, respectively, but they may or may not be the same on your system. Additionally, there is a "SSL tree" directory that is usually in /usr/ssl or /usr/local/ssl and contains certificates, revocation lists, and so on. Open the Makefile with a text editor and look at line 11 to 14, which reads:
#SSL_TREE = /usr/local/ssl
#SSL_DEFS = -DUSE_SSL
#SSL_INC = -I$(SSL_TREE)/include
#SSL_LIBS = -L$(SSL_TREE)/lib -lssl -lcrypto
Change them to the following (assuming the given directories are correct):
SSL_TREE = /usr/ssl
SSL_DEFS = -DUSE_SSL
SSL_INC = -I/usr/include
SSL_LIBS = -L/usr/lib -lssl -lcrypto
Now compile and install http_loadwith the following command:
$ make all install
Now we're all set to load-test our Lighttpd.
Running http_load tests
We just need a URL file, which contains URLs that lead to the pages our Lighttpd serves. http_load will then fetch these pages at random as long as, or as often as we ask it to. For example, we may have a front page with links to different articles. We can just start putting a link to our front page into the URL file, which we will name urls to get started; for example,.
Note that the file just contains URLs, nothing less, nothing more (for example, http_load does not support blank lines). Now we can make our first test run:
$ http_load -parallel 10 -seconds 60 urls
This will run for one minute and try to open 10 connections per second. Let's see if our Lighttpd keeps up:
343 fetches, 10 max parallel, 26814 bytes, in 60 seconds
78.1749 mean bytes/connection
5.71667 fetches/sec, 446.9 bytes/sec
msecs/connect: 290.847 mean, 9094 max,15 min
msecs/first-response: 181.902 mean, 9016 max, 15 min
HTTP response codes:
code 200 - 327
As we can see, it does. http_load needs one of the two start conditions and one of the two stop conditions plus a URL file to run. We can create the URL file manually or crawl our document root(s) with the following python script called crawl.py:
#!/usr/bin/python
#run from document root, pipe into URLs file. For example:
# /path/to/docroot$ crawl.py > urls
import os, re, sys
hostname = ""
for (root, dirs, files) in os.walk("."):
for name in files:
filepath = os.path.join(root, name)
print re.sub("./", hostname, filepath)
You can download the crawl.oy file from.
Capture the output into a file to use as URL file. For example, start the script from within our document root with:
$ python crawl.py > urls
This will give us a urls file, which will make http_load try to get all files (given that we have specified enough requests). Then we can start http_load as discussed in the preceding example. http_load takes the following options:
For the -sip option, we will need a list of IP addresses. Here is a useful python script that will write a number of distinct IP addresses below a given subnet (which we can then route to our loopback device):
#!/bin/env python
# run with: makeips.py 1000 101.202.0.0
# to create 1000 ip entries in the subnet 101.202.*.*
import random, sys
ips = {}
def makeip(subnet, ip=None):
while ip is None or ips.get(ip):
ip = ".".join(x != "0" and x or str(int(random.random()*256))
for x in subnet.split("."))
ips[ip] = 1
return ip
def makeips(amount, subnet):
maxips = 256 ** sum("0" == x for x in subnet.split("."))
if maxips < amount:
print "Can only fit %i ips in the subnet %s." % (maxips, subnet)
amount = maxips
ipfile = open("ips", "w")
for i in xrange(amount):
ipfile.write(makeip(subnet) + "n")
ipfile.close();
if __name__ == "__main__":
try: makeips(argv[1], argv[2])
except: print "usage: python makeips.py [amount] [subnet]"
You can download the makeips.py code file at.
With this we can route the subnet to the loopback device and make it look as if different clients are requesting the pages. Use this to counter the effect of expiry on our tests; as the only alternative would be to remove mod_expire from the configuration, which is probably not desirable.
Route a whole subnet to our local host or use one we already have With UNIX-like operating systems (Linux, Solaris, BSD, and MacOS X), use the route add command. On Windows (with or without cygwin), we can make use of the fact that the whole 127.*.*.* network is looped back (using the default IP 127.0.0.1). So running python makeips.py 255 127.0.0.0 will give us a range of IP addresses we can use even if we cannot change our routing tables
Before we work on fine tuning our network, we can tweak some configuration settings to increase performance:
Select the best event handler and write the backend for the job. Here is the recommendation per system:
- Use sendfile64 only if large files (> 2GB) are disabled, which we should do if we do not serve files that big.
- If we have dynamic content, we should choose our CGI protocol wisely. FastCGI and SCGI are better choices than CGI. If you have the luxury of choosing your CGI language, you might want to try a small and fast scripting language such as Python or even Lua.
- Static data is best served from static files. The usual file systems in use today will easily outperform any database/CGI solution. If we have a big page with lots of JavaScript and a smaller part of the page is dynamic (for example, not the JavaScript), we should put the JavaScript in a static .jsfile and link them.
- Use SSL only for sensitive data. Clients do not cache data sent over SSL. So if we have images or other static data that does not compromise the client's information, send it over to plain HTTP.
- Remove unused modules from the configuration. This is a win-win option for both speed and memory.
There are some settings that affect speed and stability, and depend on the scenario we deploy Lighttpd in. For example, if we have a huge number of concurrent connections open, we can run out of file descriptors. We can counter that by increasing the number of file descriptors in the kernel and setting server.max-fds higher (default is 1024). If we have a lot of small requests, we might increase server.max-keepalive-requests. On the other hand, if we send out a few big files at any given time, we might want to increase the send buffer (note that this has to be allocated for each request, so it might eat into our memory pretty fast). The following are the three scenarios with settings that should give good performance:
- Many small requests (typical for AJAX applications): The defaults are quite good here, although for big applications we might raise server.max-keep-alive-requests to 256 or even higher (try how many sessions we can keep alive without running into the file handle barrier).
- Big requests (for example, YouTube): Increase the send file buffer; for example, on Linux set the kernel configuration to:
net.ipv4.tcp_wmem = 4096 65536 524288
net.core.wmem_max = 1048576
On BSD set net.inet.tcp.sendspace = 8192 (or even higher, but remember it eats a lot of the kernel RAM per open connection).
- Big files upload (for whatever): Do the same to the read file buffer: Under Linux do the same as in step 3, but replace "wmem" with "rmem", and under BSD set net.inet.tcp.recvspace = 8192.
With any server that handles many requests per second, a huge pile of file descriptors is a good thing to have. Note that other applications are also using up file descriptors, for example, the CGI backends (if we have more than one).
These are just common scenarios and some tips to work with them. In any case, run http_load and look at the result. If the throughput is higher, and/or the latency lower, good! If not, roll back the change and try something else.
Specific optimizations
Until now, our methods and tools to measure performance are quite blunt—we can see how fast our Lighttpd is with a specific optimization, but we do not know where to start. Ahmdahl's law (see) implies that if we optimize a portion of the code that takes up a portion X of the time by the ratio Y, the resulting speedup is limited by X. The downside of this is optimizing code that never gets called which is a good way to throw away our time. The upside is that if we know which portions of the code takes up most of the time, we know where to optimize.
A crude way of finding out where Lighttpd spends its time (at least between reading and writing) is log timing. As of Lighttpd 1.5.0, there is a new configuration option: debug.log-timing. This option can be enabled to insert timing information into the log files. For each request, the start time plus three intervals will be timed. The interval between receiving and queuing the request, the time used for reading the request, and the time used for writing a response, is in the following format:
write-start: #.#### read-queue-wait: #### ms read-time: #### ms
write-time: #### ms
This timing can be helpful if we want to know whether we should spend our time on optimizing the read cycle or the write cycle. As a rule of thumb, if we have a big read-queue-wait time, we may have too many requests. So increasing file handles or maybe even load-balancing on multiple systems might help. If there is a long read time, look out for uploads or big forms, and try to select a better event handler. If the write time is long see if we can improve the network backend; or if Lighttpd serves a dynamic page, see if we can improve the web application. Perhaps we can use a different CGI backend, introduce caching, and use mod_magnet for very small tasks.
Example: Caching with mod_magnet
Suppose we have a PHP script that runs through a database, fetches a set of records, and creates a HTML page. So far so slow; our database, PHP interpreter, and CGI interface are taxed on every request. Further, suppose that we do not really need millisecond up-to-date data. We could run the PHP script say every five minutes, thus improving its performance as it runs.
Firstly, we can change our PHP script to write the HTML output into a file instead of standard output and send a X-Lighttpd-Sendfile header (enable this in the CGIbackend configuration—refer to Appendix B). This has two benefits: Lighttpd can send out the file directly with no speed penalty and we have the cached file. Make sure our Lighttpd is built with Lua support. Now, we can add the following configuration:
server.modules = ( ..., "mod_magnet", ...)
magnet.attract-physical-path-to = ("/application/" => "app.lua")
Our app.lua can then use the cache to see if the file is older than five minutes and if so call the PHP. The following code does exactly that:
-- app.lua: cache a PHP application for 5 minutes
php_path = "/app.php"
cache_dir = lighty.env["physical.doc-root"] .. "/cache/"
cache_time = 300 -- 300 seconds = 5 minutes
path = lighty.env["physical.rel-path"]
s = lighty.stat(cache_dir .. path)
if s ~= nil then -- not in cache, call out to PHP
lighty.env["request.uri"] = php_path
return lighty.RESTART_REQUEST
end
if s[8] + cache_time > os.time() then -- too old, call out to PHP
lighty.env["request.uri"] = php_path
return lighty.RESTART_REQUEST
end
lighty.header["Content-Type"] = "text/html"
lighty.content = {{ filename = cache_dir .. path }}
return 200
This may look like a special case, but there are many web applications out there which do not use any caching at the application level. Plus, its integration into the web server makes this a winning performance for all cases. When the page is cached, it is served almost as fast as a static file.
On the other hand, if the page is not in the cache or is too old, the X-Lighttpd-Sendfile header trick at least reduces the number of file handles needed for the transaction and improves the throughput by shifting the work from our Lighttpd process to the operating system.
Measuring system load
From a holistic viewpoint (or if we plan to invest in hardware), we might be interested in the resource, which is limiting the performance of our Lighttpd. Most UNIX-like systems have a command, vmstat, which shows a small table of system load parameters:
procs ---------memory---------- --swap-- ---io--- --system- ----cpu---
r b swpd free buff cache si so bi bo in cs us sy id wa
1 0 0 302064 0 0 0 0 0 0 0 0 0 0 100 0
In this case, the system is sitting idle. The following fields are of particular interest:
Under Microsoft Windows operating systems, the task manager shows CPU load, memory/swap file usage, and network performance. If one of these maxes out, we have a candidate for improvement. The basic idea is the same as with the UNIX-like systems.
Profiling with gprof
To see where Lighttpd is spending its time in more detail, the use of a profiler is recommended. gcc comes with a profiling tool called gprof. We first need to tell gcc to prepare a Lighttpd version for profiling, then put it under load with http_load, stop Lighttpd, and run gprof to get a list of functions sorted by the time spent, which we can then interpret to see what to optimize. Now, let's see each step in more detail.
We can create a gprof ready Lighttpd by specifying a flag for the C compiler. This is done with the following commands before calling configure:
$ export CFLAGS=-pg
$ export LDFLAGS=-pg
Otherwise, proceed to create a Lighttpd build. We might also want to install this Lighttpd in a location different from our production build, as the profiling code will slow down our Lighttpd just slightly, and may also fill our file system with profiling data while running. So use the configure –prefix argument to specify a different location, for example, configure –prefix=/opt/lighttpd-gprof.
The build might fail with an error of "undefined references to _mcount" In this case, edit the libtool shell script created by configure. Search for a line compiler_flags= and add -pg so that the line says compiler_flags=-pg. Now make clean all should build our Lighttpd with profiling support.
Given that our build succeeded, we can now execute our profiling Lighttpd and test load to get the profiling data.
Load testing our profiling build
Our profiling build can be run exactly as usual. For directions on load testing using http_load, see the example. For this example, we use a 100-byte HTML file and set http_load to fetch 10,000 times with 10 parallel connections. After running the test and stopping our Lighttpd, we should find a new file with the name gmon.out (given a post-20th century-version of gprof). We can now run gprof to get some statistics. gprof needs at least two parameters: the path to the Lighttpd executable and the path to the gmon.out, our profiling run just created. For example:
$ gprof /opt/lighttpd-gprof/sbin/lighttpd gmon.out
This will show a lot of text, including two interesting tables: the flat profile and the call graph. The flat profile is a table of functions with a percentage of the full runtime, the cumulative runtime in seconds, the internal runtime (self) in seconds, the number of calls, the internal and cumulative runtimes per call, and finally the function name.
The cumulative runtime of a function is the time from when the first line of the function is executed until the execution returns from the function, whereas the internal runtime is the complete runtime minus the sum of complete runtimes of all functions called from the function.
The flat profile is very helpful to determine where our time is best spent optimizing. For us, the internal runtime and the number of calls show how much an optimization might affect total performance. The list is ordered by the percentage of the total time. So the higher on the list a function is, the more time we can shave off by optimizing it. The following is our example flat profile:
% cumulative self self total
time seconds seconds calls ms/call ms/call name
12.79 0.50 0.50 10000 0.05 0.08 http_request_parse
7.42 0.79 0.29 150179 0.00 0.00 array_get_index
5.63 1.01 0.22 370497 0.00 0.00 buffer_caseless...
4.35 1.18 0.17 13806 0.01 0.02 connection_hand...
3.84 1.33 0.15 20128 0.01 0.02 connection_reset
3.84 1.48 0.15 20599 0.01 0.16 connection_stat...
3.32 1.61 0.13 300039 0.00 0.00 buffer_append_s...
3.07 1.73 0.12 10000 0.01 0.06 http_response_p...
2.56 1.83 0.10 10000 0.01 0.05 http_response_w...
2.56 1.93 0.10 10000 0.01 0.01 network_write_c...
2.30 2.02 0.09 370095 0.00 0.00 buffer_prepare_...
2.30 2.11 0.09 40018 0.00 0.00 LI_ltostr
1.66 2.18 0.07 350705 0.00 0.00 buffer_prepare_...
1.66 2.24 0.07 120001 0.00 0.00 buffer_is_equal
1.66 2.31 0.07 633052 0.00 0.00 buffer_reset
1.53 2.37 0.06 310064 0.00 0.00 buffer_copy_str...
1.53 2.43 0.06 80855 0.00 0.00 chunkqueue_remo...
1.53 2.49 0.06 10000 0.01 0.01 connection_close
1.53 2.55 0.06 __divdi3
1.53 2.61 0.06 70019 0.00 0.00 array_insert_un...
1.28 2.66 0.05 120000 0.00 0.00 buffer_append_s...
1.28 2.71 0.05 20000 0.00 0.00 hashme
1.28 2.76 0.05 10000 0.01 0.02 stat_cache_get_...
1.28 2.81 0.05 etag_mutate
1.02 2.85 0.04 60384 0.00 0.00 array_reset
1.02 2.89 0.04 40018 0.00 0.00 buffer_append_long
1.02 2.93 0.04 30256 0.00 0.00 config_setup_co...
1.02 2.97 0.04 10238 0.00 0.02 connection_accept
1.02 3.01 0.04 10000 0.00 0.02 network_write_c...
1.02 3.05 0.04 10000 0.00 0.01 request_check_h...
... ... ... ... ... ... ...
The long function names were cut off in the name of readability, as well as all the following functions one percent of the runtime. As we can see, the http_request_ parse function takes the biggest chunk of runtime. This should be so, given that we are sending out the same short file over and over again, which should be cached from the second request onwards. Note that the http_request_parse function would be top priority on our list should we want to optimize the code, because it has the biggest internal runtime and also gets a decent number of calls (one per request).
An even more detailed report is the call graph. It shows a table for every function with a list of callers before and a list of callees after it. For each entry, the time (complete and internal), and the number of calls (from the parent function and total) is shown. We can use this to find out why a function is called so often, and trace the code paths. However, without a decent visualization, we can easily get lost in the mountains of data. Here is an example call tree (again, function names are cut off for brevity):
index % time self children called name
<spontaneous>
[1] 94.7 0.01 3.69 main [1]
0.00 1.90 288/288 network_server_h... [3]
0.08 1.67 10599/20599 connection_state... [2]
0.00 0.02 1/1 connections_free [60]
0.01 0.01 599/599 connection_hand... [61]
0.00 0.00 1/1 config_read [90]
0.00 0.00 1/1 server_free [95]
0.00 0.00 2/3 log_error_write [104]
0.00 0.00 1/1 plugins_load [107]
0.00 0.00 4/50159 array_get_element [15]
0.00 0.00 1/1 log_error_open [109]
0.00 0.00 1/1 network_init [110]
0.00 0.00 292/292 stat_cache_tri... [111]
0.00 0.00 1/1 plugins_free [115]
0.00 0.00 1/1 config_set_def... [117]
0.00 0.00 1/1 server_init [122]
0.00 0.00 1/10001 fdevent_unregister [42]
0.00 0.00 1/1 network_close [124]
0.00 0.00 1/1 network_regist... [127]
0.00 0.00 1/26794 fdevent_event_del [64]
0.00 0.00 10599/20599 plugins_call_h... [133]
0.00 0.00 887/887 fdevent_event_... [150]
0.00 0.00 887/887 fdevent_event_... [149]
0.00 0.00 887/887 fdevent_event_... [148]
0.00 0.00 887/887 fdevent_get_ha... [152]
0.00 0.00 887/887 fdevent_get_co... [151]
0.00 0.00 639/639 fdevent_poll [156]
0.00 0.00 292/292 plugins_call_h... [160]
0.00 0.00 1/1 plugins_call_init [188]
0.00 0.00 1/1 plugins_call_s... [189]
0.00 0.00 1/1 fdevent_init [180]
0.00 0.00 1/1 stat_cache_init [192]
0.00 0.00 1/10001 fdevent_fcntl_set [134]
0.00 0.00 1/1 log_error_close [186]
--------------------------------------------------------
0.07 1.58 10000/20599 network_server_h... [3]
0.08 1.67 10599/20599 main [1]
[2] 86.9 0.15 3.25 20599 connection_state_mac... [2]
0.02 1.07 10000/10000 connection_handl... [4]
0.50 0.28 10000/10000 http_request_parse [5]
0.12 0.50 10000/10000 http_response_pr... [6]
0.16 0.06 13207/13806 connection_hand... [14]
0.02 0.18 10000/10000 connection_hand... [19]
0.07 0.10 10000/20128 connection_reset [10]
... ... ... ... ... ...
Although we now have specific numbers where our Lighttpd uses its time, and even which functions gets called from where, we still do not know how to optimize the settings to reduce the runtime.
Alas, unless we want to optimize directly in the source code (which thanks to Lighttpd underlying the revised BSD license and being available in source form, we can), there is no easy way apart from trial and error to find out which setting creates which effect. At least, we can see where this effect comes into play.
Summary
Knowing what to optimize beats knowing how to optimize. Therefore, load testing and collecting usage statistics is paramount to improving throughput and minimizing latency. Probably, the most important thing about optimization is to know when to stop.
At the moment, there is no easier way than trial and error to find out what makes our Lighttpd work faster. On the other hand, optimizing for performance may conflict with other goals such as security and maintainability.
Logging the timing of the request or response phases can give us a broad overview where to optimize first. Knowing which system resources limit our Lighttpd's performance can also give us a hint on what to do. If we need a more detailed picture of where our Lighttpd spends its time, profiling is our course of action. | https://www.packtpub.com/books/content/optimizing-lighttpd | CC-MAIN-2017-13 | refinedweb | 4,366 | 74.9 |
reply must
reply must is it critical to do a software job based on games(java) i know core java & advanced java basics only please give me answer
Must to See in Agra India
Must See Sites in Agra
Agra's rich cultural past along with strong Mughal... striking of these structures are a must watch sites in the city and should... must book at least 24hours in advance for shows of the Taj under full moon
Must to See Agra Fort
was famous for bearing grapes.
Must to see
Diwan-i-am of Agra Fort: This hall...Agra Fort: Must to See
The Agra Fort, must to see place, is undoubtedly.... Along with the Agra Fort, Babur also captured the famous
Koh-i-noor diamond
I want this jsp answers
I want this jsp answers
How can we declare third party classes and interfaces inside our jsp page?
How can we declare and definr global variables and methods inside our jsp page?
If we are declaring global variables
JSP
must appear in the same page.So I tried by using dynamic page include. But I didnt get the desired result. Whenever I am clicking + I should get more textboxes...JSP I need to create the link +. On clicking +, I should get... input. All the files/pages must be stored in a folder
How i write a function/method in jsp?
How i write a function/method in jsp? How write the function/method in jsp?
Using that method i can retrieve the value coming from database.
give me example plz.
Actually i want to show the list of user detail
JSP and JDBC - JSP-Servlet
JSP and JDBC Respected sir/Madam,
I am R.Ragavendran.. I... is as follows:
1) There must be a home.jsp page in which three fields must be present... ID text Box, There must be a small button. When user clicks this button, a small
Identify the interfaces and methods a CMP entity bean must and must not implement.
Identify the interfaces and methods a CMP entity bean must and must... the interfaces and methods a CMP entity bean must and must not implement. ... class:
The class MUST implement - JSP-Servlet
the data in a html form. It must be jsp. Because, html is static where as jsp...JSP Respected sir/Madam,
I am R.Ragavendran. I am In a very very urgent need of a program. Actually I have done it 50% and for the rest, I
JSP - JSP-Servlet
);
i displayed the data from my sql to the jsp page
this is the code...JSP im having the problem related to the jsp
data base... dfjdfdfklf here is the delete pic
now what i want is when delete
I/O Java
I/O Java import java.io.File;
import java.io.FileNotFoundException...);
}
}else{
System.out.println("File name must be a TEXT... writer = new PrintWriter(outFile);
for(int i=0;i<inputFiles.length;i
JSP Declaration
JSP Declaration What is a JSP Declaration?. Explain it.
Hi,
The answer is:
The JSP declaration used to craete one or more variable and methods that are used later in the jsp file. If you want to create variable thanks for responce i know how to connect the database, i need... and another user enters for 4 times in the day when i displaying the report of total working hours of both user total working time of user1 must be displayed in first
Jsp
Jsp Can I implement interface in jsp
Charts in JSP - JSP-Servlet
Charts in JSP Hi,
Thanks for replying for the chart query I... with the datas coming from the database? Series chart in the sense, If I have x... month itself, there must be three comparisions say one showing the population
how do i upload a file by using servlet or jsp?
how do i upload a file by using servlet or jsp? hi plz tell me the write java code
jsp
jsp I Want complete note on
i need help - Development process
the result in to the files,if i want to do this i must make my program running...i need help hello,
i need help regarding this program.
public...());
}
}
}
it is printing the result of ping in to a file,but if i want
JSP
JSP How to create CAPTCHA creation by using JSP?
I need an code for CAPTCHA creation by using JSP...
You can create a captcha validation using jsp. Have a look at the following tutorial:
Captcha Creation
write data to a pdf file when i run jsp page
write data to a pdf file when i run jsp page Hi,
<%@page import... to open the pdf file when i execute the jsp page...{ document.close();}
%>
</body>
I added itextpdf jar
I Want to take mqsyl batabase backup using jsp
I Want to take mqsyl batabase backup using jsp I was develop web portal using jsp and servelt. I need to take backup my MySQL database and restore another one MySQL database.
import java.util.*;
import java.io.
Session Tracking JSP - JSP-Servlet
Session Tracking JSP Respected sir/madam,
I am R.Ragavendran.. I Immediately need a coding for session tracking in JSP.
Actually when the admin clicks "View Users logon status" Yiour coding must display the User Login
how should i can solve
how should i can solve Web based program -
Input - Person's contact details with Passport Number as Unique Key.
Save data in to oracle / MySQL.
Output - List of Persons saved in the database.
Technology to be used - JSP
how do i solve this problem?
how do i solve this problem? Define a class named Circle... objects. The first object must be created using the default constructor, while the second object must be created with the radius value of 8. Display
conert java code to jsp... plz imm i wan...
conert java code to jsp... plz imm i wan... how to convert this java code into jsp??
Java| Frameworks| Databases| Technology| Development| Build...[locales.length];
for (int i = 0; i < locales.length; i
i need help - Development process
IPAddress on command line, but i want to take it dynamically and it must store...i need help hello,
i need help regarding this program. this program gives ping to the system.
import java.net.*;
import java.io.*;
import
how do i solve this question?
how do i solve this question? 1.Define a class named Circle... to test the Circle program by creating two Circle objects. The first object must be created using the default constructor, while the second object must be created
Admin and User Login JSP - JSP-Servlet
Admin and User Login JSP Respected Sir,
I am R.Ragavendran.. i need a JSP based program immediately.. In the home page, there must be a login...",it must go to the next page where users log in and log out session time must and mysql
jsp and mysql i have a form which contains dropdown list. i have to take the values to another jsp page and perform the calculation on the database... and there must not be any change in the database.. i have to display the database do i start to create Download Manager in Java - JSP-Servlet
How do i start to create Download Manager in Java Can you tell me from where do i start to develop Download manager in java
JSP
JSP 1>>>I have 2 page.
1st page is for registration & 2nd page is for server side validation of registration page
Now, I want... object?
how i can get document & elements of registration page?
to make employee i card
how to make employee i card hello friends
can anyone help me..
I have to make a project to make Identity card for employees...but i am facing problems with database and jsp connection ...
also tell me how to retrive data
jsp
JSP User Registration Form <%@ page language="java" contentType... must be filled out");
return false;
}
if(b==null||b=="")
{
alert("Quantity must be filled out");
return false
jsp
JSP Form for registration <%@ page language="java" contentType... false;
}}
if(a==null||a=="")
{
alert("first name must...=="")
{
alert("Quantity must be filled out");
return false
jsp
JSP User Registration form <%@ page language="java" contentType... must be filled out");
return false;
}
if(b==null||b=="")
{
alert("Quantity must be filled out");
return false
jsp
JSP Registration Form <%@ page language="java" contentType="text...;
}}
if(a==null||a=="")
{
alert("first name must...=="")
{
alert("Quantity must be filled out");
return false
I this example we will show you how to validate email address in you JSP
program using JavaScriptdbc,jsp - JDBC
;
this is my jsp code
in this code i have to give hyperlink to database(selected row must be deplay) Hi keerthi,
replace the line...){
%>
<%
}
}
I didn't understand about "selected row must | http://roseindia.net/tutorialhelp/comment/86747 | CC-MAIN-2015-27 | refinedweb | 1,472 | 73.78 |
AT Command
NOTE:To get a ‘better’ Bluetooth experience on BLE 4.1 modules, we highly recommand you to update the newest firmware first.NOTE:To get a ‘better’ Bluetooth experience on BLE 4.1 modules, we highly recommand you to update the newest firmware first.
AT is the abbreviation of attention. AT command is the communication command used to configure Bluetooth parameters. It begins with AT, end with
NOTE:NOTE:
is not a part of AT Command.is not a part of AT Command.
AT Command List
Configure the BLE through AT command
1. Open the Arduino IDE.
2. Select the correct serial port in Menu->Tool->Serial port
3. Open the Serial monitor (on the upper right of the IDE windows)
4. Select the "No line ending"(①) and 115200 baud(②) in the pull-down menu
5. Type " "(③) like this and press send button(④)
6.
.
- WAKEUP: the button can wake up the device from low-power consum[ption mode (you can also connect this pin to MCU to realize the same function)
- RST: BLE4.1 reset button
Below is the BLE4.1 minimum system circuit diagram for your reference: Fig1: the BLE4.1 minimum system circuit diagram
Smartphone Bluetooth Connection
- Android Terminal and IOS Terminal
- BlunoBasicDemo Android, Android source code (DFRobot)
- LightBlue IOS
- Blynk IOS
Different from the traditional Bluetooth (such as Bluetooth headset), BLE4.1 need specified eigenvalue and device service ID to connect smartphone. The direct connection between BLE and smartphone device manager will lead to communication problems. Therefore, it needs a the third party APP, such as BunoBasicDemo (published by DFRobot), BLE Device Monitor from TI .etc. In this section, we'll take BunoBasicDemo published by DFRobot as an example.
- Set BLE4.1 as peripheral device with command AT ROLE=ROLE_PERIPHERAL. Set connection mode as P2P by AT NETWORK=P2P command and restart BLE4.1 (power off and restart).
- Open BunoBasicDemo app, click SCAN, then we'll see the scanned BLE4.1 device .
- Click the device to connect. Once it connected successfully, it will show Connected and LINK will light for 3s and blink for every 3s.
- Send data frome the Data sending Area
- Click Send Data to send data.
PC Bluetooth Connection
The direct connection between PC and BLE4.1 built-in Bluetooth is not available for temporarily (similar to smartphone, PC also need another software to realize the connection. The development is still in planning)
Bluetooth P2P Communication
The procedure of BLE4.1 P2P connection is similar to BLE4.0, and the only difference is the P2P mode command.
There are two devices in all, one should be set as the master device(ROLE_CENTRAL) and the other one should be set as the slave device(ROLE_PERIPHERAL). Config two BLE4.1 devices as P2P connection mode with AT NETWORK=P2P (Default: P2P mode).
- AT Command: AT ROLE=ROLE_CENTRAL, AT ROLE=ROLE_PERIPHERAL,
Restart BLE4.1 device and begin the approach connection.
- Approach Connection: press and hold host BOOT button and move it close to the target slave device (<10cm) until a successful connection, then the LINK will light on each 3 seconds
NOTE:
- The first time you press and hold the host BOOT button is only for add the new devices to the white list. It doesn't need the same operation for the second connection.
- BLE 4.1 device is also compatible with BLE4.0 devices (Bluno 1st generation). And BLE 4.0 only supports P2P connection, so it doesn't need to set the connection mode for 4.0, just BLE 4.1 only.
Bluetooth Star Network Connection
The star network connection mode is similar to the P2P connection mode, the difference between them in setting is that the star network uses the command AT NETWORK=STAR. The light LINK suggests the node device has been added to the white list of the central device and then it will connect the listed device automatically.
NOTE:Star network connection is only for BLE4.1 device, not applicable to Bluno 1st generation (BLE4.0) and other BLE brands device.NOTE:Star network connection is only for BLE4.1 device, not applicable to Bluno 1st generation (BLE4.0) and other BLE brands device.
In the star connection, Bluetooth device adopt special data packet compression method. You can use Arduino library to realize network data transmit. Click the link to download Arduino library files and Arduinojson library files. During the connection, the slave device which first connected to the host will get ID: 1 and hereby superimposed. The sample code shows how to get network ID of the device and ID of the data source. You’d better to power the device in turn when build star network.
#include <DFRobot_Bluno2.h> #include <ArduinoJson.h> DFRobot_Bluno2 blunoNet; int blunoID=0; void setup() { Serial.begin(9600); blunoNet.begin(Serial);//获取id } void loop() { uint8_t event=blunoNet.getEvent();//queue switch(event) { case EVENT_NETINFO: { eventNode e = blunoNet.popEvent(); StaticJsonBuffer<200> jsonBuffer; JsonObject& root = jsonBuffer.parseObject((const char *)e.payload); if (!root.success()) { return; } int s = root["r"].size(); for(int i = 0; i < s; i ){ if(root["r"][i]["s"].as<int>()){ blunoID = root["r"][i]["i"].as<int>(); break; } break; } } case EVENT_DATA: { eventNode e = blunoNet.popEvent(); blunoNet.sendPacket(e.src, blunoID, "hello12345678901234567890",26); break; } default: //no event { break; } } blunoNet.loop(); if(Serial.available()){ char message=Serial.read(); blunoNet.sendPacket(!blunoID, blunoID, &message,1); } }
Bluetooth Low Power Consumption Mode
After Bluetooth enter low power consumption mode, the BLE 4.1 consumes lower than 10uA, and it can still broadcast and keep data interaction. With command AT LOWPOWER=ON, BLE4.1 device will enable low power consumption mode after you reboot the device. BLE4.1 device will enter this mode in 10s. You can also use AT BOOT to make a software reboot. Here is something you should notice: The MCU should WAKEUP the BLE Chip first, or it will be messy code. In the low power consumption mode, if there is no extra operation, Bluetooth will enter this mode after 10s. You can awake Bluetooth by interruption pins; awake ATmega328P by Bluetooth:
- BLE4.1 wakes up the Arduino controller (ATmega328P) with P4_2 (D2_Arduino): high voltage wakeup
- Arduino controller (ATmega328P) wakes up BLE4.1 by WAKEUP (D3_Arduino): low voltage wakeup
Wireless Programming
Bluno 2 wireless programming is completely compatible with Bluno1 (BLE4.0). And it is only available under P2P connection mode: the host (the central device) to the slave side.
- Similar to P2P connection, set one as host and plug to the PC; set the other one as slave. Pairing the host and the slave, download is available.
Firmware Upgrade
DFRobot BLE4.1 has the firmware method to BLE 4.0, click to download BLE4.1 firmware update tool, BLE4.1 firmware address Firmware Download。
Update steps are as below:
- Hold BOOT
- Connect BLE4.1 to PC and loose BOOT, CHG and LINK flashes alternatively.
- Open Bluno2 Firmware and select corresponding serial number.
- Choose firmware to update, the firmware format is .img
- Click to download
- Check basics, such as power supply, board type and COM port.
- Bluetooth will occupy the serial port which will hamper uploading. Please disconnect the current Bluetooth connection, and try again.
- The device serial port may be occupied. Please disconnect all peripherals then recompile and download again.
- Arduino IDE may crashed. Please disconnect all Bluetooth (include smartphone), close all Arduino IDE software, pull USB line, reopen and test.
- Bootloader in the FireBeetle 328P may get lost. Please try re-uploading Bootloader of ATmaga328p.
- BLE 4.1 firmware may wrong. Please re-upload firmware and check the former chapter for reference. | | Q: | How to choose board when the device manager shows Arduino UNO COM x after connected to PC? | | A | The COM name in default is Arduino UNO. Please choose the board according to bootloader, e.g. choose Arduino Pro Mini 3.3V@8MHz for FireBeetle BLE4.1.| | Q: How to deal with the Bluetooth ID number varies with connection? | | A: The current Bluetooth ID number is defined with the connection order, ID1, ID2, ID3, DI4 in order and unchangeable. Please connect the host (the central device ID0) in turn.| | Q: Why the Bluetooth data been received is gibberish in the baud rate 115200? | | A: The bootloader that FireBeetle BLE4.1 uses is 3.3V Pro Mini of 8MHz oscillator. The Arduino Pro Mini 3.3V@8MHz may runs wrong with high baud rate. The lower baud rate is recommend, e.g. 9600bps| | Q: Does BLE4.1 supports HID, ibeacon and tree network? | | A: The functions HID, ibeacon and tree network are under development.|
For any questions, advice or cool ideas to share, please visit the DFRobot Forum.
Turn to the Top | http://wiki.dfrobot.com/DFRobot_Bluetooth_4.1__BLE__User_Guide | CC-MAIN-2019-18 | refinedweb | 1,446 | 69.18 |
Introduction: Interfacing 7-Segment Display With Shift Register Using CloudX Microcontroller
In this project we are publishing a tutorial on how to interface seven segment LED display with CloudX microcontroller. CloudX and 7 Segment display together! Lets begin the tutorial.
Teacher Notes
Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.
Step 1: HC595 Shift Register CloudX IDE. Simply input a number between 0 and 255 and the storage register can convert it into an 8-bit binary number and output it in parallel. This allows you to easily control the 8 pins of the 7-segment display and create any patterns you want.
Step 2: 7 SEGMENT
Let’s begin the tutorial. We are going to use CloudX M633 and a basic seven segment display with decimal point. You can identify the segments of the display with the help of figure above.
This seven segment display has a total of 8 LEDs per digit as shown in above image, seven LED’s for each segment and one for the decimal point.
As you can see there are 10 pins in total. You may notice two pins named com, as shown in the circuit diagram all the cathode (- pins) of the LEDs are connected to these two pins. We call these 2 pins as common cathodes and such displays are called Common Cathode 7 segment displays. There are some seven segment displays which have common anodes instead of common cathode. The only difference for common anode displays is all the anodes (+ pins) are connected together and they are known as Common Anode 7 segment displays. Apart from these 2 com pins, there are 8 other pins named A,B,C,D,E,F,G and DP. As you can see in the figure, these pins are anodes (+ pins) of the led segments of common cathode display (in the case of common anodes display these pins will be cathodes)
Step 3: Component Needed
- CloudX M633
- CloudX SoftCard
- V3 Usb Cable
- HC595 Shift register
- jumper wires
- Breadboard
- 7 Segment display
- 330 ohm resistor
Step 4: SETUP
Connect the 7-Segment display and 74HC595 shift register to CloudX M633:
Connect Vcc pin on 74HC595 to 5V pin on CloudX.
Connect GND and OE pins on 74HC595 to GND pin on CloudX.
Connect DS or SER pin on 74HC595 to digital pin 2 on CloudX.
Connect SHCP or SRCLK pin on 74HC595 to digital pin 1 on CloudX.
Connect STCP or RCLK pin on 74HC595 to digital pin 3 on CloudX.
Connect Q0-Q6 or QA-QG pin on 74HC595 to pin A-G on 7-segment display.
Connect Q7 or QH pin on 74HC595 to pin DP on 7-segment display.
Connect common cathode pins (pin 3 and 8 on the diagram) on 7-segment display to Gnd pin on CloudX.
Step 5: Code
#include <CloudX/M633.h> #include <CloudX/74HC595.h>
ChangeValue(unsigned char value){ switch(value){; } }
setup(){ HC595_setting(2,1,3);
loop(){ for(char i=0; i<10; i++){ HC595_shiftOut(ChangeValue(i) , MSBFIRST ); HC595_latch(); delayMs(1000); } } }
Be the First to Share
Recommendations
Discussions | https://www.instructables.com/id/Interfacing-7-Segment-Display-With-Shift-Register-/ | CC-MAIN-2020-10 | refinedweb | 525 | 71.75 |
Processing XML From Java With the XQJ API
This lesson in using the right tools for the job puts forward that if you know the kind of data you're going to be working with, start with a solution designed for it.
Join the DZone community and get the full member experience.Join For Free
This post is inspired by the article from Jay Sridhar: Load XML Into MySQL Using Java. I'd like to compare the way explained in the original article with the one provided by another Java API: XQJ (JSR-225). The steps explained in the source are not too complicated, but is it possible to get the same with less effort? Let's try to store XML documents in a native XML database. I'll walk through the same steps applied to the document/XML database Bagri DB.
1. Deploy Bagri DB
This step was not mentioned in the article, but I’ll add a line on this, just to be clear on how to start. Take the latest product release from GitHub, extract and run it.
2. Load Bagri XQJ Driver
XML databases provide their own kind of drivers to work with DBs from Java client apps. The driver API is specified in JSR-225: XQuery API for Java (XQJ). The API is quite similar to JDBC and designed for the same tasks.
So, just take the driver from the /distr folder of the extracted product and copy it to your application directory.
3. Connect to Bagri DB
This step is also similar to what it was for MySQL: set the connection properties and get a connection from DataSource:
XQDataSource xqds = new BagriXQDataSource(); xqds.setProperty(ADDRESS, “localhost:10500”); xqds.setProperty(SCHEMA, “default”); xqds.setProperty(USER, “guest”); xqds.setProperty(PASSWORD, “password”); xqds.setProperty(XQ_PROCESSOR, "com.bagri.xquery.saxon.XQProcessorClient"); xqds.setProperty(XDM_REPOSITORY, "com.bagri.client.hazelcast.impl.SchemaRepositoryImpl"); XQConnection xqConn = xqds.getConnection();
4. Create a (MySQL) Table
That is where the difference starts. There is no need to create any tables or other structures in Bagri, it’ll process XML and store it in internal DB structures automatically.
5. Parse XML
With XML DBs, there is no need to parse, it’ll do it for you. Just read the content from the file for future use. Bagri provides a set of handy utils for this:
String content = FileUtils.readTextFile(fileName);
6. Prepare XML Data
This step is also redundant in our case. We only need XML content to store it in the DB.
7. Insert Into Bagri DB
This step is closer to its counterpart from the source. Here, we’ll also prepare a statement and then execute it to store XML content to the DB:
String query = "declare namespace bgdb=\"\";\n" + "declare variable $uri external;\n" + "declare variable $xml external;\n" + "let $uri := bgdb:store-document($uri, $xml)\n" + "return $uri\n"; XQPreparedExpression xqpe = xqConn.prepareExpression(query); xqpe.bindString(new QName("uri"), fileName, xqConn.createAtomicType(XQBASETYPE_ANYURI)); xqpe.bindString(new QName("xml"), content, xqConn.createAtomicType(XQBASETYPE_STRING)); xqpe.executeQuery(); xqpe.close();
8. Read XML Data From DB
This step is not covered in the source, but let's visit it just to have the post finished. In order to read data from an XML DB, we’ll prepare and execute an expression and then iterate over the returned result set, pretty much the same as we do it with JDBC:
String query = "declare variable $genre external;\n" + "let $catalog := fn:doc(\"" + fileName + "\") return\n" + "for $book in $catalog/book/genre = $genre\n” + "return $book/author/text()"; XQPreparedExpression xqpe = xqConn.prepareExpression(query); xqpe.bindString(new QName("genre"), genre, xqConn.createAtomicType(XQBASETYPE_STRING)); XQSequence xqs = xqpe.executeQuery(); while (xqs.next()) { System.out.println("The author is: " + xqs.getAtomicValue()); } xqs.close(); xqpe.close();
Summary
There are some cases when the use of native XML DB is not relevant: When the original data source is not XML, when the data structure is relational and static, etc. But, when the processed data has floating structure and comes in form of documents (XML, JSON, or any other self-describing data format), then it can be easier to use tools which are designed for that kind of tasks.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/processing-xml-from-java-with-xqj-api | CC-MAIN-2022-27 | refinedweb | 701 | 55.44 |
Covariance and Correlation.
It is calculated as:
Note that:
t
When the two variables are identical, covariance is same as variance.
Covariance isn't that meaningful by itself
Let's say we have two variables
and
and we take the covariance of the two.
import os import sys import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy import stats X = np.random.rand(50) Y = 2 * X + np.random.normal(0, 0.1, 50) np.cov(X, Y)[0, 1]
0.18565571452010868
What does this mean? To make better sense of this information, we introduce correlation.
Correlation
Correlation uses information about the variance of X and Y to normalize this metric. The value of correlation coefficient is always between -1 and 1. Once we've normalized the metric to the -1 to 1 scale, we can make meaningful statements and compare correlations.
To normalize Covariance, consider
Where: \rho is the correlation coefficient of two series
and
. Just like covariance, a positive coefficient indicates that the variables are directly related and a negative coefficient indicates that the variables are inversely related. The closer to 0 the correlation coefficient is, the weaker the relationship between the variables.
Two random sets of data will have a correlation coefficient close to 0.
Correlation vs. Covariance
Correlation is simply a normalized form of covariance. They are otherwise the same and are often used semi-interchangeably in everyday conversation. It is obviously important to be precise with language when discussing the two, but conceptually they are almost identical.
print('Covariance of X and Y: %.2f'%np.cov(X, Y)[0, 1]) print('Correlation of X and Y: %.2f'%np.corrcoef(X, Y)[0, 1])
Covariance of X and Y: 0.19 Correlation of X and Y: 0.99
To get a sense of what correlated data looks like, lets plot two correlated datasets])
Correlation of X and Y: 0.97
And here's an inverse relationship:])
Correlation of X and Y: -0.94
import auquanToolbox.dataloader as dl # Pull the pricing data for our two stocks and S&P 500 start = '2013-01-01' end = '2015-12-31' exchange = 'nasdaq' base = 'SPX' m1 = 'AAPL' m2= 'LRCX' data = dl.load_data_nologs(exchange, [base,m1,m2], start, end) bench = data['ADJ CLOSE'][base] a1= data['ADJ CLOSE'][m1] a2 = data['ADJ CLOSE'][m2] plt.scatter(a1,a2) plt.xlabel('LRCX') plt.ylabel('AAPL') plt.title('Stock prices from ' + start + ' to ' + end) plt.show() print('Correlation coefficients') print('Correlation of %s and %s: %.2f'%(m1, m2, np.corrcoef(a1,a2)[0, 1])) print('Correlation of %s and %s: %.2f'%(m1, base, np.corrcoef(a1, bench)[0, 1])) print('Correlation of %s and %s: %.2f'%(m2, base, np.corrcoef(a2, bench)[0, 1]))
Reading SPX Reading AAPL Reading LRCX
Correlation coefficients Correlation of AAPL and LRCX: 0.95 Correlation of AAPL and SPX: 0.93 Correlation of LRCX and SPX: 0.96
Once we've established that two series are probably related, we can use that in an effort to predict future values of the series.
Another application is to find uncorrelated assets to produce hedged portfolios - if the assets are uncorrelated, a drawdown in one will not correspond with a drawdown in another. This leads to a very stable return stream when many uncorrelated assets are combined.
Important: Significance of Correlation
It's hard to rigorously determine whether or not a correlation is significant, especially when, as here, we are not aware if the variables are normally distributed or not. Their correlation coefficient is close to 1, so it's pretty safe to say that the two stock prices are correlated over the time period we use, but is this indicative of future correlation? If we examine the correlation of each of them with the S&P 500, we see that it is also quite high. So, we may be led to believe that two stocks have a relationship because of their high correlation, when in fact they are both caused by a third(market)
The problem is we may determine a good correlation by picking the right time period but it may not hold out of sample. To avoid this, one should compute the correlation of two quantities over many historical time periods and examine the distribution of the correlation coefficient.
As an example, remember that the correlation of AAPL and LRCX from 2013-1-1 to 2015-1-1 was 0.95. Let's take the rolling 60-day correlation between the two to see how that varies.
rolling_correlation = pd.rolling_corr(a1, a2, 60) plt.plot(rolling_correlation) plt.xlabel('Day') plt.ylabel('60-day Rolling Correlation') plt.show()
if __name__ == '__main__':
We see the correlation is not only unstable, but also reverses sign!
Another shortcoming is that two variables may be associated in different, predictable but non-linear ways which this analysis would not pick up. For example, a variable may be related to the rate of change of another which will not be detected by correlation alone.
Just remember to be careful not to interpret results where there are none.
Confidence Intervals
We mentioned in the notebook on Expected Value and Standard Deviation that statistics derived from a sample (data available to us) may differ from the true value (population statistic). For example, we want to measure the population mean, but we can only calculate a sample mean. We then want to use the sample mean to estimate the population mean. We use confidence intervals in an attempt to determine how accurately our sample mean estimates the population mean.
A confidence interval gives an estimated range of values between which the variable is likely to lie. This range is calculated from a given set of data or from a probability distribution The selection of a confidence level for the interval determines the probability that the confidence interval will contain the value of the variable over many computations (read subtlety note below). So, a 95% confidence interval for a variable states that the interval will contain the true population mean 95% of the time.
For example, if you want to estimate the average height of students in a university, you might do this by measuring 100 students and estimating that the mean of that sample was close to the population. Let's try that.
np.random.seed(100) # Let's define some 'true' population parameters, we'll pretend we don't know these. POPULATION_MU = 64 POPULATION_SIGMA = 5 # Generate our sample by drawing from the population distribution sample_size = 100 heights = np.random.normal(POPULATION_MU, POPULATION_SIGMA, sample_size) mean_height = np.mean(heights) print('sample mean: %.2f'%mean_height)
sample mean: 63.48
Unfortunately simply reporting the sample mean doesn't do much for us, as we don't know how it relates to the population mean. To get a sense for how it might relate, we can look for how much variance there is in our sample. Higher variance indicates instability and uncertainty.
print('sample standard deviation: %.2f'%np.std(heights))
sample standard deviation: 4.85
This still doesn't help, to really get a sense of how our sample mean relates to the population mean we need to compute a standard error. The standard error is a measure of the variance of the sample mean.
IMPORTANT Computing a standard error involves assuming that the way you sample is unbiased and that the data are normal and independent. If these conditions are violated, your standard error will be wrong. There are ways of testing for this and correcting.
The formula for standard error is.
Where
is the sample standard deviation and
is the number of samples.
SE = np.std(heights) / np.sqrt(sample_size) print('standard error: %.2f'%SE)
standard error: 0.48
Assuming our data are normally distributed, we can use the standard error to compute our confidence interval.
To do this we set the desired confidence level (say 95%) and determine 95% of data lies within a range how many standard deviations of mean for our data's distribution.
For example, for a normal distribution, 95% of the observations lie in a range
around the mean. When the samples are large enough (generally > 30 is taken as a threshold) the Central Limit Theorem applies and normality can be safely assumed; if sample sizes are smaller, a safer approach is to use a
-distribution with appropriately specified degrees of freedom. The actual way to compute the values is by using a cumulative distribution function (CDF). If you need more background on Probability Distributions, CDFs and inverse CDFs, read about them here and here. Look here for information on the
-distribution. We can check the 95% number using one of the Python functions.
NOTE: Be careful when applying the Central Limit Theorem, however, as many datasets in finance are fundamentally non-normal and it is not safe to apply the theorem casually or without attention to subtlety.
We can visualize the 95% mass bounds here.
#Generate a normal distribution x = np.linspace(-5,5,100) y = stats.norm.pdf(x,0,1) plt.plot(x,y) # Plot the intervals plt.vlines(-1.96, 0, 1, colors='r', linestyles='dashed') plt.vlines(1.96, 0, 1, colors='r', linestyles='dashed') fill_x = np.linspace(-1.96, 1.96, 500) fill_y = stats.norm.pdf(fill_x, 0, 1) plt.fill_between(fill_x, fill_y) plt.xlabel('$\sigma$') plt.ylabel('Normal PDF') plt.show()
Now, rather than reporting our sample mean without any sense of the probability of it being correct, we can compute an interval and be much more confident that the population mean lies in that interval. To do this we take our sample mean
and report
.
This works because assuming normality, that interval will contain the population mean 95% of the time.
SUBTLETY:
Note that it is incorrect to say that "The true mean lies in a range
with 95% probability," but unfortunately this is a very common misinterpretation. Rather, the 95% refers instead to the fact that over many computations of a 95% confidence interval, the true value will be in the interval in 95% of the cases (assuming correct calibration of the confidence interval, which we will discuss later).
But in fact for a single sample and the single confidence interval computed from it, we have no way of assessing the probability that the interval contains the population mean.
In the code below, we generate 100 95% Confidence Intervals around a mean of 0. Notice how for some of them, the mean lies completely outside the interval
np.random.seed(8309) n = 100 # number of samples to take samples = [np.random.normal(loc=0, scale=1, size=100) for _ in range(n)] fig, ax = plt.subplots(figsize=(10, 7)) for i in np.arange(1, n, 1): sample_mean = np.mean(samples[i]) # calculate sample mean se = stats.sem(samples[i]) # calculate sample standard error sample_ci = [sample_mean - 1.96*se, sample_mean + 1.96*se] if ((sample_ci[0] <= 0) and (0 <= sample_ci[1])): plt.plot((sample_ci[0], sample_ci[1]), (i, i), color='blue', linewidth=1); plt.plot(np.mean(samples[i]), i, 'bo'); else: plt.plot((sample_ci[0], sample_ci[1]), (i, i), color='red', linewidth=1); plt.plot(np.mean(samples[i]), i, 'ro'); plt.axvline(x=0, ymin=0, ymax=1, linestyle='--', label = 'Population Mean'); plt.legend(loc='best'); plt.title('100 95% Confidence Intervals for mean of 0') plt.show()
Going back to our height's example, we can manually construct confidence intervals using t-test
# standard error SE was already calculated t_val = stats.t.ppf((1+0.95)/2, 9) # d.o.f. = 10 - 1 print('sample mean height: %.2f'%mean_height) print('t-value: %.2f'%t_val) print('standard error: %.2f'%SE) print('confidence interval: [%.2f, %.2f]'%(mean_height - t_val * SE, mean_height + t_val * SE))
sample mean height: 63.48 t-value: 2.26 standard error: 0.48 confidence interval: [62.38, 64.58]
or use a built-in function in scipy.stats for computing the interval
print('99% confidence interval: ', stats.t.interval(0.99, df = 9,loc=mean_height, scale=SE)) print('95% confidence interval: ', stats.t.interval(0.95, df = 9,loc=mean_height, scale=SE)) print('80% confidence interval: ', stats.t.interval(0.8, df = 9, loc=mean_height, scale=SE))
('99% confidence interval: ', (61.903402665047693, 65.054938796511678)) ('95% confidence interval: ', (62.382304452952646, 64.576037008606718)) ('80% confidence interval: ', (62.808572945003085, 64.149768516556279))
Note that as your confidence increases, the interval necessarily widens.
What does this mean?
Confidence intervals allow us to set our desired confidence, and then report a range that will likely contain the population mean. The higher our desired confidence, the larger the range we report. In general once can never report a single point value, because the probability that any given point is the true population mean is incredibly small. Let's see how our intervals tighten as we change the sample size.
np.random.seed(10) sample_sizes = [10, 100, 1000] for s in sample_sizes: heights = np.random.normal(POPULATION_MU, POPULATION_SIGMA, s) SE = np.std(heights) / np.sqrt(s) print stats.norm.interval(0.95, loc=mean_height, scale=SE)
(61.148817012870381, 65.80952444868899) (62.52382122002232, 64.434520241537044) (63.186062588148623, 63.772278873410748)
sample_size = 100 heights = np.random.normal(POPULATION_MU, POPULATION_SIGMA, sample_size) SE = np.std(heights) / np.sqrt(sample_size) (l, u) = stats.norm.interval(0.95, loc=np.mean(heights), scale=SE) print('%.2f,%.2f'%(l, u)) plt.hist(heights, bins=20) plt.xlabel('Height') plt.ylabel('Frequency') # Just for plotting y_height = 5 plt.plot([l, u], [y_height, y_height], '-', color='r', linewidth=4, label='Confidence Interval') plt.plot(np.mean(heights), y_height, 'o', color='r', markersize=10) plt.show()
62.29,64.08
Important: Violation of Assumptions
The computation of a standard deviation, standard error, and confidence interval all rely on certain assumptions. If these assumptions are violated then the 95% confidence interval will not necessarily contain the population parameter 95% of the time. Here is an example.
Example: Autocorrelated Data
If your data generating process is autocorrelated, then estimates of standard deviation will be wrong. This is because autocorrelated processes tend to produce more extreme values than normally distributed processes. In such a process, new values depend on previous values, so series that are already far from the mean are likely to stay far from the mean.
def generate_autocorrelated_data(theta, mu, sigma, N): # Initialize the array X = np.zeros((N, 1)) for t in range(1, N): # X_t = theta * X_{t-1} + epsilon X[t] = theta * X[t-1] + np.random.normal(mu, sigma) return X X = generate_autocorrelated_data(0.5, 0, 1, 100) plt.plot(X) plt.xlabel('t') plt.ylabel('X[t]') plt.show()
Now, we need to know the true population of this series. For larger sample sizes, the sample mean should still asymptotically converge to zero. This is because the process is still centred around zero, but let's check if that's true. We'll vary the number of samples drawn, and look for convergence as we increase the sample size.
sample_means = np.zeros(200-1) for i in range(1, 200): X = generate_autocorrelated_data(0.5, 0, 1, i * 10) sample_means[i-1] = np.mean(X) plt.bar(range(1, 200), sample_means); plt.xlabel('Sample Size') plt.ylabel('Sample Mean') plt.show()
Definitely looks like there's some convergence, we can also check what the mean of the sample means is.
np.mean(sample_means)
-0.0027245570485071994
Pretty close to zero. We could also derive symbolically that the mean is zero, but let's assume that we've convinced ourselves that the true population mean is 0. Now that we know the population mean, we can check the calibration of confidence intervals. Let's first compute an interval using our earlier process and then check whether the interval actually contains the true mean, 0.
def compute_unadjusted_interval(X): T = len(X) # Compute mu and sigma MLE mu = np.mean(X) sigma = np.std(X) SE = sigma / np.sqrt(T) # Compute the bounds return stats.norm.interval(0.95, loc=mu, scale=SE) # We'll make a function that returns true when the computed bounds contain 0 def check_unadjusted_coverage(X): l, u = compute_unadjusted_interval(X) # Check to make sure l <= 0 <= u if l <= 0 and u >= 0: return True else: return False
Now we'll run many trials, in each we'll sample some data, compute a confidence interval, and then check if the confidence interval contains the population mean. Over many runs, we should expect to see 95% of the trials succeed if the intervals are computed correctly.
T = 100 trials = 500 times_correct = 0 for i in range(trials): X = generate_autocorrelated_data(0.5, 0, 1, T) if check_unadjusted_coverage(X): times_correct += 1 print 'Empirical Coverage: ', times_correct/float(trials) print 'Expected Coverage: ', 0.95
Empirical Coverage: 0.764 Expected Coverage: 0.95
Clearly the coverage is wrong. In this case, we'd need to do what's known as a Newey-West correction on our standard error estimate to account for the autocorrelation.
In practice, it's important to check for the assumptions you make. It is quick and easy to check if your data are stationary (which implies not autocorrelated), and it can save you a lot of pain and suffering to do so. A normality test such as
Jarque Bera will also be a good idea, as it may detect certain distribution properties which may violate assumptions of many following statistical analyses.
This work derives from the works of Michael Halls-Moore on Quantstart and Quantopian Lecture Series. | https://blog.quant-quest.com/community/time-series/covariance-and-correlation/ | CC-MAIN-2021-49 | refinedweb | 2,907 | 50.43 |
Firefox 3.1 Alpha 2 Offers Cutting-Edge Web Standards Support
Mozilla has released a second Firefox 3.1 alpha preview, incorporating some new under-the-hood improvements like HTML 5
video tag support, more CSS 3 properties and improved performance.
Firefox 3.1 alpha 2 is still rough around the edges though and is intended for developers, not everyday users. Alpha 2 also lacks some of the standout features scheduled to land in the final release of Firefox 3.1, like the TraceMonkey JavaScript engine.
Among the features that did make the alpha 2 cut, perhaps the most important are the increased CSS 3 and HTML 5 support. The support for HTML 5’s new video tag offers web publishers an easier and better way to embed video in their page, though with Internet Explorer potentially years away from including similar support, you might not want to convert your site just yet.
Firefox 3.1 also adds some more CSS 3 properties like
border-wrap,
text-shadow,
box-shadow and several more. With the CSS3 spec still not set in stone, Mozilla has packaged the properties within the
-moz-property namespace.
So far there’s no specific date for the first beta of Firefox 3.1, but Mozilla’s roadmap calls for beta 1 to arrive in late September or early October 2008. In the mean time you can download and test alpha 2, though for everyday use we recommend sticking with Firefox 3.
See Also: | http://www.webmonkey.com/blog/Firefox_3DOT1_Alpha_2_Offers_Cutting-Edge_Web_Standards_Support | crawl-002 | refinedweb | 247 | 60.35 |
Opened 22 months ago
Last modified 4 days ago
#1527 assigned enhancement
win32 system shadow service
Description
Split from #389, similar to #1105 for Linux, we want to have a system wide service running even before the user logs in.
Users can then trigger a login.
Some links already added in ticket:389#comment:23.
Attachments (5)
Change History (16)
comment:1 Changed 22 months ago by
comment:2 Changed 22 months ago by
With the cx_freeze 5 workarounds added in ticket:1528#comment:2 and the service stub added in r15933 +
r15934 (based on cx_Freeze samples: service), a "Xpra-Service.exe" is created - it just doesn't do anything when you run it...
The documentation is non-existent, and the executable doesn't give you any help at all. But I eventually found that we're supposed to install it by running:
Xpra-Service.exe --install NAME [configfile]
Problem is that this fails with:
Service not installed. See log file for details.
What log file you ask? Well "./.log" obviously, NOT. This file contains:
[04380] 2017/05/23 22:46:14.473 starting logging at level ERROR [04380] 2017/05/23 22:46:14.520 Win32 error 0x5 encountered. [04380] 2017/05/23 22:46:14.520 Context: cannot open service manager [04380] 2017/05/23 22:46:14.520 Message: Access is denied. [04380] 2017/05/23 22:46:14.520 ending logging
Fine, let's run it as administrator:
[02964] 2017/05/23 22:49:55.695 starting logging at level ERROR [02964] 2017/05/23 22:49:55.757 Win32 error 0x57 encountered. [02964] 2017/05/23 22:49:55.757 Context: cannot start service [02964] 2017/05/23 22:49:55.757 Message: The parameter is incorrect. [02964] 2017/05/23 22:49:55.773 ending logging
At least the service is registered and visible in the "Services" control tool, and the same error message is available in the "eventvwr".
We'll need to get rid of "cx_Logging", it's unmaintained since 2014, undocumented (which filename is used from the service?) and generally not helpful.
comment:3 Changed 22 months ago by
OK, the reason why this fails with the cryptic error 0x57 is because the path to the service binary is empty (for whatever reason).
Assuming that the service has been installed using:
Xpra-Service.exe --install XPRA-TEST
The path can then be changed using regedit, or using Sc config.
First query the service:
sc qc XpraXPRA-TEST
Change the path:
sc config XpraXPRA-TEST binPath= "C:\Program Files\Xpra\Xpra-Service.exe"
We can now also set it to auto-start:
sc config XpraXPRA-TEST start= auto
With these changes, starting the service takes longer to fail.. but fail it does with: Error 1053: The service did not respond to the start or control request in a timely fashion
We can find the service PID with:
sc queryex XpraXPRA-TEST
Then kill it with:
taskkill /f /pid $PID
We could workaround the broken path installation by running the "sc config" commands after the service registration, still as part of the EXE / MSI
installation process.
But the fact that the process does not respond is more problematic...
Ideas:
- maybe the paths workarounds need to be applied to the service class (in C)
- maybe use a simple shim? a simple C service that (re)starts the real xpra proxy server?
The shim would allow us to continue to use cx_freeze 4.x (no need for #1528). Some links for that:
- MSDN: Service Programs
- The Complete Service Sample
- The Windows Services Win32 Programming
- extra difficulty with mingw? service and mingw
comment:4 Changed 22 months ago by
Difficulties in building the Complete Service Example with mingw:
- What is the difference between _tmain() and main() in C++? - just change it to "main", was missing int return value
- GetModuleFileName function signature was used wrong, pass NULL
- StringCbPrintf function: just replace
StringCchPrintfwith
snprintf, or better: add
#undef __CRT__NO_INLINEbefore
#include <strsafe.h>(maybe we should link against some lib instead?)
- to avoid string warnings, build with:
g++ -o Svc.exe Svc.cpp -Wno-write-strings
__tryand
__except: msdn: try-except Statement, workaround is to not handle this at all...
#define __try #define __finally
- after compiling, the binaries need these libs to run:
libgcc_s_dw2-1.dlland
libwinpthread-1.dll
Changed 22 months ago by
patch for building the service example with mingw
comment:5 Changed 22 months ago by
Stub cx_freeze5 service removed in r15960 (#1528 re-scheduled), replaced in r15962 by a shim implemented in C.
Still TODO:
- fix authentication problems
- remove hard-coded command line path: load settings from a config file?
- innosetup script changes: upgrading windows service using inno setup - maybe just ship the "SvcConfig" and "SvcControl" command line tools instead?
- start new sessions / locate existing ones and run the shadow under that user account
- fix event logging: we have to use event codes in the resource file (yuk)
- re-enable SSL: substitute
commonappdatato locate the cert - or just generated the path in the config file
Notes:
- the log files for the proxy process when running from the "local system account" end up here: Where can I find data stored by a Windows Service running as “Local System Account”?, ie:
C:\Windows\System32\config\systemprofile\AppData\Roaming\Xpra
- msdn: Interactive Services
- How can a Windows service execute a GUI application?
- Named Pipe Security and Access Rights
- Launching an interactive process from Windows Service in Windows Vista and later
- is there a good example of using pywin32 createprocessasuser and getting the output? covers CreateProcessWithTokenW in this answer
Changed 22 months ago by
Changed 22 months ago by
work in progress logon patch
comment:6 Changed 22 months ago by
The ugly and incomplete patch above does:
- GetCurrentProcess
- OpenProcessToken
- GetTokenInformation
- LookupPrivilegeValueW
- AdjustTokenPrivileges
- LsaRegisterLogonProcess
And adds a small
Login-Test.exe utility. Problem is that this works when running from the service context, but not when running directly from the utility - even when running from an administrator shell. This is going to make development and testing tedious.
Some useful links:
Changed 22 months ago by
logon succeeds but launching the new process does not..
comment:7 Changed 22 months ago by
With the patch above, I could logon but when trying to start the server, or even a test application like
whoami.exe with all of its dlls installed, the event log would show:
Application popup: Xpra_cmd.exe - Application Error : \ The application was unable to start correctly (0xc0000142). Click OK to close the application.
The environment looked suspicious, but since we use the
LOGON_WITH_PROFILE flag, it should be OK. (will need to re-check that)
See What is up with "The application failed to initialize properly (0xc0000142)" error?, which has lots of relevant information. (and some dead links too.. sigh)
Also some pointers here: The Perils and Pitfalls of Launching a Process Under New Credentials.
It was just missing the desktop name in the
STARTUPINFO.... (not obvious)
Now maybe we also need permission to access that desktop? As per CreateProcessAsUser() windowstations and desktops, because the resulting screen is empty.
comment:8 Changed 22 months ago by
r15980 adds all the hooks for starting the shadow process from the service.
Still TODO:
- remove hard-coded command line path: load settings from a config file?
- innosetup integration
- add firewall rules: How to use the "netsh advfirewall firewall", ie:
C:\Windows\system32>netsh advfirewall firewall add rule name="Open Port 14500" d ir=in action=allow protocol=TCP localport=14500
- re-enable SSL: substitute commonappdata to locate the cert - or just generated the path in the config file
- innosetup script changes: upgrading windows service using inno setup - maybe just ship the "SvcConfig" and "SvcControl" command line tools instead?
- don't use a fixed TCP port, use named pipes via the system proxy - or enhance the client to support a redirect and use OTP (which we can supply to the shadow process using env auth)
- html5 client connection fails, re-tries: we end up creating new shadow server instances... don't retry on fatal error (html5), don't create a new shadow if one exists!
- fix event logging: we have to use event codes in the resource file (yuk)
- the desktop we get is empty! why?
- start new sessions / locate existing ones and run the shadow under that user account
- integrate with "remote desktop services" #1532
Changed 22 months ago by
this implementation does not work - but has some useful functions
comment:9 Changed 11 months ago by
See ticket:389#comment:23 for
LogonUser links.
comment:10 Changed 8 months ago by
See Another Windows 10 SKU is on its way, this time for remote desktops: With the new SKU, the multi-session capability is now a part of desktop Windows
Blocked by #1528. | https://www.xpra.org/trac/ticket/1527 | CC-MAIN-2019-13 | refinedweb | 1,461 | 62.27 |
Introduction to Open Source Swift on Linux
Note: This tutorial has been updated to work with the latest versions of Ubuntu 14.04 and the Swift 3.0 development snapshots as of April 20, 2016. As a result, some dates and version numbers in this tutorial have been updated from the time of the initial relase of Swift on Linux.
Less than a week ago, the Swift world woke up to an early Christmas present — open source Swift — that you can run on Linux!
And there was even a present inside the present: Apple announced new projects and tools intended to make Swift an incredibly practical choice for Linux development. This creates exciting possibilities, such as running Swift on platforms from Linux servers right down to five-dollar Raspberry Pi Zeros, or in the kajillions of other environments that host.
This tutorial does not require any previous knowledge of Linux and you don’t even need Linux installed yet – but if you also have Ubuntu running, all the better! All you need is a Mac running at least OS X El Capitan and an interest in open source Swift. Let’s get started!
Installing Swift on Linux
If you’re already running Ubuntu 14.04 LTS or Ubuntu 15.10, either directly or in a VM on Mac or Windows, you can simply follow the instructions on swift.org to download and install Swift for Linux and skip to the next section.
If you’re not running one of the above versions of Ubuntu, follow the instructions below to install Virtualbox and Ubuntu on your Mac. This will use less than 1 GB of disk space and confine Linux to a virtual machine — without affecting your current OS X installation.
Installing VirtualBox
VirtualBox is a free, open-source application that lets you run other operating systems as virtual machines in parallel with OS X.
Go to the VirtualBox downloads page, and download the disk image for VirtualBox 5.0.16 or later. Double-click the downloaded DMG and run the VirtualBox.pkg package installer:
Installing and Using Vagrant
Vagrant is a command-line interface to VirtualBox; it can download virtual machine images for you, run provisioning scripts, and coordinate the interaction between OS X and the machine by setting up things like networking and shared folders.
Go to the Vagrant downloads page and download Vagrant for Mac OS X. Double-click the downloaded DMG disk image and run the Vagrant.pkg package installer:
Now you’ll need a Vagrantfile to tell Vagrant exactly which version of Linux you want to use and how to install Swift on that version of Linux.
Create an empty directory in your Documents folder (or wherever makes sense for your workflow) and name it vagrant-swift. Inside that directory, create a file named Vagrantfile and add to it the lines below:
Vagrant.configure(2) do |config| ## 1 config.vm.> .profile echo "Swift has successfully installed on Linux" SHELL end
Now to run your Vagrantfile. Open Terminal on your Mac (found in the /Applications/Utilities folder), change to the vagrant-swift directory that contains the Vagrant file above, then enter the following command to run your script:
vagrant up
Sit back and wait while Vagrant performs the following steps based on your Vagrantfile:
- Downloads a disk image of Ubuntu LTS 14.04 (the latest version as published by Canonical, the Ubuntu company, whenever you are running the script). It will only perform this download once and then cache the image for later use. You will likely see an “Attempting to find and install…” message for the Box file, followed by a message about “Adding it directly…”.
- Runs the downloaded disk image in virtualization.
- Installs Apple’s C compiler
clangand the internationalization library
libicu, both components which the Swift compiler requires.
- Downloads Swift (as distributed by swift.org on April 12th, 2016) and uncompresses it.
- Adjust some file permissions needed to use the Swift Package Manager.
- Configures the default user’s home
PATHvariable, so it can run the swift binary, REPL, and other tools.
If this completes successfully, the final message will say that “Swift has successfully installed on Linux”.
Next, you’ll need to connect to your Linux virtual machine. In the same vagrant-swift directory, execute the following command:
vagrant ssh
You should now find yourself at an Ubuntu prompt as a user called “vagrant”. To verify that you can access Swift and it’s functioning properly, execute the following command:
swift --version
You should see something like the following:
Swift version 3.0-dev (LLVM 752e1430fc, Clang 3987718dae, Swift 36739f7b57) Target: x86_64-unknown-linux-gnu
Tada! Swift on Linux. It’s a Christmas miracle! :]
Compiling a Program
You’ve installed Swift on Linux. Now it’s time to compile and run something.
Of course, hallowed coding tradition dictates that your first program do nothing but say “Hello, world”. And in true developer form, you’ll do it the easiest way possible. :]
Switch to the Linux shell prompt and execute the following command:
cat > helloworld.swift
Now enter the following single line of Swift code:
print("Hello, world")
Press Enter once followed by Ctrl-D to create the file:
Execute
ls in the shell to show the directory listing and confirm that you have created a file named helloworld.swift.
Now execute the following command at the shell prompt to invoke the swift compiler and compile your program:
swiftc helloworld.swift
sudo apt-get install clang-3.6 sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-3.6 100 sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.6 100
Thanks to @phildev for pointing this out!
Execute
ls -l h* at the shell prompt to see detailed information on all files beginning with h:
-rwxrwxr-x 1 vagrant vagrant 13684 Dec 4 17:55 helloworld -rw-rw-r-- 1 vagrant vagrant 22 Dec 4 17:55 helloworld.swift
helloworld has x’s in the first column as it’s an executable file. Execute the following command to run helloworld:
./helloworld
You’ll see the following output:
Hello, world
Lightning and thunderbolts! You’ve run Swift on Linux. So easy! :]
But what does this all mean? What can you really do with Swift on Linux? To answer these questions, put the brakes on this runaway freight train of cross-platform, bleeding-edge and technological euphoria, and take a moment to review what it is that Apple has actually released.
What Apple Has Released
Apple has released five categories of software to date:
1) The Swift compiler (source code and executable binaries), debugger, and interactive prompt (i.e., REPL).
This is the heart of the Swift language itself. Apple has released the source code for the the Swift compiler, the same
swiftc program that Xcode uses to compile Swift for iOS and Mac apps.
2) The Swift standard library
This is (almost) exactly the same standard library that’s been used since Swift’s release. It defines strings, collection types, protocols, and other fundamental constructs. Have you been yearning to see how the standard library implements a basic type, like
Double or
Array? Now you can.
But of course, the Swift standard library alone doesn’t get you very far. How many Swift applications have you written where you don’t
import UIKit? Probably not very many. The functionality of Foundation, at a minimum, is indispensable for writing useful software (instead of, you know, “Hello, world”, or the five-millionth example of the factorial function). All of this makes it very promising that Apple has also released …
3) Swift Core Libraries
These are brand new, cross-platform, Objective-C-free re-implementations of existing Apple libraries. They provide higher-level functionality such as networking, file system interaction, date and time calculation. A caveat: they’re not quite finished. But that’s not all. Apple has also released …
4) Swift Package Manager
The Swift package manager is a bit like Carthage; it can download dependencies, compile them, and link them together to create libraries and executables. As of April 2016, it is only distributed with the development builds of Swift rather than the more mature release builds. This is why we have downloaded the development build, which contains Swift 3.
5) Other Components
If you browse Apple’s Github page, you can find other components as well: a Swift wrapper for libdispatch (aka, Grand Central Dispatch), notes on the future plans for Swift 3.0, even a parser/renderer for the Markdown dialect CommonMark.
What Apple Hasn’t Released
That’s quite a pile of functionality — but what hasn’t Apple released?
Well, there’s no Xcode, no AppKit and no UIKit. There’s no Core Graphics, no Core Animation, no AVFoundation, nor many of the other familiar core Objective-C libraries. Basically, most of what you need to create beautiful iOS or Mac apps isn’t here yet.
But what Apple has released is quite significant. Consider the Core Libraries project. Why did Apple take the trouble of re-implementing its own mature, battle-tested Foundation libraries?
The fact that the Core Libraries project doesn’t rely on the Objective-C runtime suggests that Apple is creating the underpinnings for Swift to replace Objective-C completely in the long run. And the fact that it’s cross-platform by design suggests Apple is seriously hoping people will use the language for Linux software development — at least for server software, if not for GUI apps.
But the package manager is most significant of all. Before diving into the reasons why, take a quick kick at the tires and see what it does.
Using the Swift Package Manager
The package manager defines a simple, common-sense directory structure for any Swift code that you would like to build into an executable or library. You’ll look at that format using your VirtualBox install of Ubuntu and Vagrant.
First, execute the following command at the shell prompt to create a directory helloworld-project and dive into it:
mkdir helloworld-project && cd helloworld-project
Now execute the following to to create an empty file named
Package.swift:
touch Package.swift
The presence of this file indicates that the current directory defines a Swift package.
Now create a directory for source code files with the following command:
mkdir Sources
Next, execute the following to copy your old program,
helloworld.swift, into
Sources/ with the new name
main.swift:
cp ../helloworld.swift Sources/main.swift
The directory structure of
helloworld-project now defines the most basic package possible, and should look as follows:
. ├── Package.swift └── Sources/ └── main.swift
Execute the following command to build the package:
swift build
You should see the following:
vagrant@vagrant-ubuntu-trusty-64:~/helloworld-project$ swift build Compiling Swift Module 'helloworldproject' (1 sources) Linking .build/debug/helloworld-project
This creates a new, hidden folder for build products —
.build. Your directory structure should now look like the following:
. ├── .build/ │ └── debug/ │ ├── helloworld-project* │ ├── helloworld-project.o/ │ │ ├── build.db │ │ ├── helloworld-project/ │ │ │ ├── main.d │ │ │ ├── main~partial.swiftdoc │ │ │ ├── main~partial.swiftmodule │ │ │ ├── main.swiftdeps │ │ │ ├── master.swiftdeps │ │ │ └── output-file-map.json │ │ ├── home/ │ │ │ └── vagrant/ │ │ │ └── helloworld-project/ │ │ │ └── .build/ │ │ │ └── debug/ │ │ ├── llbuild.yaml │ │ └── Sources/ │ │ └── main.swift.o │ ├── helloworldproject.swiftdoc │ └── helloworldproject.swiftmodule ├── Package.swift └── Sources/ └── main.swift
You can verify this hidden folder structure by executing
ls -aR.
The most important file here is .build/debug/helloworld-project, which is marked with an asterisk above to indicate that it’s executable. This is your executable, which you can run now just by entering it’s name on the command line, like so:
vagrant@vagrant-ubuntu-trusty-64:~/helloworld-project$ .build/debug/helloworld-project Hello, world
Cool. But what’s all that other gunk in the directories used for?
All of those intermediate build products are indications of the true scope of the package manager’s functionality. Remember — it’s more than just a compiler. In its capacity as a build tool (like
make), the package manager is responsible for compiling multiple files required for a single package and linking them together.
In its capacity as a package manager (like Carthage or CocoaPods), it also has the responsibility of linking together multiple packages and fetching dependent packages on the Internet. This implies the package needs some concept of versioning and compatibility (e.g, “Which dependency can meet my needs?”), and of location (e.g., “Where do I get it?”).
For a less-trivial example, take a look at Apple’s own sample project; it’s an app that simulates the dealing of a deck of cards.
Install Git, change to a new directory, and get the top-level package with the following shell commands:
cd ~ sudo apt-get --assume-yes install git git clone cd example-package-dealer
Crack open the Apple project and have a look; you’ll see it includes almost nothing:
. ├── CONTRIBUTING.md ├── main.swift ├── Package.swift └── README.md
However, Package.swift is not empty this time; it includes a small snippet of Swift that declares this package depends on version 1 of another package,
example-package-deckofplayingcards, which in turn lives at a URL on github, and that package in turn depends on others, and so on.
The net result is that if you call
swift build for the example project, you’ll get more than 400 files, as the build tool downloads those other package repositories, compiles them, and links them together.
Apple provides more details on the package manager on the new Swift.org website. Below is a quick list of notable points about the new package manager:
- Uses a simple directory structure for package layout and a simple Swift-based manifest file, as opposed to Xcode, which allows any directory structure, but requires a proprietary Xcode project file to track the freeform chaos this implies.
- Uses semantic versioning, the defacto standard for declaring package versioning and compatibility information
- Is tightly integrated with Swift’s notion of a module, which Apple uses for Objective-C and has promoted as a standard for C.
- Overlaps with some of xcodebuild’s functionality.
- Performs transitive dependency analysis, but doesn’t yet handle dependency conflicts.
- Builds executable and static libraries, but doesn’t yet handle dynamic libraries.
- Uses git, but has no support for other version control system yet.
- Includes a very thoughtful community proposal document, which describing the thinking behind its design.
If you’ve used CocoaPods, Carthage, or other package managers, this will all seem quite familiar. And indeed, technically, it is nothing new. But it is new to Apple, and this is notable. So let us gaze into the mists of time and ask …
What Does All This Mean?
Why does a package manager matter so much? It’s because a package manager is more than just a tool. Package managers tend to be inextricably tied to the technical community surrounding a software ecosystem, since they define how people interact with each other in the fundamental business of helping each other to make software.
Would the Ruby or Node communities be the same without the
gem and
npm package managers? No. And it’s no exaggeration to say that CocoaPods has brought iOS developers closer together by making it easier to share work and help each other.
Apple has a bit of a reputation for communicating to developers; it’s not known for supporting channels for feedback from developers or encouraging developer interaction. A good example of this is the Radar bug tracking system, which functions like an interplanetary black hole, silently gobbling up information, and leaving behind no trace visible from the external universe.
But a package manager is inevitably a piece of community infrastructure; it’s something other developers will use to interact with each other, not with Apple. So it’s a bit of a departure for Apple to take the lead in promoting such a tool.
It’s also a good sign that the tool looks and feels like a normal package manager that uses semantic versioning, Git, and other conventional tools and patterns which originated outside of Apple. Apple’s even replaced Radar with a new bug tracking system for Swift based on JIRA, which allows developers to actually view known bugs. And there’s also a long document that solicits contributions from the open source community and establishes a process and a community code of conduct.
It really feels like the Swift team has rolled out the welcome mat! I imagine it as an eerily opalescent welcome mat, with hairline grey trim, which magically hovers exactly one centimer above the ground so it never gets dirty. Others may see it differently. :]
The package manager feels like a sign of the broader spirit behind this open source release. With this open source release, Apple hasn’t just thrown a bunch of code “over the wall”. Apple’s taken the first steps toward supporting production uses of Swift on Linux. And more than that, they’ve made big steps toward encouraging and welcoming others to help with this effort.
Exiting the Virtual Machine
When you’re done with your virtual machine, just use
logout to exit the shell, and call
vagrant suspend to freeze it for later use, or
vagrant destroy to blow it away completely and free up the disk space.
Where to Go From Here?
In this tutorial, you’ve installed Linux, installed Swift on Linux, compiled code using Swift on Linux, and taken a quick look at Apple’s package management tool. The fact that you can now run Swift on Linux is incredibly interesting, but the fact that Apple seems to be actually encouraging it, and providing technical and community support for it, is awesome! :]
You’ve only had a really quick look at Swift on Linux, but a lot of the new tooling such as the package manager has consequences for Swift on OS X as well; it’s now easier to share code and to build command line tools. It’s hard to imagine this doesn’t at least hint of new directions in Xcode. The new repositories, the exposure of the roadmap and discussion process for future Swift development are promising — and surprising — developments.
There are interesting days to come!
What are your thoughts on this new paradigm for Swift development? Share your thoughts with us below! | https://www.raywenderlich.com/122189/introduction-to-open-source-swift-on-linux | CC-MAIN-2017-43 | refinedweb | 3,049 | 54.83 |
Testing Jobs
Hazelcast project uses JUnit testing framework to test itself in various scenarios. Over the years there has been some repetition within the test implementations and it led us to come up with our own set of convenience methods for testing.
Hazelcast provides test support classes to verify correctness of
your pipelines. Those support classes and the test sources are published
to the Maven central repository for each version with the
tests
classifier.
To start using them, please add following dependencies to your project:
compile 'com.hazelcast:hazelcast:5.0.3:tests'
<dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast</artifactId> <version>5.0.3</version> <classifier>tests</classifier> </dependency>
After adding the dependencies to your project, the test classes should be available to your project.
Creating Hazelcast members with Mock Network
Test utilities contains factory methods to create Hazelcast instances with the mock network stack. Those Hazelcast members communicate with each other using intra-process communication methods. This means we can create multiple lightweight Hazelcast members in our tests without using any networking resources.
To create Hazelcast members with mock network(along with a lot
of convenience methods), you need to extend
com.hazelcast.jet.core.JetTestSupport
class.
Here is a simple test harness which creates 2 node Hazelcast cluster with mock network:
public class ClusteringTest extends JetTestSupport { @Test public void given_2nodeCluster_when...._then...() { // given HazelcastInstance instance1 = createHazelcastInstance(); HazelcastInstance instance2 = createHazelcastInstance(); // Alternatively // HazelcastInstance[] instances = createHazelcastInstances(2); // when ... ... // then ... ... } ... }
If needed, a
Config object can be passed to the factory methods
like below:
public class ClusteringTest extends JetTestSupport { @Test public void given_2nodeClusterWith16CooperativeThreads_when...._then...() { // given Config config = new Config(); config.getJetConfig().setCooperativeThreadCount(16); HazelcastInstance[] instances = createHazelcastInstances(config, 2); // when ... ... // then ... ... } ... }
Similar to the Hazelcast members, you can create Hazelcast HazelcastInstance[] instances = createHazelcastInstances(2); HazelcastInstance client = createHazelcastClient(); // when ... ... // then ... ... } ... }
When the above test run it should create 2 Hazelcast members and a Hazelcast] Members }
First two blocks are the member list printed from each member’s point of view and the last one is the cluster from the client’s point of view.
So far, we’ve seen how to create any number of Hazelcast clusters
and clients using factory methods provided within the
com.hazelcast.jet.core.JetTestSupport
class to create the test environments. Let’s explore other utilities to
write meaningful test.
Integration Tests
For integration testing, there might be a need to create real instances
without the mock network. For those cases you can create real instances
with
Hazelcast.newHazelcastInstance() method.
Using Random Cluster Names
If multiple tests are running in parallel there is a chance that the clusters in each test can discover others, interfere the test execution and most of the time causing both of them to fail.
To avoid such scenarios, you need(); Config config = new Config(); config.setClusterName(clusterName); HazelcastInstance[] instances = createHazelcastInstances(config, 2); ClientConfig clientConfig = new ClientConfig(); clientConfig.setClusterName(clusterName); HazelcastInstance client = createHazelcastClient(clientConfig); // when ... ... // then ... ... } ... }
In the example above
randomName() utility method has been used to
generate a random string from
com.hazelcast.jet.core.JetTestSupport
class.
Cleaning you can write a teardown method like below to shut down all instances created.
@After public void after() { Hazelcast.shutdownAll(); }
Either way you have to shut down Hazelcast members after the test has been finished to reclaim resources and not to leave a room for interference with the next test execution due to distributed nature of the product.
Test Sources and Sinks
Hazelcast comes with batch and streaming test sources along with a assertion sinks where you can write tests to assert the output of a pipeline without having to write boilerplate code.
Test sources allow you to generate events for your pipeline.
Batch Source
These sources create a fixed amount of data. These sources are non-distributed.
Pipeline p = Pipeline.create(); p.readFrom(TestSources.items(1, 2, 3, 4)) .writeTo(Sinks.logger());
This will yield an output like below:
12:33:01.780 [ INFO] [c.h.j.i.c.W.loggerSink#0] 1 12:33:01.780 [ INFO] [c.h.j.i.c.W.loggerSink#0] 2 12:33:01.780 [ INFO] [c.h.j.i.c.W.loggerSink#0] 3 12:33:01.780 [ INFO] [c.h.j.i.c.W.loggerSink#0] 4
Streaming:
12:33:36.774 [ INFO] [c.h.j.i.c.W.loggerSink#0] SimpleEvent(timestamp=12:33:36.700, sequence=0) 12:33:36.877 [ INFO] [c.h.j.i.c.W.loggerSink#0] SimpleEvent(timestamp=12:33:36.800, sequence=1) 12:33:36.976 [ INFO] [c.h.j.i.c.W.loggerSink#0] SimpleEvent(timestamp=12:33:36.900, sequence=2) 12:33:37.074 [ INFO] [c.h.j.i.c.W.loggerSink#0] SimpleEvent(timestamp=12:33:37.000, sequence=3) 12:33:37.175 [ INFO] [c.h.j.i.c.W.loggerSink#0] SimpleEvent(timestamp=12:33:37.100, sequence=4) 12:33:37.274 [ INFO] [c.h.j.i.c.W.loggerSink#0] SimpleEvent(timestamp=12:33:37.200, sequence=5)
Assertions
Hazelcast contains several sinks to support asserting directly in
the pipeline. Furthermore, there’s additional convenience to have the
assertions done inline with the sink without having to terminate the
pipeline, using the
apply() operator.
Batch Assertions
Batch assertions collect all incoming items, and perform assertions on the collected list after all the items are received. If the assertion passes, then no exception is thrown. If the assertion fails, then the job will fail with an AssertionError.
Ordered Jet, or cluster is in a desired state.
Classcast Runner
com.hazelcast.test.HazelcastSerialClassRunner is a JUnit test class
runner which runs the tests in series. Nothing fancy, it just executes
the tests with the features listed above.
Parallel
While dealing with intermittently failing tests, it is helpful to run
the test multiple times in series to increase chances to make it
fail. In those cases
com.hazelcast.test.annotation.Repeat annotation
can be used to run the test repeatedly.
@Repeat annotation can be
used on both the class and method level. On the class level it repeats the
whole class execution specified items. On the method level it only
repeats particular test method.
Following a Job to be in a Desired State
On some use cases, you need HazelcastInstance hz = createHazelcastInstance(); // when Pipeline p = buildPipeline(); Job job = hz.getJet(). | https://docs.hazelcast.com/hazelcast/5.0/test/testing | CC-MAIN-2022-40 | refinedweb | 1,046 | 51.44 |
Jane Medium : Designed and made based on MM32F3277 Of MicroPython Test circuit , Downloaded from SeekFree Known MicroPython, Prove that it can complete normal use .
key word: MM32F3277,MicroPython, Fast plate making
I passed the following test the day before yesterday , For those from flying by MicroPython The test board was preliminarily tested :
Use in Make smart MCU MM32F3277 The beta The smallest plate made , as well as utilize Python Simulate the mouse to complete automatically MM32-LINK Program download The automatic download process given , Design and make one that can be completed directly MM32F3277 MicroPython Minimum test circuit board .
stay SeekFree / Flying technology MM32F3277 Open source library Download to fly by fly MM32F3277 Core board circuit design diagram .
▲ chart 1.2.1 Fly by fly MM32F3277 Development board, motherboard packaging and component library
According to the flight by flight OneOS From the debugging interface design of the evaluation board , Its corresponding PIN5-2 The definition of debugging interface is the same as that defined on the minimum mainboard screen の Debugging interfaces are the same .
▲ chart 1.2.2 OneOS Debugging interface in the core board
▲ chart 1.2.3 Fly by fly MM32F3277 Minimum motherboard debugging interface
Therefore, we can know the of flight by flight transplantation MicroPython What is used REPL yes MM32F3277 Of UART1(A9-TX, A10-RX).
According to the information provided by flight by flight MicroPython Descriptive information ,MicroPython UART Corresponding MM32F3277 Of UART3(B10-TX,B11-RX).
▲ chart 1.2.4 MicroPython UART Corresponding MM32F3277 Of UART3
▲ chart 2.1.1 Schematic diagram of test circuit board
The following is to use A minute One side of quick plate making receipt PCB Territory .
▲ chart 2.1.2 Fast plate making single-sided circuit board design
▲ chart 2.1.3 The test circuit board obtained after one minute
take Make smart MCU MM32F3277 The beta The single chip microcomputer is disassembled and welded down , Weld on the fabricated single-sided circuit board . Form test circuit board .
▲ chart 2.1.4 Test circuit board after welding
exert +5V voltage , At (AS1117-3.3)PIN2 measurement 3.29V. The operating current is approximately 6mA .
Install the rear 【3.3.1: download MicroPython】 after , Measure the crystal oscillation signal of the circuit board . It is found that the crystal clock has no oscillation signal . This explanation MicroPython When running, the internal oscillator is used .
▲ chart 2.1.5 After the crystal is soldered off, the chip can still work normally
utilize MM32-LINK Read Debugging comes from flying by flying MM32F3277 Transplantation has MicroPython Development board The program on the motherboard .
▲ chart 3.1.1 Use 5PIN Read SeekFree The program in the smallest core board
▲ chart 3.1.2 Read MicroPython Program
Store the read program in :SeeFreeMP.HEX.
Put the above HEX Download the file to OneOS In the experimental board .
▲ chart 3.2.1 take SeekFree MicroPython Download to OneOS In the development board
Select serial port as CH340, When you come out on the side, you can CH340 Conduct MicroPython REPL function .
▲ chart 3.2.2 Select serial port as CH340
Use in Test the flight by flight MM32F3277 MicroPython The basic functions of the development board The establishment of a be based on STM32BOOT-Loader Development tool chain , Write test applet , Download and execute .
utilize OneOS The buzzer on the beta ( be located B5), test MicroPython For its operation .
▲ chart 3.2.3 OneOS The buzzer on the
from seekfree import GPIO beep = GPIO(0x15, 1, 1) def delay(loop = 50000): for _ in range(loop): pass count = 0 for i in range(10): beep.high() delay() beep.low() delay() print(i)
Reset MicroPython... Wait for MicroPython comeback... Download MicroPython : 32 lines/665 characters. Begin to download programm... ------------------------------------------------------------------------- 0 1 2 3 4 5 6 7 8 9 >>>
You can see that after the above test , Download the corresponding program to OneOS On board , It can be executed correctly .
▲ chart 3.4.1 download MicroPython Program
utilize utilize CH340C Make MicroPython ESP8266,ESP32 The downloader - Improved Connect UART1 Corresponding REPL, test MicroPython REPL.
from seekfree import GPIO beep = GPIO(0x12, 1, 1) def delay(loop = 50000): for _ in range(loop): pass count = 0 for i in range(1000): beep.high() delay(20000) beep.low() delay(20000) print(i)
▲ chart 3.4.2 Running test results
set up Based on MM32F3277 Of MicroPython Test circuit , Downloaded from SeekFree Known MicroPython, Prove that it can complete normal use .
■ Links to related literature :
● Related chart Links :
MM32 MicroPython Small board development project Wendan :AD\MM32\TestMM32\TestMicroPythonMM32F3277.SchDoc ︎ | https://pythonmana.com/2021/11/20211125111028263r.html | CC-MAIN-2022-21 | refinedweb | 763 | 53.61 |
is OpenTK compatible with PowerVR sdk?Posted Friday, 18 December, 2009 - 03:46 by aik6980 in
Hi,
My target platform is using PowerVR SGX, and I would like to extend OpenTK to support their extensions. (Shaders binary, Texture compression) Is that possible that I could replace their VRsdk header (egl.h, etc.) into Generator project.
Do I need to modify the parser? or anything specific that I have to be concerned about?
Thanks,
Re: is OpenTK compatible with PowerVR sdk?
Are you certain that these extensions are not already exposed by OpenTK? A quick checks reveals functions both for texture compression and for shader binaries in the ES20 namespace.
The generation process works like this:
However, Converter is not a generic project and will not work with random headers without modification. Right now, it can only parse the OpenCL and OpenGLES headers from Khronos. Note that there's no need to parse egl.h, these bindings are trivial to write by hand (check Egl.cs in the source tree).
I'd suggest verifying that PowerVR extensions are missing from both OpenTK and from the master OpenGLES headers. If they are only missing from OpenTK, then it's mainly a matter of updating our copy of gl2.h and rerunning the generator. If they are missing from both there are two solutions:
Re: is OpenTK compatible with PowerVR sdk?
thanks a lot! I will see which way that will suit me the best :)
btw, I'm tried replaced "libegl.dll" and "libglesv2.dll" from AMD Emulator (which is working fine now) to PowerVR PC Emulator and the application is clashed again :(.
I debugged it roughly and found it raised the "Platform exception", but haven't got any chance to investigate further.
any idea?
Re: is OpenTK compatible with PowerVR sdk?
Can't tell what's wrong without at least a stacktrace.
Is the PowerVR emulator available for free? If so, do you know where I can find it? (google seems to be failing me).
Re: is OpenTK compatible with PowerVR sdk?
thank you very much for helping me investigate this
here is the PowerVR website where PC Emulation can be downloaded
you can download either PC Emulator, or the whole SDK (including PC Emulator)
Re: is OpenTK compatible with PowerVR sdk?
Thanks for the link.
Re: is OpenTK compatible with PowerVR sdk?
any good news?
Re: is OpenTK compatible with PowerVR sdk?
I am getting an AccessViolationException on Egl.Initialize when running with the PowerVR SDK. I haven't been able to find the cause yet.
In the meantime, AMD's ES emulator is working fine so you might wish to take a look into that.
Re: is OpenTK compatible with PowerVR sdk?
thanks! I'm about to come update that I found the error at the same place as well.
Again, thanks for mentioning AMD Emulator, I'm using that at the moment. Anyway, I also aimming to test the application on Linux that why PowerVR emulator is come in my concern.
Hopefully we will find the fix soon
Re: is OpenTK compatible with PowerVR sdk?
Filed as issue #1487: PowerVR ES emulator throws AccessViolationException on Egl.Initialize.
Re: is OpenTK compatible with PowerVR sdk?
I have forwarded this issue to the ImgTec support, and I got their responses as following
Hi,
Thanks for the clarification, however, I found the application is crashed even before the point you have mentioned (GraphicsContext.cs : 263) as far as I debug, it never reach the point that the program try to get the EGL context from available_contexts either
I'm not sure how to make this as a question, but I still a bit curious why the similar routine working fine with AMD emulator but not PVR? I thought both emulators do mostly the same stuff to emulate EGL, but I could be wrong
Well, it will be great if you could guide me a bit about the idea to debug this error.
I also post this further investigation on OpenTK forum.
Many thanks,
Wittawat K.
--------------------------------------------------------------------------------
Subject: RE: From aik6980 : PVRFrame ES20 PC Emulator, C# interop crash
Date: Tue, 19 Jan 2010 12:11:00 +0000
From: Jacek.Czaja@imgtec.com
To: aik_canhelp@hotmail.com
CC: IMGKL-DevTech@imgtec.com
Hi,
I'm sorry I haven't written exactly how it works. What I have written on the forum means that previously there were a problems with obtaining the functions from
libEGL libraries (part of pvrvframe). And With the version I have sent you this part works fine. However there is some problem somewhere later related to context.
We tried to investigate it a little bit and it seems that in the same code first you use our EGL interface to create a context , surface etc.. and later on try trying to adress
the same context using WGL interface. eg. You seem to create graphich context with EGL and store it in :available_contexts (GraphicsContext.cs) and then
later on refer to it using handle returned by wgl method (GraphicsContext.cs : 263). Current context you are getting comes from WGL which is something else than
current egl context and they handle is diffrent so accessing available_contexts (storage of egl contexts) with egl context handles will cause access violation.
Hope this will help
Regards
Jacek
--------------------------------------------------------------------------------
From: Wittawat Keawcharoen [mailto:aik_canhelp@hotmail.com]
Sent: 18 January 2010 21:53
To: Jacek Czaja
Cc: IMGKL - DevTech
Subject: RE: From aik6980 : PVRFrame ES20 PC Emulator, C# interop crash
Hi,
Unfortunately, it still didnt work.
I tested them with my project, both on Debug and Release build, and still give me the
"AccessViolationException"
However, the function that throw out the error is different this time,
Here is where the exception has been occured
.\OpenTK\Source\OpenTK\Platform\Egl\EglContext.cs - line 108
Egl.MakeCurrent(WindowInfo.Display, WindowInfo.Surface, WindowInfo.Surface, HandleAsEGLContext);
It is interesting you said that you can run the program on your system,
Have you modified any project properties?
Best Regards,
Wittawat K.
"
Hi,
Please find attach beta version of our pvrvframe. Send us some feedback as soon as you test them. I don’t know what is the reason that libraries you have tried did not work properly in your case.
What I can say is that in those attached , mechanism of exporting the functions was reimplemented to make it more friendly for dynamic loading by other applications , which is also your case .
But this case should also working with previous edition. Try it and let us now.
Regards,
Jacek
"
"
Hi,
I was able to reproduce the issue that you had reported. However this problem seems not to appear with our PVRVFrame candidate for our next release (2.6, around end of febuary). So If you want I can send you these libraries (still in prebeta stage) so you can give it a try.
Regards
Jacek
"
I'm still try to find the workaround on this problem, and I'm happy to send the PVRFrame 2.6 Beta to OpenTK if you want to investigate this further.
What ImgTec tried to say is that We are using the wrong context after the EGL context is created,
Appriciate any helps,
Wittawat K. | http://www.opentk.com/node/1454 | CC-MAIN-2014-52 | refinedweb | 1,195 | 65.73 |
Create an RSS 0.91 document using a template, and gain a little essential background in RSS history.
RSS 0.91 is probably the most popular RSS format because it is the oldest and is so simple, which, as with so many other technologies, encourages adoption by the teeming masses. Here is a minimal 0.91 document, containing all the required elements and a few optional ones (it is named news.xml in the file archive):
<rss version="0.91"> <channel> <title>Wy'east Communications</title> <link></link> <description> Wy'east Communications is an XML consultancy.</description> <language>en-us</language> <image> <url></url> <title>Wy'east</title> <link></link> </image> <item> <title>Legend of Wy'east</title> <link></link> <description>The Native American story behind the name Wy'east.</description> </item> </channel> </rss>
RSS 0.91 doesn't declare a namespace for its elements. The rss element is the document element. It has a required attribute, version, whose value is 0.91. This element must have exactly one channel child and one or more item children. Following the channel element are these elements:
A descriptive title for this channel. This should usually be the same as the content of the HTML element title on your main site page (such as index.html). The maximum number of characters allowed here is 100.
A URI for the channel. This should be a link to the web site that originates the feed?in this case,. Maximum length of this element is 500 characters.
A description of the channel, usually answering the question "What's this site all about?" Limited to 500 characters.
For a comparison of the required and optional child elements of channel for both RSS 0.91 and 2.0, see Table 6-2 in [Hack #83] .
The image is an optional element that has three required child elements: url, which contains a URL for a JPG, GIF, or PNG image representing the channel (500 character limit); title, which contains the alt attribute value from the img element in HTML used for the graphic whose link is in url (100 character limit); and link, a link to the web site represented by the link in url. The elements title and link should have the same content as the elements with the same names that are children of channel (500 character limit).
The optional children of image are description, width, and height. description should contain the same advisory text as might be found in the title attribute on the a element that creates the link associated with the graphic; width and height are the width and height of the graphic. By default, the value of width is 88 with a max of 144; the default value of height is 31 with a max of 400.
This document has only one item element, though it is common to have several (you can only have up to 15 in RSS 0.91 according to). A channel element may have one or more item children, which can contain: title, the title of the article or story (100 character limit); link, the URL to the story (500 character limit); and description, which holds a summary of the article or story (500 character limit).
Other optional children of channel are shown in Table 6-1. For more information on these and other RSS 0.91 elements, see. | https://etutorials.org/XML/xml+hacks/Chapter+6.+RSS+and+Atom/Hack+81+Create+an+RSS+0.91+Document/ | CC-MAIN-2021-31 | refinedweb | 561 | 65.22 |
Created on 2010-10-19 03:15 by jcea, last changed 2012-10-05 02:25 by jcea. This issue is now closed.
ZFS supports SEEK_HOLE/SEEK_DATA in "lseek()" syscall.
Oracle Solaris man page por "lseek":
"""
[...].
"""
Implementation would be trivial. Simply conditionally compile the constant export in the C module. Or adopt the approach in the last phrase.
Any novice?.
Martin, any thoughts on adding a ZFS dependent feature? ISTM this Solaris feature hasn't taken hold elsewhere and it may be a mistake to immortalize it in Python.
Seems to be adopted too in *bsd: .
The feature has patches available too for Linux, but never integrated in mainline kernel, AFAIK. Googling "SEEK_HOLE" is interesting.
If it's just additional constants then I don't see the problem. We already have a lot of platform-specific constants.
However, it would be a lot better if the io module were made to work properly with these constants, too. There are a lot of places where we hardcode tests such as `whence == SEEK_SET` or even `whence == 0`, and whence values above 2 aren't generally considered.
So the patch is probably a bit less trivial than what you imagine :)
Am 19.10.2010 06:58, schrieb Raymond Hettinger:
>
> Raymond Hettinger <rhettinger@users.sourceforge.net> added the
> comment:
>
> Martin, any thoughts on adding a ZFS dependent feature? ISTM this
> Solaris feature hasn't taken hold elsewhere and it may be a mistake
> to immortalize it in Python.
There isn't any specific patch to review yet. However, Python has
a long tradition of exposing all symbolic constants that users have
asked for, and these are no different (e.g. how many systems support
EX_SOFTWARE, or ENOTACTIVE). As long as it's just new constants, and
as long as they are guarded with an ifdef, no approval is necessary
for adding them.
Jesús, can you attach a patch (with the appropriate #ifdefs)?
I attach patch. I have reviewed the IO module and I think we don't need to do any change there, since values over 2 are not touched.
The patch is trivial. My plan was to leave this patch for a novice :-).
Please, review. But let me do the final commit (I have commit privileges).
[jcea@babylon5 py3k]$ ./python
Python 3.2a3+ (py3k:85834M, Oct 25 2010, 15:37:04)
[GCC 4.5.1] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.SEEK_DATA
3
>>> os.SEEK_HOLE
4
>>>
The patch lacks a documentation change. Otherwise, it looks fine.
I think the docs should also make it clear that these flags are only supported by os.lseek() (unless you have tested the IO lib to work properly, that is, but in this case it would be nice to add unit tests).
I will update documentation.
Antoine, it is difficult to write a testcase when I can only test under a system with ZFS. I don't think we have a buildbot with Solaris/*BSD and ZFS.
Any suggestion?.
> I will update documentation.
>
> Antoine, it is difficult to write a testcase when I can only test
> under a system with ZFS. I don't think we have a buildbot with
> Solaris/*BSD and ZFS.
If you ascertain yourself that the test works under ZFS then I think it
is enough. Of course, it would be better if a buildbot ran that test,
but we can live without it (IMHO).
> If you ascertain yourself that the test works under ZFS then I think it
> is enough. Of course, it would be better if a buildbot ran that test,
> but we can live without it (IMHO).
I agree. I trust that the patch is correct, and we really don't need to
test whether ZFS works correctly (but trust that Oracle will)..
Please, review this. I had changed IO to support the new flags too. To do it, I must relax error control in IO, a bit.
So, the new flag are supported both in "os.lseek()" and in standard file objects.
Please, Antoine, could you review?.
I have checked the patch manually, but I can't think a way to automate it. We don't have any ZFS machine in buildbot.
I would love to commit this next week. Thanks for your time.
"""
>>> import os
>>> f=open("XX","w+b")
>>> f.seek(1024*1024)
1048576
>>> f.write(b"hello")
5
>>> f.seek(1024*1024*2)
2097152
>>> f.write(b"bye")
3
>>> f.seek(0,os.SEEK_HOLE)
0
>>> f.seek(0,os.SEEK_DATA)
1048576
>>> f.seek(1048576,os.SEEK_HOLE)
1179648
>>> f.seek(1179648,os.SEEK_DATA)
2097152
>>> f.seek(2097152,os.SEEK_HOLE)
2097155
>>> fd=f.fileno()
>>> os.lseek(fd,0,os.SEEK_HOLE)
0
>>> os.lseek(fd,0,os.SEEK_DATA)
1048576
>>> os.lseek(fd,1048576,os.SEEK_HOLE)
1179648
>>> os.lseek(fd,1179648,os.SEEK_DATA)
2097152
"""
- The patch modifies the _io module but not _pyio, why?
(try f=_pyio.open("XX","w+b") at the beginning of the script above)
- One test was *removed*, but nothing was added to test this new feature.
This is the most likely way to lose it in future versions!
An idea for the test is to do like the MockRawIO class in test_io.py, which "implements" a file but fakes all system calls, and can be wrapped in a BufferedReader.
- The feature seems to be not applicable to text files, this should be tested.
Amaury, thanks for your valuable feedback.
1. I forgot about the python implementation. I am not familiar with the new IO framework. Implemented now.
3. These new SEEK modes should not be used in text mode. In my new patch the modes are rejected in text mode, allowed in binary mode.
2. I have spend the last 3 hours studying "test_io.py", and I don't understand the Mock* usage. Your MockRawIO hint is valuable, but I can't think a way to test that C/Python implementation passes the new flags to the OS. If I understand correctly, any method implemented in the Mock will be hit instead of the IO implementation, and anything that reach IO implementation will not go back to the Mock. I don't understand... :-?. Or can you magically insert the Mock between the IO module and the OS?. I know something like this is happening, but I don't understand the mechanism.
How do you choose what Mock* are you using in each test?.
I have read about Mock testing in the past, but I don't understand the use here. Are they actually Mocks, as explained in , for example?
Sorry.
Could you provide some hint?. Maybe in python-dev, for more audience?.
I have implemented a test "test_posix", if your OS can report holes in a file (so far modern Solaris/OpenSolaris/OpenIndiana, don't know about *bsd). Other OSs will ignore the test.
I know your time is valuable. Thanking for investing in me.
Jesus, perhaps you can address Amaury's comments by uploading a new patch?
> ZFS supports SEEK_HOLE/SEEK_DATA in "lseek()" syscall.
> The feature has patches available too for Linux, but never integrated in mainline kernel, AFAIK.
> it is difficult to write a testcase when I can only test under a system with ZFS
I don't know if this could help, but recently Linux did get some commits regarding SEEK_HOLE/SEEK_DATA ( e.g. ). I haven't tested whether it works / which filesystems support it. Grepping the Linux sources for SEEK_HOLES gives me several hits, e.g. for btrfs.
+ /* SEEK_SET and SEEK_CUR are special because we could seek inside the
+ buffer. Other whence values must be managed without this optimization.
+ Some Operating Systems can provide additional values, like
+ SEEK_HOLE/SEEK_DATA. */
+ if (((whence == 0) || (whence == 1)) && self->readable) {
Why not using SEEK_SET and SEEK_CUR instead of 0 and 1 here?
+ .. versionadded:: 3.2
This is now outdated, it should be 3.3.
Victor, internally Python uses 0, 1 and 2 as wired values independently of the platform values. This is probably an historic accident.
Please, review.
I am going to integrate next week
Please, review.
Is there a reason to say (several times) 'can support' instead of just 'support'? Do the OSes in question just optionally support rather than always support?
The first version added: change 'depend of' to 'depend on'.
In several functions you delete error checks:
- if not (0 <= whence <= 2):
- raise ValueError("invalid whence value")
(or C equivalent). What happens with patch if invalid whence value is passed? Error from deeper in the call stack? Silently pass error, with no message?
Could import of io create set of valid_whences for system? Then check would be "if whence not in valid_whences:" (or C equivalent).
In 3.3, unittest has new mock submodule. Perhaps that would help testing.
Terry, yes, skiping the test in the code will raise an error anyway when doing the real "seek()" OS syscall.
> Is there a reason to say (several times) 'can support' instead of
> just 'support'? Do the OSes in question just optionally support
> rather than always support?
Sometimes depends of the concrete filesystem used, or the concrete OS version.
> The first version added: change 'depend of' to 'depend on'.
Done in my repository. Thanks.
> Could import of io create set of valid_whences for system?
> Then check would be "if whence not in valid_whences:" (or C
> equivalent).
This is far from trivial and I don't see the point if OS "seek()" is going to give an error anyway. The only point would to provide a maybe more useful error message.
> In 3.3, unittest has new mock submodule. Perhaps that would help
> testing.
This is a very thin layer over the OS.
Thanks for the feedback.
> I don't see the point if OS "seek()" is going to give an error anyway.
Please check that Windows won't crash the interpreter with bad 'whence' values, like it already does for closed file descriptors.
New version, addressing Amaury concerns and Neologix review.
Please, do a final review.
- In test_posix.py: it's better to use the "with" statement when opening a file
- In Misc/NEWS: the entries should be kept in reverse chronological order
Another version, after Antoine feedback.
Please, review.
New changeset 86dc014cdd74 by Jesus Cea in branch 'default':
Close #10142: Support for SEEK_HOLE/SEEK_DATA
You broke test_io Gentoo Non-Debug 3.x/builds/2143/steps/test/logs/stdio
Yes, backing out changeset.
Never suppose anything...
New patch proposed, with testsuite fixed.
Please, review. Last chance :-).
New patch, after neologix@free.fr review.
<bikeshed>In some cases you change "invalid" to "unsupported" when encountering an invalid/unsupported `whence' and in others you keep them on "invalid". I find it rather hard to really differentiate these two words in that context; care to shed a light and tell me the thought process behind that?</bikeshed>
New changeset de2a0cb6ba52 by Jesus Cea in branch 'default':
Closes #10142: Support for SEEK_HOLE/SEEK_DATA
Looks like the FreeBSD bot fails in test_posix:
======================================================================
ERROR: test_fs_holes (test.test_posix.PosixTester)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/home/buildbot/buildarea/3.x.krah-freebsd/build/Lib/test/test_posix.py", line 1033, in test_fs_holes
self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
OSError: [Errno 25] Inappropriate ioctl for device
----------------------------------------------------------------------
Ran 81 tests in 1.878s
New changeset 13f5a329d5ea by Jesus Cea in branch 'default':
Kernel bug in freebsd9 - #10142: Support for SEEK_HOLE/SEEK_DATA
This looks like a bug in freebsd:
Since looks like a kernel bug, skipping test in that case.
Committed patch.
Thanks for the head-up.
New changeset 8acaa341df53 by Jesus Cea in branch 'default':
Skip the test only if neccesary - Kernel bug in freebsd9 - #10142: Support for SEEK_HOLE/SEEK_DATA
> This looks like a bug in freebsd:
>
>
I tested that one already yesterday (it was late, so I forgot to mention
it) and the test case attached to the bug report runs fine on the buildbot:
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
int main(void)
{
int fd = open("ccc.c", O_RDONLY);
off_t offset=lseek(fd,0,SEEK_HOLE);
if (offset==-1) {
if (errno==ENXIO) {
// No more data
printf("no more data\n");
close(fd);
exit(-1);
}
}
return 0;
}
The skip looks good to me though, I wouldn't be surprised if there is a kernel
bug. This bug is still present on my machine:
> int main(void)
> {
> int fd = open("ccc.c", O_RDONLY);
> off_t offset=lseek(fd,0,SEEK_HOLE);
> if (offset==-1) {
> if (errno==ENXIO) {
Darn, the errno in test_posix should be ENOTTY. Indeed, with ENOTTY the
test case for the bug is positive.
The test case is till failing for the freebsd7 buildbot:
And the Ubuntu ARM buildbot.
New changeset 814557548af5 by Jesus Cea in branch 'default':
Skip test in freebsd entirely - Kernel bug in freebsd7/8/9 - #10142: Support for SEEK_HOLE/SEEK_DATA
Stefan, I am confused with your comments. The thing is that freebsd defines SEEK_HOLE/SEEK_DATA but reports an error when you use them. I guess they are errors when used on a filesystem that doesn't support them. This is a bug, in my opinion (if a FS doesn't support them, compatible implementation are trivial).
In the meantime, I am skipping the test completely under freebsd7/8/9. patch just committed.
Testing the patch, but freebsd7 buildbot is really SLOW.
Greog, I am confused about ARM ubuntu errors. Do we know what ubuntu version is running there?. What is the filesystem?.
I am seriously thinking about supporting these flags only in "real" OSs like Solaris & derivatives :-)
Jesus, what do you think about removing that test entirely?
IMO it is not our job to verify the OS' proper behavior in the face of SEEK_HOLE/SEEK_DATA; it is enough to provide the constants, and let whoever uses it face the perils of the platform.
Georg, I am fine with that if you are fine with that :-). Please, confirm :)
(sorry for mistyping your name before!)
Jes??s Cea Avi??n <report@bugs.python.org> wrote:
> Stefan, I am confused with your comments.
The FreeBSD bug report you linked to had a test case attached. The test case
uses errno == ENXIO. I could not reproduce the failure, so in my *first* comment
I questioned whether the failures in test_posix were caused by that particular
bug.
Then I noticed that the test_posix traceback shows errno == 25 == ENOTTY.
So I ran the test case with errno == ENOTTY and I *could* reproduce the
bug.
In short, I think you linked to the right bug after all. :)
As long as we have a test confirming that SEEK_HOLE/SEEK_DATA are *accepted* by the io module (which is a big part of the patch), it is fine.
E.g. calling seek() with the constants and check that it only raises OSError or nothing should work, right?
Ping. The ARM buildbot still fails on test_fs_holes:
New changeset d69f95e57792 by Jesus Cea in branch 'default':
Cope with OSs lying - #10142: Support for SEEK_HOLE/SEEK_DATA
Thanks for the head-up, Antoine. | https://bugs.python.org/issue10142 | CC-MAIN-2020-34 | refinedweb | 2,482 | 76.42 |
.
I started to get a bit curious about why I was doing so poorly. Typically my "projected" points were pretty good each week, but my team just never seemed to deliver.
Thus, here is my first post looking at the biggest out performers and the biggest misses relative to ESPN projections. All data are from ESPN. So - lets get to it!
import psycopg2 import pandas.io.sql as psql import pandas as pd from matplotlib import pyplot as plt from __future__ import division #now division always returns a floating point number import numpy as np import seaborn as sns %matplotlib inline
db = psycopg2.connect("dbname='fantasyfootball' host='localhost'") def get_combined_df(): actual_points = psql.read_sql(""" select name, team, position, sum(total_points) as points_actual from scoring_leaders_weekly group by name, team, position;""", con=db) predicted_points = psql.read_sql(""" select name, team, position, sum(total_points) as points_predicted from next_week_projections group by name, team, position;""", con=db) combined_df = actual_points.merge(predicted_points, on=['name', 'team', 'position'], how='left') combined_df = combined_df.dropna() combined_df = combined_df[combined_df['points_predicted'] > 0] combined_df['points_diff'] = combined_df.points_actual - combined_df.points_predicted combined_df['points_diff_pct'] = (combined_df.points_actual - combined_df.points_predicted) / combined_df.points_predicted return combined_df def get_top_bottom(df): group = df.groupby('position') top_list = [] bottom_list = [] for name, data in group: top = data.sort('points_diff', ascending=False) top_list.append(top.head()) tail = top.tail() tail = tail.sort('points_diff') bottom_list.append(tail) top_df = pd.concat(top_list) bottom_df = pd.concat(bottom_list) return top_df, bottom_df def run_analysis(): combined_df = get_combined_df() top, bottom = get_top_bottom(combined_df) return combined_df, top, bottom
For the results, I decided to show the top 5 out performers and the top 5 under performers for the cumulative season based on the absolute point difference (not the percentage). First, here are the out performers. This is pretty interesting. Travis Benjamin, for example, has in the first 3 weeks produced an extra 33.6 fantasy points relative to expectations. Not too bad.
combined_df, top_1, bottom_1 = run_analysis()
top_1
Now here are the under performers. These are the people you don't want to be playing...For example, C.J. Anderson comes in at a whopping 42 points under expectation. Who is my running back you ask... Drew Brees takes the cake, though, under performing by 46.2 points on the season. He was injured, though.
bottom_1
Next, I wanted to take a look at the distribution of point differences by position. The below chart shows that the median player in all positions is under performing, except for TE which is pretty close to zero. There are a few break out WRs and quite a bunch of under performing running backs. The spread is also pretty wide for most of the positions.
ax = sns.boxplot(combined_df.points_diff, groupby=combined_df.position) plt.title("Distribution of Point Differences by Position") sns.despine()
I also looked at the distribution of actual points by position. One thing you hear in fantasy is to select RBs early because they are high variance players. Meaning that you suffer more by getting a lower ranked RB than a lower ranked QB. This is also due to the fact that a lot more RBs are getting drafted than QBs. Below is the distribution for all players and provides a general sense.
ax = sns.boxplot(combined_df.points_actual, groupby=combined_df.position) plt.title("Distribution of Actual Points by Position") sns.despine()
To see if the high variance difference is playing out, we can look at the top 12 quarterbacks and top 36 running backs so far in the season (assume 12 team league with 1 starting QB and 3 starting RBs). You can see below that indeed the RBs standard deviation is quite a bit higher (about 7 points) than the QBs.
combined_df[combined_df['position'] == "QB"].sort('points_actual', ascending=False).head(n=12).describe()
combined_df[combined_df['position'] == "QB"].sort('points_actual', ascending=False).head(n=36).describe()
These were just some quick analyses I did to try and get a sense of which players are doing well/poorly and how various positions are performing.
If people find this interesting, I can try and update the data as the season goes on.
I am hoping to find time to investigate the ESPN projections to see how sensical they really are. Based on the chart above, they seem to aim high, leading to many under performers. I would like to try and build my own projection model to see how well I can compare. Now that I think about it, here are the overall summary statistics below. It looks like on average ESPN is over projecting by about 4 points with a standard deviation of 10.5 points.
combined_df.describe() | https://nbviewer.ipython.org/github/tfolkman/learningwithdata/blob/master/Biggest_Misses.ipynb | CC-MAIN-2021-43 | refinedweb | 758 | 50.63 |
#include <irtkImageToFile.h>
This is the abstract base class which defines a common interface for all filters which take an image as input and produce an image file as output. Each derived class has to implement all of the abstract member functions.
Definition at line 27 of file irtkImageToFile.h.
Static constructor.
This constructor allocates a derived class which can be used to read the image file. This involves checking the file format of the file and dynamically allocating the corresonding derived class.
Start address of the data in the image file.
Should be initialized by calling Initialize().
Definition at line 41 of file irtkImageToFile.h. | http://wwwhomes.doc.ic.ac.uk/~dr/software/classirtkImageToFile.html | CC-MAIN-2017-17 | refinedweb | 106 | 58.38 |
NAME
ggGetScope, ggFromScope, ggDelScope, ggNewScope - Portable code module loading facilities
SYNOPSIS
#include <ggi/gg.h> gg_scope ggGetScope(const char *location); void ggDelScope(gg_scope scope); void *ggFromScope(gg_scope, const char *symbol); typedef void *(*ggfunc_scope_get)(void * handle, const char * symbol); typedef void (*ggfunc_scope_del)(void * handle); gg_scope ggNewScope(const char * location, void * handle, ggfunc_scope_get get, ggfunc_scope_del del)
DESCRIPTION
LibGG abstracts dynamic code loading (and emulates dynamic code loading for statically linked embedded binaries) through a simple API which represents the very lowest level required of any loadable module system. The actual underlying mechanisms used in various operating systems to load additional code into an application on demand vary drastically, however, minus OS-specific frills, they can all be mapped to the above three LibGG API functions. ggGetScope finds a loadable collection of symbols known by its location through whatever system is available on the operating system. Those symbols were once supposed to be code from modules, but the scope abstraction does not impose this restriction. The scopes can have different implementations and are not restricted to dynamic libraries. They could also be used as an interface to a attribute/value configuration system. Note that when a scope happens to be dynamic library, the symbols are loaded into the address space of the caller, but libgg does not guarantee that the imported symbols will be seen by other modules. ggDelScope unloads the symbol collection represented by the handle scope, which must have been previously loaded with ggGetScope (scope should be a return value from a previous call to ggGetScope.) Reference counts are kept to ensure that redundantly loaded symbol collections are not discarded until their last owner releases them. Calling ggDelScope on a handle too many times, or on an invalid handle, may produce undefined results. Accessing symbols after the collections they were contained in are unloaded will produce undesirable and undefined results. ggFromScope searches the symbol collection represented by the handle scope, which has been loaded with ggGetScope (and not yet unloaded with ggDelScope, of course) for a symbol named symbol, so that the application may use the item associated with the symbol. The parameter scope should be a return value from a previous call to ggDelScope. As ggFromScope may have no way of knowing what the symbol represents, the application must take the responsibility for assigning the item a correct C type. ggNewScope allows to register a custom scope to libgg. The primary purpose is to allow libraries to provide builtin modules that are accessible through the same interface as dynamic ones. location is the string at which the scope can be retreived. handle is a opaque pointer provided by the caller that will be passed to the callbacks. get is a function that take an opaque handle, a symbol name, and that must return the requested symbol address, or NULL if not found. del is a function that will take the provided handler, and that must cleanup everything before the scope is removed from the scope registry. This scheme allows to implement all kind of scopes in a very flexible way. Note that ggNewScope will take a reference on the scope.
RETURN VALUE
On success, ggGetScope returns an opaque pointer to a handle representing a newly loaded symbol collection (which must be retained in order to use or free the collection.) These pointers are not guaranteed to be unique. On failure, ggGetScope returns NULL. ggFromScope returns the address of the item that the named symbol represents, if it has been loaded into the caller’s address space. Otherwise it returns NULL. Note that the value associated to a symbol really depends on the scope itself and the caller must know what is behind it. So a NULL value does not necessarily means failure. It could be a valid value for a specific scope. ggNewScope returns an opaque pointer to a handle representing the custom scope. On failure, ggNewScope returns NULL. | http://manpages.ubuntu.com/manpages/jaunty/man3/ggGetScope.3.html | CC-MAIN-2015-48 | refinedweb | 649 | 51.89 |
Wikitude
play_for_work
Forum
Documentation
Download
wikitude.com
How can we help you today?
Enter your search term here...
Search
Start a new topic
Discussions
Wikitude SDK (Android, iOS, UWP)
Wikitude SDK Questions or Problems
Android ArchitectView seg fault
Y
Yegor Vedernikov
started a topic
almost 9 years ago
Android ArchitectView seg fault
9 Comments
Oldest First
Popular
Newest First
Sorted by
Oldest First
Y
Yegor Vedernikov
said
almost 9 years ago
Hello,
We're having the following issue when trying to switch from the ArchitectView before it finishes loading all the POIs:
10-17 13:48:33.168: E/libEGL(3072): call to OpenGL ES API with no current context (logged once per thread)
10-17 13:48:33.536: D/CameraHal(1030): stopPreview
10-17 13:48:33.536: I/HPAndroidHAL(1030): APILOG: S1Up
10-17 13:48:33.536: D/CameraHal(1030): stop preview thread
10-17 13:48:33.543: D/dalvikvm(3072): GC_FOR_MALLOC freed 552 objects / 303304 bytes in 285ms
10-17 13:48:33.575: I/HPAndroidHAL(1030): APILOG: Disable Preview
10-17 13:48:33.582: D/CameraHal(1030): stopPreview
10-17 13:48:33.582: I/HPAndroidHAL(1030): APILOG: S1Up
10-17 13:48:33.582: D/CameraHal(1030): CameraHal release
10-17 13:48:33.582: D/CameraHal(1030): deinitPvOverlay()
10-17 13:48:33.582: I/HPAndroidHAL(1030): APILOG: DeinitializePreviewMemory
10-17 13:48:33.676: I/HPAndroidHAL(1030): Exiting thread OMAPHAL_Thread (ID: 0xdaae8)
10-17 13:48:33.684: D/TIOverlay(1289): overlay_destroyOverlay:IN dev (0x126cb8) and overlay (0x2d86e8)
10-17 13:48:33.684: I/TIOverlay(1289): Destroying overlay/fd=91/obj=002d86e8
10-17 13:48:33.684: D/TIOverlay(1289): overlay_destroyOverlay:OUT
10-17 13:48:33.692: I/HPAndroidHAL(1030): APILOG: ExitHPLibraries
10-17 13:48:33.692: I/HPAndroidHAL(1030): Exiting thread CaptureDirectorThread (ID: 0xd5730)
10-17 13:48:33.692: I/HPAndroidHAL(1030): APILOG: state machine shutting down...
10-17 13:48:33.692: I/HPAndroidHAL(1030): Exiting thread HALThread (ID: 0xd5328)
10-17 13:48:33.692: I/HPAndroidHAL(1030): Exiting thread AutoExposureThread (ID: 0xd5368)
10-17 13:48:33.692: I/HPAndroidHAL(1030): Exiting thread RenderingAnalysisModule (ID: 0xd53a8)
10-17 13:48:33.692: I/HPAndroidHAL(1030): Exiting thread BoxcarThread (ID: 0xd53e8)
10-17 13:48:33.692: I/HPAndroidHAL(1030): Exiting thread S2ProcessingThread (ID: 0xd5428)
10-17 13:48:33.700: I/HPAndroidHAL(1030): Exiting thread LensThread (ID: 0xd5468)
10-17 13:48:33.700: I/HPAndroidHAL(1030): Exiting thread FocusThread (ID: 0xd54a8)
10-17 13:48:33.700: I/HPAndroidHAL(1030): Exiting thread paxelMotionThread (ID: 0xd5500)
10-17 13:48:33.700: I/HPAndroidHAL(1030): Exiting thread CallbackThread (ID: 0xd5540)
10-17 13:48:33.700: I/HPAndroidHAL(1030): Exiting thread FlickerThread (ID: 0xd56a0)
10-17 13:48:33.700: I/HPAndroidHAL(1030): Exiting thread FaceDetectThread (ID: 0xd56f0)
10-17 13:48:33.700: I/HPAndroidHAL(1030): Exiting thread S2PostProcessingThread (ID: 0xd5770)
10-17 13:48:33.700: I/HPAndroidHAL(1030): APILOG: components shutting down...
10-17 13:48:33.700: I/HPAndroidHAL(1030): APILOG: all components uninitialized.
10-17 13:48:33.762: I/HPAndroidHAL(1030): APILOG: all components destroyed.
10-17 13:48:33.762: I/HPAndroidHAL(1030): APILOG: library shutdown complete.
10-17 13:48:33.762: D/CameraHal(1030): CameraHal destructor
10-17 13:48:33.762: D/CameraHal(1030): CameraHal release
10-17 13:48:33.762: D/CameraSettings(1030): CameraSettings destructor
10-17 13:48:33.832: D/dalvikvm(3072): GC_FOR_MALLOC freed 181 objects / 269720 bytes in 147ms
10-17 13:48:33.832: D/PVRShellView(3072): View will be destroyed. Engine dead
10-17 13:48:33.832: E/libEGL(3072): call to OpenGL ES API with no current context (logged once per thread)
10-17 13:48:33.840: D/ServiceManager(3072): stopping platform service with name: sensors
10-17 13:48:33.840: D/ServiceManager(3072): stopping platform service with name: camera
10-17 13:48:33.872: D/webviewglue(3072): nativeDestroy view: 0x127ca8
10-17 13:48:33.973: I/DEBUG(3068): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
10-17 13:48:33.973: I/DEBUG(3068): Build fingerprint: 'MOTO_RTEU/umts_sholes/umts_sholes/sholes:2.2.1/SHOLS_U2_05.26.3/296482885:user/release-keys'
10-17 13:48:33.973: I/DEBUG(3068): pid: 3072, tid: 3098 >>> com.skyhookwireless.apps.arinflight <<<
10-17 13:48:33.973: I/DEBUG(3068): signal 11 (SIGSEGV), fault addr 000000d4
10-17 13:48:33.973: I/DEBUG(3068): r0 00000000 r1 0041e570 r2 00000000 r3 000000d4
10-17 13:48:33.973: I/DEBUG(3068): r4 8140f1c8 r5 0041e570 r6 81216e81 r7 3f2aaaab
10-17 13:48:33.973: I/DEBUG(3068): r8 002f0050 r9 00000001 10 a87ddb80 fp 484a2750
10-17 13:48:33.973: I/DEBUG(3068): ip 00000000 sp 484a2250 lr 81136927 pc 81120828 cpsr 00000030
10-17 13:48:33.973: I/DEBUG(3068): d0 643a64696f72646e d1 6472656767756265
10-17 13:48:33.973: I/DEBUG(3068): d2 8080808080808080 d3 8080808080808080
10-17 13:48:33.973: I/DEBUG(3068): d4 8080808080808080 d5 8080808080808080
10-17 13:48:33.973: I/DEBUG(3068): d6 8080808080808080 d7 8080808080808080
10-17 13:48:33.973: I/DEBUG(3068): d8 0000000000000000 d9 0000000000000000
10-17 13:48:33.973: I/DEBUG(3068): d10 0000000000000000 d11 0000000000000000
10-17 13:48:33.973: I/DEBUG(3068): d12 0000000000000000 d13 0000000000000000
10-17 13:48:33.973: I/DEBUG(3068): d14 0000000000000000 d15 0000000000000000
10-17 13:48:33.973: I/DEBUG(3068): d16 436cfd9445994148 d17 0000000000000000
10-17 13:48:33.973: I/DEBUG(3068): d18 0000000000000000 d19 0000000000000000
10-17 13:48:33.973: I/DEBUG(3068): d20 3ff0000000000000 d21 8000000000000000
10-17 13:48:33.973: I/DEBUG(3068): d22 0000000000000000 d23 bda8fae9be8838d4
10-17 13:48:33.973: I/DEBUG(3068): d24 40dd4c2013880000 d25 40ed4c1013880000
10-17 13:48:33.973: I/DEBUG(3068): d26 40cd4c4013880000 d27 0000000000000000
10-17 13:48:33.973: I/DEBUG(3068): d28 0000000000000000 d29 3ff0000000000000
10-17 13:48:33.973: I/DEBUG(3068): d30 0000000000000000 d31 3ff0000000000000
10-17 13:48:33.973: I/DEBUG(3068): scr 60000013
10-17 13:48:34.168: I/DEBUG(3068): #00 pc 00120828 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): #01 pc 00136922 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): #02 pc 0013398a /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): #03 pc 0014a40e /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): #04 pc 00216b16 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): #05 pc 00016e74 /system/lib/libdvm.so
10-17 13:48:34.168: I/DEBUG(3068): code around pc:
10-17 13:48:34.168: I/DEBUG(3068): 81120808 9b019a02 1c111c08 f0521c1a b005fe95
10-17 13:48:34.168: I/DEBUG(3068): 81120818 46c0bd00 b088b510 91029003 23d49a03
10-17 13:48:34.168: I/DEBUG(3068): 81120828 9a0258d3 1c191c10 f8aef7fe 23d49a03
10-17 13:48:34.168: I/DEBUG(3068): 81120838 1c5958d3 23d49a03 9b0350d1 9b021d1c
10-17 13:48:34.168: I/DEBUG(3068): 81120848 f7e81c18 1c02faf7 9b02a906 1c111c08
10-17 13:48:34.168: I/DEBUG(3068): code around lr:
10-17 13:48:34.168: I/DEBUG(3068): 81136904 001742fa 00174302 001742de b084b510
10-17 13:48:34.168: I/DEBUG(3068): 81136914 91009001 685a9b01 1c109b00 f7e91c19
10-17 13:48:34.168: I/DEBUG(3068): 81136924 9b01ff7b 34201c1c 1c189b00 fa84f7d2
10-17 13:48:34.168: I/DEBUG(3068): 81136934 93031c03 1c20ab03 f0001c19 1c03fcdb
10-17 13:48:34.168: I/DEBUG(3068): 81136944 601a9a00 1c189b00 fa76f7d2 1c181c03
10-17 13:48:34.168: I/DEBUG(3068): stack:
10-17 13:48:34.168: I/DEBUG(3068): 484a2210 484a24c5
10-17 13:48:34.168: I/DEBUG(3068): 484a2214 0041e5e8
10-17 13:48:34.168: I/DEBUG(3068): 484a2218 01012274
10-17 13:48:34.168: I/DEBUG(3068): 484a221c 8110b557 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): 484a2220 484a224c
10-17 13:48:34.168: I/DEBUG(3068): 484a2224 0041e570
10-17 13:48:34.168: I/DEBUG(3068): 484a2228 484a24bc
10-17 13:48:34.168: I/DEBUG(3068): 484a222c 811332cd /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): 484a2230 40386823
10-17 13:48:34.168: I/DEBUG(3068): 484a2234 0041e570
10-17 13:48:34.168: I/DEBUG(3068): 484a2238 0000000b
10-17 13:48:34.168: I/DEBUG(3068): 484a223c 811496d3 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): 484a2240 3f2aaaab
10-17 13:48:34.168: I/DEBUG(3068): 484a2244 0041e570
10-17 13:48:34.168: I/DEBUG(3068): 484a2248 df002777
10-17 13:48:34.168: I/DEBUG(3068): 484a224c e3a070ad
10-17 13:48:34.168: I/DEBUG(3068): #00 484a2250 8140f1c8 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): 484a2254 81149085 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): 484a2258 0041e570
10-17 13:48:34.168: I/DEBUG(3068): 484a225c 00000000
10-17 13:48:34.168: I/DEBUG(3068): 484a2260 00000012
10-17 13:48:34.168: I/DEBUG(3068): 484a2264 3f800000
10-17 13:48:34.168: I/DEBUG(3068): 484a2268 00000000
10-17 13:48:34.168: I/DEBUG(3068): 484a226c 3f800000
10-17 13:48:34.168: I/DEBUG(3068): 484a2270 8140f1c8 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): 484a2274 81136927 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.168: I/DEBUG(3068): #01 484a2278 0041e570
10-17 13:48:34.168: I/DEBUG(3068): 484a227c 00439068
10-17 13:48:34.168: I/DEBUG(3068): 484a2280 0000000b
10-17 13:48:34.168: I/DEBUG(3068): 484a2284 8140f1c8 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.192: I/DEBUG(3068): 484a2288 8140f1c8 /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.192: I/DEBUG(3068): 484a228c 8113398f /data/data/com.skyhookwireless.apps.arinflight/libarchitect.so (deleted)
10-17 13:48:34.348: D/dalvikvm(3072): GC_FOR_MALLOC freed 3721 objects / 209248 bytes in 242ms
10-17 13:48:34.348: D/PVRShellView(3072): Stop rendering
After this application closes immediately. Everything works fine if the POIs finish loading by the time we decide to switch from the view however.
This happens on all of the devices we use for testing including Milestone with Froyo and Nexus S with JB. We are using Wikitude SDK 1.1.
This doesn't seem to reproduce with Wikitude application itself, probably because ArchitectView has its own activity there. In our case we're using a number of views (one of which is AR view) in the same activity. By "switching from" I mean calling onPause and onDestroy for AR view and setting the content view to another view.
Is there a way to switch between AR view and other view in the same activity without having to destroy and recreate the AR view every time btw? I've tried some but none of it worked.
A
Andreas Fötschl
said
almost 9 years ago
Hi there!
Please use Fragments to switch between views in same Activity.
They are supported for
SDK 11+
.
I recommend you to use the
custom compatibility pack
which allows you to use MapViews inside Fragments too.
You can then use transactions to change views on the fly.
Since MapView and Cam consume quite a lot memory I recommend you not to have both views/fragments in memory but restore fragment instead.
Find more details about the compatibility pack at
Android Developer Website
.
Yepp, it's a bit more to read through, but you then know you are using latest technology and can even use latest titlebar across all version using the
ActionBar
.
Hope that helps.
Kind regards,
Andi
Y
Yegor Vedernikov
said
almost 9 years ago
Hi Andreas,
Thanks for the hint. We'll try that out and get back to you with the results.
Y
Yegor Vedernikov
said
almost 9 years ago
Hi again,
I'm trying out the Fragments with our app atm. It looks like the seg fault doesn't happen with them but I can't switch to AR view now (switching from it and between other views works fine). I'm using the dynamic fragments.
If I start with, say, list view and then replace it with the AR view I get this:
10-25 14:47:57.942: E/AndroidRuntime(5179): FATAL EXCEPTION: GLThread 62
10-25 14:47:57.942: E/AndroidRuntime(5179): java.lang.RuntimeException: Failed to initialise PVRShell
10-25 14:47:57.942: E/AndroidRuntime(5179): at com.wikitude.architect.PVRShell.initialise(Unknown Source)
10-25 14:47:57.942: E/AndroidRuntime(5179): at com.wikitude.architect.PVRShellView$OurContextFactory.createContext(Unknown Source)
10-25 14:47:57.942: E/AndroidRuntime(5179): at android.opengl.GLSurfaceView$EglHelper.start(GLSurfaceView.java:922)
10-25 14:47:57.942: E/AndroidRuntime(5179): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1246)
10-25 14:47:57.942: E/AndroidRuntime(5179): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1116)
I get the same if I start with AR view, then switch to list, then to AR again having ArchitectView.onDestroy() call in onDestroy() fragment method.
If I comment it out I get an empty cam view in the end of this scenario (I expect to see at least a radar). This basically looks the same to problems I had with switching to AR view using setContentView() before coming up with a solution to always destroy it when switching from and recreate from scratch when switching to it.
So the question is... what am I doing wrong? :)
It would be nice to have a snippet for AR view with switching fragments.
Y
Yegor Vedernikov
said
almost 9 years ago
Ok, I've made some progress here actually. I can switch from/to AR view using the Fragments API now... well, with some strings attached.
I had to make the following changes to achieve the desired behavior:
* Inflate AR layout only the first time and return the cached AR view on the subsequent calls to the onCreateView
* Remove AR view from it's parent view in onDetach
* don't destroy AR view in fragment onDestroy(), add a specific method that is called when activity gets destoyed
* move the AR onPostCreate and load the world code to happen right after AR onCreate in onCreateView (this way I can start with another view and then switch to AR as well as start with AR view and switch to another one)
However, this only works currently for Nexus S with JB 4.1.2 or Galaxy Nexus with JB 4.1.1 and doesn't for Milestone with Froyo 2.2.1 or i9000 with Gingerbread 2.3.5. So I suspect that it only works for android-11+ devices (there is a delay begore radar and the objects get visible however). On the older devices I get an empty cam view after switching back to AR view and it never updates even after I see my app communicates (calls the js method) with AR in logs.
I can also reproduce the seg fault using the Fragments API on JB Nexus S if I put the AR onDestroy call in fragment onDetach method and try to replace the AR view while it's still loading the objects.
Now to the funny part - I've reverted to use the setContentView instead of fragment transactions and managed to get rid of seg fault by cutting out the AR onDestroy during switching from it (I still call it when the app is destroyed) and use the cached AR view in setContentView. This works fine on JB Nexus S and JB Galaxy Nexus but I still get an empty cam view after going back to AR on older devices. So it looks like this behavior is the same regardless of using fragments and the real issue is that AR onDestroy should not be called while removing it from scene while some activity is happening there.
And I'm a bit stuck here :(
I have a version that is working across all devices but has a seg fault and I have a seg fault free version which doesn't work on older devices.
Please advice.
M
Markus Eder
said
almost 9 years ago
Hello!
Can you tell me more about your project setup, especially are you using a ViewPager to switch between your fragments? If that's the case you could prevent that the ArchitectView is destroyed when you switch between Fragments, by overriding the destroyItem-method of the FragmentPagerAdapter class, as can be seen in this example:
Hope that helps,
Markus
Y
Yegor Vedernikov
said
almost 9 years ago
Hello Markus,
I'm not using the ViewPager, should I? Also, I've already mentioned above that I can overcome the seg fault issue with onDestroy but then the solution doesn't work with 2.2, 2.3 devices (empty cam view).
General project setup is as follows:
- min sdk is android-8
- main activity with 3 switching views/fragments (AR, list, map) which are updated with live data
- data service class (not a service) fetching data in a background thread
- other minor activities launched from the main one
Application tracks the current location and provides a feedback in form of relevant POIs displayed in form of AR markers / List entries / Map pushpins).
Relevant code for AR view (for the version using fragments):
public abstract class PoiView
extends Fragment
{
...
}
public class ARPoiView
extends PoiView
implements ArchitectUrlListener
{
public ARPoiView()
{
super("Augmented Reality");
}
@Override
public void onDetach()
{
super.onDetach();
((ViewGroup)_architectView.getParent()).removeView(_architectView);
}
public View onCreateView(final LayoutInflater inflater,
final ViewGroup container,
final Bundle savedInstanceState)
{
_logger.debug("onCreateView");
if (_architectView != null)
return _architectView;
final View view = inflater.inflate(R.layout.poi_ar, container, false);
_architectView = (ArchitectView) view.findViewById(R.id.architectView);
// onCreate method for setting the license key for the SDK
if (_architectView != null)
_architectView.onCreate(LICENSE_KEY);
doPostCreate();
return view;
}
@Override
public void onPostCreate()
{
_logger.debug("onPostCreate");
// doPostCreate();
}
private void doPostCreate()
{
_logger.debug("doPostCreate");
if (_architectView == null)
return;
// IMPORTANT: creates ARchitect core modules
_architectView.onPostCreate();
// register as handler of "architectsdk://" urls
_architectView.registerUrlListener(this);
try
{
_architectView.load("world.html");
}
catch (final IOException e)
{
_logger.error("failed to load AR world", e);
}
}
@Override
public void onLowMemory()
{
if (_architectView != null)
_architectView.onLowMemory();
}
@Override
public void onPause()
{
_logger.debug("onPause");
super.onPause();
if (_architectView != null)
_architectView.onPause();
}
@Override
public void onResume()
{
_logger.debug("onResume");
super.onResume();
if (_architectView != null)
_architectView.onResume();
}
@Override
public void onDestroy()
{
_logger.debug("onDestroy");
super.onDestroy();
// if (_architectView != null)
// _architectView.onDestroy();
}
@Override
public void onDestroyActivity()
{
super.onDestroyActivity();
if (_architectView != null)
_architectView.onDestroy();
}
...
}
M
Markus Eder
said
almost 9 years ago
Hello!
We've tested the usage of the ArchitectView in Fragments mostly using ViewPager and FragmentPagerAadapter, so maybe you wanna try out that way as well. The problem on 2.2 and 2.3 devices you mentioned is related to the Android Webkit implemententation on those devices. The ArchitectView is currently optimized for usage in activities and therefore this problem doesn't exist in those scenarios. We are working on a solution for that problem for your scenario and will include it in the upcoming release of our SDK.
Hope that helps,
Markus
Y
Yegor Vedernikov
said
almost 9 years ago
Hello Markus,
Unfortunately ViewPager didn't work out for us. We have a requirement to have 2 map views available in application and it's not possible with ViewPager concept. Also it only works for old devices if we use FragmentStatePagerAdapter with destroyItem() overriden to skip destroying the item which probably keeps all the views in memory and Andreas already mentioned this as a bad practice.
We have switched to use the separate activities for our views and the problem doesn't seem to reproduce any more.
Thanks for your hints.
Yegor Vedernikov | https://support.wikitude.com/support/discussions/topics/5000075913 | CC-MAIN-2021-39 | refinedweb | 3,419 | 61.33 |
digitalmars.D - C++ traps that D2 doesn't avoid yet?
- bearophile <bearophileHUGS lycos.com> Nov 05 2008
- Walter Bright <newshound1 digitalmars.com> Nov 05 2008
- Walter Bright <newshound1 digitalmars.com> Nov 05 2008
- bearophile <bearophileHUGS lycos.com> Nov 06 2008
- Walter Bright <newshound1 digitalmars.com> Nov 06 2008... The nice thing of that list is that I think most (maybe 80-90%) of those traps and pitfalls (and several others that aren't listed, like allowing simple syntactical mistakes like putting a & where a && was requires or vice versa, etc) can be avoided by a language like D with little or no penalty in running space and time (and actually D avoids several of them already), but to avoid some of them you have to pay the price of sometimes having to step away from C/Java syntax,). Bye, bearophile
Nov 05 2008
bearophile wrote).
The trouble with this is when translating code. For example, take the md5 algorithm which is published in C, and translate it to D. It has some fairly complex arithmetic expressions in them. Do you know how they work? I don't. I have no idea. I doubt hardly anyone interested in translating them does. This means that if the meaning of an expression *silently* is altered by transliterating them to D, the new md5.d will give wrong results and it will be very difficult for the programmer to figure out where the problem is. This is why when D changes the semantics, it tries to restrict itself to changes that will produce compile time errors if the C is not transliterated correctly. For example, the C-style cast gives an error when it appears in D code, which prompts the user that some changes are necessary.
Nov 05 2008
bearophile wrote...
At a glance, D does resolve a lot of them. But preparing a detailed response to his list is many hours of work.
Nov 05 2008
Walter Bright:At a glance, D does resolve a lot of them. But preparing a detailed response to his list is many hours of work.
I have removed the most obvious ones and cleaned up the list a little: 1) C++ is officially based on C. C features like name hiding can interfere with C++ features like function overriding. 2) Function name overloading is convenient and good when appropriate; but confusing if misused. Be careful that overloading and name hiding don't interfere. 3) Primitive operands, arguments and returns get converted to their operators' and functions' expectations. 4) The presence of templates means that class member declarations involving a pointer to a template parameter might be interpreted as multiplication if you don't disambiguate with "typename". 5) Because the default for both objects and primitives is to pass to and from functions by copy, copy constructors are called more often than one might first imagine. 6) The special functions will be used more than a sub-guru C++er would imagine. C++ makes copies and temporaries under several circumstances. Special functions have even more reason than usual to avoid side-effects and to be very careful about throwing. (And never throw from a destructor.) 7) C++ doesn't take the attitude that incorrect primitive operand or argument types should be compile errors; it assumes you meant what you wrote and want the operands and arguments to be converted. 8) Although you can start an identifier with an underscore, you shouldn't. Leading underscores are added to identifiers by C++ translators. 9) You might find bizarre things happening if you have an identifier like bitor or compl. They are alternative keyword forms of | and ~. 10) Tidying up columns of numbers with leading zeroes turns them into octal (base 8) numbers. 11) It's not an error to have two character symbols within the single quote marks of a char literal (constant). 12) The encodings for char and wchar_t are not defined. Don't assume ASCII or Unicode. 13) Literal floating-point values (constants) do not have type float; they have type double. 14) Dividing by zero doesn't result in an exception. It results in undefined behavior. You must check your divisors yourself. 15) Because assignment expressions are expressions and evaluate to values, and because values can frequently be converted to bool, accidentally using assignment where you meant comparison will almost always compile and fail silently at run-time 16) The order in which operands are evaluated is not defined. The fact that, for example, addition is defined to be left-associative, doesn't necessarily mean that the operands of the addition operator are evaluated from the left. 17) The operands of logical and and logical or are evaluated from the left; however, there is a new uncertainty: not all the operands need be evaluated at all. 18) Variables can hold values or pointers; and this applies to objects of class type as well as primitives. Be careful you don't assign to a pointer thinking it's a value, or vice-versa. Consider "Hungarian naming". 19) Under assignment, when a pointer to an object is assigned another pointer to an object, they end up pointing at the same object. However, if an object-holding variable (or a reference to an object) is assigned another object, it becomes some kind of copy. 20) The increment (but not the decrement) operator can be applied to bool! It will set it to true whatever it was. 21) The precedence order of some operators including the assignment operators and the conditional (arithmetic if) was changed in ISO C++. 22) Whether you use curly brackets or not, selection and iteration statements control blocks. And the block begins at the opening parenthesis, not at the opening curly bracket (if there is one). 23) Selection and iteration statements should be controlled by boolean expressions, but it is not a compile error to put in numeric expression. 24) Although the (somewhat redundant) parentheses that hold the control logic are mandatory, curly brackets are not. Don't leave traps for maintenance programmers always put the curly brackets in. 25) The = symbol is actually the assignment operator, so it's all too easy to say "if I can assign b to a" rather than "if a is equal to b". In C++, because numeric results can be converted to bool, such mistakes usually compiles, to fail silently later. 26) If you don't put the curly brackets into an "if", it will be difficult to tell which "if" an "else" belongs to, if the "if" is, or ever becomes, nested. 27) The switch statement is really a slightly-tarted-up goto. This hints that maybe the switch should be avoided. 28) The switch statement involves just one block. The sections within are demarcated only with statement labels. You will need break statements after each (including the last for maintainers) section. 29) Accidentally drop one of the colons (:s) of a scope resolution operator, and you might just end up with a labeled statement. 30) A switch gets exponentially more difficult to maintain. One new type to be handled can involve updating many, many switch statements. Contrast this with adding a new class behind a polymorphic type. Prefer object-orientation over switches. 31) Many, many examples of the for statement have i++ to increment the loop counter. If i is an int, it's not really significant, but there's always a chance that it might become an iterator, and then ++i is more efficient and here does just the same as i++. 32) A C++ compiler isn't required to report an error if a value-returning function has no return statement. 33) (-PI <= theta <= PI) is always true, because the first comparison results in true or false which then convert to 0 or 1 which are both less than PI. In languages that don't convert boolean the expression is thankfully a compile error. 34) This is almost an anti-trap since consts are nearly always good. However, if you forget to make your query-only member functions const, then const objects of your class won't be able to accomplish much. 35) Applying delete to a pointer doesn't set it to zero; but you should probably consider doing so. 36) Incorrectly accessing an array of arrays (when simulating a multi-dimensional array) as arr[i, j] instead of arr[i][j] is not a compile error even though it won't do what you probably expect. 37) References create aliases for identifiers. Be careful not to end up doing daft things like self-assignment. Self assignment might go horribly wrong for classes with badly-written copy assignment operators. 38) Do not return via references unless you are absolutely sure that you know exactly what you are doing. (And make sure you know if and how your compiler supports the return value optimization.) 39) Don't try to be tidy by including empty parentheses when initializing object in variables via the default constructor. You will actually declaring parameterless functions instead. 40) Don't think of public as meaning the same for data and function members. Public data members can be accessed; but public member functions can't be called. Public member functions define the signatures of messages that all other objects can send. 41) Unlike, say, Smalltalk, C++ has class-level encapsulation. An object isn't prevented from accessing the private data members of another instance of its class. Apart from the copy constructor and the copy assignment operator, don't allow one instance to access the data of another instance. 42) C++ doesn't enforce the private access category for data members. One day you'll be tempted to make a data member of a base class protected. Resist. Don't do it. From that moment on, the base class becomes unmaintainable. 43) Object instance arguments are passed by value, i.e. by copying. But forget to provide the copy constructor and one will be provided for you. And Finagle's Law says that anytime you do forget, the implicit copy constructor's behavior won't be right. 44) Forgotten parentheses on an argumentless message or call will often compile because a function's address is a valid numeric expression. 45) Const objects can change. While passing out a pointer (or reference) to a data member is hardly a subtle trap, data members can be declared mutable however; so we hope that such data member have been designed to be undetectable from outside their object. 46) Static data members are close to global. Static member function uses are close to calls (rather than messages). Overusing static members takes one away from object-orientation and towards the less useful class-orientation. 47) Never mix up the two initialization syntax schemes of "=" and "()". Try to always use ()-style initialization. Never, ever allow the initialization of an object of class type to involve = and () at the same time. 48) The C memory mechanisms malloc and free still exist in C++, of course. It's not a compile mistake to free() something newed or to delete something malloc()ed; just lethal. 49) It's not a compile error to "delete" (rather than "delete[]") something that was "new []"ed. It's almost certainly a memory problem though. 50) To realize how quickly it could become impossible to decide who takes out the garbage, one only has to recall that the default argument passing and return mechanisms are by-copy; and that the implicit copy constructor does shallow copy. 51) Looking for smart pointers to help with garbage collection and with polymorphic collections, one turns to the library. But the smart pointer one finds there auto_ptr mustn't be used for either of those purposes. 52) Don't pass an auto_ptr to a function by value. The auto_ptr will be copied and the copy will become the owner When the function finishes, the local copied auto_ptr goes out of scope and it will delete what it was pointing at. 53) Almost uniquely among languages today, C++ allows one to store entire objects in variables. This leads to no end of complications; and certainly leads to the special functions being special. 54) A class without constructors may well have implicit constructors. There are only two circumstance when an implicit copy constructor wouldn't be provided; and only a few more where a default constructor wouldn't. And the implicit ones are public. 55) People sometimes try to call one constructor from another. Don't. You can write something that looks like it might just be a call to a constructor but it won't be. Constructors are always declaration statement stuff rather than expression statement stuff. 56) A one-argument constructor will be implicitly used as a conversion function (argument type to class type) unless you say not to with the "explicit" keyword. And constructors with default parameter values might be also be considered single-argument. 57) Another reason not to use the = sign in declaration/initialization is to avoid encouraging the mistaken belief that the copy assignment operator would be used. It wouldn't be. The copy constructor will be used for both = style and () style initialization. 58) The implicit copy constructor effectively does shallow copy it copies pointers but not pointees. 59) Lulled into complacency by constructor chaining, you might imagine that the copy assignment operator automatically chains as well. It doesn't. You will probably want to though. 60) Data members holding objects of class type are default constructed before the constructor's code block runs. Initialize them via the member initialization list instead. 61) If you initialize an object of class type via {} expression lists, almost any change to the class will invalidate such an initialization. 62) The order of initializers in a member initialization list is irrelevant. Don't try, in a member intiailzation list, to initialize one member in terms of another unless you know the initialization order rules. 63) Although destructors can be called explicitly, it is an exotic and probably dangerous thing to do. Be happy with automatic calling of destructors. 64) The implicit destructor is non-polymorphic (non-virtual). Just about everyone, just about all the time must consider whether their destructor should be polymorphic (virtual); and probably conclude that it should be. 65) You might not think you need a destructor, but unless you can prove that your class could never be a base class, you should provide a virtual (not pure virtual) destructor, even it is has an empty code block. 66) Remember that neither the number of arguments nor their position contribute to the "name" of a member function. So an overload of unary +, say, in a derived class would hide a binary + in a base class. 67) Operator overloads are inherited but the implicit copy assignment operator usually hides any base class copy assignment operator. 68) You can't make && or || (or ,) operator overloads work intuitively, so don't provide them. (You can't mimic guaranteed operator evaluation order or lazy evaluation with member functions.) 69) You might be tempted to provide operator bool in order that your objects can easily be tested for validity. But beware that once your objects can be converted to bool, they can also be converted to int. 70) [Well known but] Not only is int converted to long, for example, but long is converted to int, and float is even converted to int. If you're lucky, a friendly compiler will issue a warning. So treat C++ compiler warnings as though they were errors. 71) Inheritance of implementation has not turned out to be the labor-saving device we thought it would be. (Unlike composition, it doesn't function through low-coupling, program-by-contract messages.) 72) While the maintainability of the derived classes goes up because of factoring, the maintainability of the base class rapidly goes down. So be sure your code is stable before you start introducing inheritance of implementation. 73) Given the fragility of base classes, they should always be destined and designed to be base classes. A class should never just slip into becoming a base class. Design your concrete, derived classes so that they could never become base classes. So why don't we ban inheritance? Because there's something more important than implementation to inherit. Public inheritance gives objects extra types; it supports polymorphism. 74) Private data members are present in the instances of derived classes. They just can't be accessed by derived class code (which is a good thing). 75) The class keyword brings private access for the members. But that includes inheritance; and private inheritance is not the object-oriented way. Private inheritance is the (now not very popular) mixin way. 76) Don't be trapped into mentioning base class names any more than you have to. Use the "typedef BaseClass super" trick to avoid it. And don't use any class name as part of a function name. 77) [As mentioned earlier] Beware if you think you're overloading a member function from a base class. A derived class member function with the same name as a base class member function name-hides the base class one. A using declaration can sort this out. 78) Unless you use virtual member functions, C++ doesn't give you polymorphic behavior. By default C++ uses the pointer type to select member functions. That way lies redundant overriding and inconsistent binding. 79) Don't be misled into thinking that there's anything "ghostly" or "not really there" about virtual member functions. Pronounce "virtual" as "polymorphic". (The ghostly ones are the pure virtuals.) 80) It's not a compile error to forget to pass a derived class object by pointer or reference, when the parameter declaration was for a base class object. What will happen is that the derived bits will be "sliced" off as the argument is copied onto the stack. 81) Although making a member function polymorphic (virtual) means that the object selects the member function, it's still the pointer type that selects the access category. If you override a member function in a different access category, a) we hope you've done it to be more restrictive, not less, and b) the type of the pointer chooses the access category determining class. 82) Don't be misled by the unforgivably obscure syntax (= 0) into thinking that pure virtual member functions are some dark and dusty corner that is to be ignored. They are pivotal to good OO. 83) Don't imagine that a class with no code and no data members is worthless. A class with nothing but pure virtual member functions (a pABC) is an excellent and simple type that classes can implement. 84) Don't by misled by some books (or even libraries and frameworks) into thinking it's OK to instantiate base classes. It's almost never a good idea you end up with a class doing three jobs, and two is bad enough. 85) If you disregard the earlier advice to allow one or none of your base classes to have implementation, you will also and always have to consider whether your inheritance should be virtual inheritance. 86) Don't imagine that because the RTTI (run-time type identification) was introduced, you should use it. Treat "What's your class?" as a rude question and use it only once in a blue moon. Overuse of the RTTI probably indicates an architecture that is failing not having enough 1:m association relationships or the 1:m association relationships having the wrong types. 87) It's not an afterthought (I hope) that the type_info object supports one in avoiding mentioning a class by name. Avoid building class names into anything but declarations. And even in declarations avoid concrete class names as types. 88) Putting "using namespace std" makes a very large set of unseen names available to clash in "what on earth's going on" kinds of ways with your identifiers - particularly at some point in the future. 89) There might be more namespaces than you thought in which C++ will look for a function. C++ also searches for a function in the namespaces in which any of a function's arguments of class type are defined. 90) If any function you call (or that it calls, or ...) could throw, you need to be an order of magnitude more careful a programmer than you would otherwise have needed. 91) A derived object catcher that follows a catcher for its base class can never be reached. 92) Although you don't have to catch exception objects by reference, getting into the habit of doing anything else is asking for trouble. See bit slicing. This list isn't complete, there are several things we have discussed in the past that aren't listed there. And then, there are other traps/troubles not listed there because specific of D and probably absent from C++. Bye, bearophile
Nov 06 2008 | http://www.digitalmars.com/d/archives/digitalmars/D/C_traps_that_D2_doesn_t_avoid_yet_79361.html | CC-MAIN-2014-42 | refinedweb | 3,496 | 64.1 |
CLOCK_GETTIME(2) BSD Programmer's Manual CLOCK_GETTIME(2)
clock_gettime, clock_settime, clock_getres - get/set/calibrate date and time
#include <sys/time.h> int clock_gettime(clockid_t clock_id, struct timespec *tp); int clock_settime(clockid_t clock_id, const struct timespec *tp); int clock_getres(clockid_t clock_id, struct timespec *tp);
The clock_gettime() and clock_settime() allow the calling process to re- trieve or set the value used by a clock which is specified by clock_id. clock_id can be one of four values: CLOCK_REALTIME for time that incre- ments as a wall clock should, CLOCK_VIRTUAL for time that increments only when the CPU is running in user mode on behalf of the calling process, CLOCK_PROF for time that increments when the CPU is running in user or kernel mode, or CLOCK_MONOTONIC for time that increments at a steady rate (monotonically). The structure pointed to by tp is defined in <sys/time.h> as: struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* and nanoseconds */ }; Only the superuser may set the time of day. If the system securelevel is greater than 1 (see init(8)), the time may only be advanced. This limita- tion is imposed to prevent a malicious superuser from setting arbitrary time stamps on files. The system time can still be adjusted backwards us- ing the adjtime(2) system call even when the system is secure. The resolution (granularity) of a clock is returned by the clock_getres() call. This value is placed in a (non-null) *tp.
A 0 return value indicates that the call succeeded. A -1 return value in- dicates an error occurred, and in this case an error code is stored into the global variable errno.
The following error codes may be set in errno: [EINVAL] The clock_id was not a valid value. [EFAULT] The tp argument address referenced invalid memory. [EPERM] A user other than the superuser attempted to set the time.
date(1), adjtime(2), ctime(3), timed(8)
The clock_gettime(), clock_settime(), and clock_setres() functions con- form to IEEE Std 1003.1b-1993 ("POSIX"). MirOS BSD #10-current May 8,. | http://www.mirbsd.org/htman/i386/man2/clock_gettime.htm | CC-MAIN-2016-07 | refinedweb | 336 | 52.7 |
Hide Forgot
upstream has new version 3.0.0, it was released on 2006-12-23
We've been hesitating to bump CherryPy because the current version of TurboGears
does not work with v3.0. TG 1.0.2 should be coming out next week, so I'll be
pulling CherryPy 3.0 in shortly.
Now that TurboGears 1.0.2 is out, this is no longer a barrier to CherryPy 3.
TurboGears 1.0.2.2 does not yet support CherryPy 3.
15:14 #turbogears: Lawouach> lmacken: from what I gathered I don't think the
TG core team will focus on CP3 for TG2 and I
doubt they'll spend much of their time on TG1.x
Hmm. Luke, do you think it is sensible to wait for TG to support CP3? If I
understand comment #4 correctly, the TG team doesn't plan to support CP3 with
TG2 either... which would be very unfortunate.
Perhaps we could package CP2 separately for TG, e.g. into a different tree and
extend sys.path so TG uses CP2 rather than CP3 if both are installed. What do
you think?
Yeah, it's definitely not sensible to wait for TG.
I was thinking we could either,
- create python-cherrypy3 package, and keep python-cherrypy the 2.x branch
or
- create python-cherrypy2 package, and keep python-cherrypy up to date with
latest (3.x for now)
Is there anything else we could / should do instead ?
What do you guys think?
The Packaging Guidelines currently want the latest version to have <packagename>
and earlier versions to have <packagename><majorversion>. I'm trying to get
that relaxed in today's Packaging meeting so hopefully either one of these
packages, python-cherrypy3 or python-cherrypy2 will be fine.
What I'd suggest is playing around with eggs to see if we can parallel install a
python-cherrypy2 that turbogears can continue to use with import cherrypy. I
think both python-cherrypy2 and python-cherrypy3 will need to be installed this
way in order to work. (Installing one the "normal" way and the other as an egg
should allow us to escape filesystem conflicts but I think we need to use eggs
for both so that setuptools can decide which module version is to be used.)
I can help get the Packaging Guidelines changed to accomodate eggs as well.
I've started a packaging draft to add to as we figure out how to use eggs to our
advantage:
Hey Ignacio, do you have any suggestions for supporting parallel installs of
CherryPy{2,3} ?
Well, the way I see it we have 2 options for supporting parallel installs.
The first is to rename one of the packages. We would need to e.g. rename the
package in cherrypy 2.x to cherrypy2, then modify all scripts that currently use
cherrypy 2.x to use it. It's not pretty, but it would certainly work.
The second is to use alternatives, with either eggs or renamed packages. I get
nauseous just thinking about this option, but it is there.
There is, of course, a third option. We could forgo supporting parallel installs
entirely and just have the 2 packages conflict. While not a perfect solution, it
may be the best.
(In reply to comment #10)
> Well, the way I see it we have 2 options for supporting parallel installs.
>
Really? I thought that this:
meant that you could have two eggs of different versions on the system and then
use this:
to constrain the version. No need for alternatives or renaming the modules.
Note that this is all book learning, I haven't played with actual eggs to see if
this is true, just that reading the docs seems to imply this. If I'm wrong just
point out my error so I can stop thinking that eggs will solve this problem :-)
(In reply to comment #11)
> Really? I thought that this:
>
>
> meant that you could have two eggs of different versions on the system and then
> use this:
>
> to constrain the version. No need for alternatives or renaming the modules.
But what if someone says "import cherrypy"? Which version does that load? 3? But
what if 3 isn't installed?
I'd say that the main package (usu. the latest version) would be imported from
import cherrypy. The cherrypy2 package will be treated as a compat package.
(Should it be named compat-python-cherrypy2?)
If the main package isn't installed then a bare import cherrypy will not work.
pkg_resources will have to be used. Packages wanting to select a specific older
version of cherrypy will have to use the pkg_resource API to select the older
version anyway...
Does this sound reasonable?
Created attachment 179621 [details]
First cut at a compat package spec file
I created this to test out the proposed Python Egg/python module compat
guidelines.
Created attachment 184281 [details]
Minor cleanups
Here's some minor cleanups to the spec for a new cherrypy2 package.
Created attachment 184301 [details]
Update to python-cherrypy.spec for 0.3
Here's a python-cherrypy.spec updated to 3.0
Those two spec files parallel install cherrypy with the following characteristics:
1) python-cherrypy is installed such that import cherrypy imports it.
2) python-cherrypy2 is available by doing::
import pkg_resources
pkg_resources.require('cherrypy < 3.0beta1')
import cherrypy
3) Since cherrypy does not use setuptools or provide eggs by default these
packages don't provide eggs in the default branch. This means that you cannot
use pkg_resources to load cherrypy3.
These mostly follow the draft guidelines posted on::
The only thing I know is wrong is that I forgot to write and include a
README.fedora for python-cherrypy2 that explains it is as compat package and how
to use pkg_resources.
If you think the draft has issues, please get back to me before Tuesday next
week (when the packaging committee will talk about them and vote.)
Looks good to me.
The only thing that requires cherrypy2 is TurboGears, and we currently patch the
"CherryPy >= 2.2.1,<3.0.0alpha" out of our setup.py. So, theoretically if we
leave that in there, we should be good to go ?
Theoretically. Of course I'm trying to get it working now and it's having
difficulties. TurboGears needs to find eggs for the packages listed in
requires.txt but it seems that it doesn't do the equivalent of
pkg_resources.requires() on them so we are getting the cherrypy3 version instead
of cherrypy2.
I'm looking at the pkg_resources code right now to see if I can find the problem.
Created attachment 184641 [details]
Setuptools patch
I sent this to the distutils list and setuptools maintainer to look over. Once
they let us know if some version of it can go into seutptools, I'll try to get
it applied to our setuptools package. Parallel install works with this and
with the CherryPy requirement in TurboGears added back in. We also need to set
a maximum version on the SQLAlchemy requirement:
SQLAlchemy>=0.3,<0.4.0beta1
And get the python-sqlalchemy0.3 package reviewed.
I think all our ducks are lined up now.
* Egg Guidelines have been approved
* setuptools has been upgraded in F-8.
* We have a method for making TurboGears start-APP.py scripts use the compat
modules.
Since we're currently in freeze for F-8 we need to decide whether we'll be doing
this as an F-8 update after initial release or for F-9 only.
(In reply to comment #21)
> Since we're currently in freeze for F-8 we need to decide whether we'll be doing
> this as an F-8 update after initial release or for F-9 only.
As TG is AFAIK the only component relying on cherrypy (and I guess it works),
perhaps you should check with release engineering whether an exception can be
made to get cherrypy3 into F8 proper. A zero day update from 2.x to 3 doesn't
make much sense...
still not fixed in Fedora 7, 8 or rawhide :-/
I'd also like to add my hope for this bug. A program I use (which I'd love in
Fedora 8) called rdiff-web:
is now blocked by this as they don't support CherryPy 2.x anymore.
(In reply to comment #24)
> I'd also like to add my hope for this bug. A program I use (which I'd love in
> Fedora 8) called rdiff-web:
>
>
>
> is now blocked by this as they don't support CherryPy 2.x anymore.
I should add it's the "testing" version of rdiff-web, but there are many
improvements in the testing branch that I might need.
(In reply to comment #24)
> is now blocked by this as they don't support CherryPy 2.x anymore.
Also I got cherrypy with fastcgi using python-flup only with cherrypy 3 working.
I do not know, whether using the old cherrypy works, but with version 3 it
worked like it was documented.
I've got a suggestion:
I need to submit a python-cherrypy2 package so we can move to cherrypy3 on
rawhide but that's not going to help people get their packages running on F7/8.
What does everyone think of a python-cherrypy3 package for F8(possibly F7)?
Good idea?
I'll submit my python-cherrypy2 package for review so that you have a spec file
to base off of. The maintainers of python-cherrypy3 should probably sign up as
comaintainers of python-cherrypy and vice versa so we're all in the loop.
python-cherrypy2 compat package for rawhide has been submitted::
If someone wants to help review and test that, it will help move this along in
rawhide. If someone wants to adapt the spec for a python-cherrypy3 package for
F8, I can help review that.
The review in #429007 has been completed. Changes to update python-cherrypy in
rawhide and the python-cherrypy2 compat package are checked into cvs. I'll wait
until tomorrow to build them so as to avoid breaking things just in time for the
alpha release. If you want to get an early start on testing, download the
packages from
The relevant packages are
We need to confirm that the two packages can coexist with CP3 being the default
and TurboGears using the CP2 package.
Rawhide packages built::
python-cherrypy2-2:
python-cherrypy-3:
Brief testing shows that we're able to select between the versions as expected
in the python shell. The ipython shell doesn't work, however. It must be
overriding the standard import somehow....
Once we restore this line in the rawhide TurboGears setup.py file, TurboGears
apps will run as well:
"CherryPy >= 2.2.1,<3.0.0alpha",
I'll leave this bug open until that change is made but otherwise I think we're
about done.
python-cherrypy-2.3.0 stable repository. If problems still persist, please make note of it in this bug report.
python-cherrypy-2.3.0-3.fc8 has been pushed to the Fedora 8 stable repository. If problems still persist, please make note of it in this bug report. | https://bugzilla.redhat.com/show_bug.cgi?id=224683 | CC-MAIN-2020-34 | refinedweb | 1,871 | 74.19 |
A while back I got tired of looking for a simple solution to performing 'on the fly' XSL Transformations. I didn't want some memory-hog tool to completely isolate me from the details of the transform through layers of abstraction—just a light-weight tool that would act as a simple transformation engine. I just needed something to run a transform based on my stylesheet and let me quickly check the results in an iterative fashion. I looked for a while, and didn't find anything like that available. So I built my own simple solution. It wasn't much—just a simple WinForm where I could specify the location of an XML file and a corresponding XSL file and then push a button to fire the results of the transformation to a text box for review. While that worked fine, I recently decided that my home-grown solution needed a bit of a face-lift. Nothing dramatic. Just a few tweaks to make it easier to fine-tune my stylesheets on the fly.
To keep things simple, I just wanted the added ability to edit my XML and XSL (mostly the latter) documents in the same tool that I used to transform them. I'd been using either an open instance of Visual Studio to edit them (nice, but heavy), or NotePad. In a perfect world, I'd get some of the key benefits of an editor like Visual Studio, but with the "weight" of something like NotePad. NotePad is actually fine for editing text files—only I hate the fact that it doesn't remember my tab position. In other words, if I've "tabbed over" three times (for formatting purposes) and type something followed by a carriage return, I'm back at the left margin, and not tabbed to the place where I was in the previous line. So, my thoughts on the upgrade were that if I could just get the text boxes where I would be doing my editing to remember my tab position, then I'd be happy. Only... I really like having tag completion in Visual Studio as well. It's not like I can't do it myself, but I certainly like having my tags closed automatically. So, I figured I needed both aspects in my new "editor" enabled version of my transform tool to make me happy.
Figuring out how to remember tab positioning turned out to be tougher than I imagined—but in a strange way. Coding the solution wasn't very hard at all, and only took about half an hour to perfect. The hard part was figuring out that I had to code it myself. For some reason I figured that something in the Framework would make the task almost as easy as tweaking a property on one of the built-in TextBox controls that ship with the Framework. After poring over the MSDN docs, trying to track down existing solutions on the web, and bugging a listserve that I spend a lot of time on, I decided to just write the functionality myself.
Once I made the decision to code the functionality myself, the task became fairly easy. The trick was just to figure out what the number of preceding tabs were in the previous line, and plunk the same number of tabs in front of the cursor each time that a carriage return was detected. The logic to handle all of this was pretty simple and just revolved around getting a handle on the textbox housing the desired text, and then calculating the preceding line and existing tab count. Once those were located, all I had to do was insert a corresponding number of tabs into the textbox at the current position, and then advance the cursor by moving the SelectionStart property:
Visual C#
private bool HandleBlockTabbing(object sender){ TextBox current = (TextBox)sender; int charIndex = current.SelectionStart; string work = current.Text.Substring(0, charIndex); int currentLineNumber = current.GetLineFromCharIndex(charIndex); // the carriage return hasn't happened yet... // so the 'previous' line is the current one. string previousLineText; if(current.Lines.Length <= currentLineNumber) previousLineText = current.Lines[current.Lines.Length - 1]; else previousLineText = current.Lines[currentLineNumber]; if (previousLineText.StartsWith("\t")) { string tabs = string.Empty; // first non-TAB character Match m = Regex.Match(previousLineText, "[^\t]"); if (m.Success) tabs = previousLineText.Substring(0, previousLineText.IndexOf(m.Value)); else // there were only tabs (no other chars) tabs = previousLineText; string added = "\r\n" + tabs; current.Text = current.Text.Insert(charIndex, added); current.SelectionStart = charIndex + added.Length; return true; } return false;}
Visual Basic
Private Function HandleBlockTabbing(ByVal sender As Object) As Boolean Dim current As SimpleEditBox = CType(sender, SimpleEditBox) Dim charIndex As Integer = current.SelectionStart Dim work As String = current.Text.Substring(0, charIndex) Dim currentLineNumber As Integer = current.GetLineFromCharIndex(charIndex) ' the carriage return hasn't happened yet... ' so the 'previous' line is the current one. Dim previousLineText As String If current.Lines.Length <= currentLineNumber Then previousLineText = current.Lines(current.Lines.Length - 1) Else previousLineText = current.Lines(currentLineNumber) End If If previousLineText.StartsWith("" & vbTab) Then Dim tabs As String = String.Empty ' first non-TAB character Dim m As Match = Regex.Match(previousLineText, "[^\t]") If m.Success Then tabs = previousLineText.Substring(0, previousLineText.IndexOf(m.Value)) Else tabs = previousLineText End If Dim added As String = (vbCrLf + tabs) current.Text = current.Text.Insert(charIndex, added) current.SelectionStart = (charIndex + added.Length) Return True End If Return FalseEnd Function
One big thing to note about the above code is that it's taking place in the KeyPress event—so the carriage return hasn't really "happened" yet; it's currently in the state of being processed. But once the KeyPress event is handled for a carriage return, the logic above makes a screen shot like the one below possible:
The cool thing is that in the above screen shot, the logic discerned that the previous line was one tab over and then just inserted a carriage return plus a single tab into the current line of text (technically the third line of text, because the carriage return hasn't actually happened yet). Once that was put in place, the current selection was advanced to the end of the carriage return and the newly inserted tab. Then the textbox was "told" that the keystroke was handled (the return true part of the code—more on that in a second), and the textbox therefore doesn't need to do any more processing on the keystroke (like add a carriage return of its own). The beauty of this approach is that there are no spooky characters in place; a simple BACKSPACE will remove the existing tab. It's like we've just used the textbox to do our typing for us, that's all.
return true
I initially figured that tag completion would just be a question of using a regular expression to determine the name of the currently uncompleted tag (if there was one) each time a ">" was detected, and then adding closing tags as needed. It turned out to be about that hard, only I needed to account for directives, comments, and empty tags as well. I also needed to be able to account for stray ">" characters. The goal of my tag completion was to create functionality that was more like cruise control (a lazy person's driving aid), instead of an auto-pilot (where you'd effectively give up control of what was going on). To handle all of these contingencies, I just threw in a helper method where I could encapsulate all of the various permutations and just report to the caller (main logic) if it was to close the tag or not. Here's the code to handle the detection of a ">" in the KeyPress event:
Note that, in many ways, it's very similar to the code that handles tabbing: it just determines if characters need to be added, and then inserts them if needed. The difference is that it only advances the cursor one space when it's done doing the inserting task, so as to place the cursor between the beginning and ending tags. Whether or not the tag needs to be closed is decided by the following bit of helper logic:
private bool CurrentPositionNeedsClosingTag(string input){ string scrubbedText = input.Replace("\r", string.Empty); scrubbedText = scrubbedText.Replace("\n", string.Empty); scrubbedText = scrubbedText.Replace(" ", string.Empty); // check lots of various tag ending types, and then other issues/hacks // ignore directives, comments, and empty tags: bool isDirective = scrubbedText.EndsWith("?"); bool isComment = scrubbedText.EndsWith("--"); bool isEmptyTag = scrubbedText.EndsWith("/"); if (isDirective || isComment || isEmptyTag) return false; // watch out for stray tags and truly empty tags ("<>") if (scrubbedText.EndsWith(">") || scrubbedText.EndsWith("<>")) return false; // watch out for explicit closing tags // ("</endMyTagByHand>" - don't want: "</end><//end>") // HACK: should be done with a regex.. int position = scrubbedText.LastIndexOf("<"); if (scrubbedText.Substring(position).StartsWith("</")) return false; return true;}
Private Function CurrentPositionNeedsClosingTag(ByVal input As String) As Boolean Dim scrubbedText As String = input.Replace(vbCr, String.Empty) scrubbedText = scrubbedText.Replace(vbLf, String.Empty) scrubbedText = scrubbedText.Replace(" ", String.Empty) ' check lots of various tag ending types, and then other issues/hacks ' ignore directives, comments, and empty tags: Dim isDirective As Boolean = scrubbedText.EndsWith("?") Dim isComment As Boolean = scrubbedText.EndsWith("--") Dim isEmptyTag As Boolean = scrubbedText.EndsWith("/") If (isDirective _ OrElse (isComment OrElse isEmptyTag)) Then Return False End If ' watch out for stray tags and truly empty tags ("<>") If (scrubbedText.EndsWith(">") OrElse scrubbedText.EndsWith("<>")) Then Return False End If ' watch out for explicit closing tags ' ("</endMyTagByHand>" - don't want: "</end><//end>") ' HACK: should be done with a regex.. Dim position As Integer = scrubbedText.LastIndexOf("<") If scrubbedText.Substring(position).StartsWith("</") Then Return False End If Return TrueEnd Function
Once in place, the tag completion turned out to be pretty spiffy. It won't close comments, directives, or empty tags (i.e. <tag />); just open tags, even ones that span multiple lines:
<tag />
Coupled with the "tab memory" functionality, I now had enough editor functionality to make me happy.
When I was first testing out the tabbing and tag-completion logic, I just did it in a WinForm, and handled the KeyPress event. My long-term goal, though, was to create a subclass of System.Windows.Forms.TextBox that would encapsulate this logic away to make reuse much easier. Imagine trying to handle tabbing and tag-completion for three textboxes on the same form, for example; it could be done, but wouldn't be pretty. Creating the subclass of TextBox was very easy. I just added a new user control to my current project, changed its inheritance from UserControl to TextBox and then dropped in the code as follows:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing;using System.Data;using System.Text;using System.Windows.Forms;using System.Text.RegularExpressions;namespace XSLT_Former{ public partial class SimpleEditorBox : TextBox { public SimpleEditorBox() { InitializeComponent(); // make sure that tab and enter are allowed by // default in this specialized text box: base.AcceptsReturn = true; base.AcceptsTab = true; } protected override void OnKeyPress(KeyPressEventArgs e) { if (e.KeyChar == 13) // enter/carriage return e.Handled = this.HandleBlockTabbing(this); if (e.KeyChar == '>') e.Handled = this.HandleTagCompletion(this); base.OnKeyPress(e); } private bool HandleBlockTabbing(object sender) { // elided - code same as above } private bool HandleTagCompletion(object sender) { // elided - code same as above } private bool CurrentPositionNeedsClosingTag(string input) { // elided - code same as above } }}
Imports System.Text.RegularExpressionsPublic Class SimpleEditBox Inherits System.Windows.Forms.TextBox Public Sub New() ' This call is required by the Windows Form Designer. InitializeComponent() MyBase.AcceptsReturn = True MyBase.AcceptsTab = True End Sub Protected Overrides Sub OnKeyPress(ByVal e As KeyPressEventArgs) If (e.KeyChar = CType(ChrW(13), Char)) Then e.Handled = Me.HandleBlockTabbing(Me) End If If (e.KeyChar = CType(ChrW(62), Char)) Then e.Handled = Me.HandleTagCompletion(Me) End If MyBase.OnKeyPress(e) End Sub Private Function HandleBlockTabbing(ByVal sender As Object) As Boolean ' elided - code same as above End Function Private Function HandleTagCompletion(ByVal sender As Object) As Boolean ' elided - code same as above End Function Private Function CurrentPositionNeedsClosingTag(ByVal input As String) As Boolean ' elided - code same as above End FunctionEnd Class
As you can see, nothing special. The KeyPress event is no longer being handled; rather, the OnKeyPress method has been safely overridden such that this control can be further sub classed if desired. The big plus, of course, is that dropping a SimpleEditBox onto a WinForm provides a textbox that now remembers tab position and closes XML (and HTML) tags.
With a SimpleEditorBox control now available to handle the whiz-bang features for text editing, it was time to create a WinForm that I could use as a work area. In it I needed an area to display the XML document, an XSL document (or my stylesheet) as well as the output. I wanted all three areas to editable, but maximizing the space for each area would have been problematic to try and manage. So I cheated and just used two splitter controls to allow a high degree of flexibility at run time. The first splitter divided the top (work area) from the bottom (output/results area) so that either section could be sized as needed. The second splitter—placed in the top half of the previous splitter—was to divide the XML work area from the XSL work area as follows:
Each work area was then fitted with a few simple controls to allow for the loading and saving of files. A button to execute the transform was placed in the bottom of the form, which only becomes enabled once both work areas have a file loaded. By playing around with the Anchor properties for each control and GroupBox, each work area not only retains a decent perspective when the Winform is maximized, but as the sliders are moved around to focus on one are or the other, the other two areas maintain a decent aspect ratio as well (even when seriously "scrunched" so as to appear inside an image like the one below):
As seen in the above image, I'm focusing my attention on the transform, where I've dedicated more of my real estate by tugging on the splitter bars to the desired sizing. However, the output and XML areas are still coherent and could easily become the focus of my efforts just through some more dragging on the darkened splitter bars.
The logic to handle the transform itself ends up being some pretty simple code. All it needs to be able to do is stream the contents of the XML and XSL SimpleEditBoxes in as XML, and run them through a transform.
private void TransformOutput(){ string xml = this.edtXml.Text.Trim(); string xsl = this.edtXsl.Text.Trim(); try { // stream the xml: byte[] data = Encoding.UTF8.GetBytes(xml); MemoryStream ms = new MemoryStream(data); XmlReader input = XmlReader.Create(ms); // to allow modification by xform // load the xsl: XmlDocument stylesheet = new XmlDocument(); stylesheet.LoadXml(xsl); XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(stylesheet); // create output streams: MemoryStream buffer = new MemoryStream(); StreamWriter sw = new StreamWriter(buffer); // transform the document: transform.Transform(input, null, sw); // turn results into a string: byte[] chars = buffer.ToArray(); string output = Encoding.UTF8.GetString(chars); this.edtOut.Text = output; this.btnSaveOutput.Enabled = true; } catch (Exception ex) { this.edtOut.Text = "Error Occurred: " + Environment.NewLine + ex.Message; }}
Private Sub TransformOutput() Dim xml As String = Me.edtXml.Text.Trim Dim xsl As String = Me.edtXsl.Text.Trim Try ' stream the xml: Dim data() As Byte = Encoding.UTF8.GetBytes(xml) Dim ms As MemoryStream = New MemoryStream(data) Dim input As XmlReader = XmlReader.Create(ms) ' to allow modification by xform ' load the xsl: Dim stylesheet As XmlDocument = New XmlDocument stylesheet.LoadXml(xsl) Dim transform As XslCompiledTransform = New XslCompiledTransform transform.Load(stylesheet) ' create output streams: Dim buffer As MemoryStream = New MemoryStream Dim sw As StreamWriter = New StreamWriter(buffer) ' transform the document: transform.Transform(input, Nothing, sw) ' turn results into a string: Dim chars() As Byte = buffer.ToArray Dim output As String = Encoding.UTF8.GetString(chars) Me.edtOut.Text = output Me.btnSaveOutput.Enabled = True Catch ex As Exception Me.edtOut.Text = ("Error Occurred: " _ + (Environment.NewLine + ex.Message)) End TryEnd Sub
Exceptions are handled in a very simple fashion by just outputting the details of the exception to the output window. If no exception occurs, then the transform results are written to the output window. There they can be modified as needed or saved to disk using the menu options or button control available.
And there it is: a simple tool that allows you to get your hands dirty with the gory details of XSLT, along with a simple button that will render the transform for you whenever you are ready. The simple additions to the editor panes make it easier to perform ad hoc modification of the XML and XSL documents, and being able to render the transform on the fly helps make for a great way to modify your stylesheet in an iterative fashion.
If you would like to receive an email when updates are made to this post, please register here
RSS
Cool little utility, however the code snippets are missing the HandleTagCompletion() code.
Hi there
Check my own XSL transform tool:
it supports html-output preview and XML synthax highlightning
Thanks much. This was very useful.
Thank you. I used your code. Works fine.
Thank you. This little utility is quite useful and didactic as well :) | http://blogs.msdn.com/coding4fun/archive/2006/10/31/913470.aspx | crawl-002 | refinedweb | 2,889 | 55.24 |
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b12pre) Gecko/20110209 Firefox/4.0b12pre ID:20110209030359 We run into a huge memory leak which can also freeze the system, just by performing the following steps: 1. Create a fresh profile and stick the attached users.js file into it 2. Install the latest alpha version of Firebug 1.7 () 3. Open the given URL Within seconds the memory will be filled-up completely and the system can freeze. This is a regression and happened between Beta 7 and Beta 8. I will nail down the regression range tomorrow morning.
Created attachment 512631 [details] user.js
Regressed between the builds 10120903 and 10121003: PASS: FAIL: Pushlog: Could be related to the tracemonkey merge during that day. I will do a hg bisect tomorrow.
what advanced js settings are set? user_pref("javascript.options.strict", true); user_pref("pref.advanced.javascript.disable_button.advanced", false); why are you using strict? This is a known problem, believe we have bugs on it already.
If you use the strict option, you will get lots of warnings to the error console on pretty much any site. If Firebug saves all error console output, you will get a "leak".
It only happens with all those three prefs set. Removing only one will not cause this leak. Even with GreaseMonkey not installed, I don't see how that pref has an influence here.
This is a regression from: Bug 588648 - Don't copy chars when scanning. r=brendan. author Nicholas Nethercote <nnethercote@mozilla.com> Tue Dec 07 15:22:52 2010 -0800 (at Tue Dec 07 15:22:52 2010 -0800) changeset 58990 2b9d805d77a1 parent 58989 25e9c434bb19 child 58991 4c18087c8bda pushlog: 2b9d805d77a1
(In reply to comment #5) > It only happens with all those three prefs set. What three prefs? I see two in comment 3. > Removing only one will not > cause this leak. Even with GreaseMonkey not installed, I don't see how that > pref has an influence here. What does "that pref" mean in the last sentence? Nick, can you take and investigate? /be
(In reply to comment #7) > (In reply to comment #5) > > It only happens with all those three prefs set. > > What three prefs? I see two in comment 3. See the user.js file I have attached to this bug. > > Removing only one will not > > cause this leak. Even with GreaseMonkey not installed, I don't see how that > > pref has an influence here. > > What does "that pref" mean in the last sentence? You will see when checking the above mentioned attachment.
Blocking on investigation. We'll retriage once we find out what the problem is.
Before that patch, in certain places we would parse JS files by reading them and parsing them one chunk at a time, where a chunk was a few KB. After that patch, we instead read the whole file into memory before parsing. This made scanning much simpler and faster at the cost of higher (transient) memory use. Compiler::compileScript() was the top-level function whose API changed. It's called by the following functions: - JS_CompileFile (affected) - JS_CompileFileHandleForPrincipals (affected), which is called by: - JS_CompileFileHandleForPrincipalsVersion (affected) - JS_CompileFileHandle (affected) - JS_CompileUCScriptForPrincipals (unaffected) - EvalKernel (unaffected) Of the affected functions, only JS_CompileFileHandleForPrincipalsVersion() is used in the browser, AFAICT, and only then if HAVE_PR_MEMMAP isn't defined. So I can't see off the top of my head what could be going wrong, but I've written this down to (a) refresh the details in my own head, and (b) in case it sparks an idea in someone else. I'll now try to reproduce.
I can reproduce on Linux64, more or less. Viewing that page without Firebug installed, process size topped out at ~800MB. With Firebug, it topped out at ~3100MB, with ~2300 resident. about:memory claimed only 256MB mapped, so it's not a heap problem. The browser was responsive the whole time, maybe because I have 4GB of RAM. But in the time it's taken me to write this comment, process size has dropped to 869MB. So it looks like a big transient spike. Time to pull out Massif.
Oh, wait, I tried again. The big drop didn't occur until after I opened about:memory. And this time about:memory said "memory mapped" was 2.0GB and "memory in use" was 1.9GB, but none of the individual counts below that were out of the ordinary. So it *is* heap memory that's the problem..)
(In reply to comment #13) >.) Thanks for checking on this. From what I gather, that pref is considered harmful, and bug 620218 doesn't block, so neither should this bug.
Oh, I know what's happened. Bug 588648 also changed error reporting a bit. Previously, because we were dealing with chunks, there was a limit to how much of a line an error message could include. But now the error message contains the entire line. If you have very long lines and lots of errors, it's a recipe for high memory usage, especially since we call js_DeflateString() on the error message string, resulting in two copies of it (one made of jschars, the other made of chars). On the site in question, heaps of errors occurred on a line containing 122,895 chars, resulting in over 1G of chars (at 3 bytes per char!) being put into error messages. As for why it only occurs when Firebug is installed... without Firebug, I think we do lots of big allocations but then free each one as soon as the error has been reported. So there's lots of malloc churn, but no big spike. With Firebug, the error reports are evidently held onto somehow. Furthermore, if I disable Firebug but open the error console the spike also occurs. It should be a pretty easy fix; I just need to truncate the line if it's larger than a certain size. I think it's reasonable to keep this as a hardblocker.
(In reply to comment #14) > > Thanks for checking on this. From what I gather, that pref is considered > harmful, and bug 620218 doesn't block, so neither should this bug. The question is whether we can get thousands of error messages in other situations. I don't have a good sense of how likely that is, and thus whether this should block.
Just to clarify, the cause of this bug the interaction of the following things: (1) Bug 588648 allowed error messages to contain entire lines (which can be very wrong). (2) The presence of javascript.options.strict can lead to thousands of error messages. (3) The presence of a console (be it the error console or Firebug) causes those error messages to be held onto. (3) is controlled by the user. (2) is a bad option, but large numbers of errors may occur due to other reasons. (1) is stupid and can be fixed easily.
You could have some sort of minified JS (so it's all on one line; I'll bet that's what happens with the site in question) that has a bug in a setInterval it sets. Then you'll get an error every 10ms or worse if there are multiple copies of the interval.
Created attachment 513032 [details] [diff] [review] patch (against TM 62203:d7a8d64336ba) This patch adjusts the syntax error reporting to truncate long lines -- it'll show at most 2*WINDOW+1 chars of a line in an error message, where WINDOW=100. 100 seems reasonable but I'm open to changing it. The patch also fixes another defect that bug 588648 introduced, whereby tp->begin.index could be set to -1, which became 4294967295 because it's unsigned. I found this because the new line truncation code uses begin.index and when it was 4294967295 all hell broke loose. This required fiddling with the |adjust| parameter to getChar() for a couple of cases. I added an assertion in newToken() to prevent this defect from arising again. I've confirmed that the big memory spike seen in the browser no longer happens when javascript.options.strict is true and a console is present.
Comment on attachment 513032 [details] [diff] [review] patch (against TM 62203:d7a8d64336ba) Looks good, nits only. The "sline" name looks like "slime" but maybe that is fitting ;-). >-TokenStream::findEOL() >+TokenStream::findEOLorTrunc(jschar *tokptr, int max) This isn't quite camelCaps but I see why "or" is all-lowercase. Still kind of overlong and unsightly. Just "findEOL" seems fine to me, better than trying to say more yet still chopping "ate" off. > TokenStream::reportCompileErrorNumberVA(JSParseNode *pn, uintN flags, uintN errorNumber, > va_list ap) > { > JSErrorReport report; > char *message; >- size_t linelength; >- jschar *linechars; >- jschar *linelimit; >- char *linebytes; Blank line here if you keep the comment. >+ /* "sline" is short for "shown part of line", because we might not show it all. */ Could use "wline" or "window" instead of "sline" -- would fit the WINDOW name better. Digging the non-camelCaps localnames. Don't change (but see below). >+ size_t slinelength; >+ jschar *slinechars; >+ jschar *slinelimit; >+ jschar *slinebase; >+ jschar *tokptr; >+ char *slinebytes; Blank line here couldn't hurt. >+ /* >+ * We only show a portion of the line around the erroneous token -- WINDOW s/only show/show only/ r=me with some nit-picking; good fix. /be
Follow-up for assertion failure:
This needs to be backed out and not included in Firefox 4.0 -- see bug 635235 and bug 629858. If Waldo doesn't get to it today I'll back it out on Monday morning, Melbourne time (Sunday afternoon, MV time).
I agree with backing this out. (Although, to be fair, bug 635235 was pre-existing, and this only happened to trigger that concomitant bad behavior.) I'll do the deed later tonight -- I have to push a patch to m-c, so I'm going to be around watching a tree anyway. don't think it is It depends on how much it makes user's browsers crash, doesn't it?
(In reply to comment #25) > > found that paragraph hard to understand, but I think you're saying this bug shouldn't be a hardblocker. I agree, which is why we're backing it out; I'm assuming/hoping a higher-up will change this to blocking2.x and remove the "[hardblocker]" marking in the whiteboard.
I don't want to belabor it, but the point was that if we're talking something primarily affecting developers who use a console-like function, and the fix involves a bunch of unchecked pointer arithmetic (LOCAL_ASSERT-style checks might have avoided real badness), it seems reasonably clear that deferring is the right thing to do now.
(In reply to comment #24) > This needs to be backed out and not included in Firefox 4.0 -- see bug 635235 > and bug 629858. I've confirmed that both of these were pre-existing bugs that this patch just exposed. But we shouldn't include this patch in 4.0 just in case there are other similar latent bugs.
oops, this was backed out.
I've replicated this issue with a Mozmill endurance test. The first report linked below is without Firebug for comparison. Firefox 4.0b13pre (2.0b13pre, en-US, 20110303122430), without Firebug: Firefox 4.0b13pre (2.0b13pre, en-US, 20110303122430), with Firebug 1.7X.0a10:
Another page, where this problem can be reproduced, is: Seems to be the following script, which causes the problem: With SeaMonkey 2.9.1 (Firefox 12) on Windows XP this causes the browser to completely hang up.
Created attachment 623569 [details] [diff] [review] patch, v2 This is a revived version of the old patch, which shows at most 121 chars in an error message (the first char of the offending token, plus up to 60 chars before it, and up to 60 chars after it). There's no test, unfortunately, because AFAIK you can't get the context in an error message within JS code. I'd love to hear how a test might be written for this. I tested on winvistatips.com (comment 37). Without the patch (and with script option enabled and the error console open), the browser locks up. With the patch there's a pause but then it works ok again fairly quickly.
(In reply to Nicholas Nethercote [:njn] from comment #38) > There's no test, unfortunately, because AFAIK you can't get the context in > an error message within JS code. I'd love to hear how a test might be > written for this. Might be possible with xpcshell tests, or?
Comment on attachment 623569 [details] [diff] [review] patch, v2 Review of attachment 623569 [details] [diff] [review]: ----------------------------------------------------------------- This is still doing a depressing amount of raw pointer arithmetic of the sort that made me leery over a year ago here, but it looks like it checks out. Still I'm leery enough of this that I'd kind of like it if you held off landing this until after the next merge date, in a week and a few days. I'd really really really like to see this converted to use StringBuffer or something that does all the bounds-checking assertions for us. Maybe in a quick followup? ::: js/src/frontend/TokenStream.cpp @@ +403,5 @@ > return i == n; > } > > +// Finds the next EOL, but stops once 'max' jschars have been scanned *past* > +// the starting jschar. This comment should go by the declaration, in the header. @@ +416,2 @@ > break; > + if (n > max) Make this >= so that the |windowRadius| name isn't a lie, see below. @@ +500,5 @@ > + // Find EOL, or truncate at the back if necessary. > + const jschar *windowLimit = userbuf.findEOLIfNotTooFar(tokptr, windowRadius); > + > + size_t windowLength = windowLimit - windowBase; > + JS_ASSERT(windowLength <= windowRadius * 2 + 1); Okay, um, that + 1 at the end kind of makes the windowRadius name a lie. :-) Make the change mentioned earlier and I think you can make this assert a more proper, obvious, mathematically consistent condition. @@ +508,4 @@ > warning = false; > goto out; > } > + PodCopy(windowChars, windowBase, windowLength); Before the copy, let's do a last set of asserts that |linebase <= windowBase && windowBase < limit| and |linebase <= windowBase + windowChars && windowBase + windowChars < limit|. @@ +515,5 @@ > warning = false; > goto out; > } > > /* Unicode and char versions of the offending source line, without final \n */ This comment needs updating. ::: js/src/frontend/TokenStream.h @@ +751,5 @@ > static bool isRawEOLChar(int32_t c) { > return (c == '\n' || c == '\r' || c == LINE_SEPARATOR || c == PARA_SEPARATOR); > } > > + const jschar *findEOLIfNotTooFar(const jschar *p, int max); findEOLMax? I'd rather avoid phrase-y names when possible, just turns into a mouthful -- plus "not too far" is not exactly concise. Also make max size_t, please.
> Okay, um, that + 1 at the end kind of makes the windowRadius name a lie. The code shows the character, plus |windowRadius| characters before it, plus |windowRadius| characters after it. We seem to be interpreting "radius" differently in this discrete context, perhaps I should use a different name?
Created attachment 630046 [details] [diff] [review] patch, v3 This version uses StringBuffer to construct |windowChars|. I had to expose StringBuffer::extractWellSized(). I've left |windowRadius| unchanged for now, but I've addressed the other nits.
Comment on attachment 630046 [details] [diff] [review] patch, v3 Review of attachment 630046 [details] [diff] [review]: ----------------------------------------------------------------- Better. This is still too messy overall, but it's an improvement. (In reply to Nicholas Nethercote [:njn] from comment #41) > The code shows the character, plus |windowRadius| characters before it, plus > |windowRadius| characters after it. We seem to be interpreting "radius" > differently in this discrete context, perhaps I should use a different name? Oh, hm. So you're showing an *odd* number of characters, then? That seems more than a bit strange. Let's show the even number and make radius mean half width, as everyone will definitely expect. (Whether they would expect the "radius" of an odd width to be as you have it in this patch, I dunno. Let's avoid the confusion entirely and use it in a way everyone will understand.) ::: js/src/frontend/TokenStream.cpp @@ +498,5 @@ > + JS_ASSERT(windowLength <= windowRadius * 2 + 1); > + > + // Create the windowed strings. > + StringBuffer windowBuf(cx); > + if (!windowBuf.append(windowBase, windowLength) || !windowBuf.append((jschar)0)) { Make that '\0', please. @@ +503,4 @@ > warning = false; > goto out; > } > + windowChars = windowBuf.extractWellSized(); You need to handle failure here. (extractWellSized can OOM if the characters are stored inline and allocation fails, or if realloc to the smaller length fails [possible with some libc implementations].) ::: js/src/vm/StringBuffer.h @@ +88,5 @@ > JSAtom *finishAtom(); > + > + /* > + * Creates a raw string from the characters in this buffer. You should > + * append a NUL char to the StringBuffer before calling this. Well, it's not *necessarily* the case people should do that. It'll depend on people's use cases. How about having something like this instead: Creates a raw string from the characters in this buffer. The string is exactly the characters in this buffer: it is *not* null-terminated unless the last appended character was '\0'.
> > + if (!windowBuf.append(windowBase, windowLength) || !windowBuf.append((jschar)0)) { > > Make that '\0', please. Even though '\0' is not a jschar?
> > Make that '\0', please. > > Even though '\0' is not a jschar? Using '\0' caused an ambiguous overloading of append(), so I stuck with |(jschar)0|. I addressed the other nits.
Could we get this backported to the Aurora branch so we can have it in beta soon, or should it ride the train?
(In reply to Henrik Skupin (:whimboo) from comment #48) > Could we get this backported to the Aurora branch so we can have it in beta > soon, or should it ride the train? The problematic code has been present in released code for over a year without causing too many real-world problems. It should ride the trains. | https://bugzilla.mozilla.org/show_bug.cgi?id=634444 | CC-MAIN-2017-17 | refinedweb | 2,939 | 74.49 |
Asked by:
Custom Settings Provider Breaking Designer
In Visual Studio 2005 or 2008, when adding any User Controls to a Windows Form or other User Control in a Project that implements and is using a custom settings provider, a "Failed to create component" error is displayed. If all references to the custom settings provider are removed from settings.settings and that file is saved then User Controls can be added to Windows Forms and User Controls. However, if the custom settings provider is referenced again in settings.settings, then opening the designer of a Form/Control which includes a User Control results in a "One or more errors encountered while loading the designer..." error message.
I have had a very difficult time in tracking down the root cause of this issue because I assumed it had to do with my code and not the IDE. I am working within the context of a large project which uses User Controls heavily and have written a custom settings provider to persist user settings to a SQL Express database. This settings provider works properly, however if I want to open any Forms or User Controls in designer view I must first manually remove all references to my custom settings provider in setting.settings and then re-add them after the changes are done which is inconvenient to say the least. I can provide a small sample solution to demonstrate this beharior.
This problem is not present if the Project is in C#.Thursday, December 06, 2007 3:07 AM
Question
All replies
- 56 views but no replies ... has anyone else even come across this? I have tried this on multiple computers with the same result, so I don't believe it has anything to do with my configuration.Thursday, December 13, 2007 2:58 AM
- I am just now getting a similar problem on VS2008. I have a custom settings provider specified by settings the individual properties of my settings designed (f4).
Each item has my custom settings provider class.
When I load a form in the designer I get a "ResX type SimpleSettingsProvider" not found, line 102. (simpleSettingsProvider is my class)
No resx files that I have have anything to do with this on any line 102, so that's a problem, secondly, if I remove the custom settings provider property from all the settings, the form will load normally in the designer.
Then, when I re-instate the custom settings provider, the form still loads OK until I close and re-open the project. Then I get the error again.
This is on a project I worked on in Dec 2007, and am now updating it.
I can only assume that a VS2008 "fix" broke this...Saturday, January 31, 2009 2:54 PM
- I am getting this problem as well.
I don't use user control but the default controls provided. I get the error when adding a new control and also with controls which use an image from My.Resources.
Moreover the statusStrip items are not showed during runtimeThursday, June 04, 2009 12:51 PM
I'm just now getting the same problem in VS2010 (VB).
When I try to open any form in a designer it will not open and instead I get the message:
"The type "U3SettingsProvider" could not be found. Ensure that the assembly containing tyhe type is referenced. if the assembly is part of the current development project, ensure that the project has been built."
Update: Fixed it (Nobody was more surprised than me). I just fully qualified the provider name in the individual settings. So where I had U3SettingsProvider (which is the name of my settings provider class) I prefixed the root namespace of the application e.g. Root.U3SettingsProvider
Yellowbus DeveloperThursday, June 30, 2011 1:50 PM
I got this same problem in VS2008 . When i use Custom Provider then my form can't load in design time is say:
"The type 'PortableSettingsProvider' could not be found. Ensure that the assembly
containing the type is referenced. If the assembly is part of the current
development project, ensure that the project has been built. "
When i take new project then it work well. But when i use it my existing project then error rise. Is there any solution to overcome this situation.Monday, February 20, 2012 11:04 AM | https://social.msdn.microsoft.com/Forums/en-US/f72f7629-19e3-4ce8-bff7-64a08b114b26/custom-settings-provider-breaking-designer?forum=vbide | CC-MAIN-2016-50 | refinedweb | 724 | 71.14 |
CodePlexProject Hosting for Open Source Software
I just installed the 0.9 version of orchard using wpi. When I try to run the orchard site this error appears:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0234: The type or namespace name 'WebData' does not exist in the namespace 'WebMatrix' (are you missing an assembly reference?)
Source Error:
Line 23: using System.Web.Mvc;
Line 24: using WebMatrix.Data;
Line 25: using WebMatrix.WebData;
Line 26: using System.Web.Mvc.Ajax;
Line 27: using System.Web.Mvc.Html;
Source File: c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\ec900aad\eeb6dffb\App_Web_index.cshtml.d5b2430e.utgewwra.0.cs Line: 25
Anyone know what this might be about? I'm not familiar with webmatrix and don't see a place to check for missing references etc. I did a repair of the webmatrix installation and no help. I may pull down this install and choose the IIS install instead, but
thought I'd see if this could be resolved first.
The same 35 items are in the folder at \my websites\orchard\bin as are in the bin folder for the orchard 0.9 I downloaded and unzipped, including WebMatrix.Data.dll
Yes that was it - thanks!
Now I get the orchard setup page and it says it does not have write perms to app_data, but that's probably easy to resolve.
After closing the instance of orchard which had the perms error listed in my previous post, and hitting Run again, Orchard fired up without any errors.
Thanks, same issue, reinstall of MVC 3 RC2 did the trick.
I have installed it using my web host company and the error continues. Maybe the final release of webmatrix is bogus?
Or maybe your web host company does not have the latest bits installed.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://orchard.codeplex.com/discussions/238856 | CC-MAIN-2016-50 | refinedweb | 366 | 68.06 |
import /images
- electronico_nc last edited by
Hi all,
I lost this fog 1.5.9 VM.
The /images is still OK.
New fog install, then mount of /images
Is there a way to import the content of /images into fog ?
Thanks in advance for your time.
- george1421 Moderator last edited by
@electronico_nc Well lets start off by saying this. FOG Images have 2 parts. There are the raw files that are stored in the /images directory and the meta data that is stored in the database. You have the raw files so rebuilding the data will take some work, good guessing, and a bit of luck.
Just recreate your image definitions by hand as you did in the beginning. Be sure to name them exactly what they were before. In the example above the image name and directory name is almost always the same. So name this image win7_64 (watch your case). Fill out the rest of the settings as you would normally do. One could guess that this image is a windows 7 so you will need to select that in the OS field. If you did not name all of them as clearly, be a good guesser to see what OS it is. The compression values are only used on image capture so you should just guess what you might have used. Just do this for each directory in the /images folder.
The only (not a gotcha, but something to be aware of) is that on the image list view the image size will be zero. This is because the image size is set at capture time only. Since you are side loading these images that field will be zero until you recapture the image.
- electronico_nc last edited by
each image folder looks like this:
./win7_64: total 19743952 -rwxrwxrwx 1 fogproject root 4 juin 9 2020 d1.fixed_size_partitions -rwxrwxrwx 1 fogproject root 1048576 juin 9 2020 d1.mbr -rwxrwxrwx 1 fogproject root 266 juin 9 2020 d1.minimum.partitions -rwxrwxrwx 1 fogproject root 15 juin 9 2020 d1.original.fstypes -rwxrwxrwx 1 fogproject root 0 juin 9 2020 d1.original.swapuuids -rwxrwxrwx 1 fogproject root 174989773 juin 9 2020 d1p1.img -rwxrwxrwx 1 fogproject root 15691190007 juin 9 2020 d1p2.img -rwxrwxrwx 1 fogproject root 4350547200 juin 9 2020 d1p3.img -rwxrwxrwx 1 fogproject root 266 juin 9 2020 d1.partitions | https://forums.fogproject.org/topic/15863/import-images/? | CC-MAIN-2022-21 | refinedweb | 393 | 75.61 |
xdm
xdm is an MDX compiler that focusses on two things:
- Compiling the MDX syntax (markdown + JSX) to JavaScript
- Making it easier to use the MDX syntax in different places
This is mostly things I wrote for
@mdx-js/mdx which are not slated to be
released (soon?) plus some further changes that I think are good ideas (source
maps, ESM only, defaulting to an automatic JSX runtime, no Babel, smallish
browser size, more docs, import/exports in evaluate, esbuild and Rollup
plugins).
There are also some cool experimental features in 👩🔬 Lab!
Install
Use Node 12 or later.
Then install
xdm with either npm or yarn.
npm install xdm
yarn add xdm
This package is ESM only:
Node 12+ is needed to use it and it must be
imported instead of
required.
What is MDX?
MDX is different things.
The term is sometimes used for a compiler, typically implying
@mdx-js/mdx, but
there are more.
First there was
mdxc.
Then came
@mdx-js/mdx.
There’s also
mdsvex.
And now there’s xdm too.
Sometimes the term is used for a runtime/helper library.
xdm has no runtime: it’s not needed!
Most often the term is used for the format: markdown + JS(X) (there are some
caveats):
## Hello, world! <div className="note"> > Some notable things in a block quote! </div>
See?
Most of markdown works!
Those XML-like things are not HTML though: they’re JSX.
Note that there are some differences in how JSX should be authored: for example,
React expects
className, whereas Vue expects
class.
See § MDX syntax below for more on how the format works.
Use
This section describes how to use the API.
See § MDX syntax on how the format works.
See § Integrations on how to use xdm with Babel, esbuild,
Rollup, webpack, etc.
Say we have an MDX document,
example.mdx:
export const Thing = () => <>World!</> # Hello, <Thing />
First, a rough idea of what the result will be.
The below is not the actual output, but it
Now for how to get the actual output.
Add some code in
example.js to compile
example.mdx to JavaScript:
import {promises as fs} from 'node:fs' import {compile} from 'xdm' main() async function main() { const compiled = await compile(await fs.readFile('example.mdx')) console.log(String(compiled)) }
The actual output of running
node example.js is:
/* @jsxRuntime automatic @jsxImportSource react */ import {Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs} from 'react/jsx-runtime' export const Thing = () => _jsx(_Fragment, {children: 'World!'}) function MDXContent(props = {}) { let {wrapper: MDXLayout} = props.components || ({}) return MDXLayout ? _jsx(MDXLayout, Object.assign({}, props, {children: _jsx(_createMdxContent, {})})) : _createMdxContent() function _createMdxContent() { let _components = Object.assign({h1: 'h1'}, props.components) return _jsxs(_components.h1, {children: ['Hello, ', _jsx(Thing, {})]}) } } export default MDXContent
Some more observations:
- JSX is compiled away to function calls and an import of React†
- The content component can be given
{components: {wrapper: MyLayout}}to
wrap the whole content
- The content component can be given
{components: {h1: MyComponent}}to use
something else for the heading
† xdm is not coupled to React.
You can also use it with Preact, Vue, Emotion,
Theme UI, etc.
See § MDX content below on how to use the result.
API
xdm exports the following identifiers:
compile,
compileSync,
evaluate,
evaluateSync,
run,
runSync, and
createProcessor.
There is no default export.
xdm/esbuild.js exports a function as the default export that returns an
esbuild plugin.
xdm/rollup.js exports a function as the default export that returns a
Rollup plugin.
xdm/webpack.cjs exports a webpack loader as the default export.
There is also
xdm/esm-loader.js and
xdm/register.cjs, see 👩🔬 Lab
for more info.
compile(file, options?)
Compile MDX to JS.
file
MDX document to parse (
string,
Buffer in UTF-8,
vfile,
or anything that can be given to
vfile).
Example
import {VFile} from 'vfile' import {compile} from 'xdm' await compile(':)') await compile(Buffer.from(':-)')) await compile({path: 'path/to/file.mdx', value: '🥳'}) await compile(new VFile({path: 'path/to/file.mdx', value: '🤭'}))
options.remarkPlugins
List of remark plugins, presets, and pairs.
Example
import remarkFrontmatter from 'remark-frontmatter' // YAML and such. import remarkGfm from 'remark-gfm' // Tables, strikethrough, tasklists, literal URLs. await compile(file, {remarkPlugins: [remarkGfm]}) // One plugin. await compile(file, {remarkPlugins: [[remarkFrontmatter, 'toml']]}) // A plugin with options. await compile(file, {remarkPlugins: [remarkGfm, remarkFrontmatter]}) // Two plugins. await compile(file, {remarkPlugins: [[remarkGfm, {singleTilde: false}], remarkFrontmatter]}) // Two plugins, first w/ options.
options.rehypePlugins
List of rehype plugins, presets, and pairs.
Example
import rehypeKatex from 'rehype-katex' // Render math with KaTeX. import remarkMath from 'remark-math' // Support math like `$so$`. await compile(file, {remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex]}) await compile(file, { remarkPlugins: [remarkMath], // A plugin with options: rehypePlugins: [[rehypeKatex, {throwOnError: true, strict: true}]] })
options.recmaPlugins
List of recma plugins.
This is a new ecosystem, currently in beta, to transform
esast trees (JavaScript).
options.mdExtensions
List of markdown extensions, with dot (
string[], default:
['.md', '.markdown', '.mdown', '.mkdn', '.mkd', '.mdwn', '.mkdown', '.ron']).
options.mdxExtensions
List of MDX extensions, with dot (
string[], default:
['.mdx']).
Has no effect in
compile or
evaluate, but does affect esbuild,
Rollup, and the experimental ESM loader + register hook (see 👩🔬
Lab).
options.format
Format the file is in (
'detect' | 'mdx' | 'md', default:
'detect').
'detect'— use
'markdown'for files with an extension in
mdExtensions
and
'mdx'otherwise
'mdx'— treat file as MDX
'md'— treat file as plain vanilla markdown
The format cannot be detected if a file is passed without a path or extension:
mdx will be assumed.
So pass a full vfile (with
path) or an object with a path.
Example
compile({value: '…'}) // Seen as MDX compile({value: '…'}, {format: 'md'}) // Seen as markdown compile({value: '…', path: 'readme.md'}) // Seen as markdown // Please do not use `.md` for MDX as other tools won’t know how to handle it. compile({value: '…', path: 'readme.md'}, {format: 'mdx'}) // Seen as MDX compile({value: '…', path: 'readme.md'}, {mdExtensions: []}) // Seen as MDX
This option mostly affects esbuild and Rollup plugins, and the
experimental ESM loader + register hook (see 👩🔬 Lab), because in those
it affects which files are “registered”:
format: 'mdx'registers the extensions in
options.mdxExtensions
format: 'md'registers the extensions in
options.mdExtensions
format: 'detect'registers both lists of extensions
options.outputFormat
Output format to generate (
'program' | 'function-body', default:
'program').
In most cases
'program' should be used, as it results in a whole program.
Internally,
evaluate uses
outputFormat: 'function-body' to compile
to code that can be
evaled with
run.
In some cases, you might want to do what
evaluate does in separate steps
yourself, such as when compiling on the server and running on the client.
The
'program' format will use import statements to import the runtime (and
optionally provider) and use an export statement to yield the
MDXContent
component.
The
'function-body' format will get the runtime (and optionally provider) from
arguments[0], rewrite export statements, and use a return statement to yield
what was exported.
Normally, this output format will throw on
import (and
export … from)
statements, but you can support them by setting
options.useDynamicImport.
Example
A module
example.js:
import {compile} from 'xdm' main('export const no = 3.14\n\n# hi {no}') async function main(code) { console.log(String(await compile(code, {outputFormat: 'program'}))) // Default console.log(String(await compile(code, {outputFormat: 'function-body'}))) }
…yields:
import {Fragment as _Fragment, jsx as _jsx} from 'react/jsx-runtime' export const no = 3.14 function MDXContent(props = {}) { /* … */ } export default MDXContent
const {Fragment: _Fragment, jsx: _jsx} = arguments[0] const no = 3.14 function MDXContent(props = {}) { /* … */ } return {no, default: MDXContent}
options.useDynamicImport
Whether to compile to dynamic import expressions (
boolean, default:
false).
This option applies when
options.outputFormat is
'function-body'.
xdm can turn import statements (
import x from 'y') into dynamic imports
(
const {x} = await import('y')).
This is useful because import statements only work at the top level of
JavaScript modules, whereas
import() is available inside function bodies.
When you turn
useDynamicImport on, you should probably set
options.baseUrl too.
Example
Say we have a couple modules:
// meta.js: export const title = 'World' // numbers.js: export const no = 3.14 // example.js: import {compileSync} from 'xdm' const code = `import {name} from './meta.js' export {no} from './numbers.js' # hi {name}!` console.log(String(compileSync(code, {outputFormat: 'function-body', useDynamicImport: true})))
…now running
node example.js yields:
const {Fragment: _Fragment, jsx: _jsx, jsxs: _jsxs} = arguments[0] const {name} = await import('./meta.js') const {no} = await import('./numbers.js') function MDXContent(props = {}) { /* … */ } return {no, default: MDXContent}
options.baseUrl
Resolve relative
import (and
export … from) from this URL (
string?,
example:
import.meta.url).
Relative specifiers are non-absolute URLs that start with
For example:
/index.js,
./folder/file.js, or
../main.js.
/,
./, or
../.
This option is useful when code will run in a different place.
One example is when
.mdx files are in path a but compiled to path b and
imports should run relative the path b.
Another example is when evaluating code, whether in Node or a browser.
Example
Say we have a module
example.js:
import {compile} from 'xdm' main() async function main() { const code = 'export {number} from "./data.js"\n\n# hi' const baseUrl = ' // Typically `import.meta.url` console.log(String(await compile(code, {baseUrl}))) }
…now running
node example.js yields:
import {Fragment as _Fragment, jsx as _jsx} from 'react/jsx-runtime' export {number} from ' function MDXContent(props = {}) { /* … */ } export default MDXContent
options.development
Whether to add extra information to error messages in generated code
(
boolean?, default:
false).
The default can be set to
true in Node.js through environment variables: set
NODE_ENV=development.
Example
Say we had some MDX that references a component that can be passed or provided
at runtime:
**Note**<NoteIcon />: some stuff.
And a module to evaluate that:
import {promises as fs} from 'node:fs' import * as runtime from 'react/jsx-runtime' import {evaluate} from 'xdm' main() async function main() { const path = 'example.mdx' const value = await fs.readFile(path) const MDXContent = (await evaluate({path, value}, runtime)).default console.log(MDXContent()) }
Running that would normally (production) yield:
Error: Expected component `NoteIcon` to be defined: you likely forgot to import, pass, or)
But if we change add
development: true to our example:
@@ -7,6 +7,6 @@ main() async function main() { const path = 'example.mdx' const value = await fs.readFile(path) - const MDXContent = (await evaluate({path, value}, runtime)).default + const MDXContent = (await evaluate({path, value}, {development: true, ...runtime})).default console.log(MDXContent({})) }
And we’d run it again, we’d get:
Error: Expected component `NoteIcon` to be defined: you likely forgot to import, pass, or provide it. It’s referenced in your code at `1:9-1:21` in `example.mdx`)
options.SourceMapGenerator
The
SourceMapGenerator class from
source-map (optional).
When given, the resulting file will have a
map field set to a source map (in
object form).
Example
Assuming
example.mdx from § Use exists, then:
import {promises as fs} from 'node:fs' import {SourceMapGenerator} from 'source-map' import {compile} from 'xdm' main() async function main() { const file = await compile( {path: 'example.mdx', value: await fs.readFile('example.mdx')}, {SourceMapGenerator} ) console.log(file.map) }
…yields:
{ version: 3, sources: ['example.mdx'], names: ['Thing'], mappings: ';;aAAaA,QAAQ;YAAQ;;;;;;;;iBAE3B', file: 'example.mdx' }
options.providerImportSource
Place to import a provider from (
string?, example:
'@mdx-js/react').
Useful for runtimes that support context (React, Preact).
The provider must export a
useMDXComponents, which is called to access an
object of components.
Example
If
file is the contents of
example.mdx from § Use, then:
compile(file, {providerImportSource: '@mdx-js/react'})
…yields this difference:
/* @jsxRuntime automatic @jsxImportSource react */ import {Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs} from 'react/jsx-runtime' +import {useMDXComponents as _provideComponents} from '@mdx-js/react' export const Thing = () => _jsx(_Fragment, {children: 'World!'}) function MDXContent(props = {}) { - let {wrapper: MDXLayout} = props.components || ({}) + let {wrapper: MDXLayout} = Object.assign({}, _provideComponents(), props.components) return MDXLayout ? _jsx(MDXLayout, Object.assign({}, props, {children: _jsx(_createMdxContent, {})})) : _createMdxContent() function _createMdxContent() { - let _components = Object.assign({h1: 'h1'}, props.components) + let _components = Object.assign({h1: 'h1'}, _provideComponents(), props.components) return _jsxs(_components.h1, {children: ['Hello, ', _jsx(Thing, {})]}) } } export default MDXContent
options.jsx
Whether to keep JSX (
boolean?, default:
false).
The default is to compile JSX away so that the resulting file is immediately
runnable.
Example
If
file is the contents of
example.mdx from § Use, then:
compile(file, {jsx: true})
…yields this difference:
/* @jsxRuntime automatic @jsxImportSource react */ -import {Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs} from 'react/jsx-runtime' -export const Thing = () => _jsx(_Fragment, {children: 'World!'}) +export const Thing = () => <>World!</> function MDXContent(props = {}) { let {wrapper: MDXLayout} = props.components || ({}) return MDXLayout - ? _jsx(MDXLayout, Object.assign({}, props, {children: _jsx(_createMdxContent, {})})) + ? <MDXLayout {...props}><_createMdxContent /></MDXLayout> : _createMdxContent() function _createMdxContent() { let _components = Object.assign({h1: 'h1'}, props.components) - return _jsxs(_components.h1, {children: ['Hello, ', _jsx(Thing, {})]}) + return <_components.h1>{"Hello, "}<Thing /></_components.h1> } } export default MDXContent
options.jsxRuntime
JSX runtime to use (
'automatic' | 'classic', default:
'automatic').
The classic runtime compiles to calls such as
h('p'), the automatic runtime
compiles to
import _jsx from '$importSource/jsx-runtime'\n_jsx('p').
Example
If
file is the contents of
example.mdx from § Use, then:
compile(file, {jsxRuntime: 'classic'})
…yields this difference:
-/* @jsxRuntime automatic @jsxImportSource react */ -import {Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs} from 'react/jsx-runtime' +/* @jsxRuntime classic @jsx React.createElement @jsxFrag React.Fragment */ +import React from 'react' -export const Thing = () => _jsx(_Fragment, {children: 'World!'}) +export const Thing = () => React.createElement(React.Fragment, null, 'World!') …
options.jsxImportSource
Place to import automatic JSX runtimes from (
string?, default:
'react').
When in the
automatic runtime, this is used to define an import for
_Fragment,
_jsx, and
_jsxs.
Example
If
file is the contents of
example.mdx from § Use, then:
compile(file, {jsxImportSource: 'preact'})
…yields this difference:
-/* @jsxRuntime automatic @jsxImportSource react */ -import {Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs} from 'react/jsx-runtime' +/* @jsxRuntime automatic @jsxImportSource preact */ +import {Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from 'preact/jsx-runtime'
options.pragma
Pragma for JSX (
string?, default:
'React.createElement').
When in the
classic runtime, this is used as an identifier for function calls:
<x /> to
React.createElement('x').
You should most probably define
pragmaFrag and
pragmaImportSource too when
changing this.
Example
If
file is the contents of
example.mdx from § Use, then:
compile(file, { jsxRuntime: 'classic', pragma: 'preact.createElement', pragmaFrag: 'preact.Fragment', pragmaImportSource: 'preact/compat' })
…yields this difference:
-/* @jsxRuntime classic @jsx React.createElement @jsxFrag React.Fragment */ -import React from 'react' +/* @jsxRuntime classic @jsx preact.createElement @jsxFrag preact.Fragment */ +import preact from 'preact/compat' -export const Thing = () => React.createElement(React.Fragment, null, 'World!') +export const Thing = () => preact.createElement(preact.Fragment, null, 'World!') …
options.pragmaFrag
Pragma for JSX fragments (
string?, default:
'React.Fragment').
When in the
classic runtime, this is used as an identifier for fragments:
to
React.createElement(React.Fragment).
<>
See
options.pragma for an example.
options.pragmaImportSource
Where to import the identifier of
pragma from (
string?, default:
'react').
When in the
classic runtime, this is used to import the
pragma function.
To illustrate with an example: when
pragma is
'a.b' and
pragmaImportSource
is
'c' this following will be generated:
import a from 'c'.
See
options.pragma for an example.
Returns
Promise<VFile> — Promise that resolves to the compiled JS as a vfile.
Example
import remarkPresetLintConsistent from 'remark-preset-lint-consistent' // Lint rules to check for consistent markdown. import {reporter} from 'vfile-reporter' import {compile} from 'xdm' main() async function main() { const file = await compile('*like this* or _like this_?', {remarkPlugins: [remarkPresetLintConsistent]}) console.error(reporter(file)) }
Yields:
1:16-1:27 warning Emphasis should use `*` as a marker emphasis-marker remark-lint ⚠ 1 warning
compileSync(file, options?)
Compile MDX to JS.
Synchronous version of
compile.
When possible please use the async
compile.
evaluate(file, options)
☢️ Danger: It’s called evaluate because it
evals JavaScript.
Compile and run MDX.
When possible, please use
compile, write to a file, and then run with Node or
bundle with esbuild/Rollup/webpack.
But if you trust your content,
evaluate can work.
Typically,
import (or
export … from) do not work here.
They can be compiled to dynamic
import() by passing
options.useDynamicImport.
file
options
Most options are the same as
compile, with the following
exceptions:
providerImportSourceis replaced by
useMDXComponents
jsx*and
pragma*options are replaced by
jsx,
jsxs, and
Fragment
outputFormatis set to
function-body
options.jsx
options.jsxs
options.Fragment
These three options are required.
They come from an automatic JSX runtime that you must import yourself.
Example
import * as runtime from 'react/jsx-runtime' const {default: Content} = await evaluate('# hi', {...runtime, ...otherOptions})
options.useMDXComponents
Needed if you want to support a provider.
Example
import * as provider from '@mdx-js/react' import * as runtime from 'react/jsx-runtime' const {default: Content} = await evaluate('# hi', {...provider, ...runtime, ...otherOptions})
Returns
Promise<Module> — Promise that resolves to something that looks a bit like a
module: an object with a
default field set to the component and anything else
that was exported from the MDX file available too.
Example
Assuming the contents of
example.mdx from § Use was in
file, then:
import * as runtime from 'react/jsx-runtime' import {evaluate} from 'xdm' console.log(await evaluate(file, {...runtime}))
…yields:
{Thing: [Function: Thing], default: [Function: MDXContent]}
evaluateSync(file, options)
☢️ Danger: It’s called evaluate because it
evals JavaScript.
Compile and run MDX.
Synchronous version of
evaluate.
When possible please use the async
evaluate.
run(functionBody, options)
☢️ Danger: This
evals JavaScript.
Run MDX compiled as
options.outputFormat: 'function-body'.
options
You can pass
jsx,
jsxs, and
Fragment from an automatic JSX runtime as
options.
You can pass
useMDXComponents from a provider in options as well if the MDX
is compiled with
options.providerImportSource: '#' (the exact value of this
option doesn’t matter).
All other options have to be passed to
compile instead.
Returns
Promise<Module> — See
evaluate
Example
On the server:
import {compile} from 'xdm' const code = String(await compile('# hi', {outputFormat: 'function-body'}))
On the client:
import {run} from 'xdm' import * as runtime from 'react/jsx-runtime' const code = '' // To do: get `code` from server somehow. const {default: Content} = await run(code, runtime)
…yields:
[Function: MDXContent]
runSync(functionBody, options)
☢️ Danger: This
evals JavaScript.
Run MDX.
Synchronous version of
run.
When possible please use the async
run.
createProcessor(options)
Create a unified processor to compile MDX to JS.
Has the same options as
compile, but returns a configured
processor.
Note that
format: 'detect' does not work here: only
'md' or
'mdx' are
allowed (and
'mdx' is the default).
👩🔬 Lab
This section describes experimental features!
These do not adhere to semver and could break at any time!
Importing
.mdx files directly
ESM loaders are an experimental
feature in Node, slated to change.
Still, they let projects “hijack” imports, to do all sorts of fancy things!
xdm comes with experimental support for importing
.mdx files with
on-the-fly compilation, using
xdm/esm-loader.js:
Assuming
example.mdx from § Use exists, and our module
example.js
looks as follows:
import {renderToStaticMarkup} from 'react-dom/server.js' import React from 'react' import Content from './example.mdx' console.log(renderToStaticMarkup(React.createElement(Content)))
Running that with:
node --experimental-loader=xdm/esm-loader.js example.js
…yields:
<h1>Hello, World!</h1>
To pass options, you can make your own loader, such as this
my-loader.js:
import {createLoader} from 'xdm/esm-loader.js' // Load is for Node 17+, the rest for 12-16. const {load, getFormat, transformSource} = createLoader(/* Options… */) export {load, getFormat, transformSource}
Which can then be used with
node --experimental-loader=./my-loader.js.
Node itself does not yet support multiple loaders, but it is possible to combine
multiple loaders with
@node-loader/core.
Requiring
.mdx files directly
require.extensions
is a deprecated feature in Node.
Still, it lets projects “hijack”
require calls to do fancy things.
xdm comes with support for requiring
.mdx files with on-the-fly
evaluation, using
xdm/register.cjs:
Assuming
example.mdx from § Use exists, and our script
example.cjs
looks as follows:
const React = require('react') const {renderToStaticMarkup} = require('react-dom/server.js') const Content = require('./example.mdx') console.log(renderToStaticMarkup(React.createElement(Content)))
Running that with:
node -r xdm/register.cjs example.cjs
…yields:
<h1>Hello, World!</h1>
To pass options, you can make your own hook, such as this
my-hook.cjs:
'use strict' const register = require('xdm/lib/integration/require.cjs') register({/* Options… */})
Which can then be used with
node -r ./my-hook.cjs.
The register hook uses
evaluateSync.
That means
import (and
export … from) are not supported when requiring
.mdx files.
Importing
.md and
.mdx files from the web in esbuild
⚠️ Note that this includes remote code in your bundle.
Make sure you trust it!
See § Security for more info.
When passing
allowDangerousRemoteMdx to the esbuild loader, MD(X) and JS files
can be imported from
and
urls.
Take this
index.mdx file:
import Readme from ' Embed the xdm readme like so: <Readme />
And a module
build.js:
import xdm from 'xdm/esbuild.js' import esbuild from 'esbuild' await esbuild.build({ entryPoints: ['index.mdx'], outfile: 'output.js', format: 'esm', plugins: [xdm({allowDangerousRemoteMdx: true, /* Other options… */})] })
Running that (
node build.js) and evaluating
output.js (depends on how you
evaluate React stuff) would give:
<p>Embed the xdm readme like so:</p> <h1>xdm</h1> {/* … */} <p><a href=" © …</p>
MDX syntax
Note!
You don’t have to use this syntax.
Or use it always.
With
format, you can opt-in gradually or not at all.
The MDX syntax is a mix between markdown and JSX.
Markdown often feels more natural to type than HTML (or JSX) for the common
things (like emphasis, headings).
JSX is an extension to JavaScript that looks like HTML but makes it convenient
to use components (reusable things).
See this description
for a more formal description of the syntax.
This gives us something along the lines of literate programming.
MDX also gives us an odd mix of two languages: markdown is whitespace sensitive
and forgiving (what you type may not “work”, but it won’t crash) whereas
JavaScript is whitespace insensitive and does crash on typos.
Weirdly enough they combine pretty well!
It’s important to know markdown
(see this cheatsheet and tutorial for help)
and have experience with JavaScript (specifically
JSX) to write (and enjoy writing) MDX.
Some common gotchas with writing MDX are
documented here.
Markdown
Most of markdown (CommonMark) works:
# Heading (rank 1) ## Heading 2 ### 3 #### 4 ##### 5 ###### 6 > Block quote * Unordered * List 1. Ordered 2. List A paragraph, introducing a thematic break: *** ```js some.code() ``` a [link]( an , some *emphasis*, something **strong**, and finally a little `code()`.
Some other features often used with markdown are:
- GFM — autolink literals, strikethrough, tables, tasklists
(see guide below)
- Frontmatter — YAML
(see guide below)
- Math
(see guide below)
- Syntax highlighting
(see guide below)
There are many more things possible by configuring
remark plugins and rehype plugins.
There are also a couple specific remark/rehype/recma plugins that work with
xdm: see plugins.
Caveats
Some markdown features don’t work in MDX:
Indented code works in markdown, but not in MDX: console.log(1) // this is a paragraph in MDX! The reason for that is so that you can nicely indent your components. A different one is “autolinks”: <svg:rect> and <[email protected]> are links in markdown, but they crash xdm. The reason is that they look a lot like JSX components, and we prefer being unambiguous. If you want links, use [descriptive text]( HTML doesn’t work, because MDX has JSX instead (see next section). And you must escape less than (`<`) and opening braces (`{`) like so: \< or \{.
documented here.
JSX
Most of JSX works.
Here’s some that looks a lot like HTML (but is JSX):
<h1>Heading!</h1> <abbr title="HyperText Markup Language">HTML</abbr> is a lovely language. <section> And here is *markdown* in **JSX**! </section>
You can also use components, but note that you must either define them locally
or pass them in later (see § MDX content):
<MyComponent id="123" /> Or access the `thisOne` component on the `myComponents` object: <myComponents.thisOne /> <Component open x={1} label={'this is a string, *not* markdown!'} icon={<Icon />} />
documented here.
ESM
To define things from within MDX, use ESM:
import {External} from './some/place.js' export const Local = props => <span style={{color: 'red'}} {...props} /> An <External /> component and <Local>a local component</Local>.
ESM can also be used for other things:
import {MyChart} from './chart-component.js' import data from './population.js' export const pi = 3.14 <MyChart data={data} label={'Something with ' + pi} />
Expressions
Braces can be used to embed JavaScript expressions in MDX:
export const pi = 3.14 Two 🍰 is: {pi * 2}
Expressions can be empty or contain just a comment:
{/* A comment! */}
MDX content
All content (headings, paragraphs, etc) you write are exported as the default
export from a compiled MDX file as a component.
It’s possible to pass props in.
The special prop
components is used to determine how to render components.
This includes both JSX and markdown syntax.
Say we have a
message.mdx file:
# Hello, *<Planet />*! Remember when we first met in {props.year}?
This file could be imported from JavaScript and passed components like so:
import Message from './message.mdx' // Assumes an integration is used to compile MDX -> JS. <Message components={{Planet: () => 'Venus'}} year={1962} />
You can also change the things that come from markdown:
<Message components={{ // Map `h1` (`# heading`) to use `h2`s. h1: 'h2', // Rewrite `em`s (`*like so*`) to `i` with a red foreground color. em: (props) => <i style={{color: 'red'}} {...props} />, // Pass a layout (using the special `'wrapper'` key). wrapper: ({components, ...props}) => <main {...props} />, // Pass a component. Planet: () => 'Venus' }} year={1962} />
Components
The following keys can be passed in
components:
- HTML equivalents for the things you write with markdown (such as
h1for
# heading)†
wrapper, which defines the layout (but local layout takes precedence)
foo,
Components,
_,
$x,
a1) for the things you write with JSX (like
<So />or
<like.so />, note that locally defined components take
precedence)‡
† Normally, in markdown, those are:
a,
blockquote,
br,
code,
em,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
img,
li,
ol,
p,
pre,
strong, and
ul.
With
remark-gfm (see guide below), you
can also use:
del,
section,
sup,
table,
tbody,
td,
th,
thead,
and
tr.
Other remark plugins that add support for new constructs and advertise that they
work with rehype, will also work with xdm.
‡ The rules for whether a name in JSX (
x in
<x>) is a literal tag name
or not, are as follows:
- If there’s a dot, it’s a member expression (
<a.b>->
h(a.b))
- Otherwise, if the name is not a valid identifier, it’s a literal (
<a-b>->
h('a-b'))
- Otherwise, if it starts with a lowercase, it’s a literal (
<a>->
h('a'))
- Otherwise, it’s an identifier (
<A>->
h(A))
Layout
Layouts are components that wrap the whole content.
They).
Integrations
Bundlers
esbuild
Install
xdm and use
xdm/esbuild.js.
Add something along these lines to your
build call:
import xdm from 'xdm/esbuild.js' import esbuild from 'esbuild' await esbuild.build({ entryPoints: ['index.mdx'], outfile: 'output.js', format: 'esm', plugins: [xdm({/* Options… */})] })
esbuild takes care of turning modern JavaScript features into syntax that works
wherever you want it to.
No Babel needed.
See esbuild’s docs for more info.
options are the same as from
compile with the addition of:
options.allowDangerousRemoteMdx
Whether to allow importing from
and
URLs (
boolean, default:
false).
See § Importing
.md and
.mdx files from the web in
esbuild.
⚠️ Note that this evaluates any JavaScript and MDX found over the wire!
Rollup
Install
xdm and use
xdm/rollup.js.
Add something along these lines to your
rollup.config.js:
import path from 'node:path' import xdm from 'xdm/rollup.js' export default { // … plugins: [ // … xdm({/* Options… */}) ] }
If you use modern JavaScript features you might want to use Babel through
@rollup/plugin-babel
to compile to code that works:
// … import {babel} from '@rollup/plugin-babel' export default { // … plugins: [ // … xdm({/* Options… */}), babel({ // Also run on what used to be `.mdx` (but is now JS): extensions: ['.js', '.jsx', '.es6', '.es', '.mjs', '.mdx', '.md'], // Other options… }) ] }
Source maps are supported.
You do not need to pass
options.SourceMapGenerator.
options are the same as from
compile, with the additions of:
options.include
options.exclude
List of
picomatch patterns to include and/or exclude
(
string,
RegExp,
Array<string|RegExp>, default:
[]).
Webpack
Install
xdm and use
xdm/webpack.cjs.
Add something along these lines to your
webpack.config.js:
module.exports = { module: { // … rules: [ // … {test: /\.mdx?$/, use: [{loader: 'xdm/webpack.cjs', options: {}}]} ] } }
Source maps are supported based on how you configure webpack.
You do not need to pass
options.SourceMapGenerator.
If you use modern JavaScript features you might want to use Babel through
babel-loader to compile to
code that works:
// … use: [ // Note that Webpack runs right-to-left: `xdm` is used first, then // `babel-loader`. {loader: 'babel-loader', options: {}}, {loader: 'xdm/webpack.cjs', options: {}} ] // …
Note that
webpack-cli doesn’t support loaders in ESM directly or even
indirectly.
Because
xdm itself is ESM, this means the
xdm/webpack.cjs loader (even
though it’s CJS) doesn’t work with
webpack-cli (it does work when using the
webpack API).
To use this loader with
webpack-cli, set the
DISABLE_V8_COMPILE_CACHE=1
environment variable.
See
GH-11 for
details.
DISABLE_V8_COMPILE_CACHE=1 webpack
Build systems
Snowpack
Snowpack uses Rollup (for local files) which can
be extended.
Unfortunately,
snowpack.config.js is currently, ironically, CommonJS.
So figuring out a way to
import('xdm/rollup.js') and use it in Snowpack, is
left as an exercise to the reader.
Vite
Vite supports Rollup plugins directly in
plugins in
your
vite.config.js.
WMR
WMR supports Rollup plugins directly by
adding them to
plugins
in
wmr.config.mjs.
import {defineConfig} from 'wmr' import xdm from 'xdm/rollup.js' export default defineConfig({ plugins: [ xdm({/* Options… */}) ] })
See § Preact if you want to use Preact.
Compilers
Babel
You should probably use webpack or Rollup instead of Babel directly as that
gives the neatest interface.
It is possible to use xdm in Babel and it’s fast, because it skips
xdm
xdm or
@babel/parser.
This Babel plugin,
plugin.js:
import path from 'node:path' import parser from '@babel/parser' import estreeToBabel from 'estree-to-babel' import {compileSync} from 'xdm' export function babelPluginSyntaxMdx() { // Tell Babel to use a different parser. return {parserOverride: babelParserWithMdx} } // A Babel parser that parses `.mdx` files with xdm xdm to return a Babel tree instead of serialized JS. {recmaPlugins: [recmaBabel]} ).result } return parser.parse(value, options) } // A “recma” plugin is a unified plugin that runs on the estree (used by xdm //]})
Site generators
Create React App (CRA)
Create a new app with CRA and
change directory to enter it:
npx create-react-app my-app cd my-app
Install
xdm as a dev dependency:
yarn add xdm --dev
Now we can add our MDX content.
Create an MDX file
Content.mdx in the
src/ folder:
export const Box = () => ( <div style={{padding: 20, backgroundColor: 'tomato'}} /> ) # Hello, world! This is **markdown** with <span style={{color: "red"}}>JSX</span>: MDX! <Box />
To use that content in the app, replace the contents of
App.js in the
src/
folder with:
/* eslint-disable import/no-webpack-loader-syntax */ import Content from '!xdm/webpack.cjs!./Content.mdx' export default function App() { return <Content /> }
Done!
To start the development server run:
yarn start
Next.js
Next uses webpack.
Install
xdm and extend
Next’s config
in a
next.config.js file like so:
module.exports = { // Support MDX files as pages: pageExtensions: ['mdx', 'md', 'tsx', 'ts', 'jsx', 'js'], // Support loading `.mdx`: webpack(config) { config.module.rules.push({ test: /\.mdx?$/, use: [{loader: 'xdm/webpack.cjs', options: {/* Options… */}}] }) return config } }
Hyperscript implementations (frameworks)
React
Works out of the box.
What about React server components?
While they are currently alpha and not shipping soon, there is an
experimental demo
combining xdm with RSC.
You can set
providerImportSource to
'@mdx-js/react' (which has to be
installed) to support context-based components passing.
import {MDXProvider} from '@mdx-js/react' import Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS. <MDXProvider components={{em: props => <i {...props} />}}> <Post /> </MDXProvider>
But the above can also be written without configuring and importing a provider:
import Post from './post.mdx' <Post components={{em: props => <i {...props} />}} />
Preact
Define a different import source in options:
compile(file, {jsxImportSource: 'preact'})
You can set
providerImportSource to
'@mdx-js/preact' (which has to be
installed) to support context-based components passing.
See React above for more information (but use
@mdx-js/preact).
Svelte
Vue
Use Vue 3, which adds support for functional components and fragments, two
features heavily used in MDX.
Vue has a special way to compile JSX: xdm can’t do it but Babel can.
Tell
xdm to keep the JSX:
const jsx = String(await compile(file, {jsx: true}))
Then compile the JSX away with Babel and
@vue/babel-plugin-jsx:
import babel from '@babel/core' const js = (await babel.transformAsync(jsx, {plugins: ['@vue/babel-plugin-jsx']})).code
You are probably already using webpack and/or Rollup with Vue.
If not directly, then perhaps through something like Vue CLI.
In which case, see the above sections on these tools for how to use them, but
configure them as shown in this section to import
.mdx files.
Runtime libraries
Emotion
Define a different import source in options at compile time:
compile(file, {jsxImportSource: '@emotion/react'})
Otherwise, Emotion is React based, so see the React section for more info.
Theme UI
Theme UI is a React-specific library that requires using context to access its
effective components.
This can be done at the place where you’re using MDX content at runtime:
import {base} from '@theme-ui/preset-base' import {components, ThemeProvider} from 'theme-ui' import Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS. <ThemeProvider theme={base}> <Post components={components} /> </ThemeProvider>
If using a
providerImportSource set to
'@mdx-js/react' while compiling,
Theme UI automatically injects its components into that context:
import {base} from '@theme-ui/preset-base' import {ThemeProvider} from 'theme-ui' import Post from './post.mdx' <ThemeProvider theme={base}> <Post /> </ThemeProvider>
Otherwise, Theme UI is Emotion and React based, so see their sections for more
info.
Guides
GitHub flavored markdown (GFM)
To support GFM (autolink literals, strikethrough, tables, and tasklists) use
remark-gfm.
Say we have an MDX file like this:
# GFM ## Autolink literals, and [email protected] ## Footnote A note[^1] [^1]: Big note. ## Strikethrough ~one~ or ~~two~~ tildes. ## Table | a | b | c | d | | - | :- | -: | :-: | ## Tasklist * [ ] to do * [x] done
Then do something like this:
import {promises as fs} from 'node:fs' import remarkGfm from 'remark-gfm' import {compile} from 'xdm' main() async function main() { console.log( String( await compile(await fs.readFile('example.mdx'), {remarkPlugins: [remarkGfm]}) ) ) }
Show equivalent JSX
<h1>GFM</h1> <h2>Autolink literals</h2> <p> <a href=" <a href=" and <a href="mailto:[email protected]">contact@example.com</a>. </p> <h2>Footnote</h2> <p>A note<sup><a href="#user-content-fn-1" id="user-content-fnref-1" data-footnote-ref1<>Tasklist</h2> <ul className="contains-task-list"> <li className="task-list-item"> <input type="checkbox" disabled /> to do </li> <li className="task-list-item"> <input type="checkbox" checked disabled /> done </li> </ul> <section data-footnotes <h2 id="footnote-label" className="sr-only">Footnotes</h2> <ol> <li id="user-content-fn-1"> <p> Big note. <a href="#user-content-fnref-1" data-footnote-backref↩</a> </p> </li> </ol> </section>
Syntax highlighting
There are two ways to accomplish syntax highlighting: at compile time or at
runtime.
Doing it at compile time means much less code is sent down the wire (syntax
highlighting needs a lot of code).
Doing it at runtime gives flexibility.
Syntax highlighting at compile time
Use either
rehype-highlight
(
highlight.js) or
@mapbox/rehype-prism
(Prism) by doing something like this:
import rehypeHighlight from 'rehype-highlight' import {compile} from 'xdm' main(`~~~js console.log(1) ~~~`) async function main(code) { console.log( String(await compile(code, {rehypePlugins: [rehypeHighlight]})) ) }
…you still need to load a relevant style sheet.
Show equivalent JSX
<pre> <code className="hljs language-js"> <span className="hljs-built_in">console</span>.log( <span className="hljs-number">1</span>) </code> </pre>
Syntax highlighting at run time
Use for example
react-syntax-highlighter,
by doing something like this:
import SyntaxHighlighter from 'react-syntax-highlighter' import Post from './example.mdx' // Assumes an integration is used to compile MDX -> JS. <Post components={{code}} /> function code({className, ...props}) { const match = /language-(\w+)/.exec(className || '') return match ? <SyntaxHighlighter language={match[1]} PreTag="div" {...props} /> : <code className={className} {...props} /> }
Show equivalent JSX
<pre> <div className="language-js" style={{ display: 'block', overflowX: 'auto', padding: '0.5em', background: '#F0F0F0', color: '#444' }} > <code style={{whiteSpace: 'pre'}}> <span>console.</span> <span style={{color: '#397300'}}>log</span> <span>(</span> <span style={{color: '#880000'}}>1</span> <span>)</span> </code> </div> </pre>
Syntax highlighting with the
meta field
Markdown supports a meta string for code:
```js filename="index.js" console.log(1) ```
This is a hidden part of markdown: it’s normally not rendered.
But as the above example shows, it’s a useful place to put some extra fields.
xdm doesn’t know whether you’re handling code as a component or what the
format of that meta string is, so it defaults to how markdown handles it:
meta
is ignored.
The short answer is:
use
remark-mdx-code-meta,
it lets you type JSX attributes in the
meta part and exposes them on the
pre component.
Or you can do it yourself, however you want, by writing a custom plugin to
interpret the
meta field.
For example, it’s possible to pass that string as a prop by writing a rehype
plugin:
function rehypeMetaAsAttribute() { return transform } function transform(tree) { visit(tree, 'element', onelement) } function onelement(node) { if (node.tagName === 'code' && node.data && node.data.meta) { node.properties.meta = node.data.meta } }
This would yields the following JSX:
<pre> <code class="language-js" meta='filename="index.js"'> console.log(1) </code> </pre>
Note that the
meta attribute is not valid HTML, so make sure to handle
code
with a component.
The meta string in this example looks a lot like HTML attributes.
What if we wanted to parse that string and add each “attribute” as a prop?
Using the same rehype plugin as above, but with a different
onelement
function, that can be achieved:
const re = /\b([-\w]+)(?:=(?:"([^"]*)"|'([^']*)'|([^"'\s]+)))?/g // … function onelement(node) { let match if (node.tagName === 'code' && node.data && node.data.meta) { re.lastIndex = 0 // Reset regex. while ((match = re.exec(node.data.meta))) { node.properties[match[1]] = match[2] || match[3] || match[4] || '' } } }
This would yields the following JSX:
<pre> <code class="language-js" filename="index.js"> console.log(1) </code> </pre>
Note that the these added attributes are not valid HTML, so make sure to handle
code with a component.
Math
Use
remark-math
and either
rehype-katex
(KaTeX) or
rehype-mathjax
(MathJax) by doing something like this:
import rehypeKatex from 'rehype-katex' import remarkMath from 'remark-math' import {compile} from 'xdm' main() async function main() { console.log( String( // You only need one backslash in an MDX file but because this is JS wrapping it, // a double backslash is needed. await compile('# $\\sqrt{a^2 + b^2}$', { remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex] }) ) ) }
…you still need to load a KaTeX style sheet when using
rehype-katex.
Show equivalent JSX
<h1> <span className="math math-inline"> <span className="katex"> <span className="katex-mathml"> <math xmlns=" </span> <span className="katex-html" aria-…</span> </span> </span> </h1>
Frontmatter
Frontmatter, typically in YAML format, is frequently combined with markdown.
MDX comes with support for ESM (import/exports) which is a powerful dynamic
alternative.
Say we had this
post.mdx:
export const name = 'World' export const title = 'Hi, ' + name + '!' # {title}
Used like so:
import * as Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS. console.log(Post.title) // Prints 'Hi, World!'
Still, you might prefer frontmatter because it lets you define data that can be
extracted from files without (or before) compiling:
Say our
post.mdx with frontmatter looked like this:
--- title: Hi, World! --- # Hi, World!
Then without compiling or evaluating that file the metadata can be accessed like
so:
import {promises as fs} from 'node:fs' import yaml from 'js-yaml' main() async function main() { console.log(yaml.loadAll(await fs.readFile('example.mdx'))[0]) // Prints `{title: 'Hi, World!'}` }
xdm doesn’t understand YAML frontmatter by default but can understand it
using
remark-frontmatter:
import {promises as fs} from 'node:fs' import remarkFrontmatter from 'remark-frontmatter' import {compile} from 'xdm' main() async function main() { console.log( await compile(await fs.readFile('example.mdx'), { remarkPlugins: [remarkFrontmatter] }) ) }
Now it “works”: the frontmatter is ignored.
But it’s not available from inside the MDX.
What if we wanted to use frontmatter from inside the MDX file too?
Like so?
--- title: Hi, World! --- # {frontmatter.title}
That’s what
remark-mdx-frontmatter
does.
Plugins
xdm has several extension points:
- Components and a layout (wrapper) can be defined internally or passed at
runtime (see § MDX content)
- Plugins can hook into several stages of compilation (remark
plugins, rehype plugins, and the new
recma plugins)
There are also a few of these extensions made specifically for MDX:
Components
None yet!
Plugins
rehype-mdx-title
— expose the page title as a string
remark-mdx-code-meta
— interpret the code
metafield as JSX props
remark-mdx-images
— change image sources to JavaScript imports
remark-mdx-frontmatter
— change frontmatter (YAML) metadata to exports
Types
This package is fully typed with TypeScript.
To enable types for imported
.mdx,
.md, etcetera files, first make sure
the TypeScript
JSX namespace is typed (such as by importing the
react
types).
Then install
@types/mdx, which adds types to import statements of supported
files.
import Post from './post.mdx' // `Post` is now typed.
Differences from
@mdx-js/mdx
API (build):
- Remove
skipExportor
wrapExportoptions
- Add support for automatic JSX runtime
- Add support for non-react classic runtime
- Add support for source maps
- Add
evaluateinstead of
runtimepackage to eval MDX
- Remove JSX from output (by default)
- Default to automatic JSX runtime
- No GFM by default
API (run):
- No providers by default
- No runtime at all
exports work in
evaluate
- Add support for compiling import statements to dynamic import expressions
- Add support for resolving import/export sources
Input:
- ± same as
mainbranch of
@mdx-js/mdx
- Fix JSX tags to prevent
<p><h1 /></p>
- Plain markdown can be loaded (
format: 'md')
Output:
- No
isMDXContentprop on the
MDXContentcomponent
- Missing components throw instead of warn
- Sandbox: when passing
components: {h1 = () => ...}that component gets
used for
# headingbut not for
<h1>heading</h1>
- Local components (including layouts) precede over given components
- Remove support for passing
parent.childcombos (
ol.li) for components
- Remove support for passing
inlineCodecomponent (use
preand/or
code
instead)
- Support for import and exports in
evaluate
- Fix a bug with encoding
Experiments:
- Add support for
import Content from './file.mdx'in Node
- Add support for
require('./file.mdx')in Node
- Add support
allowDangerousRemoteMdxin esbuild to load MD(X) from the web
Architecture
To understand what this project does, it’s very important to first understand
what unified does: please read through the
unifiedjs/unified readme (the part
until you hit the API section is required reading).
xdm is a unified pipeline — wrapped so that most folks don’t need to know
about unified:
core.js#L76-L102.
The processor goes through these steps:
- Parse MDX (serialized markdown with embedded JSX, ESM, and expressions)
to mdast (markdown syntax tree)
- Transform through remark (markdown ecosystem)
- Transform mdast to hast (HTML syntax tree)
- Transform through rehype (HTML ecosystem)
- Transform hast to esast (JS syntax tree)
- Do the work needed to get a component
- Transform through recma (JS ecosystem)
- Serialize esast as JavaScript
The input is MDX (serialized markdown with embedded JSX, ESM, and
expressions).
The markdown is parsed with
micromark and the embedded JS with
one of its extensions
micromark-extension-mdxjs
(which in turn uses acorn).
Then
mdast-util-from-markdown
and its extension
mdast-util-mdx are used to
turn the results from the parser into a syntax tree:
mdast.
Markdown is closest to the source format.
This is where remark plugins come in.
Typically, there shouldn’t be much going on here.
But perhaps you want to support GFM (tables and such) or frontmatter?
Then you can add a plugin here:
remark-gfm or
remark-frontmatter,
respectively.
After markdown, we go to hast (HTML).
This transformation is done by
mdast-util-to-hast.
Wait, why, what does HTML have to do with it?
Part of the reason is that we care about HTML semantics: we want to know that
something is an
<a>, not whether it’s a link with a resource (
[text](url))
or a reference to a defined link definition (
[text][id]\n\n[id]: url).
So an HTML AST is closer to where we want to go.
Another reason is that there are many things folks need when they go MDX -> JS,
markdown -> HTML, or even folks who only process their HTML -> HTML: use cases
other than xdm.
By having a single AST in these cases and writing a plugin that works on that
AST, that plugin can supports all these use cases (for example,
rehype-highlight
for syntax highlighting or
rehype-katex
for math).
So, this is where rehype plugins come in: most of the plugins,
probably.
Then we go to JavaScript: esast (JS; an
AST which is compatible with estree but looks a bit more like other unist ASTs).
This transformation is done by
hast-util-to-estree.
This is a new ecosystem that does not have utilities or plugins yet.
But it’s where xdm does its thing: where it adds imports/exports, where it
compiles JSX away into
_jsx() calls, and where it does the other cool things
that it provides.
Finally, The output is serialized JavaScript.
That final step is done by astring, a
small and fast JS generator.
Security
MDX is unsafe: it’s a programming language.
You might want to look into using
<iframe>s with
sandbox, but security is
hard, and that doesn’t seem to be 100%.
For Node, vm2 sounds interesting.
But you should probably also sandbox the whole OS (Docker?), perform rate
limiting, and make sure processes can be killed when taking too long.
Related
A lot of things are going on in
xdm: parsing markdown to a syntax tree,
handling JavaScript (and JS) inside that markdown, converting to an HTML syntax
tree, converting that to a Js syntax tree, all the while running several
transforms, before finally serializing JavaScript.
Most of the work is done by:
micromark
— Handles parsing of markdown (CommonMark)
acorn
— Handles parsing of JS (ECMAScript)
unifiedjs.com
— Ties it all together
License
MIT © Titus Wormer, Compositor, and Vercel, Inc. | https://reactjsexample.com/xdm-a-really-good-mdx-compiler-no-runtime-with-esbuild-rollup-and-webpack-plugins/ | CC-MAIN-2022-21 | refinedweb | 7,771 | 50.33 |
User Details
- User Since
- May 1 2018, 4:00 AM (128 w, 6 d)
Aug 28 2020
Aug 21 2020
Aug 20 2020
LGTM from a spec point of view, but I don't think I should be the one to approve.
I'm not qualified to review the CodeGen stuff (or accept the patch, obvs. :-)) but FWIW, here are some comments on the doc and Sema side.
Aug 19 2020
Aug 18 2020
LGTM, but I don't think I should be the one to accept.
Aug 13 2020
Thanks the update, the idea looks good in general. Two questions though:
- Is it worth having two functions? I thought it might be simpler to have just getCustomEHPadPreservedMask(), with nullptr meaning “no clobbers”.
- It looks from the tests like the function isn't saving or restoring z8-z23 and p4-p15, is that right? That's fine for landing pads that can't return directly to the callee (e.g. because they rethrow). But in these tests the landing pad does return to the caller. Since the extra callee-saved registers are clobbered on the EH edge, we need to save and restore those registers ourselves on control paths that include an EH edge and a return.
Aug 12 2020
Aug 4 2020
Jul 31 2020
Jul 27 2020
Jul 16 2020
Thanks for doing this. FWIW, the patch LGTM from a spec point of view. I just saw one minor spelling nit.
May 7 2020
May 6 2020
May 5 2020
Put two other related warnings under the new option
OK, thanks! Reclaiming and reopening the revision in that case.
May 4 2020
OK, I'll leave the file as-is in that case.
May 1 2020
I'd like to promote this from an RFC to an RFA. The associated cfe-dev discussion was:
Don't refer to the sizeless types as "scalars"
Mar 31 2020
Require operators to be defined as static or inside a namespace
Mar 30 2020
Mar 27 2020
Mar 25 2020
Mar 24 2020
Mar 17 2020
Mar 16 2020
Mar 13 2020
Allow pointers to sizeless types to be caught.
Mar 12 2020
Allow pointers to sizeless types to be thrown.
Allow pointers to sizeless types to be thrown.
Add a test for the BuildCaptureField change | http://reviews.llvm.org/p/rsandifo-arm/ | CC-MAIN-2020-45 | refinedweb | 384 | 80.62 |
Tools that honor the Cell size environment setting set the output raster cell size, or resolution, for the operation. The default output resolution is determined by the coarsest of the input raster datasets.
Usage notes
- To use a specific numeric cell size, type the value in the box directly.
- The default output resolution is determined by the coarsest of the input raster datasets.
- The default cell size when a feature dataset is used as input to a tool is to take the width or height (whichever is shorter) of the extent of the feature dataset, divided by 250.
- If a numeric cell size value is specified, then it will not be projected if the output is in a spatial reference which is different from that of the input data. In the other cases the input dataset will be projected and the new cell size will be used.
- Exercise caution when specifying a cell size finer than the input raster datasets. No new data is created; cells are interpolated using nearest neighbor resampling. The result is only as precise as the coarsest input.
Dialog syntax
- Maximum of Inputs—Use the largest cell size of all input datasets. This is the default.
- Minimum of Inputs—Use the smallest cell size of all input datasets.
- Same as Layer <name>—Use the cell size of the specified layer or raster dataset.
Scripting syntax
arcpy.env.cellSize = cellsize_option
import arcpy # Set the cell size environment using a keyword. arcpy.env.cellSize = "MINOF" # Set the cell size environment using a number. arcpy.env.cellSize = 20 # Set the cell size environment using a raster dataset. arcpy.env.cellSize = "C:/sapyexamples/data/myraster" | http://pro.arcgis.com/en/pro-app/tool-reference/environment-settings/cell-size.htm | CC-MAIN-2019-09 | refinedweb | 275 | 56.76 |
EP first pages.
Templates
- FirstNewsTemplate
- SecondNewsTemplate
- ThirdNewsTemplate
- FourthNewsTemplate
- HeaderTemplate
- FooterTemplate
- NewsTemplate
- PagingHeaderTemplate
- PagingFooterTemplate
The properties are the same as with the PageList class (they both inherit from PageListData).
The NewsList is per default sorted by PageStartPublish with the newest at the
Example
As you can see I’m using a few extension methods (GetIntroText, GetNewsImage, GetMainNewsImage):
You also have to add <%@ Import Namespace="EPiServer.Templates.Util"%> (replace it with your namespace for your extensions class) to your web form.
HTML markup rendered
Now with a little CSS we can do a lot of cool things to the layout.
Result
Other posts in this series
- EPiServer web controls: Property
- EPiServer web controls: PageList
- EPiServer web controls: MenuList and PageTree
Mathias Nohall says:Post Author June 27, 2011 at 16:26
Nice guide!
I am also trying to build a news page template.
Hoewever Im new to EpiServer so I am trying to build stuff as low key as possible
I get this error
” Error 1 ‘EPiServer.Core.PageData’ does not contain a definition for ‘GetTitle’ and no extension method ‘GetTitle’ accepting a first argument of type ‘EPiServer.Core.PageData’ could be found (are you missing a using directive or an assembly reference?)”
this is my code:
web form..
<— shouldt really have to do this since um using the code behind?
.
.
.
.
code behind..
public static string GetTitle(this PageData pageData){
string text = pageData[“Title”] as string;
return text;
}
any ideas?
Mathias Nohall says:Post Author June 27, 2011 at 16:32
hehe, some code where filtered out in my previous post.
and I also now have some problem getting past your spam filter..
web form..
@ Import Namespace=”Qwerty.Templates.Pages <— shouldt really have to do this since um using the code behind?
.
.
Container.CurrentPage.GetTitle()
.
put some text here to get by spam filter, tra la la la hej på dig. | http://www.frederikvig.com/2009/07/episerver-web-controls-newslist/ | CC-MAIN-2017-30 | refinedweb | 309 | 54.12 |
I have a simple program like this:
package test;
public class TestGenericsInheritance {
public static void main(String[] args) {}
public static abstract class A<Q>{
public void foo2(Q obj){}
public abstract <T> void foo(T obj);
}
public static class C extends A<Object>{
@Override
public <T> void foo(T obj) {}
}
public static class B extends A{
@Override
public <T> void foo(T obj) {}
}
}
/D:/Projects/.../test/TestGenericsInheritance.java:[24,19]
test.TestGenericsInheritance.B is not abstract and do es not override
abstract method foo(java.lang.Object) in
test.TestGenericsInheritance.A
/D:/Projects/.../test/TestGenericsInheritance.java:[27,25] name clash:
foo(T) in test.TestGenericsInheritance .B and foo(T) in
test.TestGenericsInheritance.A have the same erasure, yet neither
overrides the other
/D:/Projects/.../test/TestGenericsInheritance.java:[26,9] method does
not override or implement a method from a supertype
public void foo(Object obj)
B extends the raw type
A. Because you use a raw type, all generic information is erased, not only the type variable you failed to specify (see Section 4.6 of the Java Language Specification). This means that
A has a method
void foo(Object obj), whereas
A<SomeType> has a method
<T> void foo(T obj).
If you override a method, it must have the same signature (optionally after taking the type erasure of the overridden method) -- interestingly, the overriding method may have a different, more specific, return type. The signatures of your two methods are different (you would need type erasure in the overriding method), and therefore your example doesn't compile.
The reason type erasure was implemented as it is, is backwards compatibility. The idea was that new code would only use generics, and that only old code would use raw types. So, the goal was not to make raw types the most convenient (because new code shouldn't use them anyway), but to make raw types the most compatible.
Consider for example the class
ArrayList, which was introduced in Java 2 (well before generics). It had a method
public Object[] toArray(Object[] a). In Java 5 generics were introduced, and the signature of this method could be changed to
public <T> T[] toArray(T[] a) (where
T is not the element type) without difficulty: because of the way type erasure is implemented, for old code which used (or subclassed)
ArrayList rather than
ArrayList<SomeType> the method signature stayed the same. | https://codedump.io/share/30LFwxZgxMFY/1/java-generics---extending-generic-class-with-generic-function | CC-MAIN-2017-17 | refinedweb | 399 | 51.58 |
[ ]
Sameer Paranjpye commented on HADOOP-334:
-----------------------------------------
Dhruba:
Yes, we would get correct semantics if the image and edits overlap. While not strictly necessary,
we could also add timestamps to entries in the image and edits for validation. Suppose the
edits file has the following transactions:
- x: add file /a/b/c, time=t0
- y: remove file /b/c, time=t1
- z: rename directory /a --> /d, time=t2
which all overlap with the image. In this case, when the image and edits are being merged
the following would happen for each transaction:
x: the image already has file /a/b/c, assert that directory /a/b has timestamp t3 >= t0,
we're consistent with the edits, move on
y: the image does not have the file /b/c, assert that directory /b has timestamp t4 >=
t1, we're consistent with the image, move on
z: the image already has the directory /d, assert that directory /d has timestamp t5 >=
t2, we're consistent with the edits, move on
this sort of logic can be followed for all transactions. So we don't need a transaction number,
a timestamp will suffice.
> Redesign the dfs namespace datastructures to be copy on write
> -------------------------------------------------------------
>
> Key: HADOOP-334
> URL:
> Project: Hadoop
> Issue Type: Improvement
> Components: dfs
> Affects Versions: 0.4.0
> Reporter: Owen O'Malley
> Assigned To: Konstantin Shvachko
>
> The namespace datastructures should be copy on write so that the namespace does not need
to be completely locked down from user changes while the checkpoint is being made.
--
This message is automatically generated by JIRA.
-
If you think it was sent incorrectly contact one of the administrators:
-
For more information on JIRA, see: | http://mail-archives.apache.org/mod_mbox/hadoop-common-dev/200611.mbox/%3C1425357.1162855180514.JavaMail.jira@brutus%3E | CC-MAIN-2015-11 | refinedweb | 277 | 50.8 |
. You say "nobody has done it", but that is
an incorrect argument. Nobody has been ABLE to do it because we
glommed shit into a mother REPORT. And serf needs some more work
before people can TRY it. So I respectfully disagree with any argument
about cachability being a non-requirement.
Cheers,
-g
On Tue, Sep 30, 2008 at 3:30 PM, Ben Collins-Sussman
<sussman_at_red-bean.com> wrote:
> On Tue, Sep 30, 2008 at 3:24 PM, <gstein_at_tigris.org> wrote:
>
>> Unfortunately, DeltaV is an insanely complex and inefficient protocol,
>> and doesn't fit Subversion's model well at all. The result is that
>> Subversion speaks a "limited portion" of DeltaV, and pays a huge price
>> for this complexity: speed.
>>
>> +### GJS: doesn't fit? heh. IMO, it does... you should have seen it
>> + *before* I grok'd the design and started providing feedback. it
>> + just doesn't match it *precisely*
>
> Sure, I remember. But still, we only implement "just enough" DeltaV
> to look like a DAV server to a dumb DAV client. But there are no
> 3rd-party DeltaV clients that run against mod_dav_svn, and there are
> no 3rd-party DeltaV servers that can talk to an svn client. Nearly
> every single "interesting" svn_ra.h interface is done through a custom
> REPORT -- checkout, update, log, etc. We've surrounded ourselves with
> DeltaV formalities that provide a lot of complexity and zero value.
>
>
>> +
>> A typical network trace involves dozens of unnecessary turnarounds
>> where the client keeps asking for the same information over and over
>> again, all for the sake of following DeltaV. And then once the client
>> @@ -33,6 +38,19 @@ has "discovered" the information it need
>> custom REPORT request anyway. Most svn operations are at least twice
>> as slow over HTTP than over the custom svnserve protocol.
>>
>> +### GJS: that is the fault of the client, not the protocol. somewhere
>> + around the time that I stopped working on SVN for a while, I
>> + identified several things that an RA layer could cache in order to
>> + avoid looking them up again. nobody ever implemented that. thus,
>> + it is hard to claim the fault lies in the protocol when we KNOW we
>> + don't have to re-fetch certain items.
>
> But this just makes our existing clients more and more complex. Why
> are we doing PROPFINDs at all, ever? Unless we're actually trying to
> implement svn_ra_get_prop(), every single PROPFIND we do before our
> custom REPORTs are just weird formalities related to DeltaV discovery.
> Even if we completely remove all the redundant PROPFIND requests, we
> still get absolutely nothing out of following the DeltaV rules in
> these cases.
>
>> +
>> +### GJS: turnarounds don't have to be expensive if you can pipeline
>> + them. that is one of the (design) reasons for Serf. Again,
>> + unrelated to the protocol, but simply the implementation. And
>> + proposing a *new* implementation rather than fixing an existing
>> + one seems to be a much more monumental task.
>
> I have to do a reality check here: the promise of serf is that
> checkouts/updates would be faster than neon, because we could pipeline
> a bunch of GET requests rather than suck down the tree in one
> response. In practice, serf has proven to be no faster than neon in
> this regard. (Or if faster, only by a tiny percent.)
>
> I understand that the "real" promise here is that of caching proxy
> servers, which will supposedly deliver serf's original speed promises
> to us... but I've lost my faith in this idea:
>
> * nobody's actually done it yet and demonstrated it
>
> * given that BDB and/or FSFS is (typically) already serving popular
> fs-nodes out of RAM (due to OS caching), I don't think a proxy-server
> serving nodes out of RAM will be any faster.
>
>
>> +
>>
>> PROPOSAL
>> ========
>> @@ -41,15 +59,22 @@ Write a new HTTP protocol for svn; map
>> requests.
>>
>> * svn over HTTP would be much faster (eliminate turnarounds)
>> +
>> +### GJS: again: pipelining.
>
> Are we going to pipeline every single request in svn_ra.h? Does it
> even make sense to do so? I don't view it as a magic bullet.
>
>
>>
>> * svn over HTTP would be almost as easy to extend as svnserve.
>>
>> +### GJS: have we had an issue with extending our current HTTP use?
>
> Let's ask folks who have implement the mod_dav_svn get-lock-report,
> get-locations report, mergeinfo-report, etc.
>
> But meanwhile, I maintain it's not so much about extending as it is
> about maintaining. Anyone should be able to understand what's
> happening in the HTTP layer, debug it, rev an interface by adding a
> new parameter. Nobody is scared of doing this in svnserve. To do
> this in mod_dav_svn, people need a 3 hour lecture in the architecture
> of the system, DeltaV terminology, etc.
>
>
>> +
>> * svn over HTTP would be comprehensible to devs and users both
>> (require no knowledge of DeltaV concepts).
>>
>> * We'd still maintain almost all of Apache's advantages
>> (propositions A through E above).
>>
>> +### GJS: and with the right design, should be able to get the G that I
>> + added above.
>> +
>> * We'd give up proposition F, which hasn't given us anything but the
>> ability to mount svn repositories as network drives. (For those
>> who *really* need this rarely-used feature, mod_dav_svn would
>> @@ -58,6 +83,11 @@ requests.
>> * We could freely advertise a fixed syntax for browsing older
>> revisions, without worrying about violating DeltaV.
>>
>> +### GJS: we can do this today. DeltaV certainly doesn't proscribe what
>> + we can do in our URL namespace. my reluctance to advertise one was
>> + to give us maximum flexibility on the server, and to defer browing
>> + to external tools like ViewVC or Trac.
>
> Agreed, this feature isn't tied to a protocol rewrite at all. I'll
> remove it from the doc.
>
>
>
>> +
>>
>> MILE-HIGH DESIGN
>> ================
>> @@ -124,6 +154,9 @@ DESIGN
>>
>> GET /repos?cmd=get-file&r=23&path=/trunk/foo.c
>>
>> +### GJS: in order to allow for intermediate caches to work, the URLs
>> + need to be well-designed up-front. I can help with that.
>
> Is caching really a goal? Why is it so important on your list?
>
>
>> +
>> For requests which require large data exchanges, the big payloads go
>> into request and/or response bodies. For example:
>>
>> @@ -131,6 +164,11 @@ DESIGN
>>
>> [body contains complete 'update report' describing working copy's
>> revisions; response is a complete editor-drive.]
>> +
>> +### GJS: no. I've never seen a GET request with a body. You want to
>> + avoid that, or you could end up being incompatible with many
>> + proxies. If you need input data, then make it a POST, or use one
>> + of the other HTTP methods defined by HTTP, WebDAV, or DeltaV.
>
> Ah, ok, so any request bodies will probably need to be POSTs or somesuch.
>
>
>
>>
>> POST /repos?cmd=commit&keeplocks=true
>>
>> @@ -170,6 +208,12 @@ DESIGN
>> embedded s-expressions, exactly like svnserve does. Heck, maybe we
>> could even use svnserve's parsing/unparsing code!)
>>
>> +### GJS: personally, I'd recommend protocol buffers, or Apache Thrift
>> + (a third-party reimplementation of PBs done at facebook). just
>> + toss out the formats used in FS and the svn protocol, and let a
>> + new/external library do the marshalling for us.
>> +
>
> Hmmm, interesting.
>
> Honestly, it sounds to me like you might be willing to toss away all
> the DeltaV junk, just as long as we still make individual GETs of
> (rev, path) objects (1) possible, (2) cacheable, (3) pipelineable.
> Those seem to be the things that are important to you.
>
> If that's the case, I *still* think we need a new protocol, and a new
> server and client to implement it. The idea is to start clean, build
> the smallest possible protocol with the smallest amount of code,
> directly corresponding with svn_ra.h as much as possible... and heck,
> if we can get pipelining and cacheability in there too, great. But I
> cannot comprehend achieving this goal by modifying the existing
> codebase.... it would just be adding even more complexity to something
> already incomprehensible to most of the svn developers.
>
> ---------------------------------------------------------------------
>-01 01:01:03 CEST
This is an archived mail posted to the Subversion Dev
mailing list. | http://svn.haxx.se/dev/archive-2008-10/0005.shtml | CC-MAIN-2013-20 | refinedweb | 1,342 | 64.81 |
Hello, I'm new to java and am completely lost in this program I am supposed to create.
This program should have six methods:
intro ()
This method will output a welcome message to the user.
getRows()
This method will ask the user for the number of rows they would like in their multiplication table. It will set the row array to the size the user requests.
getCols()
This method will ask the user for the number of columns they would like in their multiplication table. It will set the column array to the size the user requests.
fillRows()
This method will fill the row array with the numbers to be used to multiply against the column array to get the multiplication table.
fillCols()
This method will fill the column array with the numbers to be used to multiply against the row array to get the multiplication table.
printTable()
This method will print the size of the table, the headers for the columns and rows, as well use for loops to print the multiplication table
the output should be like
Welcome to the Multiplication Table Program!
Enter number of rows:6
Enter number of columns:4
Here is your 6 x 4 multiplication table:
1 2 3 4
---------------------------
1| 1 2 3 4
2| 2 4 6 8
3| 3 6 9 12
4| 4 8 12 16
5| 5 10 15 20
6| 6 12 18 24
Here's what I've got so far:
import java.util.Scanner; public class MultTable { public static void main ( String args[] ) { int[] rows; int[] cols; } public void intro(); { System.out.println("Welcome to the Multiplication Table program!"); } public int getRows(int[] rows) { int numr; Scanner input = new Scanner(System.in); System.out.print("Enter number of rows: "); numr = input.nextInt(); } public int getCols(int[] cols) { int numc; Scanner input = new Scanner(System.in); System.out.print("Enter number of columns: "); numc = input.nextInt(); } public int fillRows(int[] rows); { } public int fillCols(int[] cols); { } public int printTable(int[] cols, int[] rows); { for(int i = 1; i < rows.length; i++) { rows[i] = i; } for(int j = 1; j < cols.length; j++) { cols[j] = j; } } }
I am unsure of how I should tackle the fillRows() and fillCools() methods. I have a relative idea of what the printTable() should be like, but other than that, I am lost.
I would be grateful to anyone who can help through this. | http://www.javaprogrammingforums.com/whats-wrong-my-code/28009-java-multiplication-table.html | CC-MAIN-2014-42 | refinedweb | 402 | 70.53 |
Method of continuity for solving nonlinear equations - Part II
Posted March 01, 2013 at 06:17 PM | categories: nonlinear algebra | tags: | View Comments
Updated March 03, 2013 at 12:22 PM
Matlab post Yesterday in Post 1324 we looked at a way to solve nonlinear equations that takes away some of the burden of initial guess generation. The idea was to reformulate the equations with a new variable \(\lambda\), so that at \(\lambda=0\) we have a simpler problem we know how to solve, and at \(\lambda=1\) we have the original set of equations. Then, we derive a set of ODEs on how the solution changes with \(\lambda\), and solve them.
Today we look at a simpler example and explain a little more about what is going on. Consider the equation: \(f(x) = x^2 - 5x + 6 = 0\), which has two roots, \(x=2\) and \(x=3\). We will use the method of continuity to solve this equation to illustrate a few ideas. First, we introduce a new variable \(\lambda\) as: \(f(x; \lambda) = 0\). For example, we could write \(f(x;\lambda) = \lambda x^2 - 5x + 6 = 0\). Now, when \(\lambda=0\), we hve the simpler equation \(- 5x + 6 = 0\), with the solution \(x=6/5\). The question now is, how does \(x\) change as \(\lambda\) changes? We get that from the total derivative of how \(f(x,\lambda)\) changes with \(\lambda\). The total derivative is:
$$\frac{df}{d\lambda} = \frac{\partial f}{\partial \lambda} + \frac{\partial f}{\partial x}\frac{\partial x}{\partial \lambda}=0$$
We can calculate two of those quantities: \(\frac{\partial f}{\partial \lambda}\) and \(\frac{\partial f}{\partial x}\) analytically from our equation and solve for \(\frac{\partial x}{\partial \lambda}\) as
$$ \frac{\partial x}{\partial \lambda} = -\frac{\partial f}{\partial \lambda}/\frac{\partial f}{\partial x}$$
That defines an ordinary differential equation that we can solve by integrating from \(\lambda=0\) where we know the solution to \(\lambda=1\) which is the solution to the real problem. For this problem: \(\frac{\partial f}{\partial \lambda}=x^2\) and \(\frac{\partial f}{\partial x}=-5 + 2\lambda x\).
import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt def dxdL(x, Lambda): return -x**2 / (-5.0 + 2 * Lambda * x) x0 = 6.0/5.0 Lspan = np.linspace(0, 1) x = odeint(dxdL, x0, Lspan) plt.plot(Lspan, x) plt.xlabel('$\lambda$') plt.ylabel('x') plt.savefig('images/nonlin-contin-II-1.png')
We found one solution at x=2. What about the other solution? To get that we have to introduce \(\lambda\) into the equations in another way. We could try: \(f(x;\lambda) = x^2 + \lambda(-5x + 6)\), but this leads to an ODE that is singular at the initial starting point. Another approach is \(f(x;\lambda) = x^2 + 6 + \lambda(-5x)\), but now the solution at \(\lambda=0\) is imaginary, and we do not have a way to integrate that! What we can do instead is add and subtract a number like this: \(f(x;\lambda) = x^2 - 4 + \lambda(-5x + 6 + 4)\). Now at \(\lambda=0\), we have a simple equation with roots at \(\pm 2\), and we already know that \(x=2\) is a solution. So, we create our ODE on \(dx/d\lambda\) with initial condition \(x(0) = -2\).
import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt def dxdL(x, Lambda): return (5 * x - 10) / (2 * x - 5 * Lambda) x0 = -2 Lspan = np.linspace(0, 1) x = odeint(dxdL, x0, Lspan) plt.plot(Lspan, x) plt.xlabel('$\lambda$') plt.ylabel('x') plt.savefig('images/nonlin-contin-II-2.png')
Now we have the other solution. Note if you choose the other root, \(x=2\),” or physically reasonable? But it does give a way to solve an equation where you have no idea what an initial guess should be. You can see, however, that just like you can get different answers from different initial guesses, here you can get different answers by setting up the equations differently.
Copyright (C) 2013 by John Kitchin. See the License for information about copying. | http://kitchingroup.cheme.cmu.edu/blog/2013/03/01/Method-of-continuity-for-solving-nonlinear-equations-Part-II/ | CC-MAIN-2018-30 | refinedweb | 693 | 64.91 |
NAMEfinger - user information lookup program
SYNOPSISfinger [-lmsp ] [user ... ] [user@host ... ]
DESCRIPTIONThe finger displays information about the system users.
Options are:
- -s
- Finger displays the user's login name, real name, terminal name and write status (as a ``*'' after the terminal name if write permission described for the -s option as well as the user's home directory, home phone number, login shell, mail status, and the contents of the files ``.plan '' ``.project '' ``.pgpkey '' and ``.forward '' from the user
- Prevents the -l option of finger from displaying the contents of the ``.plan '' ``.project '' and ``.pgpkey '' files.
- -m
- Prevent matching of user names. User is usually a login name; however, standard output is a socket, finger will emit a carriage return (^M) before every linefeed (^J). This is for processing remote finger requests when invoked by fingerd(8).
SEE ALSOchfn(1), passwd(1), w(1), who(1)
Important: Use the man command (% man) to see how a command is used on your particular computer.
>> Linux/Unix Command Library | http://linux.about.com/library/cmd/blcmdl1_finger.htm | CC-MAIN-2014-10 | refinedweb | 166 | 53.81 |
cgic is a CGI library for C written by Thomas Boutell (). Like CGI.pm and cgi-lib.pl, it is used to decode data submitted by the user and make it available within your CGI program. The only difference is that this library is written to work with C programs instead of programs written in Perl or any other language.
Before you can use cgic, you have to import it into your C program. Generally, it is loaded into your CGI program using a line like:
#include "cgic.h"
Programs written to work with cgic differ from standard C programs in some ways. All C programs must contain a function named main() in order to compile and execute properly. When you write programs that use cgic, you eliminate the main() ...
No credit card required | https://www.oreilly.com/library/view/sams-teach-yourself/0672324040/0672324040_ch11lev1sec6.html | CC-MAIN-2019-30 | refinedweb | 134 | 75.2 |
Hi.
Join the conversationAdd Comment
The person who coined the name certainly went to unimaginable lengths to come up with a cool name!
Yeah… I'm not a 100% sure but I believe that he's the same guy who created the acronym RAII (Resource Acquisition Is Initialization). Although if I'm right about the guy, he still owns the credits for having invented the programming language which, without it, we wouldn't be discussing in this space. :-)
C++ syntax is very hard.Microsoft must implement new native language such as C# syntax.
C++ is depend to 1980.
new native language with garbage collection and …
Indeed it is harder, fery. But have you been following the syntax improvements achieved with the latest standard C++11? I recommend you this reading by Herb Sutter as I see you talking about garbage collection and I feel, correct me if I'm wrong, like you may not be aware about improvements like smart pointers in this case. Herb's paper is here: herbsutter.com/elements-of-modern-c-style
Hi, thanks for improvements! Maybe you can (binary compatibly!) reduce the increadible slowdown of iterators in debug mode in next release? Try something like std:vector<std:list<int>:iterator>. That would be Great!
I think the acronym RAII (for "Resource Acquisition Is Initialization") was given by Bjarne Stroustrup himself.
Narom: First, the STL gets to break binary compatibility between major releases (which is wonderful). Second, I have an idea to reduce the cost of our extensive correctness checks in debug mode, which I'd like to try someday. (Currently, we track iterators with a singly-linked list; I suspect that a doubly-linked list would be significantly more efficient when a container has many iterators.) However, it will always be quite expensive in absolute terms, since we need to take locks for operations that look like reads.
> First, the STL gets to break binary compatibility between major releases (which is wonderful).
Yes … and starting with VS10 it even refuses to link against incompatible versions (provided they are VS10+ too), which is also wonderful. Of course, that only means that I'm protected against linking my VS11 program against a VS10 library, not my VS10 program against a VS8 library. If you do that, you still get surprising runtime crashes.
To think that you guys implemented a compiler/linker extension to achieve this, when the C++11 standard has inline namespaces to achieve the same thing, only in a way that would protect against the second class of errors too.
Out of curiosity, is there a benefit to relying on SCARY iterators like that, when decltype would allow the programmer to choose the correct iterator without knowing the allocator type, while also being compatible with any compiler that supports C++11 but doesn’t implement SCARY iterators?
I can see how SCARY iterators are a major boon when working with pre-existing code that assumes everything uses the default allocator, but I don’t see how they’d be more useful than decltype, especially with compilers not required to implement them. Relying on them could cause nasty surprises in portable code, if compiled with a compiler that doesn’t use them.
Let’s imagine, we have 2 class `list` and `list`, without SCARY iterator, the compiler have to generate 2 more class for 2 kinds of generator -> increase compile time and the executable size!
ultra under selling’s person who creates shoes’ detail demand diligently, the first woman shoesSupra shoes modern design, the classics, best-selling brand’s individual inspiration is enthusiastic. The new ultra shoes, the precision and the work quality, create the ultra under selling original classical shoes. | https://blogs.msdn.microsoft.com/vcblog/2012/04/06/what-are-scary-iterators/ | CC-MAIN-2018-09 | refinedweb | 616 | 52.49 |
Memoisation is a common technique applied to reduce unnecessary repeated calculations in programming. This technique is frequently brought up as one of the dynamic programming techniques, and in articles, books aiming to help you get your first developer job.
In this article, you'll:
@lru_cachein Python
@lru_cache
@lru_cache-decorated functions
If you're already familiar with the concept of memoisation, feel free to skip the first section.
Memoisation is a technique used to ensure the results of a function is stored for the given arguments. Subsequent function invocations with the same arguments should be immediately returned with the previously-stored result.
There are ways to achieve memoisation. In Python, a decorator is a stark candidate. Let's say we defined a function called
calculate_variance() that doesn't possess any abilities to remember any previously calculated results:
from typing import Tuple import statistics def calculate_variance(numbers: Tuple[int]): return statistics.variance(numbers)
To make our
calculate_variance() memoise the previously calculated results, there is no need to reimplement the logic to calculate variance. Instead, we would use a
@memoise decorator as mentioned.
Eagle-eyed readers may also notice the input argument
numbersis typed with
Tuple[int], you will see why a
Tupleinstead of a
Listis used in the last section.
from typing import Tuple import statistics def calculate_variance(numbers: Tuple[int]): return statistics.variance(numbers)
How should we implement the
@memoise decorator? I've heard you ask. A simple implementation would be a function that keeps tracks of the input arguments and results in a hashmap and performs calculations only when the results are not found.
from typing import Tuple def memoise(target_function): memo = {} def wrapper(number: Tuple[int]): hashed_number = hash(number) if number not in memo: memo[hashed_number] = target_function(x) return memo[hashed_number] return wrapper
The
@memoise decorator should work fine with our
calculate_variance() function. However, often time, we may come across situations where we need to tailor the memoisation behaviour. For instance, we may want to limit the size of the hashmap, or inspect if the memoised function is working as intended. Fortunately, Python comes with a built-in decorator
@lru_cache that gives us the customisability we need.
@lru_cache- The One-Liner To Memoise In Python
@lru_cache is a built-in decorator provided by the
functools package that adds memoisation capability to any functions decorated. Strictly speaking, it works not just with functions but any
Callable.
Let's rewrite our
calculate_variance() function with the
@lru_cache decorator.
from functools import lru_cache # Add this line from typing import Tuple import statistics def calculate_variance(numbers: Tuple[int]): return statistics.variance(numbers)
With slight changes, we implemented another memoised version of
calculate_variance(). Let's invoke and observe our memoised
calculate_variance() with the same set of arguments several time.
We can clearly see that the function is working correctly. However, how do we know if the values returned are the memoised values?
cache_info()
Thanks to
@lru_cache, the memoised function now includes a useful method to allow us to peek into the memoisation information (or cache info).
Let's take a look at the screenshot below:
In
In[2],
calculate_variance.cache_info() is called immediately after the definition of
calculate_variance(). From
Out[2], we can see a bunch of cache info, including
hit,
miss,
maxsize, and
cursize, but what are those?
hit): number of times when a memoised result is found
miss): the contrary of cache hit, or the number of times when calculations are required
maxsize): the maximum number of memoised results stored
cursize): the current number of memoised results stored
Let's try to invoke
calculate_variance() with the same argument a few more times and inspect the cache info.
As you can see, the cache hit increases as the function is called with the same argument. ✌️✌️✌️
While I can't think of a good situation where a cache purge is required,
@lru_cache includes a handy method
cache_clear() to purge the memoised results.
@lru_cache
typed- Treat Values Of Different Types As Separate Entries
Is the integer
2 the same as
2.0? While
2 == 2.0 is evaluated to
True, we recognise they are of different types,
int and
float. The second control knob of
@lru_cache allows us to treat values with different types as separate cache entries. By default, the value of the keyword argument
typed is
False.
From the screenshot above, we can see the
cursize grows when
add() is called with the numbers but of different types.
maxsize- The Maximum Size Of The Cache
As mentioned earlier,
@lru_cache allows us to tune the maximum size of the cache. To do so, simply pass the keyword argument
maxsize into the decorator as shown:
If we want unlimited cache size, all we need is to set
maxsize to
None.
The cache replacement policy of
@lru_cache is obviously LRU or Least Recently Used. What does that mean though?
Before we think about when to replace a memoised value, let's think about when a replacement is required. Recapping how memoisation works, we know that after a new calculation is performed, the new result would be stored in the memoised results (or cache) before returning value to the caller.
With the LRU cache replacement policy, when a new result is produced and the cache is full (
cursize == maxsize), the least recently used pair will be replaced with the newer pair.
@lru_cache-Decorated Functions
@lru_cache treats
add(1, 2) and
add(2, 1) as two distinct arguments set.
In our example of
calculate_variance(), we typed the input argument
numbers with
Tuple[int].
It is because all input arguments passed to a memoised function must be hashable.
What does hashable mean? According to the official Python glossary, a value is considered hashable if it has a hash value which never changes during its lifetime and can be compared with another value of same type.
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
How do we know if a value is hashable? A quickiest way is to try to hash the value with the built-in
hash() function.
From the screenshot above, we could see that all immutable values are hashable, as well as user-defined class instances. However, Python built-in mutable containers (list, dict, etc) are not.
If we call a memoised (or
@lru_cache-decorated) function with a unhashable type, a
TypeError will be raised.
By now, you should know:
@lru_cacheworks in Python
typedand
maxsizeof
@lru_cache
@lru_cache-decorated functions
Python
functools package provides more than just the
@lru_cache. I recommend you to check it out! 🧐
I hope this article helps. Feel free to share it with your mates. I appreciate if you could give this article some claps 👏👏👏. | https://melvinkoh.me/memoisation-in-python-exploring-lru_cache-and-its-control-knobs-ck9fgbgjt060ocss17pm4b5yi?guid=none | CC-MAIN-2020-29 | refinedweb | 1,114 | 54.32 |
How many of you still use RSS?
I'm willing to bet the answer is "Not Many", but the reality is, you use it without realizing.
Take your blog.
Does it run on WordPress? Well, take a close look at it, then, because it'll be using RSS. Your browser, too, has an RSS Feed reader built into it, and let's not forget many of the Google APIs, such as the YouTube search API, that returns its results as an Atom feed, which is a newer type of the original RSS Protocol. Even this blog you're reading now has an RSS feed if you look at the .NET Nuts and Bolts index page.
The fact is that XML-based RSS & Atom feeds are still used in quite a lot of places, and although they may not be as popular as they once were, they do still have their uses.
I have a client that uses them for workplace notifications. A custom plug-in has been written for the Chrome browser all his staff use. this-plug in monitors an XML end point on a central Windows service, and when there's a short message to send out to all staff, it's sent to this service, which sends it out as an RSS feed, which is then rendered in the user's browser.
I have a similar setup on the PC I'm writing this on. It tells me when my phone's ringing. (I often don't hear it because I have headphones on.)
What many folks don't know, however, is that .NET has built-in classes for creating syndication feeds, and these can be found in the "System.ServiceModel.Syndication" namespace.
Reading a Feed
Reading a feed is simple. The RSS feed for this blog can be found at. We can easily read this and display its contents by using the following code.
Rss20FeedFormatter rssFormatter; using(var xmlReader = XmlReader.Create ("")) { rssFormatter = new Rss20FeedFormatter(); rssFormatter.ReadFrom(xmlReader); } var title = rssFormatter.Feed.Title.Text; foreach (var syndicationItem in rssFormatter.Feed.Items) { Console.WriteLine("Article: {0}", syndicationItem.Title.Text); Console.WriteLine("URL: {0}", syndicationItem.Links[0].Uri); Console.WriteLine("Summary: {0}", syndicationItem.Summary.Text); Console.WriteLine(); }
When added to a console mode program, the output looks like this:
Figure 1: The console mode output
It's up to you how you deal with it, but you can see just how easy it is to grab the XML from a feed, pass it to the Rss Version 2 formatter, and then iterate over the collection of items available.
If the feed specifies it, each item also has a list of authors, tags, and various other bits of meta information that could be used to decide how to present an item. You could, for example, in the case of an internal notification system, decide to show items with an "Urgent" tag immediately.
Producing RSS Feeds
Reading them is one thing, but the syndication classes also can be used to produce RSS feed data just as easily. Let's imagine we have the following object definition:
public class ArticleSummary { public string Title { get; set; } public string Url { get; set; } public string Summary { get; set; } }
We can produce a feed similar to this blog's, by using the formatter in the reverse direction.
First, let's create some data to add to the feed.
List<ArticleSummary> articles = new List<ArticleSummary> { new ArticleSummary {Title = "Article 1", Url = "", Summary = "This is article one"}, new ArticleSummary {Title = "Article 2", Url = "", Summary = "This is article two"}, new ArticleSummary {Title = "Article 3", Url = "", Summary = "This is article three"}, new ArticleSummary {Title = "Article 4", Url = "", Summary = "This is article four"}, new ArticleSummary {Title = "Article 5", Url = "", Summary = "This is article five"} };
Once you have some data, you can easily construct the feed by using the following code:
var newFeed = new SyndicationFeed(); newFeed.Generator = "My .NET Program"; newFeed.Language = "en-gb"; newFeed.LastUpdatedTime = DateTime.UtcNow; newFeed.Title = SyndicationContent. CreatePlaintextContent("My Article Feed"); newFeed.Items = articles.Select(article => new SyndicationItem { Title = SyndicationContent. CreatePlaintextContent(article.Title), Content = SyndicationContent. CreatePlaintextContent(article.Summary), BaseUri = new Uri(article.Url) });
To format it as an Rss version 2 feed, use the following:
SyndicationFeedFormatter formatter = new Rss20FeedFormatter(newFeed);
or for an Atom feed, this:
SyndicationFeedFormatter formatter = new Atom10FeedFormatter(newFeed);
At this point, you have a streamable XML object, so you can send it to an MVC Return type, an XML Output stream, a Linq to XML query, and all sorts of other things.
To close this post, let's push it out as a formatted XML string to the console:
var output = new StringBuilder(); using(var writer = XmlWriter.Create(output, new XmlWriterSettings{Indent = true})) { formatter.WriteTo(writer); writer.Flush(); } Console.Write(output.ToString());
If everything has worked okay, you should see the following:
Figure 2: Formatted XML is now visible
Discovered a strange .NET object you didn't know existed, or just have an idea for a subject this column should cover? Ping me on Twitter as @shawty_ds and let me know. You might see if featured in a future post. | https://mobile.codeguru.com/columns/dotnet/syndicating-feeds-using-c.html | CC-MAIN-2019-09 | refinedweb | 845 | 54.83 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How to make a field invisible using compute field based on a condition?
Hi,
Is it possible to use a computed field to make a particular field invisible based on a condition?
is it possible using compute field?
If the answer is yes, how can this effect be visible in the view?
Please help me
@chirra
You could use it like a normal field, for example:
<field name="make_invisible" invisible="1"/>
<field name="field_x" attrs="{'invisible':[('make_invisible', '=', True)]}"/>
Just note that the fields functions just compute it's value when the form is saved. You could assign a default_value for the function field or change it's value using an onchange.
Hi Axel Mendoza i need invisible the filed through python code only for field level security my issue like this: . When we want to invisible a field conditionally in same group, we using domains to “attrs”. Using browser inspect element feature we can simply remove “oe_invisible” css class and remove the invisible logic.
then change the view by override of the method fields_view_get and deal with xml nodes
Hi,
I think you may use a compute boolean field, that becomes true or false based on the condition. You can make another field visible or invisible using the "attrs" attribute, based on that boolean field. You may note that onchange is default on compute fields and it also compute the values, when you open or edit in form view.
For example, you may see the following example, in that, if the value of field1 is "Any_String", the field2 will be invisible.
in .py file:
class test_model(models.Model):
_name = "test.model"
field1 = fields.Many2one('another.model', String="First field")
check = fields.Boolean(compute='_get_value')
field2 = fields.Char(String="Second field")
@api.one
@api.depends('field1')
def _get_value(self):
if self.field1.name == "Any_String":
self.check = True
else:
self.check = False
in xml file:
<record model="ir.ui.view" id="test_model_form_view">
<field name="name">test.model.form.view</field>
<field name="model">test.model</field>
<field name="arch" type="xml">
<group>
<field name="field1" />
<field name="check" invisible="1" />
<field name="field2" attrs="{'invisible':[('check', '=', True)]}"
</field>
</record>
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/how-to-make-a-field-invisible-using-compute-field-based-on-a-condition-98226 | CC-MAIN-2017-22 | refinedweb | 412 | 58.99 |
A Youtube Video Player for iOS built with Swift.
📦 Requirements
- iOS 8+
- Xcode 9.0+
- Swift 4.0
👨🏻💻 Installation
BTYoutubePlayer is available through CocoaPods. To install
it, simply add the following line to your Podfile:
pod 'BTYoutubePlayer'
💻 Usage
It only takes a few simple steps to and setup BTYoutubePlayer to your project. First of all import BTYoutubePlayer
import 'BTYoutubePlayer'
Load video with Youtube Url
BTYoutubePlayer.loadWith(youtubeUrl: "", target: self)
or
Load video with Youtube ID
BTYoutubePlayer.loadWith(id: "AJtDXIazrMo", target: self)
💁🏻♂️ Example
The iOS Sample App included with this project demonstrates one way to correctly setup and use BTYoutubePlayer
🙋🏻♂️ Author
Bhavik Thummar, Email : [email protected]
📬 Support
Open an issue or shoot me an email. Check out previous issues to see if your’s has already been solved. (I would prefer an issue over an email. But will still happily respond to an email.)
💰 Contribution
Feel free to fork the project and send me a pull-request! 😎
📜 License
You are free to make changes and use this in either personal or commercial projects. Attribution is not required, but highly appreciated. A little "Thanks!" (or something to that affect) is always welcome. If you use BTYoutubePlayer in your app, please let us know!. BTYoutubePlayer is available under the MIT license. See the LICENSE file for more info.
Latest podspec
{ "name": "BTYoutubePlayer", "version": "1.0.0", "summary": "BTYoutubePlayer is a YouTube video player for iOS", "description": "The only official way of playing a YouTube video inside an app is with a web view & the iframe player API. So I wrote this player to play youtube videos using WKWebView & give users a better viewing experience.", "homepage": "", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "BhavikThummar": "[email protected]" }, "source": { "git": "", "tag": "1.0.0" }, "social_media_url": "", "platforms": { "ios": "8.0" }, "source_files": "BTYoutubePlayer/Classes/**/*", "resource_bundles": { "BTYoutubePlayer": [ "BTYoutubePlayer/Assets/*.png" ] } }
Fri, 09 Feb 2018 11:00:13 +0000 | https://tryexcept.com/articles/cocoapod/btyoutubeplayer | CC-MAIN-2019-13 | refinedweb | 308 | 60.11 |
18583/what-is-the-best-functional-language-to-do-hadoop-map-reduce
I'm doing an assignment for a course, which requires me to implement a parallel MapReduce engine in a functional language and then use it solve certain simple problems.
Which functional language do you think I should use?
Here are my requirements:
I am currently considering Haskell and Clojure, but both these languages are new to me - I have no idea if any of these languages are actually appropriate for the situation.
down voteacceptedBoth Clojure and Haskell are definitely worth learning, for different reasons. If you get a chance, I would try both. I'd also suggest adding Scala to your list.
If you have to pick one, I would choose Clojure, for the following reasons:
Also, Clojure makes parallel map-reduce very easy. Here's one to start with:
(reduce + (pmap inc (range 1000)))
=> 500500
Using ratherpmap than map is enough to give you a parallel mapping operation. There are also parallel reducers if you use Clojure 1.5, see the reducers framework for more details.
pmap
map
Apart from that, you can also use Scalding, which is a Scala abstraction on top of Cascading to abstract low-level Hadoop details. It was developed at Twitter, and seems mature enough today so you can start actually using it without too much trouble.
Here is an example how you would do a Wordcount in Scalding:
package com.twitter.scalding.examples
import com.twitter.scalding._
class WordCountJob(args : Args) extends Job(args) {
TextLine( args("input") )
.flatMap('line -> 'word) { line : String => tokenize(line) }
.groupBy('word) { _.size }
.write( Tsv( args("output") ) )
// Split a piece of text into individual words.
def tokenize(text : String) : Array[String] = {
// Lowercase each word and remove punctuation.
text.toLowerCase.replaceAll("[^a-zA-Z0-9\\s]", "").split("\\s+")
}
}
I think it's a good candidate since because it's using Scala it's not too far from regular Map/Reduce Java programs, and even if you don't know Scala it's not too hard to pick up.
mr-jobhistory-daemon. sh start historyserver READ MORE
MapReduce is a programming model to perform ...READ MORE
Default scheduler in hadoop is JobQueueTaskScheduler, which is ...READ MORE
Join is a clause that combines the records ...READ MORE
Firstly you need to understand the concept ...READ MORE
put syntax:
put <localSrc> <dest>
copy syntax:
copyFr ...READ MORE
In your case there is no difference ...READ MORE
The distributed copy command, distcp, is a ...READ MORE
One of the major pushes at SAS ...READ MORE
I suggest spending some time with Apache ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/18583/what-is-the-best-functional-language-to-do-hadoop-map-reduce | CC-MAIN-2020-16 | refinedweb | 441 | 66.23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.